Skip to content

Instantly share code, notes, and snippets.

@bogdanbujdea
Last active September 26, 2021 20:24
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 bogdanbujdea/76ad87eb18c96818c4ec69a32776f510 to your computer and use it in GitHub Desktop.
Save bogdanbujdea/76ad87eb18c96818c4ec69a32776f510 to your computer and use it in GitHub Desktop.
Retrieve page views from Universal Analytics property
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Google.Apis.Analytics.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
namespace GoogleUATest
{
class Program
{
static async Task Main(string[] args)
{
var credentials = PrepareCredentials();
var analyticsService = CreateAnalyticsService(credentials);
// modify this by your own needs
var startDate = "2020-10-18";
var endDate = "2021-09-25";
var metric = "ga:pageViews";
var profileId = "ga:123456";
// send the request for the page views
var getRequest = analyticsService.Data.Ga.Get(profileId, startDate, endDate, metric);
var pageViewsResponse = await getRequest.ExecuteAsync();
var views = pageViewsResponse.Rows[0][0];
Console.WriteLine($"There are {views} views in the past year");
}
private static AnalyticsService CreateAnalyticsService(ServiceAccountCredential credentials)
{
return new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "WorthlessVariable"
});
}
private static ServiceAccountCredential PrepareCredentials()
{
var certificatePath = "d:\\googlecert.p12";
var certificatePassword = "notasecret";
var accountEmailAddress = "youruser@yourapp.iam.gserviceaccount.com";
var certificate = new X509Certificate2(certificatePath, certificatePassword, X509KeyStorageFlags.Exportable);
var initializer = new ServiceAccountCredential.Initializer(accountEmailAddress)
{
Scopes = new[] {AnalyticsService.Scope.AnalyticsReadonly}
};
var credentials = new ServiceAccountCredential(
initializer.FromCertificate(certificate));
return credentials;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment