Reader Level:

Google Analytics API integration with ASP.Net

By Ravi Panara on Feb 26, 2010
In this article I will demonstrate how to integrate Google Analytics API with ASP.Net.

Recently I had a chance to work on Google Analytics API integration with application.

I searched a lot through the internet but I was not satisfied with the result and finally after doing lots of R&D and taking ideas and collecting information from different sites I decided to put that kind of code under one roof. So here is the code for those who want GA data in their application.

You must have a Google account to login to let Google track your web site visits and traffics  [such a kind of job has been handled by SEO team for the page ranking procedure].

Instead of taking much time I am directly shifting to coding part for the same. Just start with the initial code snippet.

// set username and password of your google analytics account account.
string userName = "";
string passWord = "";
const string dataFeedUrl = "";
AccountQuery query = new AccountQuery();
AnalyticsService service = new AnalyticsService("AnalyticsSampleApp");
if (!string.IsNullOrEmpty(userName))
         service.setUserCredentials(userName, passWord);
string str = "";
AccountFeed accountFeed = service.Query(query);
foreach (AccountEntry entry in accountFeed.Entries)
     str = entry.ProfileId.Value;

Once you get through with GA credential process you can start doing your stuff.

The following code snippet helps you to get the total number of visits of your site; you can set the date range to retrieve the data in-between.

DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = str;
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
query1.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
            string st = entry.Title.Text;
            string ss = entry.Metrics[0].Value;
            _intVisists = Int32.Parse(ss);
            Response.Write("Total Visits : " + ss);


This is the output for your kind consideration that I have tested for my site.

The attached ZIP is a full test solution where you can find complete source code for finding overall pageviews, bounce rate, countrywise visitors etc..  and also attached required DLL for the same. 



JetBrains ReSharper Ultimate
.NET code analysis, refactorings, navigation, unit testing, code coverage and profiling in Visual Studio, a bonus for C++ devs, bundled at 50% off.

Trending up