Wednesday 29 January 2014

Sample for Google Analytics Api Version 3.0 using dotnet (C#) and OAuth 2.0

Hello everyone, Recently I have worked on some cool stuff regarding Google, I want to share my experience with you all.

here is the source code download link:
https://docs.google.com/file/d/0B1Wv6jrLHNQkRTNObllUUDJNNHM/edit

Introduction

Google, as everyone knows is famous for its various online service which includes accurate search (crawling, indexing, powerful algorithm) and its online business. Google have huge amount data from all around the world, and Google Provide API's  to access its data programmatically (that's the good part i like), in this blog i will explain how to access the data from Google using .Net(c#).
Now Coming to Google Analytics, It is a online service of Google which track your website or blog and provide data like: what is the visit count, how many visitors you have, from which country you have visits, and etc. to study more about it here https://support.google.com/analytics/answer/1008065?hl=en.
Accessing the analytics API Requires following steps:
  1. OAuth (OAuth stands for Open Authentication, i will use OAuth 2.0 which is latest, OAuth 1.0 is deprecated by Google)
  2. GA API

OAuth 2.0

Suppose you have a website or application and in that you want, the user to sign up into your App. via his/her existing Google account and provide his/her data, for this we use Google OAuth Service.

Before using the OAuth in your application, you register your application in Google API Console.
Here are the steps to register your Application in Google developer console.

click here to go in Google developer console:  https://developers.google.com/
then go to: Developer Tools>API Console>Projects>Create Project
now create ClientId for Installed (Or any application you want) application and download the json file.

More detailed steps are below, follow the screens. 
(i have provided the sample code which is downloadable, its a windows form application)

1. Select Api Console



2. Under APIs and auth, select credentials then Create your client id


3. Select the application type you want


4. Then download the json file for OAuth.





I have been using OAuth a lot, now comes the interesting part, what is OAuth?

 Diagram above, explains the concept of OAuth clearly, to access the Google API you need the Access Token, which google provides you after authenticating you, that you are a valid and  registered user of Google.
You can  go through this whole article provided by Google, here https://developers.google.com/accounts/docs/OAuth2

Include the OAuth2 dll in your application:
  1. Open your Nuget package console manager.
  2. Just type in the following command :  PM> Install-Package OAuth2
  3. Put in the downloaded client_secrets.json file in your application.

Code sample for OAuth 2.0

using Google.Apis;
using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;
using System.IO;

................
................
UserCredential OAuthcredential;            
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                OAuthcredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { AnalyticsService.Scope.AnalyticsReadonly },
                    "user", CancellationToken.None, new FileDataStore("Analytics.Auth.Store")).Result;
            }
................
................

Google Analytics Service API

Include the Google analytics dll in your application:
  1. Open your Nuget package console manager.
  2. Just type in the following command :  PM> Install-Package Google.Apis.Analytics.v3 -Pre

This image below explains the conceptual view of GA.
before writing code, just try this tool: GA Tool, this tool will help you a lot for analysis.


Code:
using Google.Apis;
using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;
using System.IO;
using Google.Apis.Util.Store;
using Google.Apis.Services;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;

private void Form1_Load(object sender, EventArgs e)
        {
               //Performing OAuth 2.0
                UserCredential OAuthcredential;            
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                OAuthcredential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { AnalyticsService.Scope.AnalyticsReadonly },
                    "user", CancellationToken.None, new FileDataStore("Analytics.Auth.Store")).Result;
            }
            
           //we need to create AnalyticsService class object to use GA api
            AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = OAuthcredential,
                ApplicationName = "Analytics API sample",
            });

            ManagementResource.AccountsResource.ListRequest AccountListRequest =            service.Management.Accounts.List();

            //
            Profiles _Profiles = service.Management.Profiles.List("~all", "~all").Execute();

            if (_Profiles.Items.Count > 0)
            {
                // get sample statistics for first profile found
                var request = service.Data.Ga.Get(
                    "ga:" + _Profiles.Items[0].Id,
                    "2013-12-01", // start date 
                    "2014-01-29", // end date
                    "ga:visitors,ga:pageviews" // metrices
                    );

                request.Dimensions = "ga:date";                
                request.Sort = "ga:date";
                request.StartIndex = 1;
                request.MaxResults = 500;
                GaData results = request.Execute();
            }
}

here is the source code download link::
https://docs.google.com/file/d/0B1Wv6jrLHNQkRTNObllUUDJNNHM/edit
This code sample is for Installed Application.