使用.NET / C#从Google Analytics API检索数据

Who*_*AmI 5 .net c# google-analytics gdata google-analytics-api

我正在尝试使用本地控制台应用程序从Google Analytics(分析)中检索数据。我无需提取到Google帐户即可提取某些数据,而仅使用API​​。

问题是我没有获得正确的值,而且我不确定如何格式化代码以提取正确的值。我不会在特定时间范围内检索所有访客,在这种情况下,本例中为“ 2012-01-01”-“ 2014-02-20”。在Google Analytics(分析)信息中心中查看时,实际访问者人数大约是其10倍。调试代码时,我得到的数字是15000。我在控制台中显示d.TotalResults可能是错误的,变量“ d”包含许多不同的属性。

这是我正在运行的代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用此工具https://ga-dev-tools.appspot.com/explorer/查询我想要的结果。当我在代码中实现它时,它看起来像这样:

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();
            }
        }
Run Code Online (Sandbox Code Playgroud)

但是,将度量(r.Metrics = "ga:visits";)添加到项目后,出现以下错误:

错误7无法将属性或索引器“ Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.Metrics”分配给它-只读

另外,这是Analytics v3中的类索引:

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

有谁知道这是如何工作的?如何从指定的时间范围内检索访问者的总数?

谢谢

DaI*_*mTo 2

您的问题是您在 data.ga.get 方法中提供指标,而不使用 r.metrics 指标添加更多指标,并用 , 分隔它们在本例中, ga:visits 是您请求的指标。

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

尺寸不是必填字段,因此您可以删除并 r.Dimensions = "ga:visitCount"; 查看返回的内容。

请记住, Google.Apis.Analytics.v3.Data.GaData d = r.Execute(); 如果行数多于最大结果集,则简单地执行操作不会返回所有行。您需要检查下一个链接以确保没有更多行。


更新以回答以下有关下一个链接的问题。您当前将max-results设置为 10000,这是一个块中可以返回的最大行数。如果行数超过 10000 行,那么您将获得请求下一行行所需的下一个链接。TotalResult 将为您提供应返回的总行数。下面我不断使用 .execute 请求更多数据,直到不再有 Next 链接。

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);
Run Code Online (Sandbox Code Playgroud)