Retrieving data from Google Analytics API using .NET/C#

10,559

Your problem is that you supply metrics in the data.ga.get method, you dont use r.metrics metrics add more them one separate them with a ,. In this case ga:visits is the metrics you are requesting.

var r = gas.Data.Ga.Get("ga:MYProfileID", "2012-01-01", "2014-02-20", "ga:visits");

Dimensions aren't a required filed so you could and remove r.Dimensions = "ga:visitCount"; see what that returns.

Remember that simply doing Google.Apis.Analytics.v3.Data.GaData d = r.Execute(); isn't going to return all the rows if there are more then what you have max result set to. You need to check your next link to make sure you don't have more rows.


Update in response to question below about next link. You currently have max-results set to 10000 which is the max number of rows that can be returned in a chunk. If there are more then 10000 rows then you will get a nextlink you need to request the the next chunk of rows. TotalResult will give you the total number of rows that you should be returning. Below I keep requesting more data using .execute until there isn't anymore Next links.

List result = new List();
 do {
     try
       {
       GaData DataList = request.Execute();  // Make the request
       result.AddRange(DataList.Rows);       // store the Data to return later
       // hack to get next link stuff
      totalResults = (!DataList.TotalResults.HasValue) ? 0 : Int32.Parse(DataList.TotalResults.ToString());
       rowcnt = rowcnt + DataList.Rows.Count;
       NextLink = DataList.NextLink;                       
       request.StartIndex = rowcnt + 1 ;
       }
      catch (Exception e)
         {
          Console.WriteLine("An error occurred: " + e.Message);
          totalResults = 0;
         }
 } while (request.StartIndex <= totalResults);
Share:
10,559
WhoAmI
Author by

WhoAmI

me = "family" + "traveling" + "history" + "programming" + "coffee" + "guitar" + "gaming";

Updated on June 04, 2022

Comments

  • WhoAmI
    WhoAmI almost 2 years

    I'm trying to retrieve data from google analytics with a local console app. Im able to extract some data without having to log in to google account and only using the API.

    The problem is i'm not getting the right values and im not sure how to format the code to extract the correct values. I wan't to retrieve all visitors within a certain time frame, in this case "2012-01-01" - "2014-02-20". The real number of visitors is like 10 times larger when looking in the Google Analytics dashboard. I'm getting a number of 15000 when debugging the code. I'm displaying d.TotalResults in the console wich might be wrong, the variable "d" contains lots of different properties.

    This is the code i'm running:

    public static void Main(string[] args)
    {
        var serviceAccountEmail = "[email protected]";
    
        var certificate = new X509Certificate2(@"C:\Users\User\Desktop\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
    
        var credential = new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(serviceAccountEmail)
        {
            Scopes = new[] { AnalyticsService.Scope.Analytics }
        }.FromCertificate(certificate));
    
        // Create the service.
        //Twistandtango
        var gas = new AnalyticsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "TestGoogleAnalytics",
        });
    
        var r = gas.Data.Ga.Get("ga:MYProfileID", "2012-01-01", "2014-02-20", "ga:visitors");
    
        //Specify some addition query parameters
        r.Dimensions = "ga:pagePath";
        r.Sort = "-ga:visitors";
        r.MaxResults = 5;
    
        //Execute and fetch the results of our query
        Google.Apis.Analytics.v3.Data.GaData d = r.Execute();
    
    
        Console.WriteLine(d.TotalResults);
        Console.ReadLine();
    }
    

    I'm trying to query the results I want with this tool https://ga-dev-tools.appspot.com/explorer/. When I implement this in my code it looks like this:

    public static void Main(string[] args)
    {
        var serviceAccountEmail = "[email protected]";
    
        var certificate = new X509Certificate2(@"C:\Users\User\Desktop\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
    
        var credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = new[] { AnalyticsService.Scope.Analytics }
                    }.FromCertificate(certificate));
    
                    // Create the service.
                    //Twistandtango
                    var gas = new AnalyticsService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "TestGoogleAnalytics",
                    });
    
                    var r = gas.Data.Ga.Get("ga:MYProfileID", "2012-01-01", "2014-02-20", "ga:visits");
    
                    //Specify some addition query parameters
                    r.Dimensions = "ga:visitCount";
                    r.Metrics = "ga:visits";
                    r.Segment = "gaid::-1";
                    //r.Sort = "-ga:visitors";
                    r.MaxResults = 10000;
    
                    //Execute and fetch the results of our query
                    Google.Apis.Analytics.v3.Data.GaData d = r.Execute();
    
    
                    Console.WriteLine(d.TotalResults);
                    Console.ReadLine();
                }
            }
    

    However after adding the metric (r.Metrics = "ga:visits";) to the project I get this error:

    Error 7 Property or indexer 'Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.Metrics' cannot be assigned to -- it is read only

    Also here's a index of classes in analytics v3:

    https://developers.google.com/resources/api-libraries/documentation/analytics/v3/csharp/latest/annotated.html

    Does anyone have knowledge of how this works? How do i retrieve total amount of visitors from the time frame i specified??

    Thx

  • WhoAmI
    WhoAmI about 10 years
    Alright think iv'e got it, thanks. Not sure what you mean by checking the next link though. Yes it would seem my app isn't querrying all visits total, just a portion of them. How would you go about collecting total visits as an alternative to the r.Execute?
  • DaImTo
    DaImTo about 10 years
    Updated to add more info on nextlink
  • Ras
    Ras almost 10 years
    I got an error where I try to add the .Rows into the result collection. What kind of type result is?