How to use Google Analytics API in Asp.net MVC

Viewed 584

I'm creating an admin panel for my website and I want to see Google Analytics datas on admin panel of my website. I did some reseach and found "Google Analytics API". How can I use GA API on admin panel of my website. I want to create some charts, maps, nice graphics to make it more understandable. Also I'm using Asp.net MVC not Php, I couldn't find any information about using GA API on Asp.net, there are infos for Php usage only...

1 Answers

The first thing you need to understand is that the data returned by the api is in Json you will need to create all the graphs yourself.
Because you will only be connecting to your own data i recommend you look into using a service account.

Service account Authentication -> serviceaccount.cs

public static class ServiceAccountExample
    {

        /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
        public static AnalyticsreportingService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                    throw new Exception("Path to the service account credentials file is required.");
                if (!File.Exists(serviceAccountCredentialFilePath))
                    throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
                if (string.IsNullOrEmpty(serviceAccountEmail))
                    throw new Exception("ServiceAccountEmail is required.");                

                // For Json file
                if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
                {
                    GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new AnalyticsreportingService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Analyticsreporting Service account Authentication Sample",
                    });
                }
                else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
                {   // If its a P12 file

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

                    // Create the  Analyticsreporting service.
                    return new AnalyticsreportingService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Analyticsreporting Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }

            }
            catch (Exception ex)
            {                
                throw new Exception("CreateServiceAccountAnalyticsreportingFailed", ex);
            }
        }
    }

things to note

First quota you can make a limited number of calls to your view per day that being 10,000 there is no way to extend that quota at this time. I recomend that you make your request once and the cashe the data in your system and use that to display as the data once processed will not change.

Processing time. It takes between 24 - 48 hours for data to complete processing on the website that means that the data you will be requesting will not be for the most recent days.

There is additional C# sample code here Samples

Related