5

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 = "MY@developer.gserviceaccount.com";

    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 = "MY@developer.gserviceaccount.com";

    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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
WhoAmI
  • 1,188
  • 6
  • 17
  • 47
  • your also selecting the PagePath your going to have to sum them all up to get the full total over all. your sure your not looking for visits vs visitors? – Linda Lawton - DaImTo Feb 21 '14 at 14:23
  • Well i'm simply looking for all visits betwen the dates i specified. All visits total, new, old etc. How can i sum them all up? Guess i havent figured out exactly how this works yet, tried different dimensions and metrics but i think im not formatting the code correctly as i don't get the results i expect. I think you can combine filters or dimensions but i'm not sure – WhoAmI Feb 21 '14 at 15:09

1 Answers1

2

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);
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • 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? – WhoAmI Feb 24 '14 at 08:05
  • Updated to add more info on nextlink – Linda Lawton - DaImTo Feb 24 '14 at 08:23
  • I got an error where I try to add the .Rows into the result collection. What kind of type result is? – Ras Jun 23 '14 at 08:57