articles

Home / DeveloperSection / Articles / Google Analytics in ASP.NET MVC 4

Google Analytics in ASP.NET MVC 4

Anchal Kesharwani18572 04-Oct-2014

In this article, I’m explaining the concept of google analytics with asp.net mvc. In this article I explain the how to get the from the google analytics using google analytics api.

In this article how to use the google in the asp.net mvc. This article create a simple example to get the date from analytics and show in the page.

There are some steps to create the example of google analytics with asp.net mvc.

There are following steps to create this example: 

Step 1 Create track and set up it 

First create the tracking code and add in your page or where you want on the web page. It will not activate before 24 hours. So attempt to fetch the data from google analytics after 24 hours. If you want to read how to set up the track code in my previous article.

 http://www.mindstick.com/Articles/f061cb85-9b6d-4296-9f66-9cbb15e703fb/Google%20Analytics%20Setup%20Website

Step 2 Create Google Developers Console project and set up service account

 

There are following steps to create the project and set up the service account:

1.       First of login with Google Developers Console.

2.       After that create a project with your desired name.

3.       After create the project click on the project link and select the API & auth and select APIs then search the Analytics API select it.


Google Analytics in ASP.NET MVC 4

4. Next, click on the credentials in the left side under the API & auth.

5.  Click on the Create new Client ID, this will open up a new page where you’ll tell Google how you plan on authenticating with the API. Here I select the Service account look like this:

Google Analytics in ASP.NET MVC 4

6. For this post, we need to select Service Account (as above). Click Create Client ID on the window and this will be set up. You’ll see another popup which will have a download link. Download the file and save this somewhere safe (you’ll need it later) and note the password in the popup. Every time I’ve downloaded this, the password has always been the same (notasecret), so I’m assuming it will be for you too.

7.   Let’s now see your service account will be look like this:

Google Analytics in ASP.NET MVC 4

Now login with your google analytics account and add this email address as a user on the site profile you want your data to come from.

Note: After adding the user, wait 10—15 minutes before trying to connect to the API. It didn’t work instantly for me, so perhaps the changes took a little while to propagate through. 

Step 3 Register Email in User Managements in Google Analytics
 

In the google analytics if you access al data with this then select the Account tab and go to the User Management and Add permission for this service account email id. If you every section not allowed which part select or website select.

Then follow the following steps:

1.       Select the property in the property tab.

2.       Select the View which you want to select.

3.       Then select the User Management

Google Analytics in ASP.NET MVC 4

4. After select the User Management Add permission for service account email id and then and give permission according to your use.  


 Google Analytics in ASP.NET MVC 4

Now move to the coding part. 

Step 4 Coding with the API
 

You use google analytics with google apis and dot net authentication connect the your program. There are following libraries add and this:

using DotNetOpenAuth.OAuth2; 
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.Services;
using Google.Apis.Util;

For the following examples, I’ m creating an mvc application but this code snippet also work with c#.

Ok, let’s first need to add the scope, client if, keyfile, key password.

//This is the API url which we're storing to a string 
string scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue();
//For whatever reason, this is labelled wrong. It is the email address
//that you have added as a user to your Analytics account
string ServiceAccountUser = "nnnnnnnnnnnn-nnnnnnn@developer.gserviceaccount.com";
// This physical path that download earlier file from the service account
// It is the secure file that contain the information of service account
string keyFile = @"D:\nnnnnnnnnnnnnnnnnnn.p12";
//The password Google gives you, as usually notasecret
string keyPassword = "notasecret";  

In the small code snippet we understand the scope is return the url that will help to authenticate,  ServiceAccountUser is the service account email id that will connect and key file which download from the service account in google developers console, and key password are same for all as a notasecret.

This is all key that will help to authenticate from the google analytics account and now authenticate the google analytics code by this:

AssertionFlowClient client = new AssertionFlowClient(
       GoogleAuthenticationServer.Description, new X509Certificate2(keyFile, keyPassword, X509KeyStorageFlags.Exportable))             {
                  Scope = scope,
                ServiceAccountId = ServiceAccountUser
            };
var authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);

This code authenticate with the certificate with service account user, key file and key password.

Step 5 Extracting the Data from Google Analytics
 

After the authentication successfully we need to extract the data from the google account. So let’s code to extract the data from the google analytics.

// Create the service object and hold in a variable or an object
var service = new AnalyticsService(new BaseClientService.Initializer()
{
Authenticator = authenticator
});
// It is neccessary to query
// profile of google analytics. it take numbers as View ID.
string profileId = "ga:nnnnnnnnn";
// what is start date. it is necessary
string startDate = "2014-09-11";
// what is end date. it is necessary
string endDate = "2014-09-30";
// Give the paramenter what fetch from the query
string metrics = "ga:visits,ga:pageviews,ga:users,ga:sessionDuration,ga:bounceRate";
// get the request
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
// add the paramenter as category
request.Dimensions = "ga:country";
// Execute the request and GaData get the data.
GaData data = request.Execute();

And hold to the list or your wish let’s get data from the GData.

foreach (var row in data.Rows)
            {
                int i = 0;
                foreach (var h in data.ColumnHeaders)
                {
                      //status.Add(h.Name + " " + row[i].ToString());
                      // Here get the column name and its values
                      i++;
                }
            }

Let’s Add these Code in MVC and print the data. 

Step 5 Add Code in MVC
 

Add the code as mvc use let’s create an mvc project and add this function to call this service.

public List<string>  GetAnalyticsStats()
        {

            string scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue();
            string ServiceAccountUser = "nnnnnnnnnnn-pnnnnnnnnnnnnnnnnnnnnnnnnn@developer.gserviceaccount.com";
            string keyFile = @"D:\nnnnnnnnnnnnnnn.p12";
            string keyPassword = "notasecret";
            AssertionFlowClient client = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2(keyFile, keyPassword, X509KeyStorageFlags.Exportable))
            {
                  Scope = scope,
                  ServiceAccountId = ServiceAccountUser
            };
            var authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
            var service = new AnalyticsService(new BaseClientService.Initializer()
            {
                  Authenticator = authenticator
            });
            string profileId = "ga:nnnnnnn";
            string startDate = "2014-09-11";
            string endDate = "2014-09-30";
            string metrics = "ga:visits";
            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);             request.Dimensions = "ga:country";             GaData data = request.Execute();             List<string> status = new List<string>();             foreach (var row in data.Rows)             {
                int i = 0;
                foreach (var h in data.ColumnHeaders)
                {
                      status.Add(h.Name + " " + row[i].ToString());
                      i++;
                }
            }
            return status;
          }

This return as a string that show the column name and its value. Column is show countrywide that means dimension denote the category and it return all values according to the country that means which country how many visits, pageviews, or users or session duration, etc. 

Get this data into the controller and show it in the view as like this:

 @foreach (var s in ViewBag.Status)
        {
            <p>@s</p>
          }

This show all the list in the page.

Google Analytics in ASP.NET MVC 4

Let’s enjoy this is done. I hope that this article is helpful for you. Thanks!


Updated 14-Dec-2019

Leave Comment

Comments

Liked By