skip to Main Content

I have a problem, I can’t get the call to analytics to work with the example from this documentation ( Quick start ). I’ve changed some things I’ve read, since it doesn’t allow me to use the example as it is, things like the

'using Google.Analytics.Data.V1Beta;' or the part 'BetaAnalyticsDataClient client = BetaAnalyticsDataClient.Create();' I think it no longer works. Does anyone have it working? This is my code:

 using Google.Apis.AnalyticsData.v1beta;
//////

// Google Analytics 4 property ID.
 string propertyId = "407521144";

 // Credential Path
 string credentialsPath = HostingEnvironment.MapPath("~") + @"Scriptsmktwebsuitedigital-afe56dbd25f6.json";


 // Authenticate and create the service.
 GoogleCredential credential = GoogleCredential.FromFile(credentialsPath);
 AnalyticsDataService service = new AnalyticsDataService(new BaseClientService.Initializer()
 {
     HttpClientInitializer = credential,
     ApplicationName = "Google Analytics 4",
 });

 RunReportRequest request = new RunReportRequest
 {
     Property = "properties/" + propertyId,
     Dimensions = { new Dimension { Name = "city" }, },
     Metrics = { new Metric { Name = "activeUsers" }, },
     DateRanges = { new DateRange { StartDate = "2023-03-31", EndDate = "today" }, },
 };
 RunReportResponse response = service.Properties.RunReport(request, propertyId).Execute();
 // Make the request
         
 Console.WriteLine("Report result:");
 foreach (Row row in response.Rows)
 {
     Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value);
 }

I have tried this code and other variants I have researched, like the one I posted, but I can’t find a way. I know the part with the analytics id and the JSON is correct. It always fails with a

System.NullReferenceException: ‘null object’ error on the line ‘RunReportRequest request = new RunReportRequest’.

3

Answers


  1. This is my sample you should be using BetaAnalyticsDataClientBuilder

    using Google.Analytics.Data.V1Beta;
    using GoogleAnalyticsGa4Helpers;
    
    Console.WriteLine("Hello, Google Analytics data api, Service account!");
    
    // Path to the service account credentials file. 
    const string credentialsJsonPath = @"C:DevelopmentFreeLanceGoogleSamplesCredentialsServiceAccountCred.json";
    
    // Property on Google analytics which the service account has been granted access to.
    const string propertyId = "250796939";
    
    var client = new BetaAnalyticsDataClientBuilder
    {
        CredentialsPath = credentialsJsonPath
    }.Build();
    
    var metricFilter = new FilterExpression()
    {  
        Filter = new Filter()
        { FieldName = "totalUsers",
            NumericFilter = new Filter.Types.NumericFilter()
            {
                Operation = Filter.Types.NumericFilter.Types.Operation.GreaterThan,
                Value = new NumericValue() { DoubleValue = 40 }
            }
        }
    };
    
    var dimensionFilter = new FilterExpression()
    {  
        Filter = new Filter()
        { 
            FieldName = "country",
            StringFilter = new Filter.Types.StringFilter()
            {
                CaseSensitive = false,
                MatchType = Filter.Types.StringFilter.Types.MatchType.BeginsWith,
                Value = "u"
            }
        }
    };
    
    var request = new RunReportRequest
    {
        Property = "properties/" + propertyId,
        Dimensions = { new Dimension { Name = "date" }, new Dimension() { Name = "country"} },
        Metrics = { new Metric { Name = "totalUsers" }, new Metric { Name = "newUsers" } },
        DateRanges = { new DateRange { StartDate = "2021-04-01", EndDate = "today" }, },
        MetricFilter = metricFilter,
        DimensionFilter = dimensionFilter,
        OrderBys = { new OrderBy() { Metric = new OrderBy.Types.MetricOrderBy() { MetricName = "newUsers"}}}
    };
    
    var response = await client.RunReportAsync(request);
    
    // Helper Method
    response.PrintToConsole();
    
    Console.ReadLine();
    
    Login or Signup to reply.
  2. Well, the current oficial google documentation is not working, but this worked for me:

    using Google.Apis.AnalyticsData.v1beta;
    using Google.Apis.AnalyticsData.v1beta.Data;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Services;
    
    GoogleCredential credential = GoogleCredential.FromFile(YourPathToJsonFile);
    var service = new AnalyticsDataService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential
                });
    

    And then for example:

    RunReportRequest request = new RunReportRequest()
            {
    
                Property = $"properties/{YourPropertyId}",
    
                DateRanges = new List<DateRange>
                {
                    new DateRange()
                    {
                        StartDate = YourStartDate,
                        EndDate = YourEndDate
                    }
                },
    
                Dimensions = new List<Dimension>
                {
                    new Dimension()
                    {
                        Name = "eventName"
                    },
                    new Dimension()
                    {
                        Name = "customEvent:store_names"
                    },
                    new Dimension()
                    {
                        Name = "platform"
                    }
                },
    
                Metrics = new List<Metric>
                {
                    new Metric()
                    {
                        Name = "activeUsers"
                    },
                    new Metric()
                    {
                        Name = "eventCount"
                    }
                },
    
                DimensionFilter = new FilterExpression()
                {
                    AndGroup = new FilterExpressionList()
                    {
                        Expressions = new List<FilterExpression>()
                        {
                            new FilterExpression()
                            {
                                Filter = new Filter()
                                {
                                    FieldName = "eventName",
                                    StringFilter = new StringFilter()
                                    {
                                        Value = "stores"
                                    }
                                }
                            },
                            new FilterExpression()
                            {
                                Filter = new Filter()
                                {
                                    FieldName = "customEvent:type",
                                    StringFilter = new StringFilter()
                                    {
                                        Value = "enter"
                                    }
                                }
                            }
                        }
                    }
                }
            };
    
            // Execute request.
            RunReportResponse response = await service.Properties.RunReport(request, propertyId).ExecuteAsync();
    

    EDIT: The documentation is ok. My solution applies when you use Google.Apis.AnalyticsData.v1beta instead of the pre-released version

    Login or Signup to reply.
  3. The code you’ve got in the question is for the older Google.Apis.AnalyticsData.v1beta library. The more modern library used in the quickstart (and linked from the "Install the client library" step) is the more recent Google.Analytics.Data.V1Beta library, which will use gRPC+protos rather than HTTP/1.1+JSON by default.

    If you change your dependency to use Google.Analytics.Data.V1Beta, I’d expect the existing Quickstart code to work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search