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
This is my sample you should be using
BetaAnalyticsDataClientBuilder
Well, the current oficial google documentation is not working, but this worked for me:
And then for example:
EDIT: The documentation is ok. My solution applies when you use Google.Apis.AnalyticsData.v1beta instead of the pre-released version
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.