Google Analytics API with C# – Accounts, Web Properties and Profiles 16


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 – 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!

Project Setup

Make sure your project is at least set to .net 4.0.

Add the following NuGet Package

PM> Install-Package Google.Apis.Analytic.v3

Usings

You will probably need most of these using’s

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.Apis.Analytics.v3;
using Google.Apis.Auth.OAuth2;
using System.Threading;
using Google.Apis.Util.Store;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using System.IO;

Authentication

This tutorial assumes that you have already read the tutorial about Google Analytics API Authentication with C#. I will not be going into how to create a valid Analytics service if you haven’t created one already please go read that tutorial then come back here.

[wp_ad_camp_1]

Google Analytics Management API

The management API is where all of the information about what accounts the authenticated user has access to. Before you can query any Google Analytics data you need to tell the Core Reporting API what view (profile) you want to query the data from. The way we tell the API what view (profile) we want the information for is to send it the id for that view. The best way to do this is to give your users a list, but that is easier said then done. The Google Analytics account management system can be a little confusing. A user has a list of accounts , an account could be websites, mobile apps or blogs. Each account can have more then one Web Property say different sub-domains of the website for example. Then each web property can have 1 or more views (profiles) this is the id that we need to find. Confused yet?

Google Analytics Account Summaries

The Google Analytics Account Summaries report is in my opinion the best and most efficient way of getting a complete list of the authenticated Google Analytics users account tree. You get a limited amount of data back but it is enough to display a list for the User to select from.

Google Analytics Account Summaries Response

As you can see we don’t get all of the information back, but we get enough to build from. I would have liked to see if its Universal vs Classic Analytics account, but that information isn’t in the normal account request either.

{
"kind": "analytics#accountSummaries",
 "username": "AnalyticsAccount@gmail.com",
 "totalResults": 9,
 "startIndex": 1,
 "itemsPerPage": 1000,
 "items": [
 {
 "id": "45053519",
 "kind": "analytics#accountSummary",
 "name": "Daimto",
 "webProperties": [
 {
 "kind": "analytics#webPropertySummary",
 "id": "UA-45053519-1",
 "name": "Daimto.com",
 "internalWebPropertyId": "75609005",
 "level": "STANDARD",
 "websiteUrl": "https://www.daimto.com",
 "profiles": [
 {
 "kind": "analytics#profileSummary",
 "id": "78110423",
 "name": "Default",
 "type": "WEB"
 },
 {
 "kind": "analytics#profileSummary",
 "id": "81806746",
 "name": "Ecommerce",
 "type": "WEB"
 },
 {
 "kind": "analytics#profileSummary",
 "id": "81692014",
 "name": "Testing",
 "type": "WEB"
 }
 ]
 }
 ]
 }
}

Requesting Account Summeries

You need to make a request to AccountSummeries using your authenticated AnalyticsService. This will max return 1000 rows so if you happen to run across a user that has more then 1000 Accounts, Web properties and profiles (Views) Then you will need to use the following while loop to request the next 1000 rows. Also if you do find a user that has more then a 1000 you need to contact me as I would love to hear about it 🙂

  ManagementResource.AccountSummariesResource.ListRequest list = service.Management.AccountSummaries.List();
  list.MaxResults = 1000;  // Maximum number of Account Summaries to return per request. 

  AccountSummaries feed = list.Execute();
  List allRows = new List();
          
  //// Loop through until we arrive at an empty page
  while (feed.Items != null)
   {
   allRows.AddRange(feed.Items);
          
   // We will know we are on the last page when the next page token is
   // null.
   // If this is the case, break.
   if (feed.NextLink == null)
   {
       break;
    }

   // Prepare the next page of results             
   list.StartIndex = feed.StartIndex + list.MaxResults;
   // Execute and process the next page request
   feed = list.Execute();

 }

 feed.Items = allRows;  // feed.Items not contains all of the rows even if there are more then 1000 

Displaying Account Summaries

Displaying a list for our user is a little more complicated. Remember how I said that an Authenticated user can have X number of Accounts, each Account can then have X number of Web properties, each Web properties can have 0 or more Profiles (views). In order to show a tree like list to our user we are going to have to loop though each one.

Note: Check that profile is not null there can be Web properties with out Profiles, there can not be Accounts with out Web properties. Remember this one I spent a while debugging this problem once I don’t want you to have the same problem.

//Get account summary and display them.
foreach (AccountSummary account in feed.Items)
     {
      // Account
      Console.WriteLine("Account: " + account.Name + "(" + account.Id + ")");
      foreach (WebPropertySummary wp in account.WebProperties)
        {
         // Web Properties within that account
         Console.WriteLine("\tWeb Property: " + wp.Name + "(" + wp.Id + ")");

         //Don't forget to check its not null. Believe it or not it could be.
         if (wp.Profiles != null)
           {
            foreach (ProfileSummary profile in wp.Profiles)
              {
              // Profiles with in that web property.
              Console.WriteLine("\t\tProfile: " + profile.Name + "(" + profile.Id + ")");
              }
         }
       }
     }

Google Analytics Accounts

You can select just the Accounts for a user. This will return a full Google Analytics Account resource

We use the Management.Accounts.List to get a list of Accounts back from the server. As with all of the other requests we send this against our autenticated Analytics service that we created in the Google Analytics API Authentication tutorial.

ManagementResource.AccountsResource.ListRequest list = service.Management.Accounts.List();
list.MaxResults = 1000; // Maximum number of Accounts to return, per request. 
Accounts feed = list.Execute();

To then display those Accounts to our user we could do something like this.

foreach (Account account in feed.Items)
   {
   // Account
   Console.WriteLine(string.Format("Account: {0}({1})", account.Name, account.Id));
}

Google Analytics Web Properties

You can select the Web Properties for an Account the current authenticated user has access to. This will return a full Google Analytics Web Properties resource

To get a list of web properies for an account you need to send its account id to Management.Webproperties.List this will return all of the web properties associated with that account

ManagementResource.WebpropertiesResource.ListRequest list = service.Management.Webproperties.List(accountId);
Webproperties webProperties= get.Execute();

You can then display them to the user like this

foreach (Webproperty wp in webProperties.Items)
     {
      // Web Properties within that account
     Console.WriteLine(string.Format("\tWeb Property: {0}({1})", wp.Name, wp.Id ));
}

Google Analytics Views (profiles)

You can select the profiles for a Web Property with in an Account the current authenticated user has access to. This will return a full Google Analytics Profile resource .

Note: The Google Analytics Website renamed Profiles to views in the spring of 2014, as of writing this it has not been changed in the Google Analytics API, nor have I heard an rumors that it will be changed.

If you want to see a list of profiles for a web property you must send both the web property id and the account id.

ManagementResource.ProfilesResource.ListRequest list = service.Management.Profiles.List(accountId,webPropertyId);
Profiles feed  = list.Execute();

You can then display the information to the user as follows.

foreach (Profile profile in feed.Items  )
      {
      Console.WriteLine(string.Format("\t\tProfile: {0}({1})",profile.Name,profile.Id));
      }

Conclusion

You should now understand how to access the Google Analytics Management API with an authenticated user. We have looked at how to get a quick list of our Users Account tree using the Account Summary list, as well as getting each Account, Web Property, and profile which will give us access to more information about there account then the simple results from Account Summary.

If you had any problems with this tutorial you can check the a sample project for working with Google Analytics API on GitHub as part of the Google-Dotnet-Samples project. With in that project you will find a helper class for the Management API with Google Analytics. DaimtoAnaltyicsManagmentHelper.cs


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.

16 thoughts on “Google Analytics API with C# – Accounts, Web Properties and Profiles

  • Miles Newey

    Hi Linda, this is an excellent set of tutorials, many congratulations! I am a little bit of a novice when it comes to programming, I am more of a data man rather than a programmer, however I understand a little c#, and need to get some data out of GA. I have managed to authenticate myself, however on coming to the second tutorial I am getting a ‘The name ‘service’ does not exist in the current context’ error. I am assuming this is because I am missing a reference to the api somewhere along the way? Any idea as to what I should be putting at the top of the page? This is currently what I have got:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Google.Apis.Analytics.v3;
    using Google.Apis.Auth.OAuth2;
    using System.Threading;
    using Google.Apis.Util.Store;
    using Google.Apis.Services;
    using System.Security.Cryptography.X509Certificates;
    using System.IO;
    using Google.Apis.Analytics.v3.Data;

    Many thanks for your help,

    Kind Regards, Miles – UK

    • Linda Lawton

      Glad to hear you are enjoying the tutorials. Service is the Analytics service you created in the first tutorial.
      AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
      {
      HttpClientInitializer = credential,
      ApplicationName = “Analytics API Sample”,
      });

      Hope this helps.

  • Omer

    Hello Linda,

    I am facing a challenge, when i am trying to run the below code:

    ManagementResource.AccountsResource.ListRequest AccountListRequest = service.Management.Accounts.List();
    Accounts AccountList = AccountListRequest.Execute();

    I am getting the error – Unexpected character encountered while parsing value: <. Path '', line 0, position 0.

    Please help.

    thanks

  • Leon

    Hi Linda.

    I’m using “service account”.
    Any idea why I keep getting Insufficient Permission 403 error? I can’t find where to grant the relevant permission for that? I’ve tied re-creating the p12 file. Error happens on this line: AccountSummaries feed = list.Execute();

    • Linda Lawton

      You missed part of the tutorial. The service account dosent have access to your Google Analytics account until you grant it access.

      Go to the Google Analytics website in the admin section add the service account email as a user at the account level it must be the account level.

      Linda

      • Leon

        Hi Linda.

        Thanks for your patience. Please bear with me. I did think that I did that, but maybe I’m doing it wrong. My steps in my Google Analytics account were:
        1. Click on “Admin”
        2. In the “Account” column, select the relevant account.
        3. In the “Account” column, select User Management.
        4. Add the service account email (ending @developer.gserviceaccount.com)

        The error I’m getting is Google.Apis.Requests.RequestError – Insufficient Permission [403]

        Hope you can help.

        Leon

        • Leon

          Ha, I found the answer. It was to do with the scopes. Previously I just copied the code from the example in the “Service account authentication” part. I think that example needs updating to include more scopes. I’ve now copied the scopes from the other example.
          so:
          Didn’t work:
          ————

          string[] scopes =new string[] {
          AnalyticsService.Scope.Analytics,
          AnalyticsService.Scope.AnalyticsManageUsers
          };

          Is working:
          ———-

          string[] scopes = new string[] {
          AnalyticsService.Scope.Analytics,
          AnalyticsService.Scope.AnalyticsEdit,
          AnalyticsService.Scope.AnalyticsManageUsers,
          AnalyticsService.Scope.AnalyticsReadonly
          };

          • Leon

            Dope, apologies. If I had been more on the ball in the first place, I could have looked at your code example on git hub and I would have been fine. Thanks for your patience and thanks for a great tutorial.

  • Jake K

    I have: ManagementResource.AccountsResource.ListRequest list = service.Management.Accounts.List();
    list.MaxResults = 1000; // Maximum number of Accounts to return, per request.
    Accounts feed = list.Execute();

    foreach (Account account in feed)
    {
    // Account
    Console.WriteLine(string.Format(“Account: {0}({1})”, account.Name, account.Id));
    }

    But am getting an error of: foreach statement cannot operate on variables of type ‘Google.Apis.Analytics.v3.Data.Accounts’ because ‘Google.Apis.Analytics.v3.Data.Accounts’ does not contain a public definition for ‘GetEnumerator’

    Any thoughts? the Accounts class would have been brought in through the nuget so I’m reluctant to do anything with that, feel like more so I have something wrong in my program.cs file.

    • Linda Lawton

      That’s because it should be feed.Items.

      Accounts feed = list.Execute();
      foreach (Account item in feed.Items) {
      Console.WriteLine(string.Format(“Account: {0}({1})”, account.Name, account.Id));
      }

      well spotted bug thank you Tutorial fixed.

  • Harish Belamkar

    Hi

    For authentication all scope i used in the code.

    I am using below code :

    ManagementResource.AccountSummariesResource.ListRequest list = analyticsService.Management.AccountSummaries.List();

    Here i am getting error Message = “Object reference not set to an instance of an object.”

    Please kindly let me know the reason.

    Thanks & Regards,
    Harish

      • Mike

        Hi Linda,

        not sure if I am missing something but what List type are you using? VS is looking for a generic list List if i add the section AccountSummaries feed = list.Execute();
        List allRows = new List();

        and does not want to build. Am i missing a reference for this List() type?

        Thanks in advance.

        Mike