I’m a big fan of wordpress and really like the Google Analyticator plugin. It provides a dashboard widget that summarizes your analytics stats. I was working on a project that had a relatively sparse admin dashboard and figured I would provide a similar view of analytics stats. The main difference is that the project I was working on was an asp.net mvc3 project.
I searched for some analytics api examples for asp.net and didn’t really find much. So hopefully this will help someone who is looking to consume gdata apis from .net. All of the code is available on github for your viewing pleasure.
What does it look like?
Authenticating with Google Data Api
Authenticating with Google is pretty simple. Google supports a variety of authentication methods including OAuth2. I’m not entirely sure why, but I chose to go with their AuthSub method of authentication. Basically, you redirect the user to a specific Google url, they authorize your application and are returned to your application with a token. You can then use that token for one-time operation or convert the token to a long lasting token that can be used repeatedly.
The code I use to authenticate looks like:
I store the long lasting token in an embedded instance of RavenDb. It’s a quick & super easy way to store things like that.
Now that you have a token from the user, you can query analytics to get data for any site that the user has access to. Google sites have a unique id associated with them, that Google calls TableId. You need to specify this value with any analytic data query. In order to get a list of available sites, you’ll need to query the account feed:
With that snippet, I organize the sites based on their associated account.
After choosing a specific site to work with, you can query information like total page views, average amount of time spent on the site, etc. The data feed explorer is quite handy in exploring the type of data that Analytics will return. For example, the following query will get a number of general stats across all pages:
Similarly, you can add dimensions to your query. Dimensions allow you to group the metrics data, similar to sql group by. The following query will get a list of pages sorted by most page views:
The UI side of things
The graph is generated using the jquery sparkline plugin. While not as sexy as the official analytics graphs, it works for a quick view. Everything else on the page is styled with twitter bootstrap, with a few minor tweaks.
That’s about it. Have a look at the complete project to get a full understanding of how I used the analytics api to build an asp.net mvc widget that summarizes website analytics.