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.
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.
Image 2: Creating Google Developers' project
We are going to name the project “Csharpacess” and leave the auto-generated Project ID as it is.
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.
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.
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.
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.
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.
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.
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.
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
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.
Image 12: New references successfully added
Initializing and authenticating the service
We start with declaring some variables we are going to need.
- private string keyFilePath = @"Csharpaccess.p12";
- private string serviceAccountEmail = "568017249870-9pqlki56dvp3bn64hb2pnvlnais8ndes@developer.gserviceaccount.com";
- private string keyPassword = "notasecret";
- private string websiteCode = "86391935";
- private AnalyticsService service = null;
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.
- using System.Security.Cryptography.X509Certificates;
- //loading the Key file
- var certificate = new X509Certificate2(keyFilePath, keyPassword, X509KeyStorageFlags.Exportable);
- var 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
- using Google.Apis.Auth.OAuth2;
- var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
- {
- Scopes = scopes
- }.FromCertificate(certificate));
- using Google.Apis.Services;
- service = new AnalyticsService(new BaseClientService.Initializer()
- {
- HttpClientInitializer = credential
- });
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.
- DataResource.GaResource.GetRequest request = service.Data.Ga.Get(
- "ga:" + websiteCode,
- DateTime.Today.AddDays(-15).ToString("yyyy-MM-dd"),
- DateTime.Today.ToString("yyyy-MM-dd"),
- "ga:sessions");
- request.Dimensions = "ga:year,ga:month,ga:day";
- var data = request.Execute();
For easier data manipulation and chart databinding, we have created a dummy ChartRecord class and declared a list of records in the class’ scope.
- private List<ChartRecord> visitsData = new List<ChartRecord>();
- class ChartRecord
- {
- public ChartRecord(string date, int visits)
- {
- _date = date;
- _visits = visits;
- }
- private string _date;
- public string Date
- {
- get { return _date; }
- set { _date = value; }
- }
- private int _visits;
- public int Visits
- {
- get { return _visits; }
- set { _visits = value; }
- }
- }
- foreach (var row in data.Rows)
- {
- 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])));
- }
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.
- analyticsChart.Series[0].XValueMember = "Date";
- analyticsChart.Series[0].YValueMembers = "Visits";
- analyticsChart.DataSource = visitsData;
- analyticsChart.DataBind();
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 :
Post a Comment