Skip to content

Instantly share code, notes, and snippets.

@LindaLawton
Last active October 7, 2020 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LindaLawton/599b2da530fd8d02726b14d9007d4f45 to your computer and use it in GitHub Desktop.
Save LindaLawton/599b2da530fd8d02726b14d9007d4f45 to your computer and use it in GitHub Desktop.
Sample code for a google analytics console application.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.AnalyticsReporting.v4.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
namespace GoogleAnalyticsConsole
{
// Instructions:
// 1. Import nuget package: Google.Apis.AnalyticsReporting.v4
// 2. Go to GoogleDeveloper console and create installed / native application credentials
// 3. Download the json credential file.
class Program
{
private const string PathToCredentialFile = "/home/development/creds/client.json";
private const string GoogleAnalyticsViewId = "7811042";
static void Main(string[] args)
{
// Initializes an Analytics Reporting API V4 service object.
var service = Init();
// Create the DateRange object.
var dateRange = new DateRange
{
StartDate = "2015-06-15",
EndDate = "2015-06-30"
};
// Create the Metrics object.
var sessions = new Metric
{
Expression = "ga:sessions",
Alias = "Sessions"
};
//Create the Dimensions object.
var browser = new Dimension
{
Name = "ga:browser"
};
// Create the ReportRequest object.
var reportRequest = new ReportRequest
{
ViewId = GoogleAnalyticsViewId,
DateRanges = new List<DateRange> {dateRange},
Dimensions = new List<Dimension> {browser},
Metrics = new List<Metric> {sessions}
};
var requests = new List<ReportRequest> {reportRequest};
// Create the GetReportsRequest object.
var getReport = new GetReportsRequest {ReportRequests = requests};
// Make the request.
var response = service.Reports.BatchGet(getReport).Execute();
// Print the results
var report = response.Reports.FirstOrDefault();
var header = report?.ColumnHeader;
var dimensionHeaders = header.Dimensions;
var metricHeaders = header.MetricHeader.MetricHeaderEntries;
foreach (var reportRow in report.Data.Rows)
{
for (var i = 0; i < dimensionHeaders.Count && i < reportRow.Dimensions.Count; i++)
{
Console.WriteLine($"{dimensionHeaders[i]}: {reportRow.Dimensions[i]}");
}
foreach (var t in reportRow.Metrics)
{
var values = t.Values;
for (var k = 0; k < values.Count; k++)
{
var entry = metricHeaders[k];
Console.WriteLine($"{entry.Name}: {values[k]}");
}
}
}
}
private static AnalyticsReportingService Init()
{
var credentials = GetUserCredential(PathToCredentialFile, "user");
return GetService(credentials);
}
/// <summary>
/// This method get a valid service
/// </summary>
/// <param name="credential">Authecated user credentail</param>
/// <returns>AnalyticsreportingService used to make requests against the Analyticsreporting API</returns>
private static AnalyticsReportingService GetService(UserCredential credential)
{
try
{
if (credential == null)
throw new ArgumentNullException("credential");
// Create Analyticsreporting API service.
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
});
}
catch (Exception ex)
{
throw new Exception("Get AnalyticsReportingService service failed.", ex);
}
}
/// <summary>
/// ** Installed Aplication only **
/// This method requests Authentcation from a user using Oauth2.
/// Credentials are stored in System.Environment.SpecialFolder.Personal
/// Documentation https://developers.google.com/accounts/docs/OAuth2
/// </summary>
/// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
/// <param name="userName">Identifying string for the user who is being authentcated.</param>
/// <param name="scopes">Array of Google scopes</param>
/// <returns>authencated UserCredential</returns>
private static UserCredential GetUserCredential(string clientSecretJson, string userName)
{
try
{
var scopes = new[]
{Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService.Scope.AnalyticsReadonly};
if (string.IsNullOrEmpty(clientSecretJson))
throw new ArgumentNullException("clientSecretJson");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
// These are the scopes of permissions you need. It is best to request only what you need and not all of them
using var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read);
// sets the location the credentials will be stored.
var credPath = Path.Combine(Directory.GetCurrentDirectory(), "credentials",
System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
// Requesting Authentication or loading previously stored authentication for userName
return GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
catch (Exception ex)
{
throw new Exception("Get user credentials failed.", ex);
}
}
}
}
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 ConsoleApp1
{
// Instructions:
// 1. Import nuget package: Google.Apis.AnalyticsReporting.v4
// 2. Go to GoogleDeveloper console and create service account credentials
// 3. Download the json credential file.
// 4. take the service account email address and add it as a user at the Account level of the Google Analytics account you wish to access.
class Program
{
private const string PathToCredentialFile = "/home/linda/development/creds/serviceAccountCreds.json";
private const string ServiceAccountEmail = "1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com";
private const string GoogleAnalyticsViewId = "7811042";
static void Main(string[] args)
{
// Initializes an Analytics Reporting API V4 service object.
var service = Init();
// Create the DateRange object.
var dateRange = new DateRange
{
StartDate = "2015-06-15",
EndDate = "2015-06-30"
};
// Create the Metrics object.
var sessions = new Metric
{
Expression = "ga:sessions",
Alias = "Sessions"
};
//Create the Dimensions object.
var browser = new Dimension
{
Name = "ga:browser"
};
// Create the ReportRequest object.
var reportRequest = new ReportRequest
{
ViewId = GoogleAnalyticsViewId,
DateRanges = new List<DateRange> {dateRange},
Dimensions = new List<Dimension> {browser},
Metrics = new List<Metric> {sessions}
};
var requests = new List<ReportRequest> {reportRequest};
// Create the GetReportsRequest object.
var getReport = new GetReportsRequest {ReportRequests = requests};
// Make the request.
var response = service.Reports.BatchGet(getReport).Execute();
// Print the results
var report = response.Reports.FirstOrDefault();
var header = report?.ColumnHeader;
var dimensionHeaders = header.Dimensions;
var metricHeaders = header.MetricHeader.MetricHeaderEntries;
foreach (var reportRow in report.Data.Rows)
{
for (var i = 0; i < dimensionHeaders.Count && i < reportRow.Dimensions.Count; i++)
{
Console.WriteLine($"{dimensionHeaders[i]}: {reportRow.Dimensions[i]}");
}
foreach (var t in reportRow.Metrics)
{
var values = t.Values;
for (var k = 0; k < values.Count; k++)
{
var entry = metricHeaders[k];
Console.WriteLine($"{entry.Name}: {values[k]}");
}
}
}
}
private static AnalyticsReportingService Init()
{
var credentials = GetServiceAccountCredentials(ServiceAccountEmail, PathToCredentialFile);
return GetService(credentials);
}
/// <summary>
/// This method get a valid service
/// </summary>
/// <param name="credential">Authecated user credentail</param>
/// <returns>AnalyticsreportingService used to make requests against the Analyticsreporting API</returns>
private static AnalyticsReportingService GetService(GoogleCredential credential)
{
try
{
if (credential == null)
throw new ArgumentNullException(nameof(credential));
// Create Analytics Reporting API service.
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name
});
}
catch (Exception ex)
{
throw new Exception("Get AnalyticsReportingService service failed.", ex);
}
}
/// <summary>
/// Authenticating to Google using a Service account
/// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
/// </summary>
/// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
/// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
/// <returns>AnalyticsService used to make requests against the Analytics API</returns>
public static GoogleCredential GetServiceAccountCredentials(string serviceAccountEmail, string serviceAccountCredentialFilePath)
{
try
{
if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
throw new Exception("Path to the service account credentials file is required.");
if (!File.Exists(serviceAccountCredentialFilePath))
throw new Exception("The service account credentials file does not exist at: " +
serviceAccountCredentialFilePath);
if (string.IsNullOrEmpty(serviceAccountEmail))
throw new Exception("ServiceAccountEmail is required.");
var scopes = new[] {AnalyticsReportingService.Scope.AnalyticsReadonly};
using var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read);
return GoogleCredential.FromStream(stream) .CreateScoped(scopes);
}
catch (Exception ex)
{
throw new Exception("CreateServiceAccountAnalyticsReportingFailed", ex);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment