articles

Show Google Analytics Data in Chart in ASP.NET MVC

Anchal Kesharwani10965 07-Oct-2014

In this article, I’m explaining an example at google analytics as chart in mvc. 

Google analytics provides powerful digital for anyone with a web presence, large or small. It is a service offered by Google that generates detailed statics of about a website’s. It’s the most widely used statics service. The Google Analytics provides the chart show the statics. The Chart provide the facility to understand the status easily. Here, I’m creating a chart in asp.net mvc for google analytics: 

Step 1 Create a MVC Project

 

First of all create a project in asp.net as CharDemoWithGA. Let’s create the project:

Show Google Analytics Data in Chart in ASP.NET MVC

 

Step 2 Basic Steps
 

If you are beginner and you have not account or not set up the tracking code service account then follow these steps.

First of set up tracking code and service if you not do:

1.       Set up the tracking code in the web.

2.       First Create service account in the Google Developers Console.

3.       Add permission for this account in the Google analytics.

4.       Use this account.

Second install the necessary api’s to connect the google analytics.

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;
Step 3 Add Code to Connect Google Analytics
 

Let’s add the code to connect with the google analytics and get the data from google analytics. Let’s add an action in controller that show pass the data.

public ActionResult Index() 
        {
              string scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue();
            string ServiceAccountUser = "1066429862823-pj1jthvgjvlqb550bn1gvkrrag362ulq@developer.gserviceaccount.com";
            string keyFile = @"D:\Anchal\MindStick-08910c775e1e.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:91047583";
            string startDate = "2014-09-11";
            string endDate = "2014-09-17";
            string metrics = "ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:visits,ga:pageValue";
            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            GaData data = request.Execute();
            List<string> ColumnName = new List<string>();
            foreach (var h in data.ColumnHeaders)
            {
                  ColumnName.Add(h.Name);
            }
            List<double> values = new List<double>();
            foreach (var row in data.Rows)
            {
                foreach (var item in row)
                {
                      values.Add(Convert.ToDouble(item));
                }


            }
              ValueList.OrderByDescending(m => m.Min());
              ViewBag.ColumnName = ColumnName;
            ViewBag.Values = values;
            return View();
          }

This code add two temporary data that include the column name and value list. It store and use after in the chart to pass the data.  

Step 4 Add Chart in View

 Now add Chart in the View. Let’s add by this code and show the chart as pie chart. Here we use by default web helper chart in mvc.
@{ 
            var myChart = new Chart(width: 600, height: 400, theme: ChartTheme.Blue)
                 .AddTitle("Google Analytics Statics")
                 .AddSeries(chartType: "pie",
                    xValue: ViewBag.ColumnName, xField: "Name",
                    yValues: ViewBag.Values, yFields: "Visits")

                 .Write();
               }

Add the chart in the index by the simple razor code. This output is given below:

Show Google Analytics Data in Chart in ASP.NET MVC

 

Successfully add the pie chart. 

I hope that this article is helpful for you. Thanks!


Updated 07-Sep-2019

Leave Comment

Comments

Liked By