Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save markwemekamp/d309ed9a971cae5695cc5e545de16800 to your computer and use it in GitHub Desktop.
Save markwemekamp/d309ed9a971cae5695cc5e545de16800 to your computer and use it in GitHub Desktop.
Read data from Google analytics using Google Analytics Reporting v4 and a Service account
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.AnalyticsReporting.v4.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
namespace Google_api
{
class Program
{
static void Main()
{
try
{
var filepath = ""; // path to the json file for the Service account
var viewid = ""; // id of the view you want to read from
GoogleCredential credentials;
using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly };
var googleCredential = GoogleCredential.FromStream(stream);
credentials = googleCredential.CreateScoped(scopes);
}
var reportingService = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credentials
});
var dateRange = new DateRange
{
StartDate = "2016-07-01",
EndDate = "2016-07-31"
};
var sessions = new Metric
{
Expression = "ga:pageviews",
Alias = "Sessions"
};
var date = new Dimension { Name = "ga:date" };
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { date },
Metrics = new List<Metric> { sessions },
ViewId = viewid
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute();
foreach (var x in response.Reports.First().Data.Rows)
{
Console.WriteLine(string.Join(", ", x.Dimensions) + " " + string.Join(", ", x.Metrics.First().Values));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
@christiankersten
Copy link

christiankersten commented Nov 6, 2017

The code is broken.
I can get it to kind of connect I guess because the Console.WriteLine is working.
But it keeps loading. So my project is getting stuck when retrieving analytics data.

Please do you know what is wrong in the code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment