1
votes

I'm trying to connect to Google Analytics to retrieve some information and put it into the database, my code, thus far, is this:

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

        }
    }
}

Unfortunately I'm throwing an error on my execute line, this one specifically:

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

The error itself is:

Error occurred while sending a direct message or getting the response.

Google's API documentation says that a 400:Bad Response header will be sent under the following conditions:

400 Bad Request Types of bad requests include:

  • Invalid dimensions and/or metrics

  • Quantity: either no metric, or too many dimensions/metrics

  • Using OR on a filter where one side is a metric and the other a dimension

  • Invalid filter/segment syntax

  • Illegal dimension/metric combination or advanged segment

However from what I've seen I don't meet any of those - so I'm eternally confused. How can I further go about debugging this issue?

The stack trace for this error is:

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:line 96\r\n at CCQ.GoogleToSharePoint.Program.Main(String[] args) in i:\dev\CCQ.GoogleToSharePoint\CCQ.GoogleToSharePoint\Program.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 at System.Threading.ThreadHelper.ThreadStart_Context(Object state)\r\n at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)\r\n at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)\r\n at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)\r\n at System.Threading.ThreadHelper.ThreadStart()" string

1
Have you tried your query first from Google Analytics Query Explorer? First try out here ga-dev-tools.appspot.com/explorerKamran Shahid

1 Answers

2
votes

I've been the whole weekend going trough the same problem, and I found the solution, try this code for me worked :)

log4net.Config.XmlConfigurator.Configure();

        const string ServiceAccountUser = "[email protected]";
        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();   
    }