Using the Google Analytics API with C Sharp

We've recently launched the latest version of The BMC website ( and we've had some great feedback. One of the ideas to motivate and incentivise the staff to write articles was to provide analytics for each article right in the CMS. That way they could easily see how popular their article was without having to trawl through google analytics every time.

As the site is written in web forms I went straight to to look for a c# library which at the time of writing this is still in beta. I ran into a few problems getting everything to work out of the box. Here is what I did to get everything running smoothly

OpenAuth 2.0

With version 3 of it's analytics api Google strongly pushes you to use OpenAuth 2.0, there is already a mature library which google uses in it's samples - DotNetOpenAuth to do the leg work. Unfortunately I was getting the follwing error when trying to redirect to gain authorisation;

DotNetOpenAuth.Messaging.ProtocolException was caught

Message=Precondition failed.: !authorization.AccessTokenExpirationUtc.HasValue || authorization.AccessTokenExpirationUtc < DateTime.UtcNow || authorization.RefreshToken != null

Thanks to the following thread I established I needed to add

response.Headers["Location"] += "&access_type=offline&approval_prompt=force";

to the outgoing request, this would force the refresh token to be added to the response.

Retrieving Data

Now that I could authenticate the application I could start querying analytics for data. I soon ran into a problem with the ReportResource.GetRequest.Dimensions property, internally it's converted into a List<string> but that conversion fails with.

Newtonsoft.Json.JsonSerializationException was unhandled by user code

Message=Error converting value "ga:date,ga:pagePath" to type 'System.Collections.Generic.IList`1[System.String]'.

The only way I could get it to to work was to copy the Google.Apis.Analytics.v3.cs to my project and stop using the pre compiled dll. I then changed the Dimenstions property and dimensions field of the QueryData class to type String rather than IList<String>

As I said this file is generated from Google's services so it is only a temporary solution.

As these c# libraries are only in beta hopefully these kinks can be ironed out soon.

Add a comment