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

时间:2014-02-21 13:23:07

标签: c# .net google-analytics google-analytics-api gdata

我正在尝试使用本地控制台应用从Google Analytics中检索数据。我能够提取一些数据,而无需登录谷歌帐户,只使用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();
}

我正在尝试使用此工具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();
            }
        }

但是,在将度量标准(r.Metrics = "ga:visits";)添加到项目后,我收到此错误:

  

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

此处还有分析v3中的类索引:

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

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

THX

1 个答案:

答案 0 :(得分:2)

您的问题是您在data.ga.get方法中提供指标,您不使用r.metrics指标将它们与分开添加一个单独的指标。在这种情况下,ga:visits是您要求的指标。

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