利用谷歌Analytics(分析)API检索数据的.NET / C# [英] Retrieving data from Google Analytics API using .NET/C#

查看:451
本文介绍了利用谷歌Analytics(分析)API检索数据的.NET / C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从谷歌分析数据与当地的控制台应用程序。林能提取一些数据,而无需登录到谷歌帐户,并只使用API​​。

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.

问题是我没有得到正确的价值观和林不知道如何格式化code提取正确的价值观。我wan't在一定时间范围内检索所有的游客,在这种情况下2012-01-01 - 2014年2月20日。游客的实数是像10倍看在谷歌分析仪表板时。我调试了code时,得到的15000多家。我显示在控制台至极d.TotalResults可能是错的,变量D中包含许多不同的属性。

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.

这是code我快:

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/ 。当我在code实现这个,它看起来是这样的:

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

不过添加度量后( r.Metrics =GA:探访; )的项目中,我得到这个错误:

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

错误7属性或索引Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.Metrics'不能被分配​​到 - 它是只读的。

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

另外这里的班级在分析v3的一个指标:

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

<一个href="https://developers.google.com/resources/api-libraries/documentation/analytics/v3/csharp/latest/annotated.html" rel="nofollow">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

推荐答案

您的问题是,你提供给data.ga.get方法的指标,您不使用r.metrics指标添加更多的人一用一,。在这种情况下GA:访问是您所请求的指标

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

尺寸不是必需的申请,所以你可以和删除 r.Dimensions =GA:visitCount; 看看返回。

请记住,简单地做 Google.Apis.Analytics.v3.Data.GaData D = r.Execute(); 不会返回所有行,如果有更那么你所拥有的最大结果集。你需要检查你的下一个环节,以确保你没有更多的行。

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.

响应更新以低于质疑有关下一个环节。 您目前有 MAX-结果的设置为10000这是可在一大块被返回的行的最大数量。如果有更多的则10000行,那么你将得到一个 NEXTLINK 你需要请求行的下一大块。 TotalResult会给你行,你应该返回的总数。下面我继续使用.execute,直到没有了下一个环节,要求更多的数据。

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

这篇关于利用谷歌Analytics(分析)API检索数据的.NET / C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆