1

Google アナリティクスに接続して情報を取得し、それをデータベースに入れようとしています。これまでのコードは次のとおりです。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

// Google API
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Services;
using Google.Apis.Util;


namespace CCQ.GoogleToSharePoint
{
    class Program
    {
        static void Main(string[] args)
        {
            //This is the API url which we're storing to a string
            string scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue();

            //For whatever reason, this is labelled wrong. It is the email address
            //that you have added as a user to your Analytics account

            string clientId = "<redacted>@gmail.com";


            //This is the physical path to the file we downloaded earlier
            //To demonstrate this, I've kept the full path to my key file.
            //Obviously, you will need to change this to match where you've
            //stored yours.
            string keyFile = @"<redacted>";

            //The password Google gives you, probably the same as the one below
            string keyPassword = "notasecret";


            //Store the authentication description
            AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;

            //Create a certificate object to use when authenticating
            X509Certificate2 key = new X509Certificate2(keyFile, keyPassword, X509KeyStorageFlags.Exportable);

            //Now, we will log in and authenticate, passing in the description
            //and key from above, then setting the accountId and scope
            AssertionFlowClient client = new AssertionFlowClient(desc, key)
            {
                ServiceAccountId = clientId,
                Scope = scope
            };

            //Finally, complete the authentication process
            //NOTE: This is the first change from the update above
            OAuth2Authenticator<AssertionFlowClient> auth =
                new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);

            //First, create a new service object
            //NOTE: this is the second change from the update
            //above. Thanks to James for pointing this out
            AnalyticsService gas = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = auth });

            //Create our query
            //The Data.Ga.Get needs the parameters:
            //Analytics account id, starting with ga:
            //Start date in format YYYY-MM-DD
            //End date in format YYYY-MM-DD
            //A string specifying the metrics
            DataResource.GaResource.GetRequest r = gas.Data.Ga.Get("ga:<redacted>", "2013-09-09", "2013-09-23", "ga:visitors");

            //Specify some addition query parameters
            r.Dimensions = "ga:visitorType";
            r.Sort = "-ga:visitors";
            r.MaxResults = 5;

            //Execute and fetch the results of our query
            try
            {
                //Write the column headers
                GaData d = r.Execute();

                foreach (var h in d.ColumnHeaders)
                {
                    Console.WriteLine(h.Name);
                }

                //Write the data
                foreach (var row in d.Rows)
                {
                    Console.WriteLine(row[0] + " ------ " + row[1]);
                }
            }
            catch (ProtocolException webEx)
            {
                Console.WriteLine("Protocol Exception: {0}\n\n", webEx.ToString());
                Console.WriteLine("Stack Trace: {0}", webEx.StackTrace);

                throw;
            }

        }
    }
}

残念ながら、実行行でエラーをスローしています。これは具体的には次のとおりです。

//Write the column headers
GaData d = r.Execute();

エラー自体は次のとおりです。

ダイレクト メッセージの送信中または応答の取得中にエラーが発生しました。

Google の API ドキュメントによると、400:Bad Response ヘッダーは次の条件下で送信されます。

400 Bad Request 不正なリクエストの種類は次のとおりです。

  • ディメンションや指標が無効です

  • 数量: メトリックがないか、ディメンション/メトリックが多すぎます

  • 一方がメトリックで他方がディメンションであるフィルターで OR を使用する

  • フィルタ/セグメントの構文が無効です

  • ディメンションと指標の組み合わせが正しくないか、アドバンテージ セグメントです

しかし、私が見たところ、それらのどれにも会っていないので、私は永遠に混乱しています. この問題をさらにデバッグするにはどうすればよいですか?

このエラーのスタック トレースは次のとおりです。

StackTrace " at Google.Apis.Requests.ClientServiceRequest`1.Execute() in c:\code.google.com\google-api-dotnet-client\default_3\Tools\Google.Apis.Release\bin\Debug\output\ default\Src\GoogleApis\Apis\Requests\ClientServiceRequest.cs:行 96\r\n、i:\dev\CCQ.GoogleToSharePoint\CCQ.GoogleToSharePoint\Program の CCQ.GoogleToSharePoint.Program.Main(String[] args) にあります。 cs:line 121\r\n at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)\r\n at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)\r\n at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()\r\n System.Threading.ThreadHelper.ThreadStart_Context(オブジェクト状態) で\r\n System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext、ContextCallback コールバック、オブジェクトの状態、Boolean preserveSyncCtx)\r\n System.Threading.ExecutionContext.Run(ExecutionContext executionContext、ContextCallback コールバック、オブジェクト状態、Boolean preserveSyncCtx)\r\n at System.Threading.ExecutionContext.Run(ExecutionContext executionContext、ContextCallback コールバック、オブジェクトの状態)\r\n at System.Threading.ThreadHelper.ThreadStart()" 文字列

4

1 に答える 1

2

私は週末ずっと同じ問題を抱えていましたが、解決策を見つけました。このコードを試してみてください:)

log4net.Config.XmlConfigurator.Configure();

        const string ServiceAccountUser = "xxxxxxxxxx@developer.gserviceaccount.com";
        AssertionFlowClient client = new AssertionFlowClient(
            GoogleAuthenticationServer.Description, new X509Certificate2(@"C:\xxxxxxxxxxx-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
        {
            Scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),
            ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
            //,ServiceAccountUser = ServiceAccountUser
        };
        //OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
        var authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
        var service = new AnalyticsService(new BaseClientService.Initializer()
        {
            Authenticator = authenticator
        });


        string profileId = "ga:63494033";
        string startDate = "2010-10-01";
        string endDate = "2010-10-31";
        string metrics = "ga:visits";
        DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
        request.Dimensions = "ga:date";
        GaData data = request.Execute();   
    }
于 2013-10-01T16:49:13.653 に答える