With Monitis you can not only monitor your network infrastructure but also data from your business processes, such as those inside an
Microsoft SQL Server database. Using a simple script, you can exe cute a query and upload the results to a Custom Monitor in your Monitis account.
Monitis API Access
The first thing you will need in order to create this monitor is the Monitis application programming interface (API) Key and Secret Key. The API Key is a alphanumeric code that allows you to access the Monitis API’s URL and transmit or receive data about your Monitis services. The Secret Key is also an alphanumeric code — but this one allows you to digitally sign your information to ensure that only you can transmit data to your Monitis account. That’s a great safety feature!
Your API Key may be disclosed to anyone, but your Secret Key must be maintained private and should not be shared nor transmitted. To obtain your Monitis API Key and Secret Key, log into your account and from the top menu bar, go to Tools then API then API Key. It will display both your API Key and your Secret Key.
Create a MS SQL Table Monitor
A Custom Monitor is needed to display the values you get from an MS SQL Server. In order to create it, you need go through the following steps:
- Connect to Monits API and obtain an authToken
- Create the Custom Monitor tailored to your needs
The following VBScript code does it all for you:
First Enter Your API key and Secret Key
apiKey = "Your API key here"
secretKey = "Your secret key here"
Initialize HTTP connection object
dtGMT = GMTDate()
Set objHTTP = CreateObject("Microsoft.XMLHTTP")
'Request a token to use in following calls
url = "http://www.monitis.com/api?action=authToken&apikey=" + apiKey + "&secretkey=" + secretKey
objHTTP.open "GET", url, False
objHTTP.send
resp = objHTTP.responseText
token = DissectStr(resp, "authToken"":""", """")
Add the custom monitor
url = "http://www.monitis.com/customMonitorApi"
monitorParams = "sql_data:SQL+server+data:Number of orders:3:false;"
resultParams = "shipping:Shipping:N%2FA:2;processing:Processing:N%2FA:2;"
name = "Order+status"
objHTTP.open "POST", url, False
objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
postData = "apikey=" + apiKey + "&validation=token&authToken=" + token +
"×tamp=" + FmtDate(dtGMT) + "&action=addMonitor&monitorParams=" +
monitorParams + "&resultParams=" + resultParams + "&name=" + name +
"&tag=[sql+sample]"
objHTTP.send postData
resp = objHTTP.responseText
Set objHTTP = Nothing
Function DissectStr(cString, cStart, cEnd)
dim nStart, nEnd
nStart = InStr(cString, cStart)
if nStart = 0 then
DissectStr = ""
else
nStart = nStart + len(cStart)
if cEnd = "" then
nEnd = len(cString)
else
nEnd = InStr(nStart, cString, cEnd)
if nEnd = 0 then nEnd = nStart else nEnd = nEnd - nStart
end if
DissectStr = mid(cString, nStart, nEnd)
end if
End Function
Function FmtDate(dt)
FmtDate = cstr(Datepart("yyyy", dt)) + "-" + right("0"+cstr(Datepart("m", dt)),2) +
"-" + right("0" + cstr(Datepart ("d", dt)),2) + " " + right("0" +
cstr(Datepart("h", dt)),2) + ":" + right("0" + cstr(Datepart("n", dt)),2) + ":" +
right("0" + cstr(Datepart("S", dt)),2)
end function
Function GMTDate()
dim oWMI, oRes, oEntry
Set oWMI = GetObject("winmgmts {impersonationLevel=impersonate}!\\.\root\cimv2")
GMTDate = now
Set oRes = oWMI.ExecQuery("Select LocalDateTime from Win32_OperatingSystem")
For each oEntry in oRes
GMTDate = DateAdd("n", -CInt(right(oEntry.LocalDateTime, 4)), GMTDate)
next
End function
Save this code to a file with a .vbs extension (such as createCustMon.vbs); then run it executing the following from a command prompt:
cscript createCustMon.vbs
Uploading database query results to Custom Monitor
Once your custom monitor is created you can start uploading query results into it.
Follow these directions:
- Connect to Monits API and obtain an authToken
- Get the list of Custom Monitors and locate the ID of the monitor you want to add data to
- Execute your SQL Server query and get the values to need
- Upload the values to the Custom Monitor
The following script does exactly that:
Set connection = WScript.CreateObject("ADODB.Connection")
Set recordset = CreateObject("ADODB.Recordset")
'You API key and Secret Key
apiKey = "Your API key here"
secretKey = "Your secret key here"
dtGMT = GMTDate()
'Initialize HTTP connection object
Set objHTTP = CreateObject("Microsoft.XMLHTTP")
'Request a token to use in following calls
url = "http://www.monitis.com/api?action=authToken&apikey=" + apiKey + "&secretkey=" + secretKey
objHTTP.open "GET", url, False
objHTTP.send
resp = objHTTP.responseText
token = DissectStr(resp, "authToken"":""", """")
'Requests the monitor list in order to find the MonitorID
tag = "[sql+sample]"
url = "http://www.monitis.com/customMonitorApi?action=getMonitors&apikey=" + apiKey + "&tag=" + tag
objHTTP.open "GET", url, False
objHTTP.send
resp = objHTTP.responseText
monitorID = DissectStr(resp, "id"":""", """,""tag")
'Queries SQL Server to obtain data to upload
instance = "localhost\SQLEXPRESS"
database = "Customers"
'Connection string for Trusted Authentication
'connection_string = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=" + database + ";Data Source=" + instance
'Connection string for Standard Authentication
connection_string = "Provider=SQLOLEDB.1;Data Source=" + instance + ";Initial Catalog=" + database + ";User Id=user1;Password=password1;"
Set connection = WScript.CreateObject(“ADODB.Connection”)
Set recordset = CreateObject(“ADODB.Recordset”)
connection.Open connection_string
query = “select count(*) from Orders where Status = ‘Processing'”
recordset.Open query, connection
ordProcessing = recordset(0)
recordSet.Close
query = “select count(*) from Orders where Status = ‘Shipping'”
recordset.Open query, connection
ordShipping = recordset(0)
‘Posts data
url = “http://www.monitis.com/customMonitorApi”
action = “addResult”
results = “processing:” & ordProcessing & “;shipping:” & ordShipping & “;”
unixDate = CStr(DateDiff(“s”, “01/01/1970 00:00:00”, DateSerial(Year(dtGMT), Month(dtGMT), Day(dtGMT)) + TimeSerial(Hour(dtGMT), Minute(dtGMT), Second(dtGMT)))) + “000”
objHTTP.open “POST”, url, False
objHTTP.setRequestHeader “Content-Type”, “application/x-www-form-urlencoded”
postData = “apikey=” + apiKey + “&validation=token&authToken=” + token + “×tamp=” + FmtDate(dtGMT) + “&action=” + action + “&monitorId=” + monitorID + “&checktime=” + unixDate + “&results=” + results
objHTTP.send postData
resp = objHTTP.responseText
Function DissectStr(cString, cStart, cEnd)
‘Generic string manipulation function to extract value from JSON output
dim nStart, nEnd
nStart = InStr(cString, cStart)
if nStart = 0 then
DissectStr = “”
else
nStart = nStart + len(cStart)
if cEnd = “” then
nEnd = len(cString)
else
nEnd = InStr(nStart, cString, cEnd)
if nEnd = 0 then nEnd = nStart else nEnd = nEnd – nStart
end if
DissectStr = mid(cString, nStart, nEnd)
end if
End Function
Function FmtDate(dt)
FmtDate = cstr(Datepart(“yyyy”, dt)) + “-” + right(“0” + cstr(Datepart(“m”, dt)),2) + “-” + right(“0” + cstr(Datepart (“d”, dt)),2) + ” ” + right(“0” + cstr(Datepart(“h”, dt)),2) + “:” + right(“0” + cstr(Datepart(“n”, dt)),2) + “:” + right(“0” + cstr(Datepart(“S”, dt)),2)
end function
Function GMTDate()
dim oWMI, oRes, oEntry
Set oWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
GMTDate = now
Set oRes = oWMI.ExecQuery("Select LocalDateTime from Win32_OperatingSystem")
For each oEntry in oRes
GMTDate = DateAdd("n", -CInt(right(oEntry.LocalDateTime, 4)), GMTDate)
next
End function
Of course you will have to adjust the code depending on your environment:
- Assign the name of your database server and database instance to variable instance, in the form <server>\<instance>, such as SRVSQL\INST1;
If your SQL Server is installed as the default instance, just use the computer name, such as SRVSQL; - Assign the name of the database containing the table you want to query to the variable database;
- Asses the type of authentication that is enabled and comment/uncomment the appropriate connection string. If you are using Standard Authentication, fill in the username and password inside the connection string itself;
- Use appropriate queries to gather values you need.
Save this code to a file with a .vbs extension (such as pushDataSQL.vbs); then run it executing the following command from a command prompt:
cscript pushDataSQL.vbs
Testing the Monitor
Each time you run the second script a query is executed against your database and the results are uploaded to your Custom Monitor. You can use Windows Task Scheduler to run the script automatically and as frequently as you need.
Add your Custom Monitor widget to your Monitis account: from the Monitors menu select Manage Monitors and then click Custom Monitors. Select the newly created Custom Monitor and then click Add to Window.
Refresh the page after adding new data to see them show up inside the widget — such as in the above graphic.
Full source code is available open source at github.
You don’t have to sweat keeping a constant watch on data from any of your business processes. Monitis makes it easy through its ability to provide you with a Custom Monitor.
You may also read How to Monitor Windows Servers with VBScript, WMI and Monitis
The post Monitor MS SQL Server Data with VBScript on Monitis appeared first on Monitis Blog.