Tuesday 12 May 2009

Import Data from Google Analytics VB.NET

As far as I know there is no current service available for consuming data from Google Analytics. The way I got round this was by setting up my analytics account to email me xml reports and then setting up an application to check the email account for them. When the application gets an email from Google it consumes the xml. It's best to set up a dedicated email address for analytics and save each xml document as they come in, just in case you want to change what you consume to your database at a later date and need to pull the whole lot back in again.

First get the (free) Indy Sockets dll from:
http://www.indyproject.org/index.en.aspx

The Code
' create a pop3 client using indie
Dim pop3 As New Indy.Sockets.POP3
pop3.Username = "******" 'the name of the account you get analytics to email reports to
pop3.Password = "****" 'password of the account
pop3.Host = "******" 'your mail host
pop3.Connect()

Dim nrOfMsgs As Integer = pop3.CheckMessages

For i As Integer = 1 To nrOfMsgs
Dim msg As New Indy.Sockets.Message
'get message
pop3.Retrieve(i, msg)

'attatchments
'ANALYTICS DATA

For x As Integer = 1 To msg.MessageParts.Count - 1 'search through the message parts
Dim att As Indy.Sockets.Attachment
Dim isAtt As Boolean = False

Try
att = CType(msg.MessageParts.Items(x), Indy.Sockets.Attachment)
isAtt = True
Catch
End Try
Dim ct As String = msg.MessageParts.Items(x).ContentType
If isAtt = True And InStr(msg.Subject, "the subject expected") > 0 Then
Dim stream As New Indy.Sockets.TIdNetMemoryStream
att.SaveToFile("c:\analytics\" & Now.Year & Now.Month & Now.Day & "-" & Now.Hour & Now.Minute & Now.Second & ".xml")

'here you can do whatever you like with the xml document, add all the data to your sql
'database!

End If


Next

pop3.Delete(i) 'delete the email from the server

Next




pop3.Disconnect()
pop3.Dispose()

No comments: