This example uses the official Google .net Client library.
Authorization Requires one of the following OAuth scopes:
Oauth2
// These are the scopes of permissions you need.
string[] scopes = new string[] { AnalyticsReportingService.Scope.AnalyticsReadonly }; // View your Google Analytics Data
UserCredential credential;
using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
// Requesting Authentication or loading previously stored authentication for userName
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Reporting API service.
var service = new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = string.Format("{0} Authentication", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name),
});
Reporting Request
// Create the DateRange object.
DateRange June2015 = new DateRange() { StartDate = "2015-01-01", EndDate = "2015-06-30" };
DateRange June2016 = new DateRange() { StartDate = "2016-01-01", EndDate = "2016-06-30" };
List<DateRange> dateRanges = new List<DateRange>() { June2016, June2015 };
// Create the ReportRequest object.
// This should have a large number of rows
ReportRequest reportRequest = new ReportRequest
{
ViewId = ConfigurationManager.AppSettings["GoogleAnaltyicsViewId"],
DateRanges = dateRanges,
Dimensions = new List<Dimension>() { new Dimension() { Name = "ga:date" }, new Dimension() { Name = "ga:usertype" } },
Metrics = new List<Metric>() { new Metric() { Expression= "ga:users" }, new Metric() { Expression = "ga:sessions" } },
PageSize = 1000,
};
List<ReportRequest> requests = new List<ReportRequest>();
requests.Add(reportRequest);
var getReport = new GetReportsRequest() { ReportRequests = requests };
var response = service.Reports.BatchGet(getReport).Execute();