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

I am trying to get data from Google Analytics using a local console application. Im can extract some data without logging into google account and only using API.

The problem is that I am not getting the correct values, and I am not sure how to format the code to retrieve the correct values. I will not receive all visitors for a certain period of time, in this case "2012-01-01" - "2014-02-20". The actual number of visitors is 10 times greater when you view the Google Analytics toolbar. When debugging the code, I get the number 15000. I show d.TotalResults in the console, which may be incorrect, the variable "d" contains many 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 am trying to query the results that 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 The property or indexer 'Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.Metrics' cannot be assigned - it is read-only

Also here is the class index in analytics v3:

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

Does anyone know how this works? How to get the total number of visitors from the time interval I specified?

thanks

+4
1

, data.ga.get, r.metrics, , ,. ga: - , .

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

, r.Dimensions = "ga:visitCount";, , .

, Google.Apis.Analytics.v3.Data.GaData d = r.Execute(); , , . , , .


. max-results 10000, , . 10000 , nextlink, . TotalResult , . .execute , . .

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);
+1

Source: https://habr.com/ru/post/1528106/


All Articles