How to use Google Analytics API in Asp.net MVC - c#

I'm creating an admin panel for my website and I want to see Google Analytics datas on admin panel of my website. I did some reseach and found "Google Analytics API". How can I use GA API on admin panel of my website. I want to create some charts, maps, nice graphics to make it more understandable. Also I'm using Asp.net MVC not Php, I couldn't find any information about using GA API on Asp.net, there are infos for Php usage only...

The first thing you need to understand is that the data returned by the api is in Json you will need to create all the graphs yourself.
Because you will only be connecting to your own data i recommend you look into using a service account.
Service account Authentication -> serviceaccount.cs
public static class ServiceAccountExample
{
/// <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 AnalyticsreportingService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
{
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.");
// For Json file
if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
{
GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}
// Create the Analytics service.
return new AnalyticsreportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Analyticsreporting Service account Authentication Sample",
});
}
else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
{ // If its a P12 file
var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
// Create the Analyticsreporting service.
return new AnalyticsreportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Analyticsreporting Authentication Sample",
});
}
else
{
throw new Exception("Unsupported Service accounts credentials.");
}
}
catch (Exception ex)
{
throw new Exception("CreateServiceAccountAnalyticsreportingFailed", ex);
}
}
}
things to note
First quota you can make a limited number of calls to your view per day that being 10,000 there is no way to extend that quota at this time. I recomend that you make your request once and the cashe the data in your system and use that to display as the data once processed will not change.
Processing time. It takes between 24 - 48 hours for data to complete processing on the website that means that the data you will be requesting will not be for the most recent days.
There is additional C# sample code here Samples

Related

What is the simplest way to create event in G calendar using C# / .NET

! Solution added by me below !
Issue:
I am building a windows form using c# / .NET and I want to add a functionality to add a event in my personal google calendar. I've been researching over the internet for a few days already but every solution I find seems overcomlicated.
All I need is:
event title = textbox1.text;
event description = textbox2.text;
event date = datetimepicker.text;
addEvent();
But I don't know how to write it and I couldn't find any solution that is simple as that (most solutions were overcomplicated). I can tell I have some hobby experience coding, enough to build a simple project, but I confess that this is above my level and I need some guidance.
I think I've already set Calendar API and Google SDK. Also installed Google Calendars NuGet package in Visual Studio, but I will appreciate if there is way to make a connection by password and username instead of API & SDK.
Thanks in advance!
! Solution !
With the initial help of #Dalmto, I managed to link his code to a button and actually make it fire a event, because previosuly it didn't.
Here is my final code you can use it simply as copy paste. Just add your credentials.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.IO;
using System.Threading;
using Google.Apis.Calendar.v3.Data;
namespace googleCalendarTesting
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string clientSecretJson = ""; //add your json path here
string userName = ""; // add your google account here
string[] scopes = new string[n] {"n1", "n2", "n3" }; // replace n with the number of scopes you need and write them one by one
CalendarService service = GetCalendarService(clientSecretJson, userName, scopes);
Event newEvent = new Event()
{
Summary = "event title",
Description = "event description",
Start = new EventDateTime()
{
DateTime = DateTime.Parse("2022-02-28T09:00:00-07:00"),
TimeZone = "America/Los_Angeles",
},
End = new EventDateTime()
{
DateTime = DateTime.Parse("2022-02-28T09:00:00-08:00"),
TimeZone = "America/Los_Angeles",
},
}; //// more options here https://developers.google.com/calendar/api/v3/reference/events/insert#.net
String calendarId = "primary"; // choose a calendar in your google account - you might have multiple calendars
EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId);
Event createdEvent = request.Execute();
}
public static CalendarService GetCalendarService(string clientSecretJson, string userName, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(clientSecretJson))
throw new ArgumentNullException("clientSecretJson");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
var cred = GetUserCredential(clientSecretJson, userName, scopes);
return GetService(cred);
}
catch (Exception ex)
{
throw new Exception("Get Calendar service failed.", ex);
}
}
private static UserCredential GetUserCredential(string clientSecretJson, string userName, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
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))
{
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
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
credential.GetAccessTokenForRequestAsync();
return credential;
}
}
catch (Exception ex)
{
throw new Exception("Get user credentials failed.", ex);
}
}
private static CalendarService GetService(UserCredential credential)
{
try
{
if (credential == null)
throw new ArgumentNullException("credential");
// Create Calendar API service.
return new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar Oauth2 Authentication Sample"
});
}
catch (Exception ex)
{
throw new Exception("Get Calendar service failed.", ex);
}
}
}
}
scopes I used in my project:
https://www.googleapis.com/auth/calendar,
https://www.googleapis.com/auth/calendar.events,
https://www.googleapis.com/auth/calendar.events.readonly
I will appreciate if there is way to make a connection by password and username instead of API & SDK.
No, This is called client login and google shut that option down in 2015.
I want to add a functionality to add a event in my personal google calendar.
I am going to assume by personal google calendar that you mean a standard gmail account google calendar.
In order to do this you will need to use Oauth2 request offline access authorize your application once. After that you should have a refresh token stored.
The code for this is resonably strait forward
Oauth2Authentication.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.IO;
using System.Threading;
namespace GoogleSamplecSharpSample.Calendarv3.Auth
{
public static class Oauth2Example
{
/// <summary>
/// ** Installed Aplication only **
/// This method requests Authentcation from a user using 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>CalendarService used to make requests against the Calendar API</returns>
public static CalendarService GetCalendarService(string clientSecretJson, string userName, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(clientSecretJson))
throw new ArgumentNullException("clientSecretJson");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
var cred = GetUserCredential(clientSecretJson, userName, scopes);
return GetService(cred);
}
catch (Exception ex)
{
throw new Exception("Get Calendar 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, string[] scopes)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
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))
{
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
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
credential.GetAccessTokenForRequestAsync();
return credential;
}
}
catch (Exception ex)
{
throw new Exception("Get user credentials failed.", ex);
}
}
/// <summary>
/// This method get a valid service
/// </summary>
/// <param name="credential">Authecated user credentail</param>
/// <returns>CalendarService used to make requests against the Calendar API</returns>
private static CalendarService GetService(UserCredential credential)
{
try
{
if (credential == null)
throw new ArgumentNullException("credential");
// Create Calendar API service.
return new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar Oauth2 Authentication Sample"
});
}
catch (Exception ex)
{
throw new Exception("Get Calendar service failed.", ex);
}
}
}
}
This code will store the credentials to your personal google calendar account in a file in credPath directory on your machine. You may need to change this directory if you are storing it up on a server.
When you run it the first time (i recommend doing this locally) it will populate that file with a refresh token. The code will then use the refresh token to request a new access token when ever it needs it.
A few notes on this. You will need to set your project to production in google cloud console or your refresh token will only be valid for seven days. You also must be sure that this refresh token is used once every six months or it will expire. If it fails to load the refresh token this code will fail as it is designed for installed applications. This is probably a good thing as you do not a web hosted application to be requesting the users consent to their personal google calendar accounts.
service account note.
Most google apis support something called service account authentication. it is used to pre authorize account access. Google calendar only supports service account authorization for Google workspace accounts not for standard gmail accounts.
If you want to do this with a service account it would be easer but again you would need to register a workspace account and then you could only use it with that not with standard gmail accounts.
You need an API Key from the Google Developer Dashboard (https://console.developers.google.com/apis/dashboard?pli=1) in order to connect to your Calendar and reading or writing events to your calendar. Plain username and password will not work (as far as I know).
The documentation of Google is pretty straight forward and explains every step in order to retrieve events from the API.
https://developers.google.com/calendar/api/quickstart/dotnet
After understanding the SDK you can enhance your application to add events to your calendar.
If I have got the time, I will link one of my GitHub Repos with an example that you can refer.
Edit: As DalmTo mentioned, I did not create an API Key. I created Client Credentials withe the Developer Dashboard. How to create these credentials is also mentioned in the quickstart guide.

Using OAuth2 to Authenticate with a Google API in C#

I have created an console application that uses OAuth2 to authenticate with the GoogleAnalyticsApiV4 to query some data. The application works as intended but we would like to automate the process so the application can be scheduled to run once a day. The problem here is the application would be hosted on azure and there is no way for a user to accept the authentication request with google that pops up in a browser the first time the application runs.
Following posts online and googles documentation my current solution to authenticate is this
try
{
var credential = GetCredential().Result;
using (var svc = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Google Analytics API Console"
}))
{
///// Query some data/////
}
static async Task<UserCredential> GetCredential()
{
using (var stream = new FileStream("client_secret.json",
FileMode.Open, FileAccess.Read))
{
string loginEmailAddress = ConfigurationManager.AppSettings["GoogleUsername"];
return await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { AnalyticsReportingService.Scope.Analytics },
loginEmailAddress, CancellationToken.None,
new FileDataStore("GoogleAnalyticsApiConsole"));
}
}
This solution works perfectly well to authenticate with Google as long as a user is available to input credentials and accept the authentication request. Unfortunately as soon as the application is moved to another machine it needs to re-authenticate and a user needs to input credentials again and accept the request.
I have been searching for a way to take the User out of the process so the application can run on azure but have not found anything clear on how to do this in c#.
Please can someone either describe how i can authenticate my application with google without a user, or point me in the direction of documentation that accurately covers the process.
An help or examples would be greatly appreciated.
You have a couple of options.
Is this an account you have access to. If it is then you can use a service account. Service accounts are preauthorized the you take the service account email address and add it as a user in Google analytics admin at the account level and the service account will be able to access the account for as long as it is valid. No pop up window is required. I have some sample code on how to authenticate with a service account here
/// <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 AnalyticsReportingService AuthenticateServiceAccount(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.");
// These are the scopes of permissions you need. It is best to request only what you need and not all of them
string[] scopes = new string[] { AnalyticsReportingService.Scope.Analytics }; // View your Google Analytics data
// For Json file
if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
{
GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}
// Create the Analytics service.
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "AnalyticsReporting Service account Authentication Sample",
});
}
else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
{ // If its a P12 file
var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
// Create the AnalyticsReporting service.
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "AnalyticsReporting Authentication Sample",
});
}
else
{
throw new Exception("Unsupported Service accounts credentials.");
}
}
catch (Exception ex)
{
Console.WriteLine("Create service account AnalyticsReportingService failed" + ex.Message);
throw new Exception("CreateServiceAccountAnalyticsReportingFailed", ex);
}
}
If this isn't something you can do. Then you should be aware of the fact that filedatastore() by default stores your credentials in %appData% you could simply copy that file onto the new server along with the code.
You can also move the location to some were other then %appData% by using the following code:
new FileDataStore(#"c:\datastore",true)
I have a tutorial on how filedatastore works. here File datastore demystified
Preauthorizing service account to Google Analytics. Admin section of the Google analytics website. Grant it read access should be more then enough.

Alexa skill w/ Account Linking and gmail API .NET - Authentication

I have created an Alexa skill and enabled account linking. Setup my skills configuration to point to googles authorization and token servers, the skill successfully links. Then alexa sends POST Requests to my service that include the access token and state from Google. I use this to validate the token and what I want to do is use the token to access gmail api and begin calling actions.
However, the only examples online I can find include re-building the gmailservice by using the client secret and client id again. I figure since I have the access token already, why do I need to include the secret and ID again? How can i make gmail api calls with the access token I already have, or is this not possible? Here's the code I'm trying to use:
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
// List labels.
IList<Label> labels= request.Execute().Labels;
Console.WriteLine("Labels:");
if (labels != null && labels.Count > 0)
{
foreach (var labelItem in labels)
{
Console.WriteLine("{0}", labelItem.Name);
}
}
else
{
Console.WriteLine("No labels found.");
}
Console.Read();
I don't want to include the client_secret.json file because I already was authorized by google's oauth process in the alexa skill's account linking. Help ?

Gmail API service account

I want to read my gmail inbox using Gmail API. I need to use a service account due my application haven't user interaction.
I get a following error on request:
"InnerException = {"Error:\"unauthorized_client\", Description:\"Unauthorized client or scope in request.\", Uri:\"\""} "
This is my code:
string applicationName = "Gmail API .NET";
string[] scopes = { GmailService.Scope.GmailReadonly };
string certPath = "./XXXXXXXXXX.p12";
string userEmail = "MYEMAIL#gmail.com";
string serviceAccountEmail = "MYSERVICEACCOUNT...am.gserviceaccount.com";
//Carga el certificado obtenido de
var certificate = new X509Certificate2(certPath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = userEmail,
Scopes = scopes
}.FromCertificate(certificate)
);
if (credential.RequestAccessTokenAsync(CancellationToken.None).Result) <--- Here I get the error
{
GmailService gs = new GmailService(
new BaseClientService.Initializer()
{
ApplicationName = applicationName,
HttpClientInitializer = credential
}
);
}
What am I doing wrong? Can anybody help me?
Regards
Try to check this documentation about service account in .NET libraries. This documentation also provides you a sample code that you can follow on how to setup service account. This link can also give you idea on how to access GMAIL API using Service Account.
Now, for the error that you receive, check this links if it can help you.
Does the Gmail API support using OAuth Service Accounts?
Gmail Api return Unauthorized client or scope in request
You can only use a service account to send emails for a GSuite account and not a gmail account.
If you have a gmail account you can use 3-legged OAuth2 authentication
Or turn on 2FA, generate an App Password and use that as seen here
If you ARE using a GSuite account you can use the ServiceAccount but you will have to make sure it has G Suite Domain-wide Delegation as described here and then you need to give access to the GSuite Domain as described here
Have you tried the sample code from Google for this function?
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
// ...
public class MyClass {
// ...
/// <summary>
/// Retrieve a Message by ID.
/// </summary>
/// <param name="service">Gmail API service instance.</param>
/// <param name="userId">User's email address. The special value "me"
/// can be used to indicate the authenticated user.</param>
/// <param name="messageId">ID of Message to retrieve.</param>
public static Message GetMessage(GmailService service, String userId, String messageId)
{
try
{
return service.Users.Messages.Get(userId, messageId).Execute();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
return null;
}
// ...
}
Have you tried the API explorer here: https://developers.google.com/gmail/api/v1/reference/users/messages/get#net
and entered your request information? Did it work from the API page?
Service accounts cannot access #gmail.com mailboxes. You must use one of the other supported OAuth 2.0 authorization scenarios described at https://developers.google.com/identity/protocols/OAuth2.
See
https://stackoverflow.com/a/39534420/3377170 for more details.

YouTube v3 API caption download using SDK nuget package

I'm trying to download a caption track using YouTube API v3 (https://developers.google.com/youtube/v3/docs/captions/download) and official .NET SDK nuget package (https://www.nuget.org/packages/Google.Apis.YouTube.v3/, version 1.9.0.1360).
Returned stream contains the following text:
"The OAuth token was received in the query string, which this API forbids for response formats other than JSON or XML. If possible, try sending the OAuth token in the Authorization header instead."
instead of the SRT plain text content which I just uploaded and verified manually through YouTube.com UI.
I found the type of error: lockedDomainCreationFailure
My code:
...
_service = new YTApi.YouTubeService(new BaseClientService.Initializer {
ApplicationName = config.AppName,
ApiKey = config.DeveloperKey
});
...
public Stream CaptionsDownload(
string accessToken,
string trackId
)
{
var request = _service.Captions.Download(trackId);
request.OauthToken = accessToken;
request.Tfmt = YTApi.CaptionsResource.DownloadRequest.TfmtEnum.Srt;
var trackStream = new MemoryStream();
request.Download(trackStream);
trackStream.Position = 0;
return trackStream;
}
I cannot seem to find the way to set any headers on _service.HttpClient, and I guess I shouldn't do it manually. I expect that DownloadRequest (or YouTubeBaseServiceRequest) will put
/// <summary>
/// OAuth 2.0 token for the current user.
/// </summary>
[RequestParameter("oauth_token", RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
into a correct authorization header. I don't see this implemented in the version 1.9.0.1360.
Maybe I'm overlooking something? Any help is greatly appreciated.
Note: I use other caption-related methods with this SDK, and 'download' is the only one I'm having a trouble with.
You initialed the service WITHOUT the user credential (you only used the API key). Take a look in one of the samples in our developers guide, (and pick the right flow... are you using installed application, windows phone, etc.?)
You will have to change the way you create your service to do something like the following:
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YoutubeService.Scope.<THE_RIGHT_SCOPE_HERE> },
"user", CancellationToken.None);
}
// Create the service.
_service = new YouTubeService(new BaseClientService.Initializer {
ApplicationName = config.AppName,
HttpClientInitializer = credential,
ApplicationName = "Books API Sample",
});
Then, for each request to the youtube service, your OAuth access token will be included as an additional header on the HTTP request itself.

Categories