Mahdi Taghizadeh I'm who I'm!

16Apr/1010

How to use Google Data API in ASP.NET MVC. Part 1 – Google Analytics

It's really amazing that Google let developers access and use its services data via GData easily. It's really easy to interact with services like Calendar, Analytics, Google Reader, Blogger, YouTube, etc. using GData.

There are also several libraries for languages and technologies to include and use in your project.

Recently I needed to use Google API in a project to interact with YouTube and Google Analytics in an ASP.NET MVC application. My scenario was not too complicated and so I decided to share my experience in two separate blog posts and you're reading the first one of this series: using GData to retrieve a websites' visitors statistics information which is monitored by Google Analytics.

As I mentioned before, my scenario was not complicated and I just wanted to retrieves total number of page views as well as today and yesterday's page views number. Ready? Here we go!

First of all you need to download GData .NET library from Google Code and add references to these assemblies in your project:

  • Google.GData.Analytics.dll
  • Google.GData.Client.dll
  • Google.GData.Extensions.dll

UPDATE: I was working on my project two months ago and I forgot to mention in my post that Google Analytics is not yet officially a part of GData .NET library. Anyway you can download it from Google Code SVN or the easier, I uploaded it here and you can get it.

Next, we need an Action method that returns information which is retrieved from GData to pass to our View:

public ActionResult Stats()
{
    string userName = ConfigurationManager.AppSettings["GoogleUsername"];
    string passWord = ConfigurationManager.AppSettings["GooglePassword"];
    string profileId = ConfigurationManager.AppSettings["GoogleAnalyticsProfileId"];

    const string dataFeedUrl = "https://www.google.com/analytics/feeds/data";

    var service = new AnalyticsService("WebSiteAnalytics");

    service.setUserCredentials(userName, passWord);

    var dataQuery = new DataQuery(dataFeedUrl)
    {
        Ids = profileId,
        Metrics = "ga:pageviews",
        Sort = "ga:pageviews",
        GAStartDate = new DateTime(2010, 3, 1).ToString("yyyy-MM-dd"),
        GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
    };

    var dataFeed = service.Query(dataQuery);

    var totalEntry = dataFeed.Entries[0];

    ViewData["Total"] = ((DataEntry)(totalEntry)).Metrics[0].Value;

    dataQuery.GAStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
    dataQuery.GAEndDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
    dataFeed = service.Query(dataQuery);

    var yesterdayEntry = dataFeed.Entries[0];
    ViewData["Yesterday"] = ((DataEntry)(yesterdayEntry)).Metrics[0].Value;
    dataQuery.GAStartDate = DateTime.Now.ToString("yyyy-MM-dd");
    dataQuery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
    dataFeed = service.Query(dataQuery);

    var todayEntry = dataFeed.Entries[0];
    ViewData["Today"] = ((DataEntry)(todayEntry)).Metrics[0].Value;

    return PartialView(dataFeed.Entries);
}

Now, let me explain the code a little. To authenticate with GData you should pass Google Username (e.g.: myusername@gmail.com), Google Password and ProfileID of website which you want to access data. This ProfileID is in this format: ga:NNNNNNN and you can find this NNNNNNN number in query string when you're logged in to your Google Analytics dashboard.

Next you define the URL of data feed which is https://www.google.com/analytics/feeds/data. Next steps are straightforward enough to understand; you create an instance of AnalyticsService and pass credentials, then send a new DataQuery to AnalyticsService object providing your query information (in this case, PageViews, StartDate and EndDate). DataFeed result which is returned from the service is an array of informtion and in our case we need its first element. If you look at my code you see that we have repeated this process to retrieve yesterday and today statistics.

I have chosen the easiest way to pass data to View which is using ViewData dictionary collection; but you can create a Model class with properties you need and bind it to your view.

Our view to show data looks like this:

< %@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
Website Stats:
  • Total: < %= ((Convert.ToInt32(ViewData["Total"]))).ToString("##,#")%>
  • Yesterday: < %= Convert.ToInt32(ViewData["Yesterday"]).ToString("##,#")%>
  • Today: < %= Convert.ToInt32(ViewData["Today"]).ToString("##,#")%>

It was a very simple sample of how to use GData to show Google Analytics data on your ASP.NET MVC powered website. I hope it helps you :-)

Next post in these series will show you how to use GData to interact with YouTube API and upload videos from your application and stream it to your visitors.

Comments (10) Trackbacks (3)
  1. Simple and useful
    Thanks

  2. Hi
    I was download Google Data API Setup(1.4.0.2).msi but can’t find Google.GData.Analytics.dll !?
    Thanks for your articles

  3. I was working on my project two months ago and I forgot to mention in my post that Google Analytics is not yet officially a part of GData .NET library. Anyway you can download it from Google Code SVN or the easier, I uploaded it here and you can get it.

  4. I see a lot of interesting posts here. I have bookmarked for future referrence.

    [WORDPRESS HASHCASH] The poster sent us ’0 which is not a hashcash value.

  5. Works – thanks. For Mahandis – the dll is in the redist folder.

  6. Hi, do you have an example how to det analytics data using Oauth without entering users’ credentials? Thanks

  7. thanks, I mooked it a bit, forgetting to preceed the ‘id’ with the ga:, but after that, was well away……

    thanks again for spending your time writing something like this to help us progress forward – didn’t know where to start with the Google docs……

    also, the analytics is now included in the main download by default now……

  8. This is really a good help. can you maybe help me with another problem?
    I have multiple profiles on my account and I would like to have a DataGridView of all the profiles with ID, AccountID, account name, ProfileID, WebPropertyID, TableID and Title

  9. anyone else having a problem with “view data” does not exist in current context?


Leave a comment