crribs.com

the blog of brad shultz, systems design, RETS development, ETL, scripting, and windows task scheduler stuff

Archive for the ‘tools and utilities’ Category

Google Analytics Api with VBScript – Retrieving all Profile Numbers

with 2 comments

This vbscript will retrieve all of the website’s profile numbers for your google analytics account.  Borrowed some code from http://mikaelspage.blogspot.com/2009/08/excel-functions-for-fetching-data.html

Changed a lot of code myself.  Removed some functions there may be remnants of them in there.  It does work though, and seems to be the only example on the web of doing this with VBScript.  Enjoy.

‘**********************************************************************
‘*  Get Google Analytics Profiles
‘************************************************************************

Call Main()

Sub Main()

email = “youremail@gmail.com”
password = “password”
token = getGAauthenticationToken(email, password)

getGAaccountData token, “False”

End Sub

Sub getGAaccountData(authToken, includeHeaders)

If authToken = “Authentication failed” Then
getGAprofiles = “Authentication failed”
WScript.Echo “Authentication failed”
Exit sub
End If
tempFile = “c:\googleAnalytics_Temp.txt”
Set fso = CreateObject(“scripting.filesystemobject”)
If fso.FileExists(tempfile) Then fso.DeleteFile(tempFile)
Set fileTemp = fso.OpenTextFile(tempFile, 8, True)

fileTemp.WriteLine chr(34) & “AccountName”“ , ”“ProfileNumber”“ , ”“ProfileTitle” & chr(34)

URL = “https://www.google.com/analytics/feeds/accounts/default”
Set objhttp = CreateObject(“MSXML2.ServerXMLHTTP”)

objhttp.Open “GET”, URL, False
objhttp.setRequestHeader “Content-type”, “application/x-www-form-urlencoded”
objhttp.setRequestHeader “Authorization”, “GoogleLogin Auth=” & authToken
objhttp.send (“”)

gaResponse = objhttp.responseText

If InStr(1, gaResponse, “Token invalid”) > 0 Or InStr(1, gaResponse, “Authorization required”) > 0 Then
getGAprofiles = “Authentication failed”
Exit sub
End If

Set XMLdoc = CreateObject(“MSXML2.DOMDocument”)
XMLdoc.LoadXML(objhttp.responseText)
Set theRoot = XMLdoc.DocumentElement
Set children = theRoot.ChildNodes

rivi = 1
For Each child In children
If child.nodeName = “openSearch:totalResults” Then
riveja = CInt(child.Text)
If includeHeaders = True Then
ReDim TempArray(riveja, 2)
Else
ReDim TempArray(riveja, 2)
End If
End If

If child.nodeName = “entry” Then

Set children2 = child.ChildNodes
For Each child2 In children2
If child2.nodeName = “dxp:property” Then
Set attribuutit = child2.Attributes
If attribuutit.getNamedItem(“name”).Text = “ga:accountName” Then TempArray(rivi, 0) = attribuutit.getNamedItem(“value”).text

End If

If child2.nodeName = “dxp:tableId” Then TempArray(rivi, 2) = CDbl(Replace(child2.Text, “ga:”, “”))

If child2.nodeName = “title” Then TempArray(rivi, 1) = child2.text

Next
fileTemp.Write chr(34) & TempArray(rivi, 0)
fileTemp.Write chr(34) & “ , ” & chr(34) & TempArray(rivi, 2)
fileTemp.Write chr(34) & “ , ” & chr(34) & TempArray(rivi, 1) & chr(34) & vbnewline
rivi = rivi + 1
End If

If includeHeaders = True Then
TempArray(0, 0) = “AccountName”
TempArray(0, 1) = “ProfileTitle”
TempArray(0, 2) = “ProfileNumber”
End If

getGAprofiles = TempArray

Next

End sub

Function getGAauthenticationToken(email, password)
If email = “” Then
getGAauthenticationToken = “”
Exit Function
End If

If password = “” Then
getGAauthenticationToken = “Input password”
Exit Function
End If

CurChr = 1

Set objhttp = CreateObject(“MSXML2.ServerXMLHTTP”)
URL = “https://www.google.com/accounts/ClientLogin”
objhttp.Open “POST”, URL, False
objhttp.setRequestHeader “Content-type”, “application/x-www-form-urlencoded”
objhttp.send (“accountType=GOOGLE&Email=” & email & “&Passwd=” & password & “&service=analytics&Source=InternetEngineKPI”)

authResponse = objhttp.responseText

If InStr(1, authResponse, “BadAuthentication”) = 0 Then
authTokenStart = InStr(1, authResponse, “Auth=”) + 4
authToken = Right(authResponse, Len(authResponse) - authTokenStart)
getGAauthenticationToken = authToken
Else

DTSTaskExecResult_Failure

End If

If Err.Number <> 0 Then
DTSTaskExecResult_Failure
End If
End Function

Function LastDayOFPreviousMonth(aDate)
LastDayOFPreviousMonth = DateAdd(“d”, -1, DateSerial(Year(aDate), Month(aDate), 1))
End Function

Function FirstDayOFPreviousMonth(aDate)
If Month(aDate) > 1 Then
FirstDayOFPreviousMonth = DateSerial(Year(aDate), Month(aDate) - 1, 1)
Else
FirstDayOFPreviousMonth = DateSerial(Year(aDate) - 1, 12, 1)
End If
End Function

Written by bshultz

May 26th, 2010 at 7:21 pm

Get Number of Pages Indexed by Google with Vbscript

without comments

Have you ever needed to track the number of pages indexed daily for a site within Google? To save you some time, the following vbscript will grab the number of estimated pages Google returns as a single integer, the same as if you entered: site:crribs.com into the ‘Search’ box. The returned page gives you back – for example – Results 1 – 10 of about 171 from crribs.com. (0.19 seconds) . This script would return the number 171, for analytical/statistical tracking purposes. Make sure to enter the correct cannonical version of your site for the variable if youve specified one in Google Webmaster Tools.

varSite = "crribs.com"

WScript.Echo getGoogIndexedPages(varSite)

Function getGoogIndexedPages(strUrl)

strUrl = "http://www.google.com/search?hl=en&source=hp&q=site:" & strUrl & "&aq=f&aqi=&aql=&oq=&gs_rfai="

Set xmlhttp = createobject("msxml2.xmlhttp.3.0")

xmlhttp.open "get", strUrl, false

xmlhttp.send

Set objRegEx = CreateObject("VBScript.RegExp")

objRegEx.Global = True

objRegEx.Pattern = "of about \[\d|\,]*\<\/b\>"  (Google updated the format of this page.  Replace the RegEx and itll work again.)

objRegEx.Pattern = "About.\d+.\d+"

strSearchString = xmlhttp.responseText

Set colMatches = objRegEx.Execute(strSearchString)

If colMatches.count > 0 Then

For Each match In colMatches

strMatch = match

Next

End If

strMatch = Replace(strMatch, "of about ", "")

strMatch = Replace(strMatch, "", "")

getGoogIndexedPages = strMatch

End Function

Written by bshultz

May 5th, 2010 at 3:45 am

Send Twitter Update with VBScript

without comments

I was thinking of using Twitter as a kind of ‘syslog’ for all of the scripts we have running (via the task scheduler) all over the enterprise. There is no centralized logging implemented. Ive made some attempts via text files, sql server, the event log, etc., but nothing has taken hold as – easy to implement, universal, and straightforward. This is the visual basic script I came up with to upload the messages.



'**************************************************************************
'* Scriptname: PostToTwitterSimple.vbs
'* TWITTER STATUS UPDATE
'* Brad Shultz - crribs.com
'**************************************************************************
strUsername = "username" 'Username
strPassword = "password" 'Password
strMessage = "This is a test twitter update from a vbscript." 'Message for twitter

strTwitterXMLResponse = SendToTwitter(strMessage, strUsername, strPassword)

'postback what you sent to twitter
MsgBox strTwitterXMLResponse, VbOkOnly, "TWITTER STATUS UPDATE"

Function SendToTwitter(strMessage, strUsername, strPassword)
Set objHTTP = CreateObject("Microsoft.XMLHTTP")
objHTTP.open "POST", "http://twitter.com/statuses/update.xml", false, strUsername, strPassword
objHTTP.send "status=" & strMessage
SendToTwitter = objHTTP.responseText
Set objHTTP = nothing
End Function

Red Gate SQL Prompt Freeware – Intellisense for SQL Server Tools

without comments

In the spirit of sharing, and noticing that Red Gate Software’s SQL Prompt is up to $295 dollars for a single license, I’d like to offer this freeware/beta that Red Gate released to the public right after it acquired the SQL Prompt software from a company (who was giving it away for free).  This application brings intellisense/code completion to Sql Server- Management Studio, Query Analyzer, Editpad (I think), etc.  They realized that they were going to have to make substantial changes to the codebase in order to optimize it to their standards; so in the meantime, the current version of SQL Prompt was offered up for free.  I havent been able to find this anywhere else, so- here it is:  the original freeware version of Red Gate Software’s SQL Prompt.  Its a beta type version, but works very well as far as I’ve used it.  It requires no license because it was released as freeware.  Download it here.

red gate software's sql prompt

Red Gate Software's SQL Prompt - the freeware edition; Intellisense for SQL Server!!!

http://www.mediafire.com/file/ejnazzdwtwi/SQLPromptSetup.msi

CSV Files. A blessing and a curse.

without comments

In my line of work, I deal with a lot of .csv files (we refer to them as .csv – comma seperated value – files, when in actuality they may be tab or pipe seperated, quote delimited, and/or some other random variation or mixture of tabs, quotes, commas, pipes, delimiters, etc.).  They can be a nightmare if they are given to you misformatted (in a pipe, i.e. ‘|’ , seperated file, if the text is not scrubbed for pipes before it is formatted, you end up with an invalid file (aka a file not able to be parsed by DTS, SSIS, ODBC Text drivers, Excel, etc.).  I have found a few tools that are very helpful when you are working with .csv files.

1.  CSVED – (download from) http://csved.sjfrancke.nl/

CSVED is the go-to-guy (next to Excel) in terms of CSV editors.  Although a low-key app, its free (!) and integrates really well into the Windows right-click context menu.  It gives you all sorts of options, from deleting columns from the file, to exporting the .csv in XML.  Absolutely top-notch freeware program.

2.  Excel – (download the trial from Microsoft.com)

Not freeware, but Excel does do a great job at opening .csv files (and fixed length, too!).  The trick is to paste all your data into the first column, then select “Text to Columns” and tell Excel about the file it is opening.  If you are using Excel 2003 or older, you are limited to around 56,000 rows.  Excel 2007 will let you open a .csv file with up to a million rows (very helpful).

Written by bshultz

December 1st, 2009 at 4:23 pm

Add VBScript to Scheduled Tasks – from Context Menu

without comments

This has been something that’s bothered me for awhile- especially at work, with all the tasks I schedule daily.  It bothered me that I always had to look up the system account username and password that’d been designated as our ‘Task Scheduler Account’.  The password is a tough one (and rightly so- its a domain admin account).  It also bothered me that in order to schedule a task, I had to go to the GUI applet interface (Control Panel) or the command prompt, then add the task- even though I’d just written the script and was staring at it in the directory I wanted it to run from.  Thus was born the (fairly ugly, but useful) – ScheduleAsTask context menu item.

image

There is a limitation on the name of the vbs file- it cannot have spaces in it.  This is because we are using the filename as an argument – so if there is a space in the name, the Windows Scripting Host thinks there are multiple arguments.  This limitation could be overcome by getting the number of arguments found at runtime, and concatenating them fairly easily.

image

The default name is your script’s name, minus the extension.  If there is already a task scheduled with the same name, the script will throw an error.  You can change the task name to whatever you like in step 2.

image

And step 3 is just configuring the details for the task.

———————————————————————————

1.  Save the following code to a directory as “schtaskContextMenu.vbs” (the name doesnt matter as long as the extension is .vbs).

2.  Go to http://www.mvps.org/emorcillo/en/code/vb6/index.shtml and scroll down until you see “Using the Task Scheduler”.  Click the link underneath it and save the .dll in the same directory as the script.

3.  Run the script.  You may have to give it permission to run.  Tested on XP Pro sp2.  Might work on Vista, not sure.  Vista uses the TaskScheduler 2.0 interface, which has some backwards support.  Try it.

Here is the script zipped up for you.  Once you have the .dll from the above link in the same folder as the script, simply double click on the script.  It will ask you if you are installing or updating.  Click yes to install the whole shebang, no to just update the script (in case you make any changes), or cancel to, well, cancel the script.

Oh, and be sure to enter the account information in the .vbs so it will work on your machine (yep, its a security risk- anyone could open the script’s source and read the account info- maybe make a special non-admin account for scheduled tasks?  As far as I am concerned – in the environments I work in- the account info is available to any legit user.  If we have a rogue hacker looking through our scripts, plaintext passwords are the least of our concerns.)  Context Menu Task Scheduler Script for Vbscripts

Windows Task Scheduler Management – Scheduled Task Studio

without comments

scheduled task studio - windows scheduled task manager

scheduled task studio - windows scheduled task manager

So there arent many options out there for managing Windows Scheduled Tasks. There is the bizarre Tasks folder- a special folder in xp and server 2003 that you can access on remote machines if you have admin rights (so not on xp home edition…**arghh**). You can use the schtasks.exe command line interface…
You can spend 200 or so dollars on the Task Scheduler version of Sql Sentry (http://www.sqlsentry.net/event-manager/windows-task-scheduler-enterprise.asp – very nice program imo- especially the sql agent/task scheduler version. i used the trial version for 1 sweet month… then got my allocations request denied…).
There is Task Scheduler Pro (http://www.liebsoft.com/Task_Scheduler_Pro/)- which is 500 dollars (minimum license purchase: 5. each license costs 100 dollars… when I inquired about pricing last).
There used to be EMCO Remote Task Scheduling… But I recently noticed that it was not available anymore via the EMCO Software website (http://www.emco.is/). It had a price tag (if I remember correctly) of somewhere around 150 dollars per license.
The point is- not many options if you are on a budget and need some advanced management-ability for the windows task scheduler. The company I work for uses it and Sql Server Agent exclusively for our (extensive) job-scheduling needs.
So I’m building one. Here is the (very rough) initial layout. Ive got all the standard management capability plus visual schedule management. As soon as I verify that I can redistribute the components used, I’ll post the source. As of now, I havent gotten to remote task management (the machine is hardcoded in right now), but the goal is to be able to get a complete overview of the enterprise’s scheduled task in one view, or be able to manage individual machines, etc. Id like to add job-chaining and alerting, as well as log-aggregation. If youve ever looked at the SchedLgU.Txt (the task scheduler’s log file- c:\windows\SchedLgU.Txt – its a mess to parse through. If anyones written a comprehensive parsing regex- I’d love to look at it :) ).
More on this later.

VBScript IDEs, Debuggers, Editors

without comments

This is an ongoing topic.  Im going to start with the one I use the most.  Pretty much everyday. 

VBSEdit (http://vbsedit.com/)

Pretty much all you need if you do some serious vbscripting.  Right click context menu, run lines or entire scripts and debug them from the editor.  I love the ‘Snippets’ functionality…  why oh why is this not integrated into more text editors (Notepad++, Textpad, ConText, Notepad2, PSPad, Programmers Notepad…come on now….).

Its got an object browser built into it, you can do true debugging (like visual studio – hover your mouse over a variable during runtime to see its current value…). 

And to tie it all together, a single user license (that can be used on multiple machines!!) is only $49.  It always blows my mind when Im looking at code on someone elses computer and they are using notepad.  Its so… masochistic.

vbsedit in action - vbscript ide

vbsedit in action - vbscript ide

Written by admin

August 11th, 2008 at 11:28 pm