Xceedas

Xceedas
xceedas

Monday, 22 December 2014

How to Fetch Google Analytics Statistics and Display it in Your C# Application

Google Analytic is a website statistics service offered by the internet giant Google. With the basic service being free of charge, it is definitely the most popular tool that the vast majority of webmasters rely on. It helps to gather wide range of statistics about the visitors, social networks, search engines or even PPC (pay-per-click) networks and advertising.

All these statistics are comfortably accessible through the web interface, so the webmasters can easily keep an eye on them. But what if you just need to display the statistics in your own website or desktop application? In this case, the Google Analytic API (currently in version V3) comes into place that allows fetching any kind of statistics you can think of.

Please note that discussing the whole API would be out of the scope of this article. I am going to focus solely on fetching some data (statistics) and displaying it in a form of a chart in a Windows Forms application.

Google Analytic Reporting API

The reporting API is a simple yet powerful API (application programming interface) that allows the developers to retrieve the gathered data from Google Analytic. In order to retrieve the statistics, some have to be gathered first. Therefore, there is one important prerequisite in order to use the API. You have to have a Google account and a website with the tracking code. I assume you already know how to generate the JavaScript tracking code and insert it into your website.

Google Analytics tracking code
                                          Image 1: Google Analytic tracking code

Enabling the API Access

There are two different options how to fetch the data. The first option is the Simple API access that doesn’t allow accessing any private user data, so it is not sufficient for our purpose. The second approach is the Authorized API access (OAuth 2.0) that allows us to access private user data, so we are going to stick with it.

In order to rely on OAuth 2.0, our application must be authenticated and the user must grant access to it. To do so, several steps have to be taken.

First, we have to log on to the Google Developers Console with our Google account and create a new project.

Creating Google Developers project
                                             Image 2: Creating Google Developers' project

We are going to name the project “Csharpacess” and leave the auto-generated Project ID as it is.

new project
                                                   Image 3: Creating new project

Once the project is created, we are being redirected to its dashboard. Now, we need to enable the analytics API and create a new access credentials.

created project dashboard
                                                   Image 4: Newly created project's dashboard

After clicking on “APIs” in the left menu bar, we are being taken to the APIs list. Now we scroll down to find the Analytics API and turn it on by clicking on the “OFF” button.

Enabling the Analytics API
                                                         Image 5: Enabling the Analytic API

Once turned on, we are going to create new credentials by clicking the “Credentials” in the menu on the left. As mentioned above, we need to rely on OAuth if we want to access private user’s data, so we are going to create new ID by clicking on the “Create new Client ID” button.

Creating new access credentials
                                                      Image 6: Creating new access credentials

Now, we need to choose between three types of Client ID. Because we are going to use it in our desktop application, we are going to choose the “Service account” option.

Creating the Service Account client ID
                                    Image 7: Creating the Service Account client ID

Once created, the browser will prompt us to save the private key to our computer. We will need the certificate for authentication, so we are going to save it to our computer for later use. Also, we are going to rename it to “Csharpaccess.p12” for easier use. Please pay attention to the auto-generated private key’s password – “notasecret”. We are going to need it in our C# application, so I encourage you to write it down or save to some temporary file.

Downloading the certificate
                                             Image 8: Downloading the certificate

After the download, we are being redirected back to the dashboard with the added Service account credentials. These are now accessible anytime we need to through the Google Developers Console. However, we are going to need these credentials later, so we are going to copy them to some temporary text file for faster access.

Created Service Account credentials
                                          Image 9: Created Service Account credentials

From now, we have a successfully created an OAuth 2.0 access. Next step is to pair it with our website through Google Analytic.

Pairing with Google Analytic

The Reporting API credentials we have just created can be used to access as many websites as we need to. All we need to do is add a new user for the desired website(s) through the Google Analytics’ User Management. As an email address, we have to use the email address that was generated for the OAuth 2.0 authentication in the previous step.

Therefore, we are going to put “568017249870-9pqlki56dvp3bn64hb2pnvlnais8ndes@developer.gserviceaccount.com” in the email textbox while leaving the default Read & Analyze permission as that is all we need in this case.

Adding new Google Analytics user
                                                Image 10: Adding new Google Analytic user

From now, everything is set up, so we can start Visual Studio and create our desktop application.

Creating Simple WinForms Application


I assume you already have some C# basics, so I will not talk about creating the form or the buttons. Instead, I am going to focus solely on retrieving and displaying the gathered data through the OAuth 2.0 authentication we have just created.

Note: We have to make sure, that our Visual Studio project is set to target the .NET Framework 4.0 or .NET Framework 4.5.

Adding necessary references

We start with adding some required libraries’ references. To install Google.Apis.Analytics.v3 Client Library, we use the popular NuGet Package Manager Console (Tools -> NuGet Package Manager). Open the console and use the following command to install the library: Install-Package Google.Apis.Analytic.v3

NuGet Console
                                 Image 11: Installing Google.Apis.Analytics.v3 library with NuGet Console

After the installation process is over, we can open the project’s references to verify that additional libraries were added.

New references successfully added
            Image 12: New references successfully added

Initializing and authenticating the service

We start with declaring some variables we are going to need.

  1. private string keyFilePath = @"Csharpaccess.p12";    
  2. private string serviceAccountEmail = "568017249870-9pqlki56dvp3bn64hb2pnvlnais8ndes@developer.gserviceaccount.com";    
  3. private string keyPassword = "notasecret";    
  4. private string websiteCode = "86391935";    
  5. private AnalyticsService service = null;    
Authenticating the service

For authenticating purposes, we create a private method called Authenticate.

First, we start with creating the X509Certificate2 object. In order to work with this type of object, we have to import corresponding namespace with the ‘using’ directive. The object’s constructor takes three arguments – the physical file path of the certificate, the password to access it and a storage flags that handles the private key import. We have already declared the first two arguments in the previous step and for the third one, we are going to choose Exportable from the X509KeyStorageFlags enumeration.

Don’t forget: the first parameter is the physical path and name of the certificate, so do not forget to copy the downloaded certificate to the debug folder of the project.

  1. using System.Security.Cryptography.X509Certificates;    
  2.     
  3. //loading the Key file    
  4. var certificate = new X509Certificate2(keyFilePath, keyPassword, X509KeyStorageFlags.Exportable);  
Next, we define the access scopes for the service in a form of string array. There are several scopes to choose from, but the AnalyticsReadonly is the only one we care about. However, for the purpose of this tutorial we are going to add the other ones as well.
  1. var scopes =    
  2.           new string[] {     
  3.              AnalyticsService.Scope.Analytics,              // view and manage your analytics data    
  4.              AnalyticsService.Scope.AnalyticsEdit,          // edit management actives    
  5.              AnalyticsService.Scope.AnalyticsManageUsers,   // manage users    
  6.              AnalyticsService.Scope.AnalyticsReadonly};     // View analytics data    
Now, we are going to create a new ServiceAccountCredential for the certificate. After adding the Google.Apis.Auth.OAuth2 namespace with the ‘using’ directive, we use already declared variables to create and initialize the object.
  1. using Google.Apis.Auth.OAuth2;    
  2.     
  3. var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)    
  4. {    
  5.     Scopes = scopes    
  6. }.FromCertificate(certificate));    
Finally, we create the service itself and authenticate to it. Note that we need to add Google.Apis.Services namespace first.
  1. using Google.Apis.Services;   
  2.   
  3. service = new AnalyticsService(new BaseClientService.Initializer()   
  4. {   
  5.    HttpClientInitializer = credential   
  6. });   
Querying data

For querying the Analytics data, we use the service’s Get method that populates the GetRequest object. This method takes four parameters – the website code with the ‘ga:’ prefix, start date, end date and the metrics. The first three speak for themselves. When it comes to metrics, this is basically the type of data we want to query.

For further reference I advise you to visit the Dimensions & Metrics Reference guide where you can learn about all kinds of metrics and common data queries. For our purposes, I am going to use the ‘sessions’ metric because it represents the visits we are interested in. For the date range, we are going the use the last 15 days and we have to cast it to a proper string format.

We also need to add some statistical dimensions; otherwise only aggregate values for the requested date range will be return. Because we want to query the number of daily visits and display it in a chart, we add year, month and day dimensions. Finally, we execute the request to get the data.
  1. DataResource.GaResource.GetRequest request = service.Data.Ga.Get(    
  2.                "ga:" + websiteCode,    
  3.                DateTime.Today.AddDays(-15).ToString("yyyy-MM-dd"),    
  4.                DateTime.Today.ToString("yyyy-MM-dd"),    
  5.                "ga:sessions");    
  6. request.Dimensions = "ga:year,ga:month,ga:day";    
  7. var data = request.Execute();    
Populating the visits list

For easier data manipulation and chart databinding, we have created a dummy ChartRecord class and declared a list of records in the class’ scope. 
  1.     private List<ChartRecord> visitsData = new List<ChartRecord>();    
  2.      
  3.      class ChartRecord    
  4.      {    
  5.          public ChartRecord(string date, int visits)    
  6.          {    
  7.              _date = date;    
  8.              _visits = visits;    
  9.          }    
  10.          private string _date;    
  11.          public string Date    
  12.          {    
  13.              get { return _date; }    
  14.              set { _date = value; }    
  15.          }    
  16.          private int _visits;    
  17.          public int Visits    
  18.          {    
  19.              get { return _visits; }    
  20.              set { _visits = value; }    
  21.          }    
  22.      }    
Now, we can easily iterate the requested data and fill the ChartRecord list.
  1. foreach (var row in data.Rows)    
  2. {    
  3.    visitsData.Add(new ChartRecord(new DateTime(int.Parse(row[0]), int.Parse(row[1]), int.Parse(row[2])).ToString("MM-dd-yyyy"), int.Parse(row[3])));    
  4. }    
Visually displaying the data

To visually display the requested analytics data, we are going to use the out-of-the-box WinForms chart control and databind the list to it.
  1. analyticsChart.Series[0].XValueMember = "Date";    
  2. analyticsChart.Series[0].YValueMembers = "Visits";    
  3. analyticsChart.DataSource = visitsData;    
  4. analyticsChart.DataBind();   
fetched statistics in a form of chart
                                       Image 14: fetched statistics in a form of chart

Putting it altogether
There is a demo application attached for the download. I left all the accesses enabled, so you can experiment with the API and all the metrics/dimensions available.

Conclusion

Even though the Google Analytics’s web interface is sufficient for most of webmasters, they are specific occasions when you need to display the data locally in your own application. In this case, we use the Reporting API that offers wide range of functionality and its usage is straightforward and well documented.

No comments :