Monday, 24 February 2014

Acquisition Channels Report using Google Analytics API dotNet


Introduction

Hello everyone,

In this blog, i have analysed the Google Analytic Channels data and according to it i have filtered the available data through the API to form the data for Channels report.

I have fetched the data for Default Channel Grouping labels and its detailed view.

For those who don't know, can find there Channels Report under Acquisition>Channels section. see the Screenshot below:


As we can see Channels Report is new and Google didn't provided its API's. I have analysed data under All Traffic (traffic Source), and filtered that data using filters provided by google(Filter Operation) to get appropriate result.
Use this tool: GA Tool, to analyse data before implementing it in your code.

Code

Here is the sample code, you can also download it here: Samples, put the credentials in your client_secrets.json file.
List of all Metrics and Dimensions are here: Metrics and Dimension

Social:
Fetching Social data, 
Dimension = ga:socialNetwork
Metrics   = ga:visits (change it according to your need)
Filter    = ga:socialNetwork!=(not set);ga:socialNetwork!=(none)

   //Social 
   var request = service.Data.Ga.Get(
       "ga:xxxxxx",   //GA profile id 
       "2014-02-04",  // start date 
       "2014-02-10",  // end date
       "ga:visits"    // metrices
          );
   request.Dimensions = "ga:socialNetwork";
   request.StartIndex = 1;
   request.Filters = "ga:socialNetwork!=(not set);ga:socialNetwork!=(none)";
   request.MaxResults = 10000;
   request.Sort = "-ga:visits";
   GaData results = request.Execute()

Organic Searches:
Fetching Organic data,  
Dimension = ga:sourceMedium,ga:keyword
Metrics = ga:visits (change it according to your need)
Filter  = ga:sourceMedium=@/ organic

//Organic Searches
var request = service.Data.Ga.Get(
       "ga:xxxxxx",   //GA profile id 
       "2014-02-04",  // start date 
       "2014-02-10",  // end date
       "ga:visits"    // metrices
          );

request.Dimensions = "ga:sourceMedium,ga:keyword";
request.StartIndex = 1;
request.Filters = "ga:sourceMedium=@(direct)";
request.Sort = "-ga:visits";
request.MaxResults = 10000;
results = request.Execute();

Direct:
Fetching Direct data,  
Dimension = ga:sourceMedium,ga:pagePath 
Metrics  = ga:visits (change it according to your need)
Filter    = ga:sourceMedium=@(direct)

//Direct
var request = service.Data.Ga.Get(
       "ga:xxxxxx",   //GA profile id 
       "2014-02-04",  // start date 
       "2014-02-10",  // end date
       "ga:visits"    // metrices
          );
request.Dimensions = "ga:sourceMedium,ga:pagePath";
request.StartIndex = 1;
request.Filters = "ga:sourceMedium=@(direct)";
request.Sort = "-ga:visits";
request.MaxResults = 10000;
results = request.Execute();

Email:
Fetching Email data,  Dimension = ga:sourceMedium,ga:pagePath 
Metrics = ga:visits (change it according to your need)
Filter   = ga:sourceMedium=@/ email 

//Email
var request = service.Data.Ga.Get(
       "ga:xxxxxx",   //GA profile id 
       "2014-02-04",  // start date 
       "2014-02-10",  // end date
       "ga:visits"    // metrices
          );
request.Dimensions = "ga:sourceMedium,ga:pagePath";
request.StartIndex = 1;
request.Filters = "ga:sourceMedium=@/ email";
request.Sort = "-ga:visits";
request.MaxResults = 10000;
results = request.Execute();

Other
Fetching Other data,  Dimension = ga:sourceMedium,ga:pagePath 
Metrics = ga:visits(change it according to your need)
Filter = ga:ga:sourceMedium!@(direct);ga:sourceMedium!@/ referral;ga:sourceMedium!@/ email;ga:sourceMedium!@/ organic 

//Other
var request = service.Data.Ga.Get(
       "ga:xxxxxx",   //GA profile id 
       "2014-02-04",  // start date 
       "2014-02-10",  // end date
       "ga:visits"    // metrices
          );
request.Dimensions = "ga:sourceMedium,ga:source";
request.StartIndex = 1;
request.Filters = "ga:sourceMedium!@(direct);ga:sourceMedium!@/ referral;ga:sourceMedium!@/ email;ga:sourceMedium!@/ organic";
request.MaxResults = 10000;
request.Sort = "-ga:visits";
results = request.Execute();

Download sample code Samples.

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.