Google Analytic’s API v3 with C# 43


Google Analytics


Have you been trying to connect your website or application to Google Analytics? Would you like to be able to show your users Google Analytics data for your website?   If you are you trying to work with the Google Analytics API in C# .net I might be able to help.   In this tutorial series we will be looking into how to connect to Google Analytics API using OAuth2, as well as a service account. I will show you how to get a list of the users Accounts to display to them from the Google Analytics Management API. Using the Meta-data API you will be able to get a full up to date list of the current available metrics and dimensions to display to your users. Finally we will look at getting data back from Google Analytics by using either the Real-time API or the Core reporting API.

Google Analytics API – Introduction

The Google Analytics API has become very extensive over the last two years. The API is in fact more the one API and those APIs are split into sevral catagories.

Collection APIs & SDKs

The collection apis are used to gather data for Google Analytics, the JavaScript on your website is using the Collection API.

Configuration APIs

Google Analytics provides programmatic access and management to configuration data through the Management API and account creation capabilities through the Provisioning API. Some of these are still in beta and you will have to request access to use them first.

Reporting APIs

Google Analytics provides a simple and powerful APIs to retrieve report data from Google Analytics. This being the Reporting API , Real-time API and Meta-Data APIs.

About

If you have been here before then you can see this tutorial has changed drastically, I have had a lot of feed back on it over the last year and have decided to split it up into separate tutorials to make things easier for you to understand. Each tutorial covers an API or a part of an API. There is a new sample project up on GitHub that should give you a working example of all of the code found in these tutorials. Note: I am not quite dome with the Advanced and upload versions for management API they are coming soon. The original post can be found here. Google Analytics API version 1

Google Analytics API – Seven part Tutorial Series

  1. Google Analytics API Introduction
  2. Google Analytics API Authentication with C# OAuth2 vs Service Account
  3. Google Analytics Management API with C#Accounts, Web Properties and views(Profiles)
  4. Google Analytics Management API with C# – Advanced
  5. Google Analytics Management API with C# – Upload
  6. Google Analytics Meta-Data API with C# – Showing current dimensions and metrics
  7. Google Analytics Real-Time API with C# – Whats happening now!
  8. Google Analytics Core Reporting API with C#  – Its all about the data baby!

Conclusion

You should now understand the different Google Analytics APIs, and know where you can find tutorials on how to use them.

The a sample project for working with Google Analytics API on GitHub


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a Reply to Linda Lawton Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

43 thoughts on “Google Analytic’s API v3 with C#

  • baongoc

    Hi Daimto,

    I followed your tutorial but still got stuck at many points. When I fix one, another will follow. Could you please share me your sample project? Btw, if I want to get list of most viewed pages, include the pages’ url and their percent, which metric I should use? (ga:visits,ga:pageviews…).

    Thank you very much!

    Ngoc

  • Daimto

    I’m working on creating sample projects for each of the tutorials. Its taking a little longer then i thought it would. Let me know what you are stuck on and i will see if i can help.

    ga:visits is session based. while ga:pagevies is a total number of pages viewed.

    If you are looking for something behavior based go with pageViews. Ff you want a more over all look i would go with visits. Check the Google analytics website see how they use them differently for the on the different reports.

  • baongoc

    Hi Daimto,

    As I remember, I got problem at reading the client_secret.json file. I decided to do other things first and I will go back to it in about 4-5 days from now. If you finish this tutorial early, please share it to my email account: ngocnb2707@gmail.com.

    Btw, if you don’t mind, may I have your email account? It’s easier to discuss using email than post comments on your blog. But it’s fine if you want to discuss the problems here so others can see and learn from it.

    Thank you very much!

    Ngoc

    P/S: You may wonder why I’m using 2 email accounts. The ngocnb2707 is for working purpose, the other for other purposes.

    • Daimto

      I’m still working on the sample project, just have management stuff done i need to add CoreReporting and MetaData still. . There’s one for the Oauth2 stuff, that you can download over on the Oauth2 C# tutorial.

  • Mathew

    Hello!,
    Really good job! I’m creating web application but i can’t get data with custom variables filtering. Can You help me? I will be very grateful.

    Mathew.

  • Matt

    Gotta say this is the best documentation I’ve found for C# Google Analytics. Thank you for the help, you saved me a lot of time!

      • Linda Lawton

        I am not sure i understand the question. If you are referring to logging the data from a website to Google analytic’s then you are in the wrong place, you need to be looking at the Google Analytics tracking code not the API.

        If you want to extract Google Analytics Data from your own machine “localhost” and display it, then yes you can do that.

  • Sandy

    I am getting error “Access to the path ‘Analytics.Auth.Store’ is denied”, then I am logged in with Administrator account, I am getting the same error. Please suggest.

    • Sandy

      I am getting error “Access to the path ‘Analytics.Auth.Store’ is denied”, then I am logged in with Administrator account, I am getting the same error. Please suggest.

  • oksummer

    thank you share your experence,I use flowing code juse pop up ie to authorization,click accept button will auto close ie,the programe have no run the AnalyticsService service = new AnalyticsService

    this is core code juse as your example
    private void Form1_Load(object sender, EventArgs e)
    {

    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
    new ClientSecrets { ClientId = “476722162707-762q8okvs601tbed8bh9mfr6eb9piekd.apps.googleusercontent.com”, ClientSecret = “_JEEWsIsHQdLArJTtx3c2AAw” },
    new[] { AnalyticsService.Scope.AnalyticsReadonly },
    “user”,
    CancellationToken.None,
    new FileDataStore(“Analytics.Auth.Store”)).Result;

    // no run here why not?
    AnalyticsService service = new AnalyticsService(
    new BaseClientService.Initializer()
    {
    HttpClientInitializer = credential,
    ApplicationName = “Analytics API sample”,
    });
    }

      • oksummer

        break point set line in “AnalyticsService service = new AnalyticsServic “,but nothing happen, credential cannot be monitor.

        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        new ClientSecrets { ClientId = “476722162707-762q8okvs601tbed8bh9mfr6eb9piekd.apps.googleusercontent.com”, ClientSecret = “_JEEWsIsHQdLArJTtx3c2AAw” },
        new[] { AnalyticsService.Scope.AnalyticsReadonly },
        “user”,
        CancellationToken.None,
        new FileDataStore(“Analytics.Auth.Store”)).Result;

        // no run here why not?
        AnalyticsService service = new AnalyticsService(

  • Mario Sertori

    I tested the code and it works fine but when I collect the data I got an error on “result.Add(DataList.Rows)”.
    What kind of type the list “result” is? “List” is not recognized by my copy of VS2012 (I put the code in a webapp)

  • Tom Winans

    DaimtoProfile? Also FileDataStore? Could you please point to the namespace of the FileDataStore? And I am not sure where the D…Profile is defined … I fear the example is out of synch with current libs …

    Thanks

  • Wasfa

    Hi Linda

    Can you please explain how can i call StoreAsync method to store refresh token and other information.I followed your example.It is calling GetAsync method which reads the file contents but in my case code is creating directory but not file to store token info.How can i create that file.
    Need your help.

    • Linda Lawton

      I have another example of idatastore here. One stores the file in the current directory the other one stores it in the database. you can debug your way though them. I have found it very technical and haven’t had time to sit down and try and make a SIMPLE tutorial for it. I like my tutorials to be simple so doing this simple isn’t easy.

  • t_plusplus

    I really don’t know how to thank you for your great tutorials and the sample code that you provided. Really thank you!

  • Harish Belamkar

    Hi Linda,

    I am using below code to read to Custom dimension and custom metrics getting error.
    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Services;
    using Google.Apis.Util.Store;

    Google.Apis.Analytics.v3.ManagementResource.CustomDimensionsResource.ListRequest request = analyticsService.Management.CustomDimensions.List(accountId, propertyID);

    Error 19 ‘Google.Apis.Analytics.v3.ManagementResource’ does not contain a definition for ‘CustomDimensions’ and no extension method ‘CustomDimensions’ accepting a first argument of type ‘Google.Apis.Analytics.v3.ManagementResource’ could be found (are you missing a using directive or an assembly reference?)

    Please let me know your comment ASAP.
    Thanks & Regards,
    Harish Belamkar

      • Harish Belamkar

        var result = analyticsService.Management.CustomDimensions.List(accountId, propertyID).Execute();
        result.MaxResults = 100;

        Please check the code passing value from different class to method GetCDandCMData();

        Error :
        ‘Google.Apis.Analytics.v3.ManagementResource’ does not contain a definition for ‘CustomDimensions’ and no extension method ‘CustomDimensions’ accepting a first argument of type ‘Google.Apis.Analytics.v3.ManagementResource’ could be found (are you missing a using directive or an assembly reference?)

  • FRANCIS ELENDU

    Nice post. Please let me know when the sample project for the tutorials is ready. It will really help us. Thanks for your efforts.