Sunday, November 07, 2010

Retrieve Google Analytics Statistics Using .NET

Introduction
This article provides a class library that can help programmers to get Google analytics data using .Net. The data which is returned is of IEnumberable Class. So It can be bound to any bindable control to be viewed by user.
The attached file contains the GAConnect dll project along with a Winforms and Website project which you can use to retrieve your Google Analytics data.
Background  
I recently launched my website and wanted to show some statistical info (e.g. pages with most views) to the user. Well, I went for the best out there: Google Analytics. The last step was to be able to connect to Google Analytics and get the data from there and show it to the user. After searching for a while, I found out that Google has changed the way it handles Google Analytics requests and unfortunately, none of the code samples worked correctly. The best thing I could find was a great blog post at mikesdotnetting.com. (Although It didn't work either) Major parts of my code has been borrowed from his sample. To be able to use Google Analytics Data Export API, you'd have to get the corresponding tableId to you Analytics account. So, just knowing your trackingId will not do the trick. So I have created a Dll for .Net developers to connect to Google Analytics more easily. It makes it easier to perform the required 3 steps (Authentication, Account Query and Profile/Report Query) to be able to retrieve your data from Google Analytics. In the following chapters I will explain both how to use this Dll to connect to Google Analytics and also how these steps are carried out in the GAConnect dll itself.
Using the code
To use the code, you have to add a reference to GAConnect.dll.
Initialize and Authenticate: Create a new object of type GADataFetcher. Pass in your email address and password as the parameters. This object will carry out all the necessary steps for you to be able to get the data from Google:
var gaDataFetcher = new GADataFetcher(txtEmail.Text, txtPassword.Text);
The constructor tries to authenticate the user with the given credentials. If the authentication fails, it will throw an exception:
this.Email = email;
this.Password = password;
try
{
   Authenticate();
   BaseData.authenticationKey = AuthenticationKey;
}
catch
{
   throw;
}
Read more: Codeproject