Jump to content

Search the Community

Showing results for tags 'api'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • General
    • Announcements and Site News
    • Administration
  • AutoIt v3
    • AutoIt Help and Support
    • AutoIt Technical Discussion
    • AutoIt Example Scripts
  • Scripting and Development
    • Developer General Discussion
    • Language Specific Discussion
  • IT Administration
    • Operating System Deployment
    • Windows Client
    • Windows Server
    • Office

Categories

  • AutoIt Team
    • Beta
    • MVP
  • AutoIt
    • Automation
    • Databases and web connections
    • Data compression
    • Encryption and hash
    • Games
    • GUI Additions
    • Hardware
    • Information gathering
    • Internet protocol suite
    • Maths
    • Media
    • PDF
    • Security
    • Social Media and other Website API
    • Windows
  • Scripting and Development
  • IT Administration
    • Operating System Deployment
    • Windows Client
    • Windows Server
    • Office

Categories

  • Forum
  • AutoIt

Calendars

  • Community Calendar

Found 33 results

  1. Cisco Finesse UDF

    Hi all, Recently my work swapped from Cisco CTIOS to Finesse. This completely threw me off as I had been automating the Win32 application and I had never done IUIAutomation before. As such I've been messing around with the API and will be adding code as I figure it out. While I do have Supervisor access, I will likely not be adding functions for those features yet. Currently Available Functions: User API - Query and Set User Info Dialog API - Query and Set Call and other Dialog Info Queue API - Query Assigned Queues Team API - Query Users in a Team Changelog: Download:
  2. Hi, I was wondering if someone can help me to create an AutoIT script which can create a ticket in a TopDesk environment. The API is wel documented, but i have not enough knowlegde at this moment to get this up from the ground. If someone could help me or if i could hire / pay someone to help me with this, that would be great. Information about the API can be found here: https://developers.topdesk.com/ Is there a place where i maybe can hire AutoIT professionals to help me with this? On freelancer.com is an option, but there are alot of people responding which doesn't know a thing about AutoIT.
  3. 1. Description. Automate communication with Gmail API using oAuth 2.0 security. 2. Requirements. Google Gmail account. Finished Authorization process. Look here 3. Possibilities. ;======================================================================================================================== ; Date: 2018-02-12, 11:46 ; ; Bug Fixs: 2018-02-17, 7:31 -> Fixed problems with adding items to array and minor bugs. ; ; Description: UDF for using Gmail API interface. This UDF requires oAuth.au3 and Gmail account. ; ; Function(s): ; gmailUsersGetProfile() -> Information about your account. ; gmailUsersLabelsList() -> Get all available labels ids. ex. "INBOX", "UNREAD" ; gmailUsersLabelsGet() -> Get information about specific label id. ; gmailUsersMessagesBatchDelete() -> Delete many messages emails by id. ; gmailUsersMessagesBatchModify() -> Set status for many messages ex. "INBOX", "UNREAD" ; gmailUsersMessagesDelete() -> Totaly delete email from ur account. ; gmailUsersMessagesGet() -> Get all information about specific email. ; gmailUsersMessagesList() -> Get list of last ~100 emails. ; gmailUsersMessagesModify() -> Modify single message. ; gmailUsersMessagesTrash() -> Put email in trash. ; gmailUsersMessagesUntrash() -> Restore email from trash. ; gmailUsersMessagesSend() -> Send email to single or group recipients. ; gmailUsersMessagesAttachmentsGet() -> Download attachment by id. ; ; Author(s): Ascer ;======================================================================================================================== 4. Downloads. oAuth.au3 Gmail API.au3 5. Examples. Sending emails
  4. 1. Description. oAuth 2.0 is security system implemented by Google a few years ago. You are able to connect into your Google accounts and manage documents. In this UDF i show you how to pass first authorization process., this allow you to automate most of functions using API interface. 2. Requirements. Google account. oAuth.au3 Download 3. Possibilities ;============================================================================================================ ; Date: 2018-02-10, 14:21 ; ; Description: UDF for authorize your app with oAuth 2.0 Google. ; ; Function(s): ; oAuth2GetAuthorizationCode() -> Get Code for "grant". ; oAuth2GetAccessToken() -> Get "access_token" and "refresh_token" first time. ; oAuth2RefreshAccessToken() -> Get current "access_token" using "refresh_token". ; ; Author(s): Ascer ;============================================================================================================ 4. Enable your Google API. 4.1. Video Tutorial not mine! YouTube 4.2 Screenshots from authorization process (Polish language) Go to https://console.developers.google.com/apis/dashboard and accept current rules. Next create an new project Enter name of you new project and click Create Google will working now, please wait until finish. Next go to enable your API interface, we make if for Google Take "Gmail" in search input and after click in found result. Click Enable interface, Google will working now. Create your login credentials Select Windows Interface (combobox), User credentials (radio) and click button what is need bla bla Type name of a new client id for oAuth 2.0 and click Create a new Client ID. Next configure screen aplication, type some name and click Next. Google will working now. Last step on this website is download source with your credentials in *Json format. Now you received a file named client_id.json, it's how it look in Sublime Text: 5. Coding. Now we need to call a some function to get access code. #include <oAuth.au3> Local $sClientId = "167204758184-vpeues0uk6b0g4jrnv0ipq5fapoig2v8.apps.googleusercontent.com" Local $sRedirectUri = "http://localhost" oAuth2GetAuthorizationCode($sClientId, $sRedirectUri) Function will execute default browser for ask you to permission. Next Google ask you to permission for access to your personal details by application Autoit Now you can thing is something wrong but all is ok, you need to copy all after code= . It your access code. Let's now ask Google about our Access Token and Refresh Token #include <oAuth.au3> Local $sClientId = "167204758184-vpeues0uk6b0g4jrnv0ipq5fapoig2v8.apps.googleusercontent.com" Local $sClientSecret = "cWalvFr3WxiE6cjUkdmKEPo8" Local $sAuthorizationCode = "4/AAAPXJOZ-Tz0s6mrx7JbV6nthXSfcxaszFh_aH0azVqHkSHkfiwE8uamcabn4eMbEWg1eAuUw7AU0PQ0XeWUFRo#" Local $sRedirectUri = "http://localhost" Local $aRet = oAuth2GetAccessToken($sClientId, $sClientSecret, $sAuthorizationCode, $sRedirectUri) If Ubound($aRet) <> 4 then ConsoleWrite("+++ Something wrong with reading ResponseText." & @CRLF) Exit EndIf ConsoleWrite("Successfully received data from Google." & @CRLF) ConsoleWrite("access_token: " & $aRet[0] & @CRLF) ConsoleWrite("expires_in: " & $aRet[1] & @CRLF) ConsoleWrite("refresh_token: " & $aRet[2] & @CRLF) ConsoleWrite("token_type: " & $aRet[3] & @CRLF) Important! When you received error 400 and output says: Invalid grant it means that your previous generated access_code lost validity and you need to generate new calling previus code. When everything is fine you should received a 4 informations about your: access_token, expires_in, refresh_token and token_type. Access_Token time is a little short so you need to know fuction possible to refresh it (tell Google that he should generate a new Token for you) #include <oAuth.au3> Local $sRefreshToken = "1/ba8JpW7TjQH3-UI1BvPaXhSf-oTQ4BmZAbBfhcKgKfY" Local $sClientId = "167204758184-vpeues0uk6b0g4jrnv0ipq5fapoig2v8.apps.googleusercontent.com" Local $sClientSecret = "cWalvFr3WxiE6cjUkdmKEPo8" Local $sRedirectUri = "http://localhost" Local $aRet = oAuth2RefreshAccessToken($sRefreshToken, $sClientId, $sClientSecret) If Ubound($aRet) <> 3 then ConsoleWrite("+++ Something wrong with reading ResponseText." & @CRLF) Exit EndIf ConsoleWrite("Successfully received data from Google." & @CRLF) ConsoleWrite("access_token: " & $aRet[0] & @CRLF) ConsoleWrite("expires_in: " & $aRet[1] & @CRLF) ConsoleWrite("token_type: " & $aRet[2] & @CRLF) 6. Finish words If you followed all this above steps im sure that you received all informations required for coding your Google API (Gmail, Dropbox, YouTube, Calender etc. See next thread: [UDF] Gmail API - Email automation with AutoIt!
  5. Hi All i am currently trying to add a function to my project that can send SMS, i have gone with Twilio for the sms service that use a REST API. I have never worked with an API before, and could use some help. I can get my function working with using cURL.exe and copy past command from the website with the following code. And thats great unfortunately i am have issue with character like æøå when sending a SMS appears like a box or ?. this does not happen if i do it from the website so it looks like a Unicode issue in curl.exe. I have done some searching on the forum and understand that i should be able to implement this curl command with the WinHTTP UDF from @trancexx so i don't need a third part exe and it might fix my charater issue. Unfortunately i really don't understand how i am to change curl commands to the WinHTTP and i was hoping some good maybe give me an example i could learn from. Thanks in advanced i have removed the AuthToken number from the script. _SendSMS("00000000","SomeOne","SMS body info") Func _SendSMS($SendTo,$SendFrom,$Msgtxt) $AccountSID = "ACbb765b3180d5938229eff8b8f63ed1bc" $AuthToken = "Auth Token number" $Data = '"https://api.twilio.com/2010-04-01/Accounts/'&$AccountSID&'/Messages.json"'& _ '-X POST \ --data-urlencode "To=+45'&$SendTo&'" \ --data-urlencode "From='&$SendFrom&'" \ --data-urlencode "Body='&$Msgtxt&'" \ -u '&$AccountSID&':'&$AuthToken&'' ShellExecute(@ScriptDir&"\curl.exe","-k "&$Data) ;~ curl 'https://api.twilio.com/2010-04-01/Accounts/ACbb765b3180d5938229eff8b8f63ed1bc/Messages.json' -X POST \ ;~ --data-urlencode 'To=+4500000000' \ ;~ --data-urlencode 'From=Reception' \ ;~ --data-urlencode 'Body=Test Body' \ ;~ -u ACbb765b3180d5938229eff8b8f63ed1bc:[AuthToken] EndFunc
  6. Hello friends, i have a working curl command that show informations about my account on binance.com, but_it dont work with autoit code without curl.exe. I want to do it without curl, because the whole process much Slower_ with StdoutRead (I want get the response in variable.) My Curl command in Autoit: This 2 are works, but_ i would like to do it without curl.exe $apikey="XYZ" sCommand = @ScriptDir & '\curl.exe -k -H "X-MBX-APIKEY: ' & $apikey & '" -X GET "https://api.binance.com/api/v3/account?' & $request the same in .bat file curl.exe -k -H "X-MBX-APIKEY: XYZ" -X GET "https://api.binance.com/api/v3/account?timestamp=1514917812000&signature=85bdee77e53cd521e1d5229fbfb459d53799c42b3fa4596d73f1520fad5f965a" (I use curl with -k option which allows curl to make insecure connections, because there is problem with the sites certificate, (cURL error 60)) I tried many variations, this is the latest... I cant get the same response. curl $error message (I changed ): {"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."} autoit version $error message (Response code:400): Mandatory parameter 'timestamp' was not sent, was empty/null, or malformed. $request = $query & '&signature=' & $signature $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET", "https://api.binance.com/api/v3/account", False) $oHTTP.SetRequestHeader("X-MBX-APIKEY", $apikey) $oHTTP.Send($request) $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status If $oStatusCode <> 200 then MsgBox(4096, "Response code", $oStatusCode) EndIf thanks
  7. Hi Guys, I have been trying to write the API calls to Coinigy.com in AutoitScipt. I have managed to solve most of them put are having trouble with the ones that require parameters to be passed. The source to the API calls can be found here: http://docs.coinigy.apiary.io/#reference/market-data/market-data/data-{type:history} Example code from this site: curl --include \      --request POST \      --header "Content-Type: application/json" \      --header "X-API-KEY: " \      --header "X-API-SECRET: " \      --data-binary "    {         \"exchange_code\": \"GDAX\",         \"exchange_market\": \"BTC/USD\",         \"type\": \"history\"     }" \ ' https://api.coinigy.com/api/v1/data ' This data one is really annoying me. I have the following so far: #include <Array.au3> #include <string.au3> #include <MsgBoxConstants.au3> #Region Coinigy Const Global $sCoinigyAPIUrl = "https://api.coinigy.com/api/v1/" #EndRegion Coinigy Const #Region keys Global Const $sCoinigyAPIKey = "" ; just removed my APIKey Global Const $sCoinigyAPISecret = "" ; just removed my APISecret #EndRegion keys $sResults = CoinigyQueryPrivate("data", "exchange_code=GDAX&exchange_market=BTC/USD&type=history") ; Trade history, asks and bids for any supported exchange/market ConsoleWrite("Market Data: " & $sResults & @CRLF & @CRLF) Func CoinigyQueryPrivate($sMethod, $sParameters)     Local $oHTTP = ObjCreate("winhttp.winhttprequest.5.1")     $oHTTP.Open("POST", $sCoinigyAPIUrl & $sMethod, False)     $oHTTP.SetRequestHeader("X-API-KEY", $sCoinigyAPIKey)     $oHTTP.SetRequestHeader("X-API-SECRET", $sCoinigyAPISecret)    ; $oHTTP.Send(Binary($sParameters)) ; tried this as well     $oHTTP.Send($sParameters)     Local $sReceived = $oHTTP.ResponseText     Return $sReceived EndFunc   ;==>CoinigyQueryPrivate If I do other queries that don't require Parameters they work perfectly. I am just totally stumped by the parameter passing queries. I have tried everything and I still can't get it to go. Would really appreciate some help. If you want to try for yourself live, Coinigy.com give a free 30 trial.... Please help... Thanks in advance.
  8. Google Speech API

    Dear master, hello, I got the speech API from Google. But I could not find how to use. Could you help me with a simple example? "https://speech.googleapis.com/v1/speech:recognize?key=MyKey"
  9. So I have been bashing my head in for a couple days and have searched both AutoIT forums and Thwack Forums for an answer. I understand this could be hard to help sense I can't provide a server for someone to help me test against. I am trying to use the WinHTTP.au3 to connect with Solarwinds Orion SDK thru REST/JSON api calls. Here is the documentation that they provide. https://github.com/solarwinds/OrionSDK/wiki/REST I have been trying just to make a basic connection but for some reason cannot get past the authorization process with WinHTTP. Here is my test code. #Region Includes #include <log4a.au3> #include "WinHttp.au3" #EndRegion Global $sAddress = "https://usandl0213:17778/SolarWinds/InformationService/v3/Json/Query?query=SELECT+NodeID+FROM+Orion.NODES" Global $array_URL = _WinHttpCrackUrl($sAddress) ;~ Row|Col 0 ;~ [0]|https ;~ [1]|2 ;~ [2]|usandl0213 ;~ [3]|17778 ;~ [4]| ;~ [5]| ;~ [6]|/SolarWinds/InformationService/v3/Json/Query ;~ [7]|?query=SELECT+NodeID+FROM+Orion.NODES Global $hOpen = _winhttpOpen() If @error Then _log4a_Fatal("Error intializing the usage of WinHTTP functions") Exit 1 EndIf Global $hConnect = _winhttpConnect($hOpen, $array_URL[2]) If @error Then _log4a_Fatal("Error specifying the initial target server of an HTTP request.") _WinHttpCloseHandle($hOpen) Exit 2 EndIf Global $hRequest = _WinHttpOpenRequest($hConnect, _ "GET", _ "/SolarWinds/InformationService/v3/Json/Query?query=SELECT+NodeID+FROM+Orion.NODES", _ "HTTP/1.1") If @error Then _log4a_Fatal(MsgBox(48, "Error", "Error creating an HTTP request handle.") _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) Exit 3 EndIf _WinHttpAddRequestHeaders($hRequest, "Authorization: Basic YXV0b2l0X2xvZ2luOnRlc3Q=") _WinHttpAddRequestHeaders($hRequest, "User-Agent: curl/7.20.0 (i386-pc-win32) libcurl/7.20.0 OpenSSL/0.9.8l zlib/1.2.3") _WinHttpAddRequestHeaders($hRequest, "Host: usandl0213:17778") _WinHttpAddRequestHeaders($hRequest, "Accept: */*") _WinHttpSendRequest($hRequest) If @error Then MsgBox(48, "Error", "Error sending specified request.") Close_request() Exit 4 EndIf ; Wait for the response _WinHttpReceiveResponse($hRequest) If @error Then MsgBox(48, "Error", "Error waiting for the response from the server.") Close_request() Exit 5 EndIf Global $sChunk, $sData ; See what's returned If _WinHttpQueryDataAvailable($hRequest) Then Global $sHeader = _WinHttpQueryHeaders($hRequest) ;~ ConsoleWrite(@crlf) ConsoleWrite($sHeader & @CRLF) ; Read While 1 $sChunk = _WinHttpReadData($hRequest) If @error Then ExitLoop $sData &= $sChunk WEnd ConsoleWrite($sData & @CRLF) ; print to console Else MsgBox(48, "Error", "Site is experiencing problems.") EndIf Close_request() Func Close_request() ; Close open handles and exit _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) EndFunc I am definitely connecting to the server but get a 401 Unauthorized response. Output of above script: Header: HTTP/1.1 401 Unauthorized Cache-Control: private Date: Thu, 27 Jul 2017 15:31:21 GMT Content-Length: 1668 Content-Type: text/html; charset=utf-8 Server: Microsoft-IIS/7.5 Set-Cookie: ASP.NET_SessionId=lgwin2qsbbrip2mxg01fot05; path=/; HttpOnly Set-Cookie: TestCookieSupport=Supported; path=/ Set-Cookie: Orion_IsSessionExp=TRUE; expires=Thu, 27-Jul-2017 17:31:21 GMT; path=/ WWW-Authenticate: Negotiate WWW-Authenticate: NTLM X-UA-Compatible: IE=9 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET X-Same-Domain: 1 X-Content-Type-Options: nosniff X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block Body: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><link rel="stylesheet" type="text/css" href="/orion/js/jquery-1.7.1/jquery-ui.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" /> <link rel="stylesheet" type="text/css" href="/orion/styles/orionminreqs.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" /> <link rel="stylesheet" type="text/css" href="/webengine/resources/steelblue.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" /> <link rel="stylesheet" type="text/css" href="/orion/ipam/res/css/sw-events.css.i18n.ashx?l=en-US&v=42660.90.L&csd=%23b0b9c5;%23d2ddec;%2392add1;" /> <script type="text/javascript" src="/orion/js/orionminreqs.js.i18n.ashx?l=en-US&v=42660.90.L"></script> <script type="text/javascript" src="/orion/js/modernizr/modernizr-2.5.3.js.i18n.ashx?l=en-US&v=42660.90.L"></script> <script type="text/javascript" src="/orion/js/jquery-1.7.1/jquery-1.7.1.framework.min.js.i18n.ashx?l=en-US&v=42660.90.L"></script> <script type="text/javascript">(function(){var de=$(document.documentElement); de.addClass('sw-is-locale-en'); $.each(jQuery.browser,function(k,v){if(v===true){ de.addClass('sw-is-'+k); de.addClass('sw-is-'+k+'-'+parseInt(jQuery.browser.version)); }}); })();</script> <script type="text/javascript">SW.Core.Loader._cbLoaded('jquery');</script> <script type="text/javascript">SW.Core.Date._init(0,-14400000);</script> <title> </title></head> <body> <script> window.location = 'Login.aspx'; </script> </body> </html> To me this looks like it if it is still looking for my credentials. I did verify that things work as expected using Chrome and REST test client. I do get certificate errors in IE if I try to go directly. Bypass certificate issues and page will try to save out to .json file Looking for any help.
  10. Recently I was working on TeamVierwer API . I had a little break, and wanted to check out another platform. Here is the result of my attempt: #include "GHAPI.au3" _GHAPI_AccessToken('b3e8.....de..........bdc3a0c.....bd27c6f') _GHAPI_GetUser("users/mLipok") _GHAPI_GetUserOrganizations("users/mLipok") _GHAPI_RootEndpoints() and GHAPI.au3 #include-once #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w 7 #Tidy_Parameters=/sort_funcs /reel #Region GHAPI.au3 - Header ; #INDEX# ======================================================================================================================= ; Title .........: GHAPI UDF ; AutoIt Version : 3.3.10.2++ ; Language ......: English ; Description ...: This is an UDF for for communicate with https://api.github.com via GitHub RESTful API ; Author(s) .....: mLipok ; Modified ......: ; =============================================================================================================================== #cs Title: GHAPI UDF Filename: GHAPI.au3 Description: This is an UDF for for communicate with https://api.github.com via GitHub RESTful API Author: mLipok Modified: Last Update: 2017/05/23 Requirements: AutoIt 3.3.10.2 or higher #ce #EndRegion GHAPI.au3 - Header #Region GHAPI.au3 - Include #include <array.au3> #include <FileConstants.au3> #include <MsgBoxConstants.au3> #EndRegion GHAPI.au3 - Include #Region GHAPI.au3 - Declarations Global $oErrorHandler = ObjEvent("AutoIt.Error", "_GHAPI_ErrFunc") Global $__g_sGitHubAPI_BaseUrl = "https://api.github.com" ; URL of the GitHub API Global $__g_sGitHubAPI_Version = "v3" ; Put the current API version in here Global Enum _ $GHAPI_ERR_SUCCESS, _ $GHAPI_ERR_GENERAL, _ $GHAPI_ERR_COMERROR, _ $GHAPI_ERR_STATUS, _ $GHAPI_ERR_COUNTER Global Enum _ $GHAPI_EXT_DEFAULT, _ $GHAPI_EXT_PARAM1, _ $GHAPI_EXT_PARAM2, _ $GHAPI_EXT_PARAM3, _ $GHAPI_EXT_COUNTER Global Enum _ $GHAPI_RET_SUCCESS, _ $GHAPI_RET_FAILURE, _ $GHAPI_RET_COUNTER #EndRegion GHAPI.au3 - Declarations #Region GHAPI.au3 - API Functions Func _GHAPI_ErrFunc($oError) ; Do anything here. ConsoleWrite(@ScriptName & " (" & $oError.scriptline & ") : ==> COM Error intercepted !" & @CRLF & _ @TAB & "err.number is: " & @TAB & @TAB & "0x" & Hex($oError.number) & @CRLF & _ @TAB & "err.windescription:" & @TAB & $oError.windescription & @CRLF & _ @TAB & "err.description is: " & @TAB & $oError.description & @CRLF & _ @TAB & "err.source is: " & @TAB & @TAB & $oError.source & @CRLF & _ @TAB & "err.helpfile is: " & @TAB & $oError.helpfile & @CRLF & _ @TAB & "err.helpcontext is: " & @TAB & $oError.helpcontext & @CRLF & _ @TAB & "err.lastdllerror is: " & @TAB & $oError.lastdllerror & @CRLF & _ @TAB & "err.scriptline is: " & @TAB & $oError.scriptline & @CRLF & _ @TAB & "err.retcode is: " & @TAB & "0x" & Hex($oError.retcode) & @CRLF & @CRLF) EndFunc ;==>_GHAPI_ErrFunc Func _GHAPI_AccessToken($sParam = Default) ; https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/ ; https://github.com/settings/tokens Local Static $sAccessToken = '' If $sParam <> Default Then $sAccessToken = $sParam Return $sAccessToken EndFunc ;==>_GHAPI_AccessToken Func _GHAPI_GetUser($sUser) Local $oHTTP = __GHAPI_HTTP_Open("GET", $sUser) Local $oJSON = __GHAPI_HTTP_Send($oHTTP) If @error Then Return SetError(@error, @extended, False) #forceref $oJSON EndFunc ;==>_GHAPI_GetUser Func _GHAPI_GetUserOrganizations($sUser) Local $oHTTP = __GHAPI_HTTP_Open("GET", $sUser & '/orgs') Local $oJSON = __GHAPI_HTTP_Send($oHTTP) If @error Then Return SetError(@error, @extended, False) #forceref $oJSON EndFunc ;==>_GHAPI_GetUserOrganizations Func _GHAPI_RootEndpoints() Local $oHTTP = __GHAPI_HTTP_Open("GET", '') Local $oJSON = __GHAPI_HTTP_Send($oHTTP) If @error Then Return SetError(@error, @extended, False) #forceref $oJSON EndFunc ;==>_GHAPI_RootEndpoints #EndRegion GHAPI.au3 - API Functions #Region GHAPI.au3 - INTERNAL Functions Func __GHAPI_HTTP_Open($sMethod, $sCommand, $sURLParameters = '') Local $oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1") Local $sURL = $__g_sGitHubAPI_BaseUrl & "/" & $sCommand & $sURLParameters ;~ __GHAPI_DebugOut("> $sURL=" & $sURL & @CRLF) $oHTTP.Open($sMethod, $sURL, False) If @error Then Return SetError(@error, @extended, Null) $oHTTP.setRequestHeader("Authorization", "Bearer " & _GHAPI_AccessToken()) ; Accept: application/vnd.github.v3+json $oHTTP.setRequestHeader("Accept", "application/vnd.github." & $__g_sGitHubAPI_Version & "+json") ; User-Agent: Awesome-Octocat-App $oHTTP.setRequestHeader("User-Agent", "AutoIt UDF") Return $oHTTP EndFunc ;==>__GHAPI_HTTP_Open Func __GHAPI_HTTP_Send(ByRef $oHTTP, $sSendParameter = Default) If $sSendParameter = Default Then $oHTTP.Send() Else $oHTTP.Send($sSendParameter) EndIf ConsoleWrite('+' & $oHTTP.Status & @CRLF) ConsoleWrite('>' & $oHTTP.StatusText & @CRLF) ConsoleWrite($oHTTP.ResponseText & @CRLF) ConsoleWrite(@CRLF) If @error Then Return SetError(@error, @extended, $GHAPI_RET_FAILURE) ;~ Return SetError($GHAPI_ERR_SUCCESS, $oJSON.Size, $oJSON) EndFunc ;==>__GHAPI_HTTP_Send #EndRegion GHAPI.au3 - INTERNAL Functions #Region GHAPI.au3 - HOWTO / DOCS / HELP #CS https://developer.github.com/v3/ https://developer.github.com/v3/guides/ https://developer.github.com/program/ https://github.com/contact?form%5Bsubject%5D=New+GitHub+Integration https://developer.github.com/ http://stackoverflow.com/questions/28796941/github-api-authentication-with-msxml2-xmlhttp #CE #EndRegion GHAPI.au3 - HOWTO / DOCS / HELP REMARKS: This is just a modest start up and not a whole fully workable UDF, just so for a try, but maybe someone will be useful Regards, mLipok EDIT 1: If you need to make it workable just ask about specyfic feature. EDIT 2: Some changes in using word "GitHub" - to meet this rules: https://github.com/logos
  11. Hey guys, I'm looking to implement an accurate voice recognition method in my program. I tried to understand the Microsoft SAPI API, read their online documentation and found it very confusing and unclear. (Like seriously, it's so bad and vague, but that's just my opinion). I have also tried using UTTER UDF, but could not get a grasp either, because you know, that's an extension UDF to Microsoft SAPI. Let's face it, the Google Speech Recognition is much more accurate than Microsoft SAPI (by far). Right now, I am determined to just use the Google Speech API. I have dug deep in regards to implementing the Google Speech API in AutoIT and I haven't found even one post about it. I suppose it's because the Google Speech API was only recently made available to the public. In case you don't know what I'm talking about, here's the link to google api. On that page, notice that there is language support for various languages such as Java, C#, and PHP. However, there's no support for AutoIT. So my question is; how can I go about implementing the Google Speech API into my AutoIT program? Is it even possible? Cheers guys!
  12. This is TeamViewer.au3 UDF for TeamViewer API. ; #INDEX# ======================================================================== ; Title .........: TeamViewer.au3 ; AutoIt Version : 3.3.10.2++ ; Language ......: English ; Description ...: A collection of function for use with TeamViewer API ; Author ........: mLipok ; Modified ......: ; URL ...........: ; URL ...........: https://www.teamviewer.com/ ; URL ...........: https://www.teamviewer.com/en/integrations/ ; URL ...........: https://integrate.teamviewer.com/en/develop/api/get-started/ ; URL ...........: https://downloadeu1.teamviewer.com/integrate/TeamViewer_API_Documentation.pdf ; Remarks .......: This UDF was created based on TeamViewer_API_Documentation.pdf v 1.4.1 ; Remarks .......: This UDF is using Free Chilkat component look here https://www.autoitscript.com/forum/files/file/433-chilkat-udf/ ; Remarks .......: Documentation is "work in progress" ; Date ..........: 2017/02/08 ; Version .......: 0.1.1 BETA - Work in progress ; ================================================================================ in TeamViewer_Example.au3 you can see few examples: Func _Example() ; If not exist then create new INI file from template If Not FileExists('TeamViewer_Example.ini') Then FileCopy('TeamViewer_Example — Template.ini', 'TeamViewer_Example.ini') ; Read Access Token from INI Local $sTV_AccessToken = IniRead('TeamViewer_Example.ini', 'Settings', 'AccessToken', '') If $sTV_AccessToken = '' Then ; Your Access Token, can be left empty when OAuth (below) is configured. ; ClientId = <----------------- Create an app in your TeamViewer Management Console and insert the client ID to the INI ; ClientSecret = <------------- Insert your client secret to the INI ; AuthorizationCode = <-------- Visit https://webapi.teamviewer.com/api/v1/oauth2/authorize?response_type=code&client_id=YOUR$i_ClientIdHERE ; Login, grant the permissions (popup) and put the code shown in the AuthorizationCode variable to the INI Local $sTVOAuth_ClientID = IniRead('TeamViewer_Example.ini', 'OAuth2', 'ClientID', '') Local $sTVOAuth_ClientSecret = IniRead('TeamViewer_Example.ini', 'OAuth2', 'ClientSecret', '') _IECreate('https://webapi.teamviewer.com/api/v1/oauth2/authorize?response_type=code&client_id=' & $sTVOAuth_ClientID) ; Local $sTVOAuth_AuthorizationCode = IniRead('TeamViewer_Example.ini', 'OAuth2', 'authorizationCode', '') Local $sTVOAuth_AuthorizationCode = InputBox('AuthorizationCode', 'Please provide TV OAuth2 AuthorizationCode') If @error Then Return If $sTVOAuth_ClientID Then $sTV_AccessToken = _TVAPI_RequestOAuth2_AccessToken($sTVOAuth_ClientID, $sTVOAuth_ClientSecret, $sTVOAuth_AuthorizationCode) EndIf If $sTV_AccessToken Then _TVAPI_AccessToken($sTV_AccessToken) If _TVAPI_Ping() = True Then ; ping API to check connection and $sTV_AccessToken _Example_TeamViewer__1_Devices_SaveToFile() ;~ _Example_TeamViewer__2_Devices_ChangeDetails() ;~ _Example_TeamViewer__3_Devices_GetDevicesSingleID() ;~ _Example_TeamViewer__4_Reports_GetAllConnections() ;~ _Example_TeamViewer__5_Users_GetUserInfomation() ;~ _Example_TeamViewer__6_Groups_ListGroups() ;~ _Example_TeamViewer__7_Devices_AddDeleteDevice() Else MsgBox(0, '_TVAPI_Ping', "$v_Token or connection problem.") EndIf EndFunc ;==>_Example You can download it here: I'm using TeamViewer_Example.ini to store my secret tokens/keys. [Settings] AccessToken= [OAuth2] ClientID= ClientSecret= authorizationCode=
  13. Version 1.0.0

    286 downloads

    This is TeamViewer.au3 UDF for TeamViewer API. ; #INDEX# ======================================================================== ; Title .........: TeamViewer.au3 ; AutoIt Version : 3.3.10.2++ ; Language ......: English ; Description ...: A collection of function for use with TeamViewer API ; Author ........: mLipok ; Modified ......: ; URL ...........: ; URL ...........: https://www.teamviewer.com/ ; URL ...........: https://www.teamviewer.com/en/integrations/ ; URL ...........: https://integrate.teamviewer.com/en/develop/api/get-started/ ; URL ...........: https://downloadeu1.teamviewer.com/integrate/TeamViewer_API_Documentation.pdf ; Remarks .......: This UDF was created based on TeamViewer_API_Documentation.pdf v 1.4.1 ; Remarks .......: This UDF is using Free Chilkat component look here https://www.autoitscript.com/forum/files/file/433-chilkat-udf/ ; Remarks .......: Documentation is "work in progress" ; Date ..........: 2017/02/08 ; Version .......: 0.1.1 BETA - Work in progress ; ================================================================================ I'm using TeamViewer_Example.ini to store my secret tokens/keys. [Settings] AccessToken= [OAuth2] ClientID= ClientSecret= authorizationCode= in TeamViewer_Example.au3 you can see few examples: Func _Example() ; If not exist then create new INI file from template If Not FileExists('TeamViewer_Example.ini') Then FileCopy('TeamViewer_Example — Template.ini', 'TeamViewer_Example.ini') ; Read Access Token from INI Local $sTV_AccessToken = IniRead('TeamViewer_Example.ini', 'Settings', 'AccessToken', '') If $sTV_AccessToken = '' Then ; Your Access Token, can be left empty when OAuth (below) is configured. ; ClientId = <----------------- Create an app in your TeamViewer Management Console and insert the client ID to the INI ; ClientSecret = <------------- Insert your client secret to the INI ; AuthorizationCode = <-------- Visit https://webapi.teamviewer.com/api/v1/oauth2/authorize?response_type=code&client_id=YOUR$i_ClientIdHERE ; Login, grant the permissions (popup) and put the code shown in the AuthorizationCode variable to the INI Local $sTVOAuth_ClientID = IniRead('TeamViewer_Example.ini', 'OAuth2', 'ClientID', '') Local $sTVOAuth_ClientSecret = IniRead('TeamViewer_Example.ini', 'OAuth2', 'ClientSecret', '') _IECreate('https://webapi.teamviewer.com/api/v1/oauth2/authorize?response_type=code&client_id=' & $sTVOAuth_ClientID) ; Local $sTVOAuth_AuthorizationCode = IniRead('TeamViewer_Example.ini', 'OAuth2', 'authorizationCode', '') Local $sTVOAuth_AuthorizationCode = InputBox('AuthorizationCode', 'Please provide TV OAuth2 AuthorizationCode') If @error Then Return If $sTVOAuth_ClientID Then $sTV_AccessToken = _TVAPI_RequestOAuth2_AccessToken($sTVOAuth_ClientID, $sTVOAuth_ClientSecret, $sTVOAuth_AuthorizationCode) EndIf If $sTV_AccessToken Then _TVAPI_AccessToken($sTV_AccessToken) If _TVAPI_Ping() = True Then ; ping API to check connection and $sTV_AccessToken _Example_TeamViewer__1_Devices_SaveToFile() ;~ _Example_TeamViewer__2_Devices_ChangeDetails() ;~ _Example_TeamViewer__3_Devices_GetDevicesSingleID() ;~ _Example_TeamViewer__4_Reports_GetAllConnections() ;~ _Example_TeamViewer__5_Users_GetUserInfomation() ;~ _Example_TeamViewer__6_Groups_ListGroups() ;~ _Example_TeamViewer__7_Devices_AddDeleteDevice() Else MsgBox(0, '_TVAPI_Ping', "$v_Token or connection problem.") EndIf EndFunc ;==>_Example SUPPORT TOPIC IS HERE: TeamViewer_Example — Template.ini
  14. I've run into the problem where multiple script processes writing to a log file at the same time can interfere with one another. That is, file writes using FileWriteLine are not atomic, so a line of text from one process can have fragments of text from other processes mixed in with it. Exclusive file-locking should take care of the problem. Looking through the standard UDFs, I see that _WinAPI_LockFile is available, but according to the MSDN documentation it doesn't block - it returns immediately if the lock can't be obtained - and there doesn't seem to be a UDF for the LockFileEx function. I considered writing my own UDF for LockFileEx, but some aspects (e.g., creating the OVERLAPPED structure and its members) look too complex for the amount of time I have available. I think approximating LockFileEx using LockFile could solve my problem, but I'd like to keep it simple while still working reliably. I'm not confident that (e.g.) a simple retry loop to simulate blocking will be adequate. Any suggestions for a simple way to achieve exclusive file-locking with blocking?
  15. Hello, I will put it as simple as possible Why this code runs perfectly on 32bit and it fails on 64bit? Local $hWND = WinGetProcess("[CLASS:LSS_app]") ConsoleWrite($hWND & @LF) Local $hModuleList = _WinAPI_EnumProcessModules($hWND) If @error Then ConsoleWrite("Error: " & @error & @LF) For $i = 0 To $hModuleList[0][0] - 1 ;~ If StringInStr($hModuleList[$i][1], "sysCap64.dll") Then ConsoleWrite($hModuleList[$i][0] & @LF) ;~ EndIf Next As the title says EnumProcessModules returns error 10 which I have no clue what it is. It must be something with autoit or my lack of coding because a similar code in C# will work like a charm on both x86 and x64 Process[] Processes = Process.GetProcessesByName("winLSS64Cap"); Process nProcess = Processes[0]; Handle = OpenProcess(0x10, true, (uint)nProcess.Id); for(int i = 0; i < nProcess.Modules.Count; i++) { Console.WriteLine(nProcess.Modules[i].ModuleName); }
  16. I'm trying to use Sendspace API for download and upload, until now i only have learned to get token, login and get session key. My next step is upload a file. But i have no idea how to do this part. ; try to upload something ; Specify the reguest to upload.getInfo: Local $hRequest = _WinHttpOpenRequest($hConnect, Default, "/rest/?method=upload.getinfo&session_key=" & $SessonKey & "&speed_limit=0") ; Send request Local $handle = _WinHttpSendRequest($hRequest) ; Wait for the response Local $WaitRS = _WinHttpReceiveResponse($hRequest) ; Read Data Local $sData = _WinHttpReadData($hRequest) MsgBox(0, "Upload Data", $sData) _filewrite($sData) ; Get all info needed from $sData $URL = _StringBetween($sData, "<upload url=", "progress") $sURL = $URL[0] $MaxFileSize = _StringBetween($sData, "max_file_size=", "progress") $sMaxFileSize = $MaxFileSize[0] $Upload_Identifier = _StringBetween($sData, "upload_identifier=", "&amp") $sUpload_Identifier = $Upload_Identifier[0] $ExtraInfo = _StringBetween($sData, "extra_info=", "/>") $sExtraInfo = $ExtraInfo[0] ;All well done until here ;Fill in form $XML = '<form method="post" action="' & $sURL & 'enctype="multipart/form-data">' & @CRLF $XML &= '<input type="hidden" name="MAX_FILE_SIZE" value=' & $sMaxFileSize & '>' & @CRLF $XML &= '<input type="hidden" name="UPLOAD_IDENTIFIER" value=' & $sUpload_Identifier & '>' & @CRLF $XML &= '<input type="hidden" name="extra_info" value=' & $sExtraInfo & '>' & @CRLF $XML &= '<input type="file" name=' & "C:\Users\Arlen\Desktop\premisa mrotal.txt" & '>' & @CRLF $XML &= '</form>' MsgBox(0,"", $XML) ; Now how do i send it? Is it correct? _WinHttpCloseHandle($hRequest) _WinHttpCloseHandle($hConnect) _WinHttpCloseHandle($hOpen) sendspace_api_guide.pdf
  17. Autoit API

    Hi all, i need help finding a good (guide, tutorial) on how to use Autoit with API. I would like to try Gmail API and DropBox API. But i have no idea where to start.. Edit: I have learn a little bit, i know how to login to DepositFiles, But i have no idea how to upload and get the link from depositfiles any help? =) #include "WinHTTP.au3" $hSesson = _WinHttpOpen("Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0") $Username = "user" $Password = "pass" $sHost = "depositfiles.org" $sData = "login=" & $Username & "&password=" & $Password & "&recaptcha_challenge_field=&recaptcha_response_field=&g-recaptcha-response=" $sHostC = _WinHttpConnect($hSesson, $sHost) $sPacket = _WinHttpSimpleRequest($sHostC, "POST", "/api/user/login", "http://depositfiles.org/login.php?return=%2F", $sData) ;_filewrite($sPacket)
  18. Hello First i want to say that most of my problems i can solve while scripting by looking at the forum or in the help file but im stuck on this specific problem. I have been writing scripts to consume Web services and this works fine when its just plain XML responses. I work on a project now where i need to consume a SOAP response with an Attachment. I can make the plain SOAP call and get a response as well but i dont know how to handle the multipart and binary data. I have tried ADODB.Stream to write the data to a file but this just writes everything. I would be very grateful if someone could point me into the right direction. Please find below the Request and the Response i get at the momen $objHTTP = ObjCreate("Microsoft.XMLHTTP") $objReturn = ObjCreate("Msxml2.DOMDocument.3.0") $oDATA=ObjCreate("ADODB.Stream") $strEnvelope = '<?xml version="1.0" encoding="UTF-8"?>' _ '<soapenv:Envelope' _ 'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"' _ 'xmlns:xsd="http://www.w3.org/2001/XMLSchema"' _ 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' _ '<soapenv:Body>' _ '<ns1:getStorageAccessTicket' _ 'soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"' _ 'xmlns:ns1="NBRStorageService">' _ '<siteId xsi:type="xsd:long">123456</siteId>' _ '<username xsi:type="xsd:string">USERNAME</username>' _ '<password xsi:type="xsd:string">PASSWORD</password>' _ '</ns1:getStorageAccessTicket>' _ '</soapenv:Body>' '</soapenv:Envelope>' _ ; Set up to post to the server $objHTTP.open ("post", "API end point" , False) ; Set a standard SOAP/ XML header for the content-type $objHTTP.setRequestHeader ("Content-Type", "application/xml") ; Set a header for the method to be called $objHTTP.setRequestHeader ("SOAPAction", 'getStorageAccessTicket') ConsoleWrite("Content of the Soap envelope :" & @CR & $strEnvelope & @CR & @CR ) ; Make the SOAP call $objHTTP.send ($strEnvelope) ; Get the return envelope $strReturn = $objHTTP.responsetext With $oDATA .Type=1 .Open .Write($objHTTP.ResponseBody) .SaveToFile(@ScriptDir&'\captcha.arf', 2) .Close EndWith EndFunc RESPONSE: '------=_Part_5_987625235.1444159091234' 'Content-Type: text/xml; charset=UTF-8' 'Content-Transfer-Encoding: binary' 'Content-Id: <DF72463F6FAFE80B930059E761DF7225>' '<?xml version="1.0" encoding="UTF-8"?>' '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' '<soapenv:Body>' '<ns1:downloadNBRStorageFileResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="NBRStorageService">' '<ns1:downloadNBRStorageFileReturn xsi:type="soapenc:Array" soapenc:arrayType="ns1:DataHandler[2]" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">' '<item href="cid:FE782065C11E6558C9C8925EBE3D687F"/>' '<item href="cid:3CF0B37E4C5932A3E60EBA5226CFC30A"/>' '</ns1:downloadNBRStorageFileReturn>' '</ns1:downloadNBRStorageFileResponse>' '</soapenv:Body>' '</soapenv:Envelope>' ------=_Part_5_987625235.1444159091234 Content-Type: application/octet-stream Content-Transfer-Encoding: binary Content-Id: <FE782065C11E6558C9C8925EBE3D687F> Attachment.arf 2342371 false ------=_Part_5_987625235.1444159091234 Content-Type: application/octet-stream Content-Transfer-Encoding: binary Content-Id: <3CF0B37E4C5932A3E60EBA5226CFC30A>
  19. Hello. I try to register event handler for for IMbnPinManagerEvents interface. All goes well, but when event triggered i have in params strange data. For example in OnGetPinStateComplete in $iRequestID i expect same id, but getting 0 all the time, in $pPinInfo i expect pointer to the structure, but when i fills the structure on this pointer, i have incorrect data in results, and so on... This is a very specific API and work only whith usb modems, so if you do not have a modem, example does not work, but I hope that the skilled person will be able to find and show where the error in the code. I hope for your help. Thanks. https://msdn.microsoft.com/en-us/library/windows/desktop/dd323268(v=vs.85).aspx #include <WinAPI.au3> #include 'SafeArray.au3' #Region Const Global Const $sIID_IUnknown = "{00000000-0000-0000-C000-000000000046}" Global Const $sIID_IMbnPinManager = '{DCBBBAB6-2005-4BBB-AAEE-338E368AF6FA}' Global Const $dtag_IMbnPinManager = _ 'GetPinList hresult();' & _ 'GetPin hresult();' & _ 'GetPinState hresult(ulong*);' ; /* [out] */ __RPC__out ULONG *requestID Global Const $sIID_IMbnPinManagerEvents = '{DCBBBAB6-2006-4BBB-AAEE-338E368AF6FA}' Global Const $dtag_IMbnPinManagerEvents = _ 'OnPinListAvailable hresult();' & _ 'OnGetPinStateComplete hresult(' & _ 'ptr;' & _ ; /* [in] */ __RPC__in_opt IMbnPinManager *pinManager 'struct;' & _ ; /* [in] */ MBN_PIN_INFO pinInfo 'ulong;' & _ ; /* [in] */ ULONG requestID 'hresult;)' ; /* [in] */ HRESULT status Global Const $tRIID_IMbnPinManagerEvents = _WinAPI_GUIDFromString($sIID_IMbnPinManagerEvents) Global Const $sIID_IConnectionPointContainer = '{B196B284-BAB4-101A-B69C-00AA00341D07}' Global Const $dtag_IConnectionPointContainer = _ 'EnumConnectionPoints hresult();' & _ 'FindConnectionPoint hresult(clsid;ptr*;);'; /* [in] */ __RPC__in REFIID riid | /* [out] */ __RPC__deref_out_opt IConnectionPoint **ppCP Global Const $sIID_IConnectionPoint = '{B196B286-BAB4-101A-B69C-00AA00341D07}' Global Const $dtag_IConnectionPoint = _ 'GetConnectionInterface hresult();' & _ 'GetConnectionPointContainer hresult();' & _ 'Advise hresult(ptr;dword*;);' & _ ; /* [in] */ __RPC__in_opt IUnknown *pUnkSink, /* [out] */ __RPC__out DWORD *pdwCookie 'Unadvise hresult(dword);' & _ 'EnumConnections hresult();' Global Const $CLSID_MbnInterfaceManager = '{BDFEE05B-4418-11DD-90ED-001C257CCFF1}' ;MbnInterfaceManager Global Const $sIID_IMbnInterfaceManager = '{DCBBBAB6-201B-4BBB-AAEE-338E368AF6FA}' Global Const $dtag_IMbnInterfaceManager = _ 'GetInterface hresult();' & _ 'GetInterfaces hresult(ptr*);' ; /* [retval][ref][out] */ __RPC__deref_out_opt SAFEARRAY * *mbnInterfaces #EndRegion Const ;~ https://msdn.microsoft.com/en-us/library/windows/desktop/dd430416(v=vs.85).aspx Local $oMbnInterfaceManager = ObjCreateInterface($CLSID_MbnInterfaceManager, $sIID_IMbnInterfaceManager, $dtag_IMbnInterfaceManager) If @error Then Exit -@ScriptLineNumber ;https://msdn.microsoft.com/en-us/library/windows/desktop/dd430421%28v=vs.85%29.aspx Local $p_mbnInterfaces $oMbnInterfaceManager.GetInterfaces($p_mbnInterfaces) If @error Or Not $p_mbnInterfaces Then Exit -@ScriptLineNumber Local $iBound SafeArrayGetUBound($p_mbnInterfaces, $iBound) If @error Or $iBound < 0 Then Exit -@ScriptLineNumber ;Get first Local $p_mbnInterface, $iIndex = 0 SafeArrayGetElement($p_mbnInterfaces, $iIndex, $p_mbnInterface) If @error Or Not $p_mbnInterface Then Exit -@ScriptLineNumber ;~ https://msdn.microsoft.com/en-us/library/windows/desktop/dd323117(v=vs.85).aspx Local $oIMbnPinManager = ObjCreateInterface($p_mbnInterface, $sIID_IMbnPinManager, $dtag_IMbnPinManager) If @error Then Exit -@ScriptLineNumber ;Prepare Events ;~ https://msdn.microsoft.com/en-us/library/windows/desktop/dd323118(v=vs.85).aspx ;~ 1) Get an IConnectionPointContainer interface by calling QueryInterface on an IMbnInterfaceManager object. ;~ 2) Call FindConnectionPoint on the returned interface and pass IID_IMbnPinManagerEvents to riid. ;~ 3) Call Advise on the returned connection point and pass a pointer to an IUnknown interface on an object that implements IMbnPinManagerEvents to pUnk. ;1 STEP Local $oIConnectionPointContainer = ObjCreateInterface($CLSID_MbnInterfaceManager, $sIID_IConnectionPointContainer, $dtag_IConnectionPointContainer) If @error Then Exit -@ScriptLineNumber ;2 STEP Local $p_IConnectionPoint $oIConnectionPointContainer.FindConnectionPoint($tRIID_IMbnPinManagerEvents, $p_IConnectionPoint) If @error Or Not $p_IConnectionPoint Then Exit -@ScriptLineNumber Local $oIConnectionPoint = ObjCreateInterface($p_IConnectionPoint, $sIID_IConnectionPoint, $dtag_IConnectionPoint) If @error Then Exit -@ScriptLineNumber ;3 STEP ;~ https://msdn.microsoft.com/en-us/library/windows/desktop/dd323119%28v=vs.85%29.aspx Local $tIMbnPinManagerEvents Local $oIMbnPinManagerEvents = ObjectFromTag("oIMbnPinManagerEvents_", $dtag_IMbnPinManagerEvents, $tIMbnPinManagerEvents) If @error Then Exit -@ScriptLineNumber Local $p_IUnknown = $oIMbnPinManagerEvents() ;~ https://msdn.microsoft.com/en-us/library/windows/desktop/ms678815(v=vs.85).aspx Local $pdwCookie $oIConnectionPoint.Advise($p_IUnknown, $pdwCookie) If @error Or Not $pdwCookie Then ConsoleWrite('! Connection was not successfully established' & @CRLF) Exit -@ScriptLineNumber EndIf ;~ 4 STEP ;~ https://msdn.microsoft.com/en-us/library/windows/desktop/dd323117%28v=vs.85%29.aspx ;Call GetPinState and wait events Local $iRequestID $oIMbnPinManager.GetPinState($iRequestID) If @error Or Not $iRequestID Then Exit -@ScriptLineNumber ConsoleWrite('> Wait events for request: ' & $iRequestID & @CRLF) AdlibRegister('_exit', 5000) While 1 Sleep(250) WEnd ;Console Output ;~ QueryInterface {0000013D-0000-0000-C000-000000000046} ;IClientSecurity ;~ QueryInterface {0000001B-0000-0000-C000-000000000046} ;? ;~ QueryInterface {00000003-0000-0000-C000-000000000046} ;IMarshal ;~ > Wait events for request: 152 ;~ QueryInterface {0000001B-0000-0000-C000-000000000046} ;? ;~ QueryInterface {00000018-0000-0000-C000-000000000046} ;IStdMarshalInfo ;~ QueryInterface {00000019-0000-0000-C000-000000000046} ;IExternalConnection ;~ QueryInterface {4C1E39E1-E3E3-4296-AA86-EC938D896E92} ;? ;~ QueryInterface {1C733A30-2A1C-11CE-ADE5-00AA0044773D} ;ICallFactory ;~ + OnGetPinStateComplete event ;Event fired ;~ > $pIMbnPinManager: 0x00BB9684 ;WHY THE SAME? ;~ > $pPinInfo: 0x00BB9684 ;WHY THE SAME? ;~ > $iRequestID: 0 ;0 ? ;~ > $iStatus: 3 ;3 ? ;~ > pinState: 12208352 ;bla ;~ > pinType: 1 ;bla ;~ > attemptsRemaining: 12194924 ;bla Exit Func _exit() AdlibUnRegister('_exit') $oIConnectionPoint.Unadvise($pdwCookie) Exit EndFunc ;==>_exit Func oIMbnPinManagerEvents_OnGetPinStateComplete($pSelf, $pIMbnPinManager, $pPinInfo, $iRequestID, $iStatus) ; Ret: long Par: ptr;struct;ulong;long ;~ https://msdn.microsoft.com/en-us/library/windows/desktop/dd323119%28v=vs.85%29.aspx ConsoleWrite('+ OnGetPinStateComplete event' & @CRLF) ConsoleWrite('> $pIMbnPinManager: ' & $pIMbnPinManager & @CRLF) ConsoleWrite('> $pPinInfo: ' & $pPinInfo & @CRLF) ConsoleWrite('> $iRequestID: ' & $iRequestID & @CRLF) ConsoleWrite('> $iStatus: ' & $iStatus & @CRLF) ;Ok. Now create a MBN_PIN_INFO struct ;~ https://msdn.microsoft.com/en-us/library/windows/desktop/dd323226(v=vs.85).aspx Local Static $tagMBN_PIN_INFO = 'struct;dword pinState;dword pinType;ulong attemptsRemaining;endstruct' Local $tMBN_PIN_INFO = DllStructCreate($tagMBN_PIN_INFO, $pPinInfo) If Not @error Then ConsoleWrite('> pinState: ' & DllStructGetData($tMBN_PIN_INFO, 'pinState') & @CRLF) ConsoleWrite('> pinType: ' & DllStructGetData($tMBN_PIN_INFO, 'pinType') & @CRLF) ConsoleWrite('> attemptsRemaining: ' & DllStructGetData($tMBN_PIN_INFO, 'attemptsRemaining') & @CRLF) EndIf Return $S_OK EndFunc ;==>oIMbnPinManagerEvents_OnGetPinStateComplete Func oIMbnPinManagerEvents_OnPinListAvailable($pSelf) ; Ret: long Return $S_OK EndFunc ;==>oIMbnPinManagerEvents_OnPinListAvailable Func oIMbnPinManagerEvents_QueryInterface($pSelf, $pRIID, $pObj) ; Ret: long Par: ptr;ptr Local $sIID = StringFromGUID($pRIID) If $sIID = $sIID_IUnknown Then DllStructSetData(DllStructCreate("ptr", $pObj), 1, $pSelf) Return $S_OK ElseIf $sIID = $sIID_IMbnPinManagerEvents Then DllStructSetData(DllStructCreate("ptr", $pObj), 1, $pSelf) Return $S_OK Else ConsoleWrite('QueryInterface ' & $sIID & @CRLF) Return $E_NOINTERFACE EndIf EndFunc ;==>oIMbnPinManagerEvents_QueryInterface Func oIMbnPinManagerEvents_AddRef($pSelf) ; Ret: dword Return 1 EndFunc ;==>oIMbnPinManagerEvents_AddRef Func oIMbnPinManagerEvents_Release($pSelf) ; Ret: dword Return 1 EndFunc ;==>oIMbnPinManagerEvents_Release Func StringFromGUID($pGUID) Local $aResult = DllCall("ole32.dll", "int", "StringFromGUID2", "struct*", $pGUID, "wstr", "", "int", 40) If @error Then Return SetError(@error, @extended, "") Return SetExtended($aResult[0], $aResult[2]) EndFunc ;==>StringFromGUID Func ObjectFromTag($sFunctionPrefix, $tagInterface, ByRef $tInterface, $fPrint = False, $bIsUnknown = Default, $sIID = "{00000000-0000-0000-C000-000000000046}") ; last param is IID_IUnknown by default If $bIsUnknown = Default Then $bIsUnknown = True Local $sInterface = $tagInterface ; copy interface description Local $tagIUnknown = "QueryInterface hresult(ptr;ptr*);" & _ "AddRef dword();" & _ "Release dword();" ; Adding IUnknown methods If $bIsUnknown Then $tagInterface = $tagIUnknown & $tagInterface ; Below line is really simple even though it looks super complex. It's just written weird to fit in one line, not to steal your attention Local $aMethods = StringSplit(StringReplace(StringReplace(StringReplace(StringReplace(StringTrimRight(StringReplace(StringRegExpReplace(StringRegExpReplace($tagInterface, "\w+\*", "ptr"), "\h*(\w+)\h*(\w+\*?)\h*(\((.*?)\))\h*(;|;*\z)", "$1\|$2;$4" & @LF), ";" & @LF, @LF), 1), "object", "idispatch"), "hresult", "long"), "bstr", "ptr"), "variant", "ptr"), @LF, 3) Local $iUbound = UBound($aMethods) Local $sMethod, $aSplit, $sNamePart, $aTagPart, $sTagPart, $sRet, $sParams, $hCallback ; Allocation $tInterface = DllStructCreate("int RefCount;int Size;ptr Object;ptr Methods[" & $iUbound & "];int_ptr Callbacks[" & $iUbound & "];ulong_ptr Slots[16]") ; 16 pointer sized elements more to create space for possible private props If @error Then Return SetError(1, 0, 0) For $i = 0 To $iUbound - 1 $aSplit = StringSplit($aMethods[$i], "|", 2) If UBound($aSplit) <> 2 Then ReDim $aSplit[2] $sNamePart = $aSplit[0] $sTagPart = $aSplit[1] $sMethod = $sFunctionPrefix & $sNamePart If $fPrint Then Local $iPar = StringInStr($sTagPart, ";", 2), $t If $iPar Then $t = "Ret: " & StringLeft($sTagPart, $iPar - 1) & " " & _ "Par: " & StringRight($sTagPart, StringLen($sTagPart) - $iPar) Else $t = "Ret: " & $sTagPart EndIf Local $s = "Func " & $sMethod & _ "( $pSelf ) ; " & $t & @CRLF & _ "EndFunc" & @CRLF ConsoleWrite($s) EndIf $aTagPart = StringSplit($sTagPart, ";", 2) $sRet = $aTagPart[0] $sParams = StringReplace($sTagPart, $sRet, "", 1) $sParams = "ptr" & $sParams $hCallback = DllCallbackRegister($sMethod, $sRet, $sParams) If @error Then ConsoleWrite('! ' & @error & ' ' & $sMethod & @CRLF & @CRLF) EndIf DllStructSetData($tInterface, "Methods", DllCallbackGetPtr($hCallback), $i + 1) ; save callback pointer DllStructSetData($tInterface, "Callbacks", $hCallback, $i + 1) ; save callback handle Next DllStructSetData($tInterface, "RefCount", 1) ; initial ref count is 1 DllStructSetData($tInterface, "Size", $iUbound) ; number of interface methods DllStructSetData($tInterface, "Object", DllStructGetPtr($tInterface, "Methods")) ; Interface method pointers Return ObjCreateInterface(DllStructGetPtr($tInterface, "Object"), $sIID, $sInterface, $bIsUnknown) ; pointer that's wrapped into object EndFunc ;==>ObjectFromTag
  20. I have managed to implement it to the point where onResponse() is creating the desired structure and returning the new response, it also displays the amended structure in onSuccess, but it's not populating the dropdown box with the results data (the results array). Am I missing something obvious? Should I do it manually? As the doc kind of gives the impression it's automatically done if success is true (which it is!) Doc
  21. I posted this the other day, but thought I would post in a separate topic instead. #include <MsgBoxConstants.au3> ; ---- Start of Person Class ; Stored in the 'object' to verify it's our 'object' and not some random array Global Const $PERSON_GUID = '4197B285-6AB1-489B-8585-08C852E33F3D' ; Friendly names for 0, 1, 2 and 3 Global Enum $PERSON_AGE, $PERSON_NAME, $PERSON_ID, $PERSON_MAX ; Constructor Func Person($sName, $iAge) Local $hPerson[$PERSON_MAX] ; Set the GUID, so as the verification will work $hPerson[$PERSON_ID] = $PERSON_GUID Person_SetAge($hPerson, $iAge) Person_SetName($hPerson, $sName) ; Return the Person 'object' Return $hPerson EndFunc ;==>Person ; Getter for the age property Func Person_GetAge(ByRef $hPerson) Return _Person_IsObject($hPerson) ? $hPerson[$PERSON_AGE] : Null EndFunc ;==>Person_GetAge ; Setter for the age property Func Person_SetAge(ByRef $hPerson, $iAge) ; If not a valid 'object' or integer then return If Not _Person_IsObject($hPerson) Or Not IsInt($iAge) Then Return ; Set the age $hPerson[$PERSON_AGE] = $iAge EndFunc ;==>Person_SetAge ; Getter for the name property Func Person_GetName(ByRef $hPerson) Return _Person_IsObject($hPerson) ? $hPerson[$PERSON_NAME] : Null EndFunc ;==>Person_GetName ; Setter for the name property Func Person_SetName(ByRef $hPerson, $sName) ; If not a valid 'object' then return If Not _Person_IsObject($hPerson) Then Return ; Set the name $hPerson[$PERSON_NAME] = $sName EndFunc ;==>Person_SetName ; ToString() for the 'object' Func Person_ToString(ByRef $hPerson) Return _Person_IsObject($hPerson) ? StringFormat('Name: %s, Age: %i', $hPerson[$PERSON_NAME], $hPerson[$PERSON_AGE]) : Null EndFunc ;==>Person_ToString ; Check if it's a valid 'object' and not some random array. "NTERNAL ONLY! Func _Person_IsObject(ByRef $hPerson) Return UBound($hPerson) = $PERSON_MAX And $hPerson[$PERSON_ID] == $PERSON_GUID EndFunc ;==>_Person_IsObject ; ---- End of Person Class Example() Func Example() ; Store the Person 'object', which is just a glorified array Local $hP1 = Person('John', 30) ; Display the 'object' MsgBox($MB_SYSTEMMODAL, 'Person 1', Person_ToString($hP1)) ; Create a new person ; Store the Person 'object', which is just a glorified array Local $hP2 = Person('James', 36) ; Display the 'object' MsgBox($MB_SYSTEMMODAL, 'Person 2', Person_ToString($hP2)) ; Set the age for Person 2 Person_SetAge($hP2, 45) ; Display the 'object' MsgBox($MB_SYSTEMMODAL, 'Person 2 - Revised', Person_ToString($hP2)) EndFunc ;==>Example
  22. Subsonic jukebox control

    Here is the result of my playing around with Subsonic's REST API tonight. This script searches for a song in the Subsonic library, queues it in the jukebox playlist, starts it playing on the server, then stops it and clears the playlist. This requires Subsonic. At present, they include the REST API that this script uses in the 30-day trial, but then it goes away unless you upgrade to Subsonic Premium. Change the variables at the beginning to represent your server URL and user account. (My server happened to be running on the same machine on port 85.) The account must exist in Subsonic and must have permission to play files in jukebox mode (which is not a default permission). Lastly, you probably want to change the parameters in the _SubsonicJukeboxAddSong function call to represent a song that is actually on the server. #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.12.0 Author: ToasterKing Script Function: #ce ---------------------------------------------------------------------------- #Region ; --- Include files #include <Array.au3> #include <FileConstants.au3> #include <StringConstants.au3> #include <_XMLDomWrapper.au3> #EndRegion ; --- Include files Global $sSubsonicAddr = "http://localhost:85" Local $sSubsonicJukeboxName = "BlabberBox" Local $sSubsonicUsername = "jukeboxuser" Local $sSubsonicPassword = "j00kthis!" Global $sSubsonicBaseParams = "u=" & $sSubsonicUsername & "&p=" & $sSubsonicPassword & "&c=" & $sSubsonicJukeboxName ; Add a song to the jukebox playlist _SubsonicJukeboxAddSong("catch a fire","haddaway") ; Start playing _SubsonicCmd($sSubsonicAddr & "/rest/jukeboxControl.view?" & $sSubsonicBaseParams & "&v=1.10.2&action=start") ; Wait Sleep(15000) For $x = 1 To 5 If _SubsonicJukeboxIsPlaying() Then MsgBox(0,"","Subsonic jukebox is still playing!",2) Else MsgBox(0,"","Subsonic jukebox is no longer playing.",2) Exit EndIf If $x = 3 Then _SubsonicCmd($sSubsonicAddr & "/rest/jukeboxControl.view?" & $sSubsonicBaseParams & "&v=1.10.2&action=clear") ; Clear playlist and stop playing Sleep(5000) Next ; #FUNCTION# ==================================================================================================================== ; Name ..........: _SubsonicCmd ; Description ...: Makes a general REST API request. ; Syntax ........: _SubsonicCmd($sRequest) ; Parameters ....: $sRequest - The complete request URL. ; Return values .: Success: 1 ; Failure: 0 and sets @error to 1 ; Author ........: Your Name ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func _SubsonicCmd($sRequest) Local $bSubsonicResult,$sSubsonicResult,$sSubsonicReqStatus ConsoleWrite("Sending REST API request: " & $sRequest & @CRLF) $bSubsonicResult = InetRead($sRequest,1) If @error Then ConsoleWrite("Error " & @error & " in InetRead." & @CRLF) Return SetError(1,0,"") EndIf $sSubsonicResult = BinaryToString($bSubsonicResult,4) ; Convert the XML response to a string so it can be parsed ;~ ConsoleWrite("REST API response from Subsonic:" & @CRLF & $sSubsonicResult & @CRLF) ; Remove the first "xmlns" attribute for the namespace because I can't figure out how to make the XML parse otherwise Local $iToRemovePosStart = StringInStr($sSubsonicResult," xmlns=""") Local $iToRemovePosEnd = StringInStr($sSubsonicResult,"""",0,1,$iToRemovePosStart + 8) Local $sSubsonicResultEdited = StringLeft($sSubsonicResult,$iToRemovePosStart - 1) & StringTrimLeft($sSubsonicResult,$iToRemovePosEnd) ConsoleWrite("REST API response from Subsonic after editing:" & @CRLF & StringStripWS($sSubsonicResultEdited,$STR_STRIPTRAILING) & @CRLF) ;~ _Setdebug(True) ; Turn on XML debugging _XMLLoadXML($sSubsonicResultEdited) ; Load the XML response for parsing If @error Then ConsoleWrite("Error " & @error & " in _XMLLoadXML" & @CRLF) Return SetError(1,0,"") EndIf ConsoleWrite("Using MSXML version " & _XMLGetDomVersion() & " for parsing." & @CRLF) $sSubsonicReqStatus = _XMLGetAttrib("//subsonic-response","status") ; Get the "status" attribute to see if the command worked. If $sSubsonicReqStatus = "ok" Then ConsoleWrite("The REST API returned success for this request!" & @CRLF) Else ConsoleWrite("Status 'ok' not found in response! See the debug entries for the full XML response." & @CRLF) Return SetError(1,0,"") EndIf Return SetError(0,0,1) ; Success! EndFunc ; #FUNCTION# ==================================================================================================================== ; Name ..........: _SubsonicJukeboxAddSong ; Description ...: Searches for a song on the Subsonic server and adds it/them to the jukebox playlist. ; Syntax ........: _SubsonicJukeboxAddSong($sSong[, $sArtist = ""[, $sAlbum = ""[, $iSongsToAddMax = 1]]]) ; Parameters ....: $sSong - Complete, exact name of the song to find (case insensitive) ; $sArtist - [optional] Complete name of the artist name to match (case insensitive) ; $sAlbum - [optional] Complete name of the album name to match (case insensitive) ; $iSongsToAddMax - [optional] Maximum number of songs to match and add to the playlist. Default is 1. ; 0 means no limit, although there is a hardcoded limit on number of search results ; returned in the function. ; Return values .: Success: 1 ; Failure: 0 and sets @error: ; 1 - General error (check the log) ; 2 - Zero search results ; Author ........: ToasterKing ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func _SubsonicJukeboxAddSong($sSong,$sArtist = "",$sAlbum = "",$iSongsToAddMax = 1) Local $bSubsonicResult,$sSubsonicResult,$sRequest,$sSubsonicReqStatus ConsoleWrite("Searching for requested song '" & $sSong & "', artist '" & $sArtist & "', album '" & $sAlbum & "'." & @CRLF) ; Assemble the request URL (note: hardcoded here to 50 search results) $sRequest = $sSubsonicAddr & "/rest/search3.view?" & $sSubsonicBaseParams & "&v=1.10.2&query=%22" & _URLEncode($sSong) & "%22&songCount=50&artistCount=0&albumCount=0" ConsoleWrite("Sending REST API request: " & $sRequest & @CRLF) ; Make the HTTP request $bSubsonicResult = InetRead($sRequest,1) If @error Then ConsoleWrite("Error " & @error & " in InetRead." & @CRLF) Return SetError(1,0,"") EndIf $sSubsonicResult = BinaryToString($bSubsonicResult,4) ; Convert the XML response to a string so it can be parsed ;~ ConsoleWrite("REST API response from Subsonic:" & @CRLF & $sSubsonicResult & @CRLF) ; Remove the first "xmlns" attribute for the namespace because I can't figure out how to make the XML parse otherwise Local $iToRemovePosStart = StringInStr($sSubsonicResult," xmlns=""") Local $iToRemovePosEnd = StringInStr($sSubsonicResult,"""",0,1,$iToRemovePosStart + 8) Local $sSubsonicResultEdited = StringLeft($sSubsonicResult,$iToRemovePosStart - 1) & StringTrimLeft($sSubsonicResult,$iToRemovePosEnd) ConsoleWrite("REST API response from Subsonic after editing:" & @CRLF & StringStripWS($sSubsonicResultEdited,$STR_STRIPTRAILING) & @CRLF) ;~ _Setdebug(True) ; Turn on XML debugging _XMLLoadXML($sSubsonicResultEdited) ; Load the XML response for parsing If @error Then ConsoleWrite("Error " & @error & " in _XMLLoadXML" & @CRLF) Return SetError(1,0,"") EndIf ConsoleWrite("Using MSXML version " & _XMLGetDomVersion() & " for parsing." & @CRLF) $sSubsonicReqStatus = _XMLGetAttrib("//subsonic-response","status") ; Get the "status" attribute to see if the command worked. If $sSubsonicReqStatus = "ok" Then ConsoleWrite("The REST API returned success for this request!" & @CRLF) Else ConsoleWrite("Status 'ok' not found in response! See the debug entries for the full XML response." & @CRLF) Return SetError(1,0,"") EndIf ; Get ready to loop through all the search results. Dim $aAttrName[1], $aAttrValue[1], $aStats[0][5], $iCurrentId, $iSongMatched = 0 for $x = 1 to 5000 _XMLGetAllAttrib ("//subsonic-response/searchResult3/*["&$x&"]",$aAttrName,$aAttrValue ); by index, show all attribs. xml indexes are 0 based. if @error Then ExitLoop ; No more results found. ;~ _ArrayDisplay($aAttrName,"Attrib Names") ;~ _ArrayDisplay($aAttrValue,"Attrib Value") $iCurrentId = _XMLGetAttrib("//subsonic-response/searchResult3/*["&$x&"]","id") ; Get the ID attribute of the current search result. ; Compare song of the attributes of the search result to the ones specified. If _XMLGetAttrib("//subsonic-response/searchResult3/*["&$x&"]","type") = "music" And _ _XMLGetAttrib("//subsonic-response/searchResult3/*["&$x&"]","title") = $sSong And _ ($sArtist = "" Or _XMLGetAttrib("//subsonic-response/searchResult3/*["&$x&"]","artist") = $sArtist) And _ ($sAlbum = "" Or _XMLGetAttrib("//subsonic-response/searchResult3/*["&$x&"]","album") = $sAlbum) And _ _XMLGetAttrib("//subsonic-response/searchResult3/*["&$x&"]","type") = "music" Then ConsoleWrite("Song " & $iCurrentId & " matches the criteria." & @CRLF) $iSongMatched += 1 ; Increment the counter If _SubsonicCmd($sSubsonicAddr & "/rest/jukeboxControl.view?" & $sSubsonicBaseParams & "&v=1.10.2&action=add&id=" & $iCurrentId) Then ConsoleWrite("Song " & $iCurrentId & " added to the jukebox playlist." & @CRLF) Else ConsoleWrite("Song " & $iCurrentId & " could not be added to the jukebox playlist." & @CRLF) EndIf If $iSongsToAddMax > 0 And $iSongMatched >= $iSongsToAddMax Then ExitLoop ; If the number of matching songs to add has been satisfied, stop adding. Else ConsoleWrite("Song " & $iCurrentId & " doesn't match the criteria; continuing." & @CRLF) EndIf next If $iSongMatched Then Return SetError(0,0,1) Else ConsoleWrite("No songs were found matching the criteria." & @CRLF) Return SetError(2,0,0) EndIf EndFunc ; #FUNCTION# ==================================================================================================================== ; Name ..........: _SubsonicJukeboxIsPlaying ; Description ...: Check whether Subsonic jukebox is playing music. ; Syntax ........: _SubsonicJukeboxIsPlaying() ; Parameters ....: ; Return values .: Success: 1 - Playing ; 0 - Paused/stopped ; Failure: 0 and sets @error to 1. ; Author ........: ToasterKing ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........: ; Example .......: No ; =============================================================================================================================== Func _SubsonicJukeboxIsPlaying() Local $bSubsonicResult,$sSubsonicResult,$sRequest,$sSubsonicReqStatus ConsoleWrite("Querying whether Subsonic jukebox is playing." & @CRLF) ; Assemble the request URL (note: hardcoded here to 50 search results) $sRequest = $sSubsonicAddr & "/rest/jukeboxControl.view?" & $sSubsonicBaseParams & "&v=1.10.2&action=status" ConsoleWrite("Sending REST API request: " & $sRequest & @CRLF) ; Make the HTTP request $bSubsonicResult = InetRead($sRequest,1) If @error Then ConsoleWrite("Error " & @error & " in InetRead." & @CRLF) Return SetError(1,0,"") EndIf $sSubsonicResult = BinaryToString($bSubsonicResult,4) ; Convert the XML response to a string so it can be parsed ;~ ConsoleWrite("REST API response from Subsonic:" & @CRLF & $sSubsonicResult & @CRLF) ; Remove the first "xmlns" attribute for the namespace because I can't figure out how to make the XML parse otherwise Local $iToRemovePosStart = StringInStr($sSubsonicResult," xmlns=""") Local $iToRemovePosEnd = StringInStr($sSubsonicResult,"""",0,1,$iToRemovePosStart + 8) Local $sSubsonicResultEdited = StringLeft($sSubsonicResult,$iToRemovePosStart - 1) & StringTrimLeft($sSubsonicResult,$iToRemovePosEnd) ConsoleWrite("REST API response from Subsonic after editing:" & @CRLF & StringStripWS($sSubsonicResultEdited,$STR_STRIPTRAILING) & @CRLF) ;~ _Setdebug(True) ; Turn on XML debugging _XMLLoadXML($sSubsonicResultEdited) ; Load the XML response for parsing If @error Then ConsoleWrite("Error " & @error & " in _XMLLoadXML" & @CRLF) Return SetError(1,0,"") EndIf ConsoleWrite("Using MSXML version " & _XMLGetDomVersion() & " for parsing." & @CRLF) $sSubsonicReqStatus = _XMLGetAttrib("//subsonic-response","status") ; Get the "status" attribute to see if the command worked. If $sSubsonicReqStatus = "ok" Then ConsoleWrite("The REST API returned success for this request!" & @CRLF) Else ConsoleWrite("Status 'ok' not found in response! See the debug entries for the full XML response." & @CRLF) Return SetError(1,0,"") EndIf If _XMLGetAttrib("//subsonic-response/jukeboxStatus","playing") = "true" Then ConsoleWrite("Subsonic Jukebox is playing." & @CRLF) Return SetError(0,0,1) Else ConsoleWrite("Subsonic Jukebox is not playing." & @CRLF) Return SetError(0,0,0) EndIf EndFunc ;=============================================================================== ; _URLEncode() ; Description: : Encodes a string to be URL-friendly ; Parameter(s): : $toEncode - The String to Encode ; : $encodeType = 0 - Practical Encoding (Encode only what is necessary) ; : = 1 - Encode everything ; : = 2 - RFC 1738 Encoding - http://www.ietf.org/rfc/rfc1738.txt ; Return Value(s): : The URL encoded string ; Author(s): : nfwu ; Note(s): : - ; ;=============================================================================== Func _URLEncode($toEncode, $encodeType = 0) Local $strHex = "", $iDec Local $aryChar = StringSplit($toEncode, "") If $encodeType = 1 Then;;Encode EVERYTHING For $i = 1 To $aryChar[0] $strHex = $strHex & "%" & Hex(Asc($aryChar[$i]), 2) Next Return $strHex ElseIf $encodeType = 0 Then;;Practical Encoding For $i = 1 To $aryChar[0] $iDec = Asc($aryChar[$i]) if $iDec <= 32 Or $iDec = 37 Then $strHex = $strHex & "%" & Hex($iDec, 2) Else $strHex = $strHex & $aryChar[$i] EndIf Next Return $strHex ElseIf $encodeType = 2 Then;;RFC 1738 Encoding For $i = 1 To $aryChar[0] If Not StringInStr("$-_.+!*'(),;/?:@=&abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", $aryChar[$i]) Then $strHex = $strHex & "%" & Hex(Asc($aryChar[$i]), 2) Else $strHex = $strHex & $aryChar[$i] EndIf Next Return $strHex EndIf EndFunc This script uses _XMLDomWrapper.au3 by Stephen Podhajecki. Since it's been a bit hard to track down a working link to this in the past, I've just included the version I used here. #include-once ; #INDEX# ====================================================================== ; Title .........: _XMLDomWrapper ; AutoIt Version : 3.2.3++ ; Language ......: English ; Description ...: Functions to use for reading and writing XML using msxml. ; Author ........: Stephen Podhajecki Eltorro ; ============================================================================== ; XML DOM Wrapper functions #cs defs to add to au3.api _XMLCreateFile Creates an XML file with the given name and root. _XMLFileOpen Creates an instance of an XML file. _XMLSaveDoc Save the xml doc, use $iForce = 1 to force save if AutoSave is off. ; ========================================================================== _XMLGetChildNodes Selects XML child Node(s) of an element based on XPath input from root node. _XMLGetNodeCount Get node count for specified path and type. _XMLGetPath Returns a nodes full path based on XPath input from root node. ; ========================================================================== _XMLSelectNodes Selects XML Node(s) based on XPath input from root node. _XMLGetField Get XML Field(s) based on XPath input from root node. _XMLGetValue Get XML Field based on XPath input from root node. _XMLGetChildText Selects XML child Node(s) of an element based on XPath input from root node. _XMLUpdateField Update existing node(s) based on XPath specs. _XMLReplaceChild Replaces a node with a new node. ; ========================================================================== _XMLDeleteNode Delete specified XPath node. _XMLDeleteAttr Delete attribute for specified XPath _XMLDeleteAttrNode Delete attribute node for specified XPath ; ========================================================================== _XMLGetAttrib Get XML attribute based on XPath input from root node. _XMLGetAllAttrib Get all XML Field(s) attributes based on XPath input from root node. _XMLGetAllAttribIndex Get all XML Field(s) attributes based on Xpathn and specific index. _XMLSetAttrib Set XML Field(s) attributes based on XPath input from root node. ; ========================================================================== _XMLCreateCDATA Create a CDATA SECTION node directly under root. _XMLCreateComment Create a COMMENT node at specified path. _XMLCreateAttrib Creates an attribute for the specified node. ; ========================================================================== _XMLCreateRootChild Create node directly under root. _XMLCreateRootNodeWAttr Create a child node under root node with attributes. _XMLCreateChildNode Create a child node under the specified XPath Node. _XMLCreateChildWAttr Create a child node under the specified XPath Node with Attributes. ; ========================================================================== _XMLSchemaValidate Validate a document against a DTD. _XMLGetDomVersion Returns the XSXML version currently in use. _XMLError Sets or Gets XML error message generated by XML functions. _XMLUDFVersion Returns the UDF Version number. _XMLTransform Transfroms the document using built-in sheet or xsl file passed to function. _XMLNodeExists Checks for the existence of the specified path. ; ========================================================================== _XMLSetAutoFormat Turn auto indenting on or off. _XMLSetAutoSave Set the automatic save to on or off. #ce ; #VARIABLES# ================================================================== Global Const $_XMLUDFVER = "1.0.3.97" Global Const $NODE_ELEMENT = 1 Global Const $NODE_ATTRIBUTE = 2 Global Const $NODE_TEXT = 3 Global Const $NODE_CDATA_SECTION = 4 Global Const $NODE_ENTITY_REFERENCE = 5 Global Const $NODE_ENTITY = 6 Global Const $NODE_PROCESSING_INSTRUCTION = 7 Global Const $NODE_COMMENT = 8 Global Const $NODE_DOCUMENT = 9 Global Const $NODE_DOCUMENT_TYPE = 10 Global Const $NODE_DOCUMENT_FRAGMENT = 11 Global Const $NODE_NOTATION = 12 Global $strFile Global $oXMLMyError ;COM error handler OBJ ; Initialize SvenP 's error handler Global $sXML_error Global $fDEBUGGING Global $DOMVERSION = -1 Global $objDoc Global $fXMLAUTOSAVE = True ;auto save updates Global $fADDFORMATTING = True ;auto indent ; ============================================================================== ; #FUNCTION# =================================================================== ; Name ..........: _XMLFileOpen ; Description ...: Creates an instance of an XML file. ; Syntax.........: _XMLFileOpen($strXMLFile[, $strNameSpc = ""[, $iVer = -1[, $fValOnParse = True]]]) ; Parameters ....: $strXMLFile - the XML file to open ; $strNameSpc - the namespace to specifiy if the file uses one. ; $iVer - specifically try to use the version supplied here. ; $fValOnParse - validate the document as it is being parsed ; Return values .: Success - 1 ; Failure - -1 and set @error to: ; |0 - No error ; |1 - Parse error, @Extended = MSXML reason ; |2 - No object ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLFileOpen($strXMLFile, $strNameSpc = "", $iVer = -1, $fValOnParse = True) ;==== pick your poison If $iVer <> -1 Then If $iVer > -1 And $iVer < 7 Then $objDoc = ObjCreate("Msxml2.DOMDocument." & $iVer & ".0") If IsObj($objDoc) Then $DOMVERSION = $iVer EndIf Else MsgBox(266288, "Error:", "Failed to create object with MSXML version " & $iVer) SetError(1) Return 0 EndIf Else For $x = 8 To 0 Step -1 If FileExists(@SystemDir & "\msxml" & $x & ".dll") Then $objDoc = ObjCreate("Msxml2.DOMDocument." & $x & ".0") If IsObj($objDoc) Then $DOMVERSION = $x ExitLoop EndIf EndIf Next EndIf If Not IsObj($objDoc) Then _XMLError("Error: MSXML not found. This object is required to use this program.") SetError(2) Return -1 EndIf ;Thanks Lukasz Suleja $oXMLMyError = ObjEvent("AutoIt.Error") If $oXMLMyError = "" Then $oXMLMyError = ObjEvent("AutoIt.Error", "_XMLCOMEerr") ; ; Initialize SvenP 's error handler EndIf $strFile = $strXMLFile $objDoc.async = False $objDoc.preserveWhiteSpace = True $objDoc.validateOnParse = $fValOnParse If $DOMVERSION > 4 Then $objDoc.setProperty("ProhibitDTD", False) $objDoc.Load($strFile) $objDoc.setProperty("SelectionLanguage", "XPath") $objDoc.setProperty("SelectionNamespaces", $strNameSpc) If $objDoc.parseError.errorCode > 0 Then ConsoleWrite($objDoc.parseError.reason & @LF) If $objDoc.parseError.errorCode <> 0 Then _XMLError("Error opening specified file: " & $strXMLFile & @CRLF & $objDoc.parseError.reason) ;Tom Hohmann 2008/02/29 SetError(1, $objDoc.parseError.errorCode, -1) $objDoc = 0 Return -1 EndIf ;Tom Hohmann 2008/02/29 Return 1 EndFunc ;==>_XMLFileOpen ; ; #FUNCTION# =================================================================== ; Name ..........: _XMLLoadXML ; Description ...: Creates an instance for a string of XML . ; Syntax.........: _XMLLoadXML($strXML[,$strNameSpc=""[, $iVer = -1[, $fValOnParse = True]]]) ; Parameters ....: $strXML - The XML to load into the document ; $strNameSpc - the namespace to specifiy if the file uses one. ; $iVer - specifically try to use the version supplied here. ; $fValOnParse - Set the MSXML ValidateOnParse property ; Return values .: Success - 1 ; Failure - -1 and set @error to ; |1 - failed to create object, @Extended = MSXML reason ; |2 - no object found (MSXML required for _XML functions ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com>,Lukasz Suleja,Tom Hohmann ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLLoadXML($strXML, $strNameSpc = "", $iVer = -1, $fValOnParse = True) If $iVer <> -1 Then If $iVer > -1 And $iVer < 7 Then $objDoc = ObjCreate("Msxml2.DOMDocument." & $iVer & ".0") If IsObj($objDoc) Then $DOMVERSION = $iVer EndIf Else MsgBox(266288, "Error:", "Failed to create object with MSXML version " & $iVer) SetError(1) Return 0 EndIf Else For $x = 8 To 0 Step -1 If FileExists(@SystemDir & "\msxml" & $x & ".dll") Then $objDoc = ObjCreate("Msxml2.DOMDocument." & $x & ".0") If IsObj($objDoc) Then $DOMVERSION = $x ExitLoop EndIf EndIf Next EndIf If Not IsObj($objDoc) Then _XMLError("Error: MSXML not found. This object is required to use this program.") SetError(2) Return -1 EndIf ;Thanks Lukasz Suleja $oXMLMyError = ObjEvent("AutoIt.Error") If $oXMLMyError = "" Then $oXMLMyError = ObjEvent("AutoIt.Error", "_XMLCOMEerr") ; ; Initialize SvenP 's error handler EndIf $objDoc.async = False $objDoc.preserveWhiteSpace = True $objDoc.validateOnParse = $fValOnParse If $DOMVERSION > 4 Then $objDoc.setProperty("ProhibitDTD", False) $objDoc.LoadXml($strXML) $objDoc.setProperty("SelectionLanguage", "XPath") $objDoc.setProperty("SelectionNamespaces", $strNameSpc); "xmlns:ms='urn:schemas-microsoft-com:xslt'" If $objDoc.parseError.errorCode <> 0 Then _XMLError("Error loading the XML data: " & @CRLF & $objDoc.parseError.reason) ;Tom Hohmann 2008/02/29 SetError(1, $objDoc.parseError.errorCode, -1) Return -1 EndIf ;Tom Hohmann 2008/02/29 Return 1 EndFunc ;==>_XMLLoadXML ; #FUNCTION# =================================================================== ; Name ..........: _XMLCreateFile ; Description ...: Create a new blank metafile with header. ; Syntax.........: _XMLCreateFile($strPath, $strRoot[, $fOverwrite = False[, $fUTF8 = False[, $ver = -1]]]) ; Parameters ....: $strPath - The xml filename with full path to create ; $strRoot - The root of the xml file to create ; $fOverwrite - boolean flag to auto overwrite existing file of same name. ; $fUTF8 - boolean flag to specify UTF-8 encoding in header. ; $iVer - specifically try to use the version supplied here. ; Return values .: Success - 1 ; Failure - -1 and sets @Error to: ; |0 - No error ; |1 - Failed to create file ; |2 - No object ; |3 - File creation failed MSXML error ; |4 - File exists ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLCreateFile($strPath, $strRoot, $fOverwrite = False, $fUTF8 = False, $ver = -1) Local $retval, $fe, $objPI, $rootElement $fe = FileExists($strPath) If $fe And Not $fOverwrite Then $retval = (MsgBox(4097, "File Exists:", "The specified file exits." & @CRLF & "Click OK to overwrite file or cancel to exit.")) If $retval = 1 Then FileCopy($strPath, $strPath & @YEAR & "-" & @MON & "-" & @MDAY & "_" & @HOUR & "-" & @MIN & "-" & @SEC & ".bak", 1) FileDelete($strPath) $fe = False Else _XMLError("Error failed to create file: " & $strPath & @CRLF & "File exists.") SetError(4) Return -1 EndIf Else FileCopy($strPath, $strPath & ".old", 1) FileDelete($strPath) $fe = False EndIf If $fe = False Then If $ver <> -1 Then If $ver > -1 And $ver < 7 Then $objDoc = ObjCreate("Msxml2.DOMDocument." & $ver & ".0") If IsObj($objDoc) Then $DOMVERSION = $ver EndIf Else MsgBox(266288, "Error:", "Failed to create object with MSXML version " & $ver) SetError(3) Return 0 EndIf Else For $x = 8 To 0 Step -1 If FileExists(@SystemDir & "\msxml" & $x & ".dll") Then $objDoc = ObjCreate("Msxml2.DOMDocument." & $x & ".0") If IsObj($objDoc) Then $DOMVERSION = $x ExitLoop EndIf EndIf Next EndIf If Not IsObj($objDoc) Then Return SetError(2) EndIf If $fUTF8 Then $objPI = $objDoc.createProcessingInstruction("xml", "version=""1.0"" encoding=""UTF-8""") Else $objPI = $objDoc.createProcessingInstruction("xml", "version=""1.0""") EndIf $objDoc.appendChild($objPI) $rootElement = $objDoc.createElement($strRoot) $objDoc.documentElement = $rootElement $objDoc.save($strPath) ;_XMLSaveDoc (,1) If $objDoc.parseError.errorCode <> 0 Then _XMLError("Error Creating specified file: " & $strPath) ; Tom Hohmann 2008/02/29 SetError(1, $objDoc.parseError.errorCode, -1) Return -1 EndIf Return 1 Else _XMLError("Error! Failed to create file: " & $strPath) SetError(1) Return 0 EndIf Return 1 EndFunc ;==>_XMLCreateFile ; #FUNCTION# =================================================================== ; Name ..........: _XMLSelectNodes ; Description ...: Selects XML Node(s) based on XPath input from root node. ; Syntax.........: _XMLSelectNodes($strXPath) ; Parameters ....: $strXPath - xml tree path from root node (root/child/child..) ; Return values .: Success - An array of Nodes(count is in first element) ; Failure - -1 and set @Error = 1 ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLSelectNodes($strXPath) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLSelectNodes") Return SetError(2, 0, -1) EndIf Local $objNode, $objNodeList, $arrResponse[1], $xmlerr $objNodeList = $objDoc.selectNodes($strXPath) If Not IsObj($objNodeList) Then _XMLError("\nNo matching nodes found") Return SetError(1, 0, -1) EndIf If $objNodeList.length < 1 Then _XMLError("\nNo matching nodes found") Return SetError(1, 0, -1) EndIf For $objNode In $objNodeList _XMLArrayAdd($arrResponse, $objNode.nodeName) _DebugWrite($objNode.nodeName) _DebugWrite($objNode.namespaceURI) Next $arrResponse[0] = $objNodeList.length Return $arrResponse _XMLError("Error Selecting Node(s): " & $strXPath & $xmlerr) Return SetError(1, 0, -1) EndFunc ;==>_XMLSelectNodes ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetField ; Description ...: Get XML Field(s) based on XPath input from root node. ; Syntax.........: _XMLGetField($strXPath) ; Parameters ....: $strXPath - The XML tree path from root node (root/child/child..) ; Return values .: Success - An array of fields text values(count is in first element) ; Failure - -1 and sets @Error = 1 ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetField($strXPath) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetField") Return SetError(1, 2, -1) EndIf Local $objNodeList, $arrResponse[1], $xmlerr, $szNodePath $objNodeList = $objDoc.selectSingleNode($strXPath) If Not IsObj($objNodeList) Then _XMLError("\nNo Matching Nodes found") $arrResponse[0] = 0 Return SetError(2, 0, -1) EndIf If $objNodeList.hasChildNodes() Then Local $count = $objNodeList.childNodes.length For $x = 1 To $count $objChild = $objNodeList.childNodes($x) _DebugWrite("ParentNode=" & $objNodeList.parentNode.nodeType) If $objNodeList.parentNode.nodeType = $NODE_DOCUMENT Then $szNodePath = "/" & $objNodeList.baseName & "/*[" & $x & "]" Else $szNodePath = $objNodeList.baseName & "/*[" & $x & "]" EndIf $aRet = _XMLGetValue($szNodePath) If IsArray($aRet) Then If UBound($aRet) > 1 Then _XMLArrayAdd($arrResponse, $aRet[1]) _DebugWrite("GetField>Text:" & $aRet[1]) EndIf Else _XMLArrayAdd($arrResponse, "") _DebugWrite("GetField>Text:" & "") EndIf Next $arrResponse[0] = UBound($arrResponse) - 1 Return $arrResponse Else $arrResponse[0] = 0 _XMLError("\nNo Child Nodes found") Return SetError(1, 0, -1) EndIf _XMLError("Error Selecting Node(s): " & $strXPath & $xmlerr) Return SetError(1, 0, -1) EndFunc ;==>_XMLGetField ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetValue ; Description ...: Get XML values based on XPath input from root node. ; Syntax.........: _XMLGetValue($strXPath) ; Parameters ....: $strXPath - xml tree path from root node (root/child/child..) ; Return values .: Success - An array of fields text values(count is in first element) ; Failure - -1 and sets @Error = 1, @Extended to: ; |0 - No matching node. ; |1 - No object passed. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetValue($strXPath) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetValue") Return SetError(1, 1, -1) EndIf Local $objNodeList, $arrResponse[1], $objNodeChild, $xmlerr _DebugWrite("GetValue>$strXPath:" & $strXPath) $objNodeList = $objDoc.documentElement.selectNodes($strXPath) If $objNodeList.length > 0 Then _DebugWrite("GetValue list length:" & $objNodeList.length) For $objNode In $objNodeList If $objNode.hasChildNodes() = False Then _XMLArrayAdd($arrResponse, $objNode.nodeValue) Else For $objNodeChild In $objNode.childNodes() If $objNodeChild.nodeType = $NODE_CDATA_SECTION Then _XMLArrayAdd($arrResponse, $objNodeChild.data) _DebugWrite("GetValue>CData:" & $objNodeChild.data) ElseIf $objNodeChild.nodeType = $NODE_TEXT Then _XMLArrayAdd($arrResponse, $objNodeChild.Text) _DebugWrite("GetValue>Text:" & $objNodeChild.Text) EndIf Next EndIf Next $arrResponse[0] = UBound($arrResponse) - 1 Return $arrResponse Else $xmlerr = @CRLF & "No matching node(s)found!" Return SetError(1, 0, -1) EndIf _XMLError("Error Retrieving: " & $strXPath & $xmlerr) Return SetError(1, 0, -1) EndFunc ;==>_XMLGetValue ; #FUNCTION# =================================================================== ; Name ..........: _XMLDeleteNode ; Description ...: Deletes XML Node based on XPath input from root node. ; Syntax.........: _XMLDeleteNode($strXPath) ; Parameters ....: $strXPath - The XML tree path from root node (root/child/child..) ; Return values .: Success - 1 ; Failure - -1 and sets @Error to: ; |0 - No error ; |1 - Deletion error ; |2 - No object passed ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLDeleteNode($strXPath) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLDeleteNode") Return SetError(2, 0, -1) EndIf Local $objNode, $xmlerr $objNode = $objDoc.selectNodes($strXPath) If Not IsObj($objNode) Then $xmlerr = @CRLF & "Node Not found" If @error = 0 Then For $objChild In $objNode If $objChild.hasChildNodes Then For $objGrandChild in $objChild.childNodes If $objGrandChild.nodeType = $NODE_TEXT Then If StringStripWS($objGrandChild.text,7) = "" Then $objChild.removeChild($objGrandChild) EndIf EndIf Next EndIf $objChild.parentNode.removeChild($objChild) Next _XMLSaveDoc($strFile) Return 1 EndIf _XMLError("Error Deleting Node: " & $strXPath & $xmlerr) Return SetError(1, 0, -1) EndFunc ;==>_XMLDeleteNode ; #FUNCTION# =================================================================== ; Name ..........: _XMLDeleteAttr ; Description ...: Delete XML Attribute based on XPath input from root node. ; Syntax.........: _XMLDeleteAttr($strXPath, $strAttrib) ; Parameters ....: $strXPath - The XML tree path from root node (root/child/child..) ; $strAttribute - The attribute node to delete ; Return values .: Success - 1 ; Failure - -1 and sets @Error to: ; |0 - No error ; |1 - Error removing attribute ; |2 - No object ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLDeleteAttr($strXPath, $strAttrib) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLDeleteAttr") Return SetError(2, 0, -1) EndIf Local $objNode, $objAttr, $xmlerr $objNode = $objDoc.selectSingleNode($strXPath) If IsObj($objNode) Then $objAttr = $objNode.getAttributeNode($strAttrib) If Not (IsObj($objAttr)) Then _XMLError("Attribute " & $strAttrib & " does not exist!") Return SetError(2, 0, -1) EndIf $objAttr = $objNode.removeAttribute($strAttrib) _XMLSaveDoc($strFile) Return 1 EndIf _XMLError("Error Removing Attribute: " & $strXPath & " - " & $strAttrib & @CRLF & $xmlerr) $xmlerr = "" Return SetError(1, 0, -1) EndFunc ;==>_XMLDeleteAttr ; #FUNCTION# =================================================================== ; Name ..........: _XMLDeleteAttrNode ; Description ...: Delete XML Attribute node based on XPath input from root node. ; Syntax.........: _XMLDeleteAttrNode($strXPath, $strAttrib) ; Parameters ....: $strXpath - XML tree path from root node (root/child/child..) ; $strAttrib - The attribute node to delete ; Return values .: Success - 1 ; Failure - -1 and sets @Error to: ; |0 - No error ; |1 - Error removing node ; |2 - No object ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLDeleteAttrNode($strXPath, $strAttrib) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLDeleteAttrNode") Return SetError(2, 0, -1) EndIf Local $objNode, $objAttr, $xmlerr $objNode = $objDoc.selectSingleNode($strXPath) If Not IsObj($objNode) Then _XMLError("\nSpecified node not found!") Return SetError(2, 0, -1) EndIf $objAttr = $objNode.removeAttributeNode($objNode.getAttributeNode($strAttrib)) _XMLSaveDoc($strFile) If Not (IsObj($objAttr)) Then _XMLError("\nUnspecified error:!") Return SetError(1, 0, -1) EndIf Return 1 EndFunc ;==>_XMLDeleteAttrNode ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetAttrib ; Description ...: Get XML Field based on XPath input from root node. ; Syntax.........: _XMLGetAttrib($strXPath, $strAttrib[, $strQuery = ""]) ; Parameters ....: $strXPath - XML tree path from root node (root/child/child..) ; $strAttrib - The attribute node to read. ; $strQuery - The query string in xml format ; Return values .: Success - The attribute value. ; Failure - -1 and sets @Error to: ; |0 - No error ; |1 - Attribute not found. ; |2 - No object ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetAttrib($strXPath, $strAttrib, $strQuery = "") If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetAttrib") Return SetError(2, 0, -1) EndIf ;Local $objNodeList, $arrResponse[1], $i, $xmlerr, $objAttr Local $objNodeList, $arrResponse, $i, $xmlerr, $objAttr $objNodeList = $objDoc.documentElement.selectNodes($strXPath & $strQuery) _DebugWrite("Get Attrib length= " & $objNodeList.length) If $objNodeList.length > 0 Then For $i = 0 To $objNodeList.length - 1 $objAttr = $objNodeList.item($i).getAttribute($strAttrib) $arrResponse = $objAttr _DebugWrite("RET>>" & $objAttr) Next Return $arrResponse EndIf $xmlerr = "\nNo qualified items found" _XMLError("Attribute " & $strAttrib & " not found for: " & $strXPath & $xmlerr) Return SetError(1, 0, -1) EndFunc ;==>_XMLGetAttrib ; #FUNCTION# =================================================================== ; Name ..........: _XMLSetAttrib ; Description ...: Set XML Field(s) based on XPath input from root node. ; Syntax.........: _XMLSetAttrib($strXPath, $strAttrib[, $strValue = ""[, $iIndex =-1]]) ; Parameters ....: $strXPath - Xml tree path from root node (root/child/child..) ; $strAttrib - The attribute to set. ; $strValue - The value to give the attribute defaults to "" ; $iIndex - Used to specify a specific index for "same named" nodes. ; Return values .: Success - Anarray of fields text values ; Failure - -1 and sets @error to 1 ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLSetAttrib($strXPath, $strAttrib, $strValue = "", $iIndex = -1) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLSetAttrib") Return SetError(1, 8, -1) EndIf Local $objNodeList, $arrResponse[1], $i $objNodeList = $objDoc.selectNodes($strXPath) _DebugWrite(" Node list Length: " & $objNodeList.length) If @error = 0 And $objNodeList.length > 0 Then If $iIndex > 0 Then $arrResponse[0] = $objNodeList.item($iIndex).SetAttribute($strAttrib, $strValue) Else ReDim $arrResponse[$objNodeList.length] For $i = 0 To $objNodeList.length - 1 $arrResponse[$i] = $objNodeList.item($i).SetAttribute($strAttrib, $strValue) If $objDoc.parseError.errorCode <> 0 Then ExitLoop Next EndIf If $objDoc.parseError.errorCode <> 0 Then _XMLError("Error setting attribute for: " & $strXPath & @CRLF & $objDoc.parseError.reason) Return SetError(1, $objDoc.parseError.errorCode, -1) EndIf _XMLSaveDoc($strFile) Return $arrResponse EndIf _XMLError("Error failed to set attribute for: " & $strXPath & @CRLF) SetError(1) Return -1 EndFunc ;==>_XMLSetAttrib ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetAllAttrib ; Description ...: Get all XML Field(s) attributes based on XPath input from root node. ; Syntax.........: _XMLGetAllAttrib($strXPath, ByRef $aName, ByRef $aValue[, $strQry = ""]) ; Parameters ....: $strXPath - XML tree path from root node (root/child/child..) ; $aName - The array to return the attrib names ; $aValue - The array to return the attrib values ; $strQuery - DOM compliant query string (not really necessary as it becomes part of the path) ; Return values .: Success - array of fields text values(number of items is in [0][0]) ; Failure - @error set to 1 and returns -1 ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetAllAttrib($strXPath, ByRef $aName, ByRef $aValue, $strQry = "") If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetAllAttrib") Return SetError(1, 9, -1) EndIf Local $objNodeList, $objQueryNodes, $objNode, $arrResponse[2][1], $i $objQueryNodes = $objDoc.selectNodes($strXPath & $strQry) If $objQueryNodes.length > 0 Then For $objNode In $objQueryNodes $objNodeList = $objNode.attributes If ($objNodeList.length) Then _DebugWrite("Get all attrib " & $objNodeList.length) ReDim $arrResponse[2][$objNodeList.length + 2] ReDim $aName[$objNodeList.length] ReDim $aValue[$objNodeList.length] For $i = 0 To $objNodeList.length - 1 $arrResponse[0][$i + 1] = $objNodeList.item($i).nodeName $arrResponse[1][$i + 1] = $objNodeList.item($i).Value $aName[$i] = $objNodeList.item($i).nodeName $aValue[$i] = $objNodeList.item($i).Value Next Else _XMLError("No Attributes found for node") Return SetError(1, 0, -1) EndIf Next $arrResponse[0][0] = $objNodeList.length Return $arrResponse EndIf _XMLError("Error retrieving attributes for: " & $strXPath & @CRLF) Return SetError(1, 0, -1) ; EndIf EndFunc ;==>_XMLGetAllAttrib ; #FUNCTION# =================================================================== ; Name ..........: _XMLUpdateField ; Description ...: Update existing node(s) based on XPath specs. ; Syntax.........: _XMLUpdateField($strXPath, $strData) ; Parameters ....: $strXPath - Path from root node. ; $strData - The data to update the node with. ; Return values .: Success - 1 ; Failure - -1 and sets @error to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLUpdateField($strXPath, $strData) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLUpdateField") Return SetError(1, 9, -1) EndIf Local $objField, $fUpdate, $objNode #forceref $objField $objField = $objDoc.selectSingleNode($strXPath) If IsObj($objField) Then If $objField.hasChildNodes Then For $objChild In $objField.childNodes() If $objChild.nodetype = $NODE_TEXT Then $objChild.Text = $strData $fUpdate = True ExitLoop EndIf Next EndIf If $fUpdate = False Then $objNode = $objDoc.createTextNode($strData) $objField.appendChild($objNode) EndIf _XMLSaveDoc($strFile) $objField = "" Return 1 EndIf _XMLError("Failed to update field for: " & $strXPath & @CRLF) Return SetError(1, 0, -1) EndFunc ;==>_XMLUpdateField ; #FUNCTION# =================================================================== ; Name ..........: _XMLCreateCDATA ; Description ...: Create a CDATA SECTION node directly under root. ; Syntax.........: _XMLCreateCDATA($strNode, $strCDATA[, $strNameSpc = ""]) ; Parameters ....: $strNode - name of node to create ; $strData - CDATA value ; $strNameSpc - the namespace to specifiy if the xml uses one. ; Return values .: Success - 1 ; Failure - 1 and sets @Error to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: fixme, won't append to exisiting node. must create new node. ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLCreateCDATA($strNode, $strCDATA, $strNameSpc = "") If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLCreateCDATA") Return SetError(1, 10, -1) EndIf Local $objChild, $objNode $objNode = $objDoc.createNode($NODE_ELEMENT, $strNode, $strNameSpc) If IsObj($objNode) Then If Not ($objNode.hasChildNodes()) Then _AddFormat($objDoc, $objNode) EndIf $objChild = $objDoc.createCDATASection($strCDATA) $objNode.appendChild($objChild) $objDoc.documentElement.appendChild($objNode) _XMLSaveDoc($strFile) _AddFormat($objDoc) $objChild = "" Return 1 EndIf _XMLError("Failed to create CDATA Section: " & $strNode & @CRLF) Return SetError(1, 0, -1) EndFunc ;==>_XMLCreateCDATA ; #FUNCTION# =================================================================== ; Name ..........: _XMLCreateComment ; Description ...: Create a COMMENT node at specified path. ; Syntax.........: _XMLCreateComment($strNode, $strComment) ; Parameters ....: $strNode - The name of node to create. ; $strComment - The comment to add the to the xml file. ; Return values .: Success - 1 ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLCreateComment($strNode, $strComment) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLCreateComment") Return SetError(1, 11, -1) EndIf Local $objChild, $objNode $objNode = $objDoc.selectSingleNode($strNode) If IsObj($objNode) Then If Not ($objNode.hasChildNodes()) Then _AddFormat($objDoc, $objNode) EndIf $objChild = $objDoc.createComment($strComment) $objNode.insertBefore($objChild, $objNode.childNodes(0)) _XMLSaveDoc($strFile) _AddFormat($objDoc) $objChild = "" Return 1 EndIf _XMLError("Failed to root child: " & $strNode & @CRLF) Return SetError(1, 0, -1) EndFunc ;==>_XMLCreateComment ; #FUNCTION# =================================================================== ; Name ..........: _XMLCreateAttribute ; Description ...: Adds an XML Attribute to specified node. ; Syntax.........: _XMLCreateAttrib($strXPath, $strAttrName[, $strAttrValue = ""]) ; Parameters ....: $strXPath - The XML tree path from root node (root/child/child..) ; $strAttrName - The attribute to set. ; $strAttrValue - The value to give the attribute, defaults to "". ; Return values .: Success - 1 ; Failure - 0 or @error set to 0 and return -1 ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLCreateAttrib($strXPath, $strAttrName, $strAttrValue = "") If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLCreateAttrib") Return SetError(1, 12, -1) EndIf Local $objNode, $objAttr, $objAttrVal, $err $objNode = $objDoc.selectSingleNode($strXPath) If IsObj($objNode) Then $objAttr = $objDoc.createAttribute($strAttrName);, $strNameSpc) $objNode.SetAttribute($strAttrName, $strAttrValue) _XMLSaveDoc($strFile) $objAttr = 0 $objAttrVal = 0 $objNode = 0 $err = $objDoc.parseError.errorCode If $err = 0 Then Return 1 EndIf _XMLError("Error creating Attribute: " & $strAttrName & @CRLF & $strXPath & " does not exist." & @CRLF) Return 0 EndFunc ;==>_XMLCreateAttrib ; #FUNCTION# =================================================================== ; Name ..........: _XMLCreateRootChild ; Description ...: Create node directly under root. ; Syntax.........: _XMLCreateRootChild($strNode[, $strData = ""[, $strNameSpc = ""]]) ; Parameters ....: $strNode - The name of node to create. ; $strData - The optional value to create ; $$strNameSpc - the namespace to specifiy if the file uses one. ; Return values .: Success - 1 ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLCreateRootChild($strNode, $strData = "", $strNameSpc = "") If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLCreateRootChild") Return SetError(1, 14, -1) EndIf ;ConsoleWrite("_XMLCreateRootChild:"&$strNode&@LF) Local $objChild If Not ($objDoc.documentElement.hasChildNodes()) Then _AddFormat($objDoc) EndIf $objChild = $objDoc.createNode($NODE_ELEMENT, $strNode, $strNameSpc) If IsObj($objChild) Then If $strData <> "" Then $objChild.text = $strData $objDoc.documentElement.appendChild($objChild) _XMLSaveDoc($strFile) _AddFormat($objDoc) $objChild = 0 Return 1 EndIf _XMLError("Failed to root child: " & $strNode & @CRLF) Return SetError(1, 0, -1) EndFunc ;==>_XMLCreateRootChild ; #FUNCTION# =================================================================== ; Name ..........: _XMLCreateRootNodeWAttr ; Description ...: Create a child node under root node with attributes. ; Syntax.........: _XMLCreateRootNodeWAttr($strNode, $aAttr, $aVal[, $strData = ""[, $strNameSpc = ""]]) ; Parameters ....: $strNode - The node to add with attibute(s) ; $aAttr - The attribute name(s) -- can be array ; $aVal - The attribute value(s) -- can be array ; $strData - The optional value to give the node. ; Return values .: Success - 1 ; Failure - -1 and @error set to: ; |1 - Could not create node. ; |2 - Mismatch between attribute name and value counts. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: This function requires that each attribute name has a corresponding value. ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLCreateRootNodeWAttr($strNode, $aAttr, $aVal, $strData = "", $strNameSpc = "") If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLCreateRootNodeWAttr") Return SetError(1, 15, -1) EndIf Local $objChild, $objAttr, $objAttrVal $objChild = $objDoc.createNode($NODE_ELEMENT, $strNode, $strNameSpc) If IsObj($objChild) Then If $strData <> "" Then $objChild.text = $strData If Not ($objDoc.documentElement.hasChildNodes()) Then _AddFormat($objDoc) EndIf If IsArray($aAttr) And IsArray($aVal) Then If UBound($aAttr) <> UBound($aVal) Then _XMLError("Attribute and value mismatch" & @CRLF & "Please make sure each attribute has a matching value.") Return SetError(2, 15, -1) Else Local $i For $i = 0 To UBound($aAttr) - 1 If $aAttr[$i] = "" Then _XMLError("Error creating child node: " & $strNode & @CRLF & " Attribute Name Cannot be NULL." & @CRLF) Return SetError(1, 0, -1) EndIf $objAttr = $objDoc.createAttribute($aAttr[$i]);, $strNameSpc) $objChild.SetAttribute($aAttr[$i], $aVal[$i]) Next EndIf Else $objAttr = $objDoc.createAttribute($aAttr) $objChild.SetAttribute($aAttr, $aVal) EndIf $objDoc.documentElement.appendChild($objChild) _XMLSaveDoc($strFile) _AddFormat($objDoc) $objChild = 0 Return 1 EndIf _XMLError("Failed to create root child with attributes: " & $strNode & @CRLF) Return SetError(1, 0, -1) EndFunc ;==>_XMLCreateRootNodeWAttr ; #FUNCTION# =================================================================== ; Name ..........: _XMLCreateChildNode ; Description ...: Create a child node under the specified XPath Node. ; Syntax.........: _XMLCreateChildNode($strXPath, $strNode[, $strData = ""[, $strNameSpc = ""]]) ; Parameters ....: $strXPath - The node from root. ; $strNode - Node name to add. ; $strData - Value to give the node ; Return values .: Success - 1 ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLCreateChildNode($strXPath, $strNode, $strData = "", $strNameSpc = "") If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLCreateChildNode") Return SetError(1, 16, -1) EndIf Local $objParent, $objChild, $objNodeList $objNodeList = $objDoc.selectNodes($strXPath) If IsObj($objNodeList) And $objNodeList.length > 0 Then For $objParent In $objNodeList If Not ($objParent.hasChildNodes()) Then _AddFormat($objDoc, $objParent) EndIf If $strNameSpc = "" Then If Not ($objParent.namespaceURI = 0 Or $objParent.namespaceURI = "") Then $strNameSpc = $objParent.namespaceURI EndIf ;ConsoleWrite("$strNameSpc=" & $strNameSpc & @LF) $objChild = $objDoc.createNode($NODE_ELEMENT, $strNode, $strNameSpc) If $strData <> "" Then $objChild.text = $strData $objParent.appendChild($objChild) _AddFormat($objDoc, $objParent) Next _XMLSaveDoc($strFile) $objParent = "" $objChild = "" Return 1 EndIf _XMLError("Error creating child node: " & $strNode & @CRLF & $strXPath & " does not exist." & @CRLF) Return SetError(1, 0, -1) EndFunc ;==>_XMLCreateChildNode ; #FUNCTION# =================================================================== ; Name ..........: _XMLCreateChildWAttr ; Description ...: Create a child node(s) under the specified XPath Node with attributes. ; Syntax.........: _XMLCreateChildWAttr($strXPath, $strNode, $aAttr, $aVal[, $strData = ""[, $strNameSpc = ""]]) ; Parameters ....: $sPath - Path from root ; $sNode - The node to add with attibute(s) ; $aAttr - The attribute name(s) -- can be array ; $aVal - The attribute value(s) -- can be array ; $strData - The optional value to give the child node. ; Return values .: Success - 1 ; Failure - -1, @error set to: ; |1 - Could not create node. ; |2 - Mismatch between attribute name and value counts. ; |3 - Attribute Name cannot be empty string. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: This function requires that each attribute name has a corresponding value. ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLCreateChildWAttr($strXPath, $strNode, $aAttr, $aVal, $strData = "", $strNameSpc = "") If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLCreateChildWAttr") Return SetError(1, 18, -1) EndIf Local $objParent, $objChild, $objAttr, $objAttrVal, $objNodeList $objNodeList = $objDoc.selectNodes($strXPath) _DebugWrite("Node Selected") If IsObj($objNodeList) And $objNodeList.length <> 0 Then _DebugWrite("Entering if") For $objParent In $objNodeList If Not ($objParent.hasChildNodes()) Then _AddFormat($objDoc, $objParent) EndIf _DebugWrite("Entering for") If $strNameSpc = "" Then If Not ($objParent.namespaceURI = 0 Or $objParent.namespaceURI = "") Then $strNameSpc = $objParent.namespaceURI EndIf $objChild = $objDoc.createNode($NODE_ELEMENT, $strNode, $strNameSpc) If @error Then Return -1 If $strData <> "" Then $objChild.text = $strData If IsArray($aAttr) And IsArray($aVal) Then If UBound($aAttr) <> UBound($aVal) Then _XMLError("Attribute and value mismatch" & @CRLF & "Please make sure each attribute has a matching value.") Return SetError(2, 0, -1) Else Local $i For $i = 0 To UBound($aAttr) - 1 _DebugWrite("Entering inside for") If $aAttr[$i] = "" Then _XMLError("Error creating child node: " & $strNode & @CRLF & " Attribute Name Cannot be NULL." & @CRLF) Return SetError(1, 0, -1) EndIf _DebugWrite($aAttr[$i] & " " & $strNameSpc) $objAttr = $objDoc.createAttribute($aAttr[$i]);, $strNameSpc) If @error Then ExitLoop $objChild.SetAttribute($aAttr[$i], $aVal[$i]) If @error <> 0 Then _XMLError("Error creating child node: " & $strNode & @CRLF & $strXPath & " does not exist." & @CRLF) Return SetError(1, 0, -1) EndIf _DebugWrite("Looping inside for") Next EndIf Else If IsArray($aAttr) Or IsArray($aVal) Then _XMLError("Type non-Array and Array detected" & @LF) Return SetError(1, 0, -1) EndIf If $aAttr = "" Then _XMLError("Attribute Name cannot be empty string." & @LF) Return SetError(3, 0, -1) EndIf _DebugWrite($aAttr & " " & $strNameSpc) $objAttr = $objDoc.createAttribute($aAttr);, $strNameSpc) $objChild.SetAttribute($aAttr, $aVal) EndIf $objParent.appendChild($objChild) _DebugWrite("Looping for") Next _AddFormat($objDoc, $objParent) _XMLSaveDoc($strFile) _DebugWrite("Saved") $objParent = "" $objChild = "" _DebugWrite("Returning") Return 1 EndIf _XMLError("Error creating child node: " & $strNode & @CRLF & $strXPath & " does not exist." & @CRLF) Return SetError(1, 0, -1) EndFunc ;==>_XMLCreateChildWAttr ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetChildText ; Description ...: Selects XML child Node(s) of an element based on XPath input from root node. ; Syntax.........: _XMLGetChildText($strXPath) ; Parameters ....: $strXPath - The xml tree path from root node (root/child/child..) ; Return values .: Success - An array of Nodes. ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetChildText($strXPath) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetChildText") Return SetError(1, 19, -1) EndIf Local $objNodeList, $arrResponse[1], $xmlerr $objNodeList = $objDoc.selectSingleNode($strXPath) If Not IsObj($objNodeList) Then _XMLError(@CRLF & "No Matching Nodes found") $arrResponse[0] = 0 Return SetError(1, 0, -1) EndIf If $objNodeList.hasChildNodes() Then For $objChild In $objNodeList.childNodes() If $objChild.nodeType = $NODE_ELEMENT Then _XMLArrayAdd($arrResponse, $objChild.baseName) ElseIf $objChild.nodeType = $NODE_TEXT Then _XMLArrayAdd($arrResponse, $objChild.text) EndIf Next $arrResponse[0] = UBound($arrResponse) - 1 Return $arrResponse EndIf $arrResponse[0] = 0 $xmlerr = @CRLF & "No Child Text Nodes found" _XMLError("Error Selecting Node(s): " & $strXPath & $xmlerr) Return SetError(1, 0, -1) EndFunc ;==>_XMLGetChildText ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetChildNodes ; Description ...: Selects XML child Node(s) of an element based on XPath input from root node. ; Syntax.........: _XMLGetChildNodes($strXPath) ; Parameters ....: $strXPath - The xml tree path from root node (root/child/child..) ; Return values .: Success - An array of Nodes, count in [0] element. ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetChildNodes($strXPath) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetChildNodes") Return SetError(1, 20, -1) EndIf Local $objNodeList, $arrResponse[1], $xmlerr $objNodeList = $objDoc.selectSingleNode($strXPath) If Not IsObj($objNodeList) Then _XMLError(@LF & "No Matching Nodes found") $arrResponse[0] = 0 Return SetError(1, 0, -1) EndIf If $objNodeList.hasChildNodes() Then For $objChild In $objNodeList.childNodes() If $objChild.nodeType() = $NODE_ELEMENT Then _DebugWrite($objChild.NamespaceURI & "::" & $objChild.baseName & @LF) _XMLArrayAdd($arrResponse, $objChild.baseName) EndIf Next $arrResponse[0] = UBound($arrResponse) - 1 Return $arrResponse EndIf $arrResponse[0] = 0 $xmlerr = @LF & "No Child Nodes found" _XMLError("Error Selecting Node(s): " & $strXPath & $xmlerr) Return SetError(1, 0, -1) EndFunc ;==>_XMLGetChildNodes ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetChildren ; Description ...: Selects XML child Node(s) of an element based on XPath input from root node and returns there text values. ; Syntax.........: _XMLGetChildren($strXPath) ; Parameters ....: $strXPath - The XML tree path from root node (root/child/child..) ; Return values .: Success - An array where: ; |$array[0][0] = Size of array ; |$array[1][0] = Name ; |$array[1][1] = Text ; |$array[1][2] = NameSpaceURI ; |... ; |$array[n][0] = Name ; |$array[n][1] = Text ; |$array[n][2] = NamespaceURI ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetChildren($strXPath) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetChildren") Return SetError(1, 21, -1) EndIf Local $objNodeList, $arrResponse[1][3], $xmlerr $objNodeList = $objDoc.selectSingleNode($strXPath) If Not IsObj($objNodeList) Then _XMLError(@LF & "No Matching Nodes found") $arrResponse[0][0] = 0 Return SetError(1, 0, -1) EndIf If $objNodeList.hasChildNodes() Then For $objChild In $objNodeList.childNodes() If $objChild.nodeType() = $NODE_ElEMENT Then If $objChild.hasChildNodes() Then For $objChildNode in $objChild.childNodes() If $objChildNode.nodeType() = $NODE_TEXT Then Local $dims = UBound($arrResponse, 1) ReDim $arrResponse[$dims + 1][3] $arrResponse[$dims][0] = $objChildNode.parentNode.baseName $arrResponse[$dims][1] = $objChildNode.text $arrResponse[$dims][2] = $objChildNode.NamespaceURI ;_XMLArrayAdd($arrResponse, $objChild.baseName) EndIf Next EndIf EndIf Next $arrResponse[0][0] = UBound($arrResponse, 1) - 1 Return $arrResponse EndIf $arrResponse[0][0] = 0 $xmlerr = @LF & "No Child Nodes found" _XMLError("Error Selecting Node(s): " & $strXPath & $xmlerr) Return SetError(1, 0, -1) EndFunc ;==>_XMLGetChildren ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetNodeCount ; Description ...: Get Node Count based on XPath input from root node. ; Syntax.........: _XMLGetNodeCount($strXPath[, $strQry = ""[, $iNodeType = 1]]) ; Parameters ....: $strXPath - The XML tree path from root node (root/child/child.. ; $strQry - A DOM compliant query string (not really necessary as it becomes part of the path ; $iNodeType - The type of node to count. (element, attrib, comment etc.) ; Return values .: Success - Number of nodes found (can be 0) ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> & DickB ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetNodeCount($strXPath, $strQry = "", $iNodeType = 1) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetNodeCount") Return SetError(1, 22, -1) EndIf Local $objQueryNodes, $objNode, $nodeCount = 0, $errMsg $objQueryNodes = $objDoc.selectNodes($strXPath & $strQry) If @error = 0 And $objQueryNodes.length > 0 Then For $objNode In $objQueryNodes If $objNode.nodeType = $iNodeType Then $nodeCount = $nodeCount + 1 Next Return $nodeCount Else $errMsg = "No nodes of specified type found." EndIf _XMLError("Error retrieving node count for: " & $strXPath & @CRLF & $errMsg & @CRLF) SetError(1) Return -1 ; EndIf EndFunc ;==>_XMLGetNodeCount ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetAllAttribIndex ; Description ...: Get all XML Field(s) attributes based on Xpath and specific index. ; Syntax.........: _XMLGetAllAttribIndex($strXPath, ByRef $aName, ByRef $aValue[, $strQry = ""[, $iNodeIndex = 0]]) ; Parameters ....: $strXpath - The xml tree path from root node (root/child/child..) ; $aNames - The array to return the attrib names in. ; $aValue - The array to return the attrib values in. ; $strQry - DOM compliant query string (not really necessary as it becomes ; $iNodeIndex - The index of node to retrieve. ; Return values .: Success - The number of elements. ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetAllAttribIndex($strXPath, ByRef $aName, ByRef $aValue, $strQry = "", $iNodeIndex = 0) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetAllAttribIndex") Return SetError(1, 23, -1) EndIf Local $objNodeList, $objQueryNodes, $i ;, $arrResponse[2][1] $objQueryNodes = $objDoc.selectNodes($strXPath & $strQry) If $objQueryNodes.length > 0 Then $objNodeList = $objQueryNodes.item($iNodeIndex).attributes _DebugWrite("GetAllAttribIndex " & $objNodeList.length) ;ReDim $arrResponse[2][$objNodeList.length + 1] ReDim $aName[$objNodeList.length] ReDim $aValue[$objNodeList.length] For $i = 0 To $objNodeList.length - 1 ;$arrResponse[0][$i] = $objNodeList.item ($i).nodeName ;$arrResponse[1][$i] = $objNodeList.item ($i).Value $aName[$i] = $objNodeList.item($i).nodeName $aValue[$i] = $objNodeList.item($i).Value Next ;Return $arrResponse Return $objNodeList.length EndIf _XMLError("Error retrieving attributes for: " & $strXPath & @CRLF) Return SetError(1, 0, -1) EndFunc ;==>_XMLGetAllAttribIndex ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetPath ; Description ...: Return a nodes full path based on XPath input from root node. ; Syntax.........: _XMLGetPath($strXPath) ; Parameters ....: $strXPath - The XML tree path from root node (root/child/child..) ; Return values .: Success - An array of node names from root, count in [0] element. ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetPath($strXPath) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetPath") Return SetError(1, 24, -1) EndIf If $DOMVERSION < 4 Then _XMLError("Error DOM Version: " & "MSXML Version 4 or greater required for this function") Return SetError(1, 0, -1) EndIf Local $objNodeList, $arrResponse[1], $objNodeChild, $xmlerr, $nodepath, $ns $objNodeList = $objDoc.selectNodes($strXPath) If $objNodeList.length > 0 Then _DebugWrite("GetPath list length:" & $objNodeList.length) For $objNode In $objNodeList Local $objNode1 = $objNode $nodepath = "" $nodepathtag = "" If $objNode.nodeType <> $NODE_DOCUMENT Then $ns = $objNode.namespaceURI() If $ns <> "" Then $ns = StringRight($ns, StringLen($ns) - StringInStr($ns, "/", 0, -1)) & ":" EndIf If $ns = 0 Then $ns = "" $nodepath = "/" & $ns & $objNode.nodeName() & $nodepath EndIf Do $objParent = $objNode1.parentNode() _DebugWrite("parent " & $objParent.nodeName() & @LF) If $objParent.nodeType <> $NODE_DOCUMENT Then $ns = $objParent.namespaceURI() If $ns <> "" Then ;$ns = StringRight($ns, StringLen($ns) - StringInStr($ns, "/", 0, -1)) & ":" $ns &= ":" EndIf If $ns = 0 Then $ns = "" $nodepath = "/" & $ns & $objParent.nodeName() & $nodepath $objNode1 = $objParent Else $objNode1 = 0 EndIf $objParent = 0 Until (Not (IsObj($objNode1))) _DebugWrite("Path node> " & $nodepath & @LF) _XMLArrayAdd($arrResponse, $nodepath) Next $arrResponse[0] = UBound($arrResponse) - 1 Return $arrResponse EndIf $xmlerr = @CRLF & "No matching node(s)found!" _XMLError("Error Retrieving: " & $strXPath & $xmlerr) Return SetError(1, 0, -1) EndFunc ;==>_XMLGetPath ; #FUNCTION# =================================================================== ; Function Name : _XMLGetPathInternal ; Description ...: Returns the path of a valid node object. ; Syntax ........: _XMLGetPathInternal($objNode) ; Parameters ....: $objNode - A valid node object ; Return values .: Success - Path from root as string. ; Failure - An empty string and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats at netmdc.com/> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetPathInternal($objNode) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLGetPathInternal") Return SetError(1, 25, "") EndIf Local $nodepath, $na, $objParent If IsObj($objNode) Then $nodepath = "/" & $objNode.baseName Do $objParent = $objNode.parentNode() _DebugWrite("parent" & $objParent.nodeName() & ">" & @LF) If $objParent.nodeType <> $NODE_DOCUMENT Then $ns = $objParent.namespaceURI() If $ns = 0 Then $ns = "" If $ns <> "" Then $ns = StringRight($ns, StringLen($ns) - StringInStr($ns, "/", 0, -1)) & ":" EndIf $nodepath = "/" & $ns & $objParent.nodeName() & $nodepath $objNode = $objParent Else $objNode = 0 EndIf $objParent = 0 Until (Not (IsObj($objNode))) _DebugWrite("Path node>" & $nodepath & @LF) Return ($nodepath) Else Return SetError(1, 0, "") EndIf EndFunc ;==>_XMLGetPathInternal ; #FUNCTION# =================================================================== ; Name ..........: _XMLReplaceChild ; Description ...: Replaces a node with another ; Syntax.........: _XMLReplaceChild($objOldNode, $objNewNode[, $ns = ""]) ; Parameters ....: $objOldNode - The node to replace ; $objNewNode - The replacement node. ; Return values .: Success - 1. ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> adapted from ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLReplaceChild($objOldNode, $objNewNode, $ns = "") If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLReplaceChild") Return SetError(1, 26, -1) EndIf If $objOldNode = "" Or $objNewNode = "" Then Return SetError(1) Local $nodeRoot Local $nodeOld Local $nodeNew Local $nodeTemp Local $fSuccess = False ;No error handling done With $objDoc ;;.Load "c:\books.xml" $nodeRoot = .documentElement $oldNodes = $nodeRoot.selectNodes($objOldNode) ;'For each Node For $nodeOld In $oldNodes ;Create a New element $nodeNew = .createNode($NODE_ELEMENT, $objNewNode, $ns) ;Copy attributes For $nodeTemp In $nodeOld.Attributes $nodeNew.Attributes.setNamedItem($nodeTemp.cloneNode(True)) Next ;Copy Child Nodes For $nodeTemp In $nodeOld.childNodes $nodeNew.appendChild($nodeTemp) Next ;Replace with the renamed node If IsObj($nodeOld.parentNode.replaceChild($nodeNew, $nodeOld)) Then $fSuccess = 1 If Not ($objDoc.parseError.errorCode = 0) Then _XMLError("_XMLReplaceChild:" & @LF & "Error Replacing Child: " & _ $objDoc.parseError.errorCode & _ " " & $objDoc.parseError.reason) $fSuccess = False ExitLoop Else $fSuccess = True EndIf Next .save($strFile) EndWith $nodeRoot = 0 $nodeOld = 0 $nodeNew = 0 $nodeTemp = 0 If ($fSuccess = False) Then Return SetError(1, 0, -1) Return 1 EndFunc ;==>_XMLReplaceChild ; #FUNCTION# =================================================================== ; Name ..........: _XMLSchemaValidate ; Description ...: Validates a document against a dtd. ; Syntax.........: _XMLSchemaValidate($sXMLFile, $strNameSpc, $sXSDFile) ; Parameters ....: $sXMLFile - The file to validate ; $strNameSpc - xml namespace ; $sXSDFile - DTD file to validate against. ; Return values .: Success - 1 ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLSchemaValidate($sXMLFile, $strNameSpc, $sXSDFile) Local $cache, $xmldoc $cache = ObjCreate("Msxml2.XMLSchemaCache." & $DOMVERSION & ".0") If Not IsObj($cache) Then MsgBox(266288, "XML Error", "Unable to instantiate the XML object" & @LF & "Please check your components.") Return SetError(1, 0, -1) EndIf $cache.add($strNameSpc, $sXSDFile) $xmldoc = ObjCreate("Msxml2.DOMDocument." & $DOMVERSION & ".0") If Not IsObj($xmldoc) Then MsgBox(266288, "XML Error", "Unable to instantiate the XML object" & @LF & "Please check your components.") Return SetError(1, 0, -1) EndIf $xmldoc.async = False $xmldoc.schemas = $cache $xmldoc.load($sXMLFile) If Not ($xmldoc.parseError.errorCode = 0) Then _XMLError("_XMLSchemaValidate:" & @LF & "Error: " & $xmldoc.parseError.errorCode & " " & $xmldoc.parseError.reason) Return SetError($xmldoc.parseError.errorCode) EndIf Return 1 EndFunc ;==>_XMLSchemaValidate ; #FUNCTION# =================================================================== ; Name ..........: _XMLGetDomVersion ; Description ...: Returns the version of msxml that is in use for the document. ; Syntax.........: _XMLGetDomVersion() ; Parameters ....: none ; Return values .: Success - msxml version ; Failure - 0 ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLGetDomVersion() Return $DOMVERSION EndFunc ;==>_XMLGetDomVersion ; #FUNCTION# =================================================================== ; Name ..........: _XMLError ; Description ...: Sets or Gets error message that may be generated by the UDF functs. ; Syntax.........: _XMLError($sError = "") ; Parameters ....: $sError - Error message to set. ; Return values .: Success - one of the following: ; |$sError <> "" - Nothing. ; |$sError = "" - Last error set. ; Failure - Nothing. ; Author ........: Stephen Podhajecki <gehossafats@netmdc.com> ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLError($sError = "") If $sError = "" Then $sError = $sXML_error $sXML_error = "" Return $sError Else $sXML_error = StringFormat($sError) EndIf _DebugWrite($sXML_error) EndFunc ;==>_XMLError ; #FUNCTION# =================================================================== ; Name ..........: _XMLCOMEerr ; Description ...: Displays a message box with the COM Error. ; Syntax.........: _XMLCOMEerr() ; Parameters ....: None ; Return values .: ; Author ........: SvenP 's error handler ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLCOMEerr() _ComErrorHandler() Return EndFunc ;==>_XMLCOMEerr ; #FUNCTION# =================================================================== ; Name ..........: _ComErrorHandler ; Description ...: A COM error handling routine. ; Syntax.........: _ComErrorHandler($quiet = "") ; Parameters ....: $quiet - Work silently ; Return values .: None ; Author ........: ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _ComErrorHandler($quiet = "") Local $COMErr_Silent, $HexNumber ; ============================================================================== ;added silent switch to allow the func returned to the option to display custom ;error messages If $quiet = True Or $quiet = False Then $COMErr_Silent = $quiet $quiet = "" EndIf ; ============================================================================== $HexNumber = Hex($oXMLMyError.number, 8) If @error Then Return Local $msg = "COM Error with DOM!" & @CRLF & @CRLF & _ "err.description is: " & @TAB & $oXMLMyError.description & @CRLF & _ "err.windescription:" & @TAB & $oXMLMyError.windescription & @CRLF & _ "err.number is: " & @TAB & $HexNumber & @CRLF & _ "err.lastdllerror is: " & @TAB & $oXMLMyError.lastdllerror & @CRLF & _ "err.scriptline is: " & @TAB & $oXMLMyError.scriptline & @CRLF & _ "err.source is: " & @TAB & $oXMLMyError.source & @CRLF & _ "err.helpfile is: " & @TAB & $oXMLMyError.helpfile & @CRLF & _ "err.helpcontext is: " & @TAB & $oXMLMyError.helpcontext If $COMErr_Silent <> True Then MsgBox(0, @AutoItExe, $msg) Else _XMLError($msg) EndIf SetError(1) EndFunc ;==>_ComErrorHandler ; #FUNCTION# =================================================================== ; Name ..........: _DebugWrite ; Description ...: Writes a message to console with a crlf on the end ; Syntax.........: _DebugWrite($strMsg[, $sLineEnding = @LF]) ; Parameters ....: $strMsg - The message to display ; $sLineEnding - Line ending to add ; Return values .: On Succes - None. ; Failure - None. ; Author ........: ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _DebugWrite($strMsg, $sLineEnding = @LF) If $fDEBUGGING Then ConsoleWrite(StringFormat($strMsg) & $sLineEnding) EndIf EndFunc ;==>_DebugWrite ; #FUNCTION# =================================================================== ; Name ..........: _SetDebug ; Description ...: Turn debugging info on or off ; Syntax.........: _SetDebug($fDbug = True) ; Parameters ....: $fDbug - Boolean value for debugging. ; Return values .: Success - The debugging state. ; Author ........: ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _SetDebug($fDbug = True) $fDEBUGGING = $fDbug _DebugWrite("Debug = " & $fDEBUGGING) Return $fDEBUGGING EndFunc ;==>_SetDebug ; #FUNCTION# =================================================================== ; Name ..........: _XMLUDFVersion ; Description ...: Returns UDF version number ; Syntax.........: _XMLUDFVersion() ; Parameters ....: None ; Return values .: Success - The UDF version number ; Author ........: Stephen Podhajecki ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLUDFVersion() Return $_XMLUDFVER EndFunc ;==>_XMLUDFVersion ; #FUNCTION# =================================================================== ; Name ..........: _XMLTransform ; Description ...: ; Syntax.........: _XMLTransform([$oXMLDoc = ""[, $Style = ""[, $szNewDoc = ""]]]) ; Parameters ....: $oXMLDoc - The document to transform ; $Style - The stylesheet to use ; $szNewDoc - Save to this file. ; Return values .: Success - Returns True ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats at netmdc dot com>, Modified by WeaponX ; Modified ......: ; Remarks .......: Default stylesheet is used for indenting. ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLTransform($oXMLDoc = "", $Style = "", $szNewDoc = "") If $oXMLDoc = "" Then $oXMLDoc = $objDoc EndIf If Not IsObj($oXMLDoc) Then _XMLError("No object passed to function _XMLTransform") Return SetError(1, 29, -1) EndIf Local $fIndented = False Local $xslt = ObjCreate("MSXML2.XSLTemplate." & $DOMVERSION & ".0") Local $xslDoc = ObjCreate("MSXML2.FreeThreadedDOMDocument." & $DOMVERSION & ".0") Local $xmldoc = ObjCreate("MSXML2.DOMDocument." & $DOMVERSION & ".0") Local $xslProc $xslDoc.async = False If FileExists($Style) Then _DebugWrite("LoadXML:1:" & $xslDoc.load($Style) & @LF) Else _DebugWrite("LoadXML2:" & $xslDoc.loadXML(_GetDefaultStyleSheet()) & @LF) EndIf If $xslDoc.parseError.errorCode <> 0 Then _XMLError("Error Transforming NodeToObject: " & $xslDoc.parseError.reason) EndIf $xslt.stylesheet = $xslDoc $xslProc = $xslt.createProcessor() $xslProc.input = $objDoc $oXMLDoc.transformNodeToObject($xslDoc, $xmldoc) If $oXMLDoc.parseError.errorCode <> 0 Then _XMLError("_XMLTransform:" & @LF & "Error Transforming NodeToObject: " & $oXMLDoc.parseError.reason) $fIndented = False Else $fIndented = True EndIf If $fIndented Then ;Write transformed xml to a file if a filename is given If $szNewDoc <> "" Then $xmldoc.save($szNewDoc) If $xmldoc.parseError.errorCode <> 0 Then _XMLError("_XMLTransform:" & @LF & "Error Saving: " & $xmldoc.parseError.reason) $fIndented = False EndIf Else ;Overwrite original object with transformed object $objDoc = $xmldoc _XMLSaveDoc($strFile) If $oXMLDoc.parseError.errorCode <> 0 Then _XMLError("_XMLTransform:" & @LF & "Error Saving: " & $oXMLDoc.parseError.reason) $fIndented = False EndIf EndIf EndIf $xslProc = 0 $xslt = 0 $xslDoc = 0 $xmldoc = 0 If $fIndented = False Then Return SetError(1, 0, -1) Return $fIndented EndFunc ;==>_XMLTransform ; #INTERNAL_USE_ONLY#========================================================== ; Name ..........: _GetDefaultStyleSheet ; Description ...: Internal function, returns the default indenting style sheet. ; Syntax.........: _GetDefaultStyleSheet() ; Parameters ....: ; Return values .: Success - The default stylesheet. ; Failure - Nothing. ; Author ........: Hew Wolff - Art & Logic, Inc. ; Modified ......: ; Remarks .......: Posted all over the web. ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _GetDefaultStyleSheet() Return '<?xml version="1.0" encoding="UTF-8"?>' & _ '<!--' & _ 'Converts XML into a nice readable format.' & _ 'Tested with Saxon 6.5.3.' & _ 'As a test, this stylesheet should not change when run on itself.' & _ 'But note that there are no guarantees about attribute order within an' & _ 'element (see http://www.w3.org/TR/xpath#dt-document-order), or about' & _ 'which characters are escaped (see' & _ 'http://www.w3.org/TR/xslt#disable-output-escaping).' & _ 'I did not test processing instructions, CDATA sections, or' & _ 'namespaces.' & _ 'Hew Wolff' & _ 'Senior Engineer' & _ 'Art & Logic, Inc.' & _ 'www.artlogic.com' & _ '-->' & _ '<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">' & _ '<!-- Take control of the whitespace. -->' & _ '<xsl:output method="xml" indent="no" encoding="UTF-8"/>' & _ '<xsl:strip-space elements="*"/>' & _ '<xsl:preserve-space elements="xsl:text"/>' & _ '<!-- Copy comments, and elements recursively. -->' & _ '<xsl:template match="*|comment()">' & _ '<xsl:param name="depth">0</xsl:param>' & _ '<!--' & _ 'Set off from the element above if one of the two has children.' & _ 'Also, set off a comment from an element.' & _ 'And set off from the XML declaration if necessary.' & _ '-->' & _ '<xsl:variable name="isFirstNode" select="count(../..) = 0 and position() = 1"/>' & _ '<xsl:variable name="previous" select="preceding-sibling::node()[1]"/>' & _ '<xsl:variable name="adjacentComplexElement" select="count($previous/*) &gt; 0 or count(*) &gt; 0"/>' & _ '<xsl:variable name="adjacentDifferentType" select="not(($previous/self::comment() and self::comment()) or ($previous/self::* and self::*))"/>' & _ '<xsl:if test="$isFirstNode or ($previous and ($adjacentComplexElement or $adjacentDifferentType))">' & _ '<xsl:text>&#xA;</xsl:text>' & _ '</xsl:if>' & _ '<!-- Start a new line.' & _ '<xsl:text>&#xA;</xsl:text> -->' & _ '<xsl:call-template name="indent">' & _ '<xsl:with-param name="depth" select="$depth"/>' & _ '</xsl:call-template>' & _ '<xsl:copy>' & _ '<xsl:if test="self::*">' & _ '<xsl:copy-of select="@*"/>' & _ '<xsl:apply-templates>' & _ '<xsl:with-param name="depth" select="$depth + 1"/>' & _ '</xsl:apply-templates>' & _ '<xsl:if test="count(*) &gt; 0">' & _ '<xsl:text>&#xA;</xsl:text>' & _ '<xsl:call-template name="indent">' & _ '<xsl:with-param name="depth" select="$depth"/>' & _ '</xsl:call-template>' & _ '</xsl:if>' & _ '</xsl:if>' & _ '</xsl:copy>' & _ '<xsl:variable name="isLastNode" select="count(../..) = 0 and position() = last()"/>' & _ '<xsl:if test="$isLastNode">' & _ '<xsl:text>&#xA;</xsl:text>' & _ '</xsl:if>' & _ '</xsl:template>' & _ '<xsl:template name="indent">' & _ '<xsl:param name="depth"/>' & _ '<xsl:if test="$depth &gt; 0">' & _ '<xsl:text> </xsl:text>' & _ '<xsl:call-template name="indent">' & _ '<xsl:with-param name="depth" select="$depth - 1"/>' & _ '</xsl:call-template>' & _ '</xsl:if>' & _ '</xsl:template>' & _ '<!-- Escape newlines within text nodes, for readability. -->' & _ '<xsl:template match="text()">' & _ '<xsl:call-template name="escapeNewlines">' & _ '<xsl:with-param name="text">' & _ '<xsl:value-of select="."/>' & _ '</xsl:with-param>' & _ '</xsl:call-template>' & _ '</xsl:template>' & _ '<xsl:template name="escapeNewlines">' & _ '<xsl:param name="text"/>' & _ '<xsl:if test="string-length($text) &gt; 0">' & _ '<xsl:choose>' & _ '<xsl:when test="substring($text, 1, 1) = ' & "'#xA;'" & '">' & _ '<xsl:text disable-output-escaping="yes">&amp;#xA;</xsl:text>' & _ '</xsl:when>' & _ '<xsl:otherwise>' & _ '<xsl:value-of select="substring($text, 1, 1)"/>' & _ '</xsl:otherwise>' & _ '</xsl:choose>' & _ '<xsl:call-template name="escapeNewlines">' & _ '<xsl:with-param name="text" select="substring($text, 2)"/>' & _ '</xsl:call-template>' & _ '</xsl:if>' & _ '</xsl:template>' & _ '</xsl:stylesheet>' EndFunc ;==>_GetDefaultStyleSheet ; #INTERNAL_USE_ONLY#========================================================== ; Name ..........: _AddFormat ; Description ...: ; Syntax.........: _AddFormat($objDoc[, $objParent = ""]) ; Parameters ....: $objDoc - Document to format ; $objParent - Optional node to add formatting to ; Return values .: Success - 1 ; Failure - -1 and @error set to 1. ; Author ........: Stephen Podhajecki <gehossafats a t netmdc.com> ; Modified ......: ; Remarks .......: Just break up the tags, no indenting is done here. ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _AddFormat($objDoc, $objParent = "") If $fADDFORMATTING = True Then If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLAddFormat") Return SetError(1, 30, -1) EndIf Local $objFormat = $objDoc.createTextNode(@CR) If IsObj($objParent) Then $objParent.appendChild($objFormat) Else $objDoc.documentElement.appendChild($objFormat) EndIf _XMLSaveDoc($strFile) EndIf Return 1 EndFunc ;==>_AddFormat ; #FUNCTION# =================================================================== ; Name ..........: _XMLSetAutoSave ; Description ...: Set the automatic save to on or off ; Syntax.........: _XMLSetAutoSave($fSave = True) ; Parameters ....: $fSave - Boolean value to set automatic saving. ; Return values .: Success - Previous state of autosave. ; Author ........: Stephen Podhajecki <gehossafats a t netmdc.com> ; Modified ......: ; Remarks .......: Defaults to true. ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLSetAutoSave($fSave = True) Local $oldSave = $fXMLAUTOSAVE $fXMLAUTOSAVE = $fSave Return $oldSave EndFunc ;==>_XMLSetAutoSave ; #FUNCTION# =================================================================== ; Name ..........: _XMLSetAutoFormat ; Description ...: Turn auto formatting on or off ; Syntax.........: _XMLSetAutoFormat($fAutoFormat = True) ; Parameters ....: $fAutoFormat - Boolean flag for automatic formatting ; Return values .: Success - The previous state. ; Failure - Nothing. ; Author ........: Stephen Podhajecki {gehossafats at netmdc. com} ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLSetAutoFormat($fAutoFormat = True) Local $oldFormat = $fADDFORMATTING $fADDFORMATTING = $fAutoFormat Return $oldFormat EndFunc ;==>_XMLSetAutoFormat ; #FUNCTION# =================================================================== ; Name ..........: _XMLSaveDoc ; Description ...: Save the current xml doc ; Syntax.........: _XMLSaveDoc([$sFile=""[,$iForce = 0]]) ; Parameters ....: $sFile - The filename to save the xml doc as. ; $iForce - If true, save the file regardless of autosave state. ; Return values .: Success - 1 ; Failure - -1 and @error set to the following: ; |1 - error trying to save. ; |2 - Autosave is off. ; |3 - No filename given for save and default is blank. ; Author ........: Stephen Podhajecki {gehossafats at netmdc. com} ; Modified ......: ; Remarks .......: Defaults to the current filename. ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLSaveDoc($sFile = "", $iForce = 0) If ($fXMLAUTOSAVE = True) Or ($iForce = 1) Then If $sFile = "" Then $sFile = $strFile If $sFile <> "" Then $objDoc.save($sFile) If $objDoc.parseError.errorCode <> 0 Then _XMLError("_XMLSaveDoc: Saving " & $sFile & " failed.:" & @LF & _ $objDoc.parseError.errorCode & _ " " & $objDoc.parseError.reason) Return SetError(1, 0, -1) EndIf Return 1 Else _XMLError("_XMLSaveDoc:" & " Error Saving: No Filename given") Return SetError(3, 0, -1) EndIf EndIf Return SetError(2, 0, 1) EndFunc ;==>_XMLSaveDoc ; #FUNCTION# =================================================================== ; Name ..........: _XMLNodeExists ; Description ...: Checks for the existence of a node or nodes matching the specified path ; Syntax.........: _XMLNodeExists($strXPath) ; Parameters ....: $strXPath - Path to check for. ; Return values .: Success - 1 or Higher , 0 ; Failure - 0 and @Error set to: ; |0 - No error. ; |1 - No XML object @extended = 31. ; |2 - Node not found. ; Author ........: Stephen Podhajecki <gehossafats a t netmdc.com> ; Modified ......: ; Remarks .......: Returns the number of nodes found (could be greater than 1) ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLNodeExists($strXPath) If Not IsObj($objDoc) Then _XMLError("No object passed to function _XMLNodeExists") Return SetError(1, 31, 0) EndIf Local $objNode, $iCount Local $objNode = $objDoc.SelectNodes($strXPath) If IsObj($objNode) Then $iCount = $objNode.length $objNode = 0 If $iCount Then Return $iCount Return SetError(2, 0, 0) EndFunc ;==>_XMLNodeExists ; #INTERNAL_USE_ONLY#========================================================== ; Name ..........: _XMLArrayAdd ; Description ...: Adds an item to an array. ; Syntax.........: _XMLArrayAdd(ByRef $avArray, $sValue) ; Parameters ....: $avArray - The array to modify. ; $sValue - The value to add to the array. ; Return values .: Success - 1 and value added to array. ; Failure - 0 and @error set to 1 ; Author ........: ; Modified ......: ; Remarks .......: Local version of _ArrayAdd to remove dependency on Array.au3 ; Related .......: ; Link ..........; ; Example .......; [yes/no] ; ============================================================================== Func _XMLArrayAdd(ByRef $avArray, $sValue) If IsArray($avArray) Then ReDim $avArray[UBound($avArray) + 1] $avArray[UBound($avArray) - 1] = $sValue SetError(0) Return 1 Else SetError(1) Return 0 EndIf EndFunc ;==>_XMLArrayAdd EDIT: Removed a script comment related to one of my other projects.
  23. I am in the process of creating a UDF for CrowdinAPI. I have a problem with one function. https://crowdin.com/page/api/get-projects This is my implementation. Func _Crowdin_GetProjects() ; https://api.crowdin.com/api/account/get-projects?account-key={account-key} Local $sURL = 'https://api.crowdin.com/api/account/get-projects?account-key=' & _Crowdin_AccountKey() ConsoleWrite('! ' & $sURL & @CRLF) Local $oXmlHttp = ObjCreate("MSXML2.XMLHTTP.3.0") $oXmlHttp.Open('POST', $sURL, False) $oXmlHttp.Send() Local $output = $oXmlHttp.ResponseText $oXmlHttp = '' Return $output EndFunc ;==>_Crowdin_GetProjects Func _Crowdin_AccountKey($vAccountKey = Default) Local Static $sACCOUNT_API_KEY = '' If $vAccountKey = Default Then Return $sACCOUNT_API_KEY Else $sACCOUNT_API_KEY = $vAccountKey Return $sACCOUNT_API_KEY EndIf EndFunc ;==>_Crowdin_AccountKey I do not know how to use: login={crowdin-login-name} curl -F "login={crowdin-login-name}" https://api.crowdin.com/api/account/get-projects?account-key={account-key} Thank you in advance for any help. mLipok
  24. This is kind of already posted here: '?do=embed' frameborder='0' data-embedContent>> but wanted to note this in this forum of example scripts in case some people only look in this forum for examples and not the other forums with respect to AutoIt integration or relation to Selenium WebDriver. So, the example in summary is: you can use Selenium WebDriver API to do AutoIt GUI automation (the ControlXyz() and WinXyz() functons, along with mouse and "send keys" functions). Although I suppose that might be opposite or counter to what most examples here are about - using AutoIt to do or control other stuff rather than using other stuff to control/run AutoIt. But regardless, it is an example implementation of a different use case for AutoIt beyond the general AutoIt community, like those who also use Selenium WebDriver and/or need to integrate Selenium with AutoIt for remote deployment. https://github.com/daluu/AutoItDriverServer with specific demo examples here: https://github.com/daluu/AutoItDriverServer/blob/master/sample-code/CalculatorTest.java https://github.com/daluu/AutoItDriverServer/blob/master/sample-code/calculator.py https://github.com/daluu/AutoItDriverServer/blob/master/sample-code/SeleniumIntegrationTest.java https://github.com/daluu/AutoItDriverServer/blob/master/sample-code/SeleniumIntegrationWithAutoItDriver.py
  25. Has anyone tried to use Google APIs for scraping search results? I've built this simple script to demonstrate my problem I'm having with Google results scraping: #include <Array.au3> Global $oHTTP = ObjCreate("WinHttp.WinHttpRequest.5.1") _PerformSearch(); Func _PerformSearch() dim $ShowResults[0][3]; $searchPages = 3 for $j = 1 to $searchPages*8 Step 8 $SearchString = 'Apple+Juice'; Disable this line... ;~ $SearchString = 'intitle:"crazy+stink"'; ...And enable this one ;http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=1&rsz=large&q=intitle:%22crazy+stink%22 $sURL = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=" & $j & "&rsz=large&q=" & $SearchString $oHTTP.Open("GET", $sURL, False) $oHTTP.SetRequestHeader("Referer", @IPAddress1) If (@error) Then Return SetError(1, 0, 0) $oHTTP.Send() If (@error) Then Return SetError(2, 0, 0) $retVal = $oHTTP.ResponseText If (@error) Then Return SetError(3, 0, 0) $aReturn = _JSON_Decode($retVal) if NOT @error then $responseData = $aReturn[0][1] $results = $responseData[0][1] for $i = 0 to UBound($results)-1 $oneResult = $results[$i] $title = _OnlyBoldedDecode(_getJSonValue($oneResult, "title")) $url = _getJSonValue($oneResult, "url") $content = _OnlyBoldedDecode(_getJSonValue($oneResult, "content")) ReDim $ShowResults[UBound($ShowResults)+1][3] $arIndex = UBound($ShowResults)-1 $ShowResults[$arIndex][0] = $title $ShowResults[$arIndex][1] = $url $ShowResults[$arIndex][2] = $content Next EndIf Next _ArrayDisplay($ShowResults); EndFunc Func _OnlyBoldedDecode($sData);decoding only most common code Return StringReplace(StringReplace($sData, "\u003c", "<"), "\u003e", ">"); EndFunc Func _getJSonValue($_res, $getData) for $i = 0 to UBound($_res)-1 if $_res[$i][0] == $getData then Return $_res[$i][1] Next Return ""; EndFunc Func _JSON_Decode($sString) Local $iIndex, $aVal, $sOldStr = $sString, $b $sString = StringStripCR(StringStripWS($sString, 7)) If Not StringRegExp($sString, "(?i)^\{.+}$") Then Return SetError(1, 0, 0) Local $aArray[1][2], $iIndex = 0 $sString = StringMid($sString, 2) Do $b = False $aVal = StringRegExp($sString, '^"([^"]+)"\s*:\s*(["{[]|[-+]?\d+(?:(?:\.\d+)?[eE][+-]\d+)?|true|false|null)', 2) ; Get value & next token If @error Then ConsoleWrite("!> StringRegExp Error getting next Value." & @CRLF) ConsoleWrite($sString & @CRLF) $sString = StringMid($sString, 2) ; maybe it works when the string is trimmed by 1 char from the left ? ContinueLoop EndIf $aArray[$iIndex][0] = $aVal[1] ; Key $sString = StringMid($sString, StringLen($aVal[0])) Switch $aVal[2] ; Value Type (Array, Object, String) ? Case '"' ; String ; Value -> Array subscript. Trim String after that. $aArray[$iIndex][1] = StringMid($sString, 2, StringInStr($sString, """", 1, 2) - 2) $sString = StringMid($sString, StringLen($aArray[$iIndex][1]) + 3) ReDim $aArray[$iIndex + 2][2] $iIndex += 1 Case '{' ; Object ; Recursive function call which will decode the object and return it. ; Object -> Array subscript. Trim String after that. $aArray[$iIndex][1] = _JSON_Decode($sString) $sString = StringMid($sString, @extended + 2) If StringLeft($sString, 1) = "," Then $sString = StringMid($sString, 2) $b = True ReDim $aArray[$iIndex + 2][2] $iIndex += 1 Case '[' ; Array ; Decode Array $sString = StringMid($sString, 2) Local $aRet[1], $iArIndex = 0 ; create new array which will contain the Json-Array. Do $sString = StringStripWS($sString, 3) ; Trim Leading & trailing spaces $aNextArrayVal = StringRegExp($sString, '^\s*(["{[]|\d+(?:(?:\.\d+)?[eE]\+\d+)?|true|false|null)', 2) if @error Then Return SetError(@error, 0, 0); Switch $aNextArrayVal[1] Case '"' ; String ; Value -> Array subscript. Trim String after that. $aRet[$iArIndex] = StringMid($sString, 2, StringInStr($sString, """", 1, 2) - 2) $sString = StringMid($sString, StringLen($aRet[$iArIndex]) + 3) Case "{" ; Object ; Recursive function call which will decode the object and return it. ; Object -> Array subscript. Trim String after that. $aRet[$iArIndex] = _JSON_Decode($sString) $sString = StringMid($sString, @extended + 2) Case "[" MsgBox(0, "", "Array in Array. WTF is up with this JSON shit?") MsgBox(0, "", "This should not happen! Please post this!") Exit 0xDEADBEEF Case Else ConsoleWrite("Array Else (maybe buggy?)" & @CRLF) $aRet[$iArIndex] = $aNextArrayVal[1] EndSwitch ReDim $aRet[$iArIndex + 2] $iArIndex += 1 $sString = StringStripWS($sString, 3) ; Leading & trailing If StringLeft($sString, 1) = "]" Then ExitLoop $sString = StringMid($sString, 2) Until False $sString = StringMid($sString, 2) ReDim $aRet[$iArIndex] $aArray[$iIndex][1] = $aRet ReDim $aArray[$iIndex + 2][2] $iIndex += 1 Case Else ; Number, bool ; Value (number (int/flaot), boolean, null) -> Array subscript. Trim String after that. $aArray[$iIndex][1] = $aVal[2] ReDim $aArray[$iIndex + 2][2] $iIndex += 1 $sString = StringMid($sString, StringLen($aArray[$iIndex][1]) + 2) EndSwitch If StringLeft($sString, 1) = "}" Then StringMid($sString, 2) ExitLoop EndIf If Not $b Then $sString = StringMid($sString, 2) Until False ReDim $aArray[$iIndex][2] Return SetError(0, StringLen($sOldStr) - StringLen($sString), $aArray) EndFunc ;==>_JSON_Decode This works as long as you're not using "intelligent search placeholders" like using "intitle", "inurl", "site", and other placeholders with sentences (single word works, like: intitle:cake, but with sentence like: intitle:"crazy+stink" it doesn't, while searching this on google will give you approx. 35 results: https://www.google.com/search?q=intitle:"crazy+stink" ) Has anyone found a better way to legally scrape Google? This JSON API was built to be free, without big limitations (max results you get from a single query is 64), but it's not working properly, it doesn't give me results on "intelligent search placeholders". I'm aware of the Google Custom Search API, which requires API Key (which I have) but this API can search only specific website, and I need to scrape results from Google's search results. Any thoughts, suggestions, ideas? Edit: July 4th 2014: I have found a way how to use Google Custom Search API with API Key, and still search entire web (instead of only single page). I have found this: https://support.google.com/customsearch/answer/2631040?hl=en and I have followed the instructions. I got my CX code, and I formatted the URL: https://www.googleapis.com/customsearch/v1?key=[MY_API_KEY]&cx=017576662512468239146:omuauf_lfve&q=intitle:%22crazy+stink%22 (the CX in this example is the one that Google provides as an example for the API here: https://developers.google.com/custom-search/json-api/v1/using_rest, however, even with my own CX I get the same results) Here are the results: { "kind": "customsearch#search", "url": { "type": "application/json", "template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&lr={language?}&safe={safe?}&cx={cx?}&cref={cref?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googleHost?}&c2coff={disableCnTwTranslation?}&hq={hq?}&hl={hl?}&siteSearch={siteSearch?}&siteSearchFilter={siteSearchFilter?}&exactTerms={exactTerms?}&excludeTerms={excludeTerms?}&linkSite={linkSite?}&orTerms={orTerms?}&relatedSite={relatedSite?}&dateRestrict={dateRestrict?}&lowRange={lowRange?}&highRange={highRange?}&searchType={searchType}&fileType={fileType?}&rights={rights?}&imgSize={imgSize?}&imgType={imgType?}&imgColorType={imgColorType?}&imgDominantColor={imgDominantColor?}&alt=json" }, "queries": { "request": [ { "title": "Google Custom Search - intitle:\"crazy stink\"", "totalResults": "0", "searchTerms": "intitle:\"crazy stink\"", "count": 10, "inputEncoding": "utf8", "outputEncoding": "utf8", "safe": "off", "cx": "017576662512468239146:omuauf_lfve" } ] }, "searchInformation": { "searchTime": 0.35068, "formattedSearchTime": "0.35", "totalResults": "0", "formattedTotalResults": "0" } } The results are almost the same as I get them from AJAX JSON Api http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=1&rsz=large&q=intitle:%22crazy+stink%22: {"responseData": {"results":[],"cursor":{"moreResultsUrl":"http://www.google.com/search?oe\u003dutf8\u0026ie\u003dutf8\u0026source\u003duds\u0026start\u003d1\u0026hl\u003den\u0026q\u003dintitle:%22crazy+stink%22","searchResultTime":"0.10"}}, "responseDetails": null, "responseStatus": 200} Which is 0. So... maybe there isn't any error on my part, but there is on Google's? I'm just curious if anyone encountered an issue like the one I have, or if anyone have any better suggestion, but bare in mind that I want to keep this legal (scraping results from IE object is not something I want to do).
×