Tag Archives: google analytics

Intergrate with google analytics — retrieve data back from google analytics

Recently task need retrieve data back from google analytics and put it into the existing website. Online have a lot tutorial explain how to do it.

Here I just record my one over there hope could help my fans.

And I have a exsiting asp.net C# mvc project is on life and they are already embedded google analytics, and my job is to create a admin function so when the projects admin login there is a page display that google analytics datas.

And google already have a client side library for the .net developer to user it.

Step1: PM> Install-Package Google.Apis.Analytics.v3

Step2: For retrieve data from google analytics, you actially just need do two things.

1) Authenticate with google analytics

2) using Google analytics core reporter

I have some words about  Authenticate with google analytics, for me I personally think that just use the Service Account is fine. if you like restrict who is going to see that datas in asp.net mvc is very easily to retrieve it.

So for Authenticate with google analytics using Service Account steps:

1) you need have google account, I mean google account, could be your gmail account and could be your company email.

2)Then use you google account register a Google analytics account.

3) go to the google console enable Google analytics.

4)Create a service account by:

  • First click create a new OAuth2 projects( that is google recommend), then pop out a new window choose the service account, and download that key, put this key into your application,
  • Second don’t forget to go back to google analytics, register that service account email to give permission to this email address.

All of above things ready, now you could start write your code to using the core reporter service.

Here is my implementation class for

   
namespace XXX.XXX.Service.GAServices
{
    #region two way Authenticate with google analytics
    public  class GAAuthenticateHelper
    {
        public static AnalyticsService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath)
        {

            // check the file exists
            if (!File.Exists(keyFilePath))
            {
                Console.WriteLine("An Error occurred - Key file does not exist");
                return null;
            }

            string[] scopes = new string[] { 
                
                      AnalyticsService.Scope.Analytics,  // view and manage your analytics data
                     // AnalyticsService.Scope.AnalyticsEdit,  // edit management actives
                     // AnalyticsService.Scope.AnalyticsManageUsers,   // manage users
                      AnalyticsService.Scope.AnalyticsReadonly
                                           };     // View analytics data            

            var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
            try
            {
                ServiceAccountCredential credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                // Create the service.
                AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "GA Dashboard", // to do this
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }
        }
    }

    #endregion


    #region Google analytics core reporter
    // Google analytics query help for retrieve datas https://ga-dev-tools.appspot.com/query-explorer/
  public class GAReportingHelper
  {
      public class OptionalValues
      {
          private string dimensions { get; set; }
          private string filter { get; set; }
          private string sort { get; set; }
          private string segment { get; set; }
          private int maxResults { get; set; }
          private DataResource.GaResource.GetRequest.SamplingLevelEnum sampleingLevel = DataResource.GaResource.GetRequest.SamplingLevelEnum.DEFAULT;

          public string Dimensions { get { return dimensions; } set { dimensions = value; } }
          public string Filter { get { return filter; } set { filter = value; } }
          public string Sort { get { return sort; } set { sort = value; } }
          public string Segment { get { return segment; } set { segment = value; } }
          public int MaxResults { get { return maxResults; } set { maxResults = value; } }
          public DataResource.GaResource.GetRequest.SamplingLevelEnum Sampling { get { return sampleingLevel; } set { sampleingLevel = value; } }
          public OptionalValues()
          {
              this.dimensions = null;
              this.filter = null;
              this.sort = null;
              this.segment = null;
              this.sampleingLevel = DataResource.GaResource.GetRequest.SamplingLevelEnum.DEFAULT;
              this.maxResults = 1000;
          }
      }

      public static GaData Get(AnalyticsService service, string profileId, string startDate, string endDate, string metrics, OptionalValues optionalValues)
      {
          DataResource.GaResource.GetRequest request = service.Data.Ga.Get(String.Format("ga:{0}", profileId), startDate, endDate, metrics);
          if (optionalValues == null)
          {
              request.MaxResults = 1000;
          }
          else
          {
              request.MaxResults = optionalValues.MaxResults;
              request.Dimensions = optionalValues.Dimensions;
              request.SamplingLevel = optionalValues.Sampling;
              request.Segment = optionalValues.Segment;
              request.Sort = optionalValues.Sort;
              request.Filters = optionalValues.Filter;

          }
          return ProcessResults(request);
      }
      // Just loops though getting all the rows.  
      private static GaData ProcessResults(DataResource.GaResource.GetRequest request)
      {
          try
          {
              GaData result = request.Execute();
              List<IList> allRows = new List<IList>();
              // Loop through until we arrive at an empty page
              while (result.Rows != null)
              {
                  //Add the rows to the final list
                  allRows.AddRange(result.Rows);
                  // We will know we are on the last page when the next page token is
                  // null.
                  // If this is the case, break.
                  if (result.NextLink == null)
                  {
                      break;
                  }
                  // Prepare the next page of results             
                  request.StartIndex = request.StartIndex + request.MaxResults;
                  // Execute and process the next page request
                  result = request.Execute();
              }
              GaData allData = result;
              allData.Rows = (List<IList>)allRows;
              return allData;
          }
          catch (Exception ex)
          {
              Console.WriteLine(ex.Message);
              return null;
          }

      }
  }

#endregion


}

If you have some red line show, just use ctrl + . to add the reference.
Now I create a google analytics service class file, so in my controller, I just need call that method.
And In my controller, I create a method:

private static GADATA.GaData GaReportingDatas(AdminStatsVM model)//I only allow my admin to see, here I pass my admin data over there, and once I got the data will asign to my adminStatsVM model
        {
            AnalyticsService gaService;            
            string email = "yourserviceaccountemail@developer.gserviceaccount.com";
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"bin\yourprivatekey.p12");
  //this is your download file put here, 
            gaService = GAAuthenticateHelper.AuthenticateServiceAccount(email, path);
            string profileId = "XXXXX";//this can find in google analytics
            string metricsStr = "ga:sessions,ga:users,ga:pageviews,ga:pageviewspersession,ga:avgsessionDuration,ga:bounces,ga:percentNewSessions";//google allow pass multiply metrics by separate by comma
            string startDate = model.StartDate.ToString("yyyy-MM-dd");
            string endDate =  model.EndDate.ToString("yyyy-MM-dd"); 
            var gaData = GAReportingHelper.Get(gaService, profileId, startDate, endDate, metricsStr, null);
            return gaData;
        }

Now you can use it anyway you like.
How to renter to the page?
here in my model I have one member

 public GaData GaDatas { get; set; }

so in my controller, I assign it to

 var record = new AdminStatsVM
            {
                ...
                GaDatas = GaReportingDatas(model);//call that method above

            };

here in the view:

@foreach (var item in Model.GaDatas.Rows)
                        {
                                                        
                            foreach (string col in item)
                            {@col.FormatDigit()

} }@Model.GoogleAnalyticsUrl

What is FormatDigit(),

 public static String FormatDigit(this String input)
        {
            decimal myNum = decimal.Parse(input);           
            return  String.Format((Math.Round(myNum,2) == myNum) ? "{0:0.00}" : "{0:0}",myNum);
        }

I was following

http://www.daimto.com/google-analytics-api-v3-with-c/#Google_Analytics_API_8211_Introduction

Anything don’t understand it, could have view this link first.

very helpful.

Have fun!

Advertisements