Google Analytics API integration with ASP.Net


Recently I had a chance to work on Google Analytics API integration with Asp.net 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 = "https://www.google.com/analytics/feeds/data";
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("<br/>");
            Response.Write("Total Visits : " + ss);
            Response.Write("<br/>");
}

Output 

1.gif
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. 

Up Next
    Ebook Download
    View all
    Learn
    View all