How do I use a Service Account to Access the Google Analytics API V3 with .NET C#?

The following code, corrected from my original question, is based on the example provided by Ian Fraser at:

https://groups.google.com/forum/#!msg/google-search-api-for-shopping/4uUGirzH4Rw/__c0e4hj0ekJ

His code addressed three issues:

  1. It appears as though AnalyticsService.Scopes.AnalyticsReadonly does not work, at least not for me or the way I am doing it.
  2. For some reason, the ServiceAccountUser must be assigned to the ServiceAccountId property of the AssertionFlowClient instance.
  3. OAuth2Authenticator provides the IAuthenticator that I was looking for.

In your project, include references to:

  • Lib\DotNetOpenAuth.dll
  • Lib\Google.Apis.dll
  • Lib\Google.Apis.Authentication.OAuth2.dll
  • Services\AnalyticsService\Google.Apis.Analytics.v3.dll

namespace GoogleAnalyticsAPITest.Console
{
    using System.Security.Cryptography.X509Certificates;
    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Authentication.OAuth2;
    using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
    using Google.Apis.Util;

    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();            
            const string ServiceAccountId = "nnnnnnnnnnn.apps.googleusercontent.com";
            const string ServiceAccountUser = "[email protected]";
            AssertionFlowClient client = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2(@"value-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
            {
                Scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),
                ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
                //,ServiceAccountUser = ServiceAccountUser
            };
            OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);            
            AnalyticsService service = new AnalyticsService(authenticator);            
            string profileId = "ga:64968920";
            string startDate = "2010-10-01";
            string endDate = "2010-10-31";
            string metrics = "ga:visits";
            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            request.Dimensions = "ga:date";
            GaData data = request.Fetch();            
        }

    }
}

Leave a Comment