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

Google Analytics 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 a wide range of statistics about the visitors, social networks, search engines or even Pay-Per-Click (PPC) networks and advertising.

All these statistics are comfortably accessible using 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 Analytics API (currently in version V3) is available for fetching any kind of statistics you can think of.

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

Google Analytics Reporting API

The reporting API is a simple yet powerful Application Programming Interface (API) that allows developers to retrieve the Google Analytics data gathered by Google. To retrieve the statistics, some must be gathered first. Therefore, there is one important prerequisite to use the API. You need 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 Analytics tracking code

Enabling the API Access

There are two options for fetching 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 will use 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 must be taken.

First, we need 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 will 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 Analytics API

Once turned on, we will create new credentials by clicking the “Credentials” in the menu on the left. As said above, we need to rely on OAuth if we want to access private user's data, so we will create a 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 among three types of Client IDs. Because we will use it in our desktop application, we will 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 will save it to our computer for later use. Also, we will rename it to “Csharpaccess.p12” for easier use. Please pay attention to the auto-generated private key's password “notasecret”. We will need it in our C# application, so I encourage you to write it down or save it 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 will need these credentials later, so we will copy them to some temporary text file for faster access.

Created Service Account credentials
                                          Image 9: Created Service Account credentials

From now on, we have successfully created an OAuth 2.0 access. The next step is to pair it with our website through Google Analytics.

Pairing with Google Analytics

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) using the Google Analytics User Management. As an email address, we need to use the email address that was generated for the OAuth 2.0 authentication in the previous step.

Therefore, we will use “568017249870-9pqlki56dvp3bn64hb2pnvlnais8ndes@developer.gserviceaccount.com” in the email TextBox while leaving the default Read and Analyze permission since that is all we need in this case.

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

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

Creating Simple Windows Forms Application


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

Note: We must ensure 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 the 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.Analytics.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 the additional libraries were added.

New references successfully added
            Image 12: New references successfully added

Initializing and authenticating the service

We start by declaring some variables we will 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;    
These are as follows: 
  • keyFilePath: This is the private key file we have downloaded earlier. We will copy it to the Debug folder of our project, so we don't need to add the path.

  • serviceAccountEmail: This is the email address from the Service Account credentials. If you did not write it down after the creation, you can access it anytime using the Google Developers Console.

  • keyPassword: This is the private key's password that was generated along with the key.

  • websiteCode: This is the code of the website we have paired with the Reporting API. To get the code, the fastest way is to navigate to the settings of the desired website in Google Analytics and copy the eight digit code following the letter “p” from the URL of the browser.

    Getting the website code
                                                                               Image 13: Getting the website code

  • service: This is the Analytics service that will be used for querying the statistics. We need to add “using Google.Apis.Analytics.v3;” so Visual Studio is able to resolve the type.

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 need 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 will 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 the 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 will 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 will create a new ServiceAccountCredential for the certificate. After adding the Google.Apis.Auth.OAuth2 namespace with the "using" directive, we use some variables that are already declared 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 the 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 the four parameters, the website code with the "ga:" prefix, the start date, the 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 the kinds of metrics and common data queries. For our purposes, I will use the "sessions" metric because it represents the visits we are interested in. For the date range, we will use the prior 15 days and we need 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 returned. 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's 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 in 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 will use the out-of-the-box Windows Forms 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 webmasters, there 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 a wide range of functionality and its usage is straightforward and well documented. 

Up Next
    Ebook Download
    View all
    Learn
    View all