Google Ads Api Console Application - c#

I want to develop a console application that pulls all campaigns under adwords accounts using Google Ads Api.
But I could not pass the authentication step.
I do not fully understand whether I should use the Service Account or Desktop Application Flow for this process.
GoogleAdsConfig config = new GoogleAdsConfig()
{
DeveloperToken = "Dev_token",
OAuth2Mode = Google.Ads.GoogleAds.Config.OAuth2Flow.APPLICATION,
OAuth2ClientId = "client_Id",
OAuth2ClientSecret = "secrret",
OAuth2RefreshToken = " refresh_token",
};
GoogleAdsClient client = new GoogleAdsClient(config);
GoogleAdsServiceClient googleAdsService = client.GetService(Google.Ads.GoogleAds.Services.V10.GoogleAdsService);
googleAdsService.SearchStream(AdwordsClientId, query,
delegate (SearchGoogleAdsStreamResponse resp)
{
foreach (GoogleAdsRow adsRow in resp.Results)
{
}
}
);
When I try as above, I get the following error
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"unauthorized_client", Description:"Unauthorized", Uri:""
What paths should i follow?
Thank you.

unauthorized_client could have a couple of reasons. The most important ones that come to mind:
Did you make sure that your client ID and client secret match?
Have you activated the Google Ads API for the GCP project whose OAuth2 client you are using?

Related

Analytics Reporting API V4 Client Library for .NET

I'm trying to get some data from our google analytics instance and I'd like to use the Analytics Reporting API V4 Client Library for .NET (https://developers.google.com/api-client-library/dotnet/apis/analyticsreporting/v4) so that I can bake some of this data into an administration site we have built. I'm having trouble finding any examples of using this code and the documentation seems to be incredibly sparse. I would like to use a service account to authorize as we only need to view data associated with the analytics account which we control.
If anyone could provide some sample code or point me in the right direction to get some basic report data using the .net api, it would be greatly appreciated
Calling the Google Analytics Reporting API from C# is not particularly difficult, however all of the necessary steps do not seem to be outlined very clearly in the Google Analytics API documentation. I will try to list them all out here. While YMMV, I believe these steps to be correct as of 7/20/2016.
You can start by creating a new C# project. We'll make a console application to test called GoogleAnalyticsApiConsole. Once the project is created, we'll add a reference to the Google Analytics Reporting API V4 Client Library for .NET using the NuGet Package Manager Console (found under the Tools menu in Visual Studio 2015). Fire up the Console and issue the following command at the PM> prompt:
PM> Install-Package Google.Apis.AnalyticsReporting.v4
Installing that package will download the client libraries needed to call the Google Analytics Reporting web services along with a number of other dependencies.
In order to call the web services, you'll need to set up OAuth 2.0 access for your application. The documentation for this setup can be found here, but I will summarize below:
Login to the Google Cloud Platform Console: https://console.cloud.google.com/. Be sure to login with an account that has access to the Google Analytics accounts you are trying to query with the reporting API.
Click the Google Cloud Platform menu and select API Manager.
On the left hand side, click Credentials and then create a new project called Google Analytics API Console. Give it some time to create the new project.
After the project is created, click Credentials again if it is not already selected, and then click the OAuth Consent Screen link in the right panel. Set the Product name shown to users to Google Analytics API Console and then click Save.
Click Credentials again, and then click Create Credentials, and choose OAuth Client ID. Select Other for Application type and then enter Google Analytics API Console as the Name and click Create.
After the credential is created, you will be presented with a client ID and a client secret. You can close the dialog window.
Now, under Credentials you should see an entry under OAuth 2.0 client ids. Click the download icon to the far right of that entry to download the client_secret.json file (this file will have a much longer name). Add that file to your project at the root level once it has been downloaded and rename it to client_secret.json.
Now that the OAuth 2.0 credential has been created, we need to enable it to call the Reporting API. Select Overview and make sure Google APIs is selected in the right panel. Type in Reporting in the search box and select Analytics Reporting API V4 from the list. On the next screen, click Enable. Once this API has been enabled, you should be able to see it under the Enabled APIs list in the right panel.
Now that we've created our project and created our OAuth 2.0 credential, it is time to call the Reporting API V4. The code listed below will use the Google API and the client_secret.json file to create a Google.Apis.Auth.OAuth2.UserCredential to query the Reporting API for all sessions between the given date range for a View. The code is adapted from the Java example here.
Before executing the code, be sure to set the Build Action on the client_secret.json file to Content and the Copy to Output Directory setting to Copy if newer. There are also two variables that need to be properly set. First, in the GetCredential() method, set the loginEmailAddress value to the email address used to create the OAuth 2.0 credential. Then, in the Main method, be sure to set the ViewId in the reportRequest variable to the view that you want to query using the Reporting API. To find the ViewId, log in to Google Analytics and select the Admin tab. From there, select the view you want to query in the View dropdown on the far right and select View Settings. The View ID will be displayed under Basic Settings.
The first time the code is executed, it will bring up a web page asking if you want to allow the Google Analytics API Console to have access to the API data. Select Allow to proceed. From then on that permission will be stored in the GoogleAnalyticsApiConsole FileDataStore. If that file is deleted, then permission will need to be granted again. That file can be found in the %APPDATA%\GoogleAnalyicsApiConsole directory.
Please note that I believe this scenario will meet the needs of the OP. If this application were to be distributed to clients, then a different OAuth 2.0 scheme would most likely be necessary.
Here is the code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
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 GoogleAnalyticsApiConsole
{
class Program
{
static void Main(string[] args)
{
try
{
var credential = GetCredential().Result;
using(var svc = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Google Analytics API Console"
}))
{
var dateRange = new DateRange
{
StartDate = "2016-05-01",
EndDate = "2016-05-31"
};
var sessions = new Metric
{
Expression = "ga:sessions",
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 = "<<your view id>>"
};
var getReportsRequest = new GetReportsRequest {
ReportRequests = new List<ReportRequest> { reportRequest } };
var batchRequest = svc.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());
}
}
static async Task<UserCredential> GetCredential()
{
using (var stream = new FileStream("client_secret.json",
FileMode.Open, FileAccess.Read))
{
const string loginEmailAddress = "<<your account email address>>";
return await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { AnalyticsReportingService.Scope.Analytics },
loginEmailAddress, CancellationToken.None,
new FileDataStore("GoogleAnalyticsApiConsole"));
}
}
}
}
Here are the steps updated for Sep 2019.
First, understand that there are two choices under OAuth: User credentials and Service Account credentials. User credentials are meant to be used when you do not know which Google Analytics account you will be connected to, hence the user grants your application permission. Service Account credentials are meant to be used, e.g. if you build your own dashboard for your company to display Google Analytics data.
Most of the time, if you need programmatic access to Analytics data, it is the second case.
The steps below should get you started for a simple C# example. Note that the Google web console part may vary slightly, but should be easy to find nevertheless.
Go to the Google API Console. Create a Project if prompted.
Go to Service accounts.
Create a new Service Account. You should have an account with a random-generated email address (mine is ending with xxx#xxx.iam.gserviceaccount.com)
Find the Create Key button. Choose JSON and download the file. This is your private key and your only copy. Do not lose it.
Go to your Google Analytics admin panel. Grant access to the Service Account using its email address, the same way you would grant access to other users.
The Google configuration is done. Now jump into Visual Studio.
Create a new C# Console Project.
Get the Nuget package Google.Apis.AnalyticsReporting.v4. It should also automatically download the core packages as well.
Grab the JSON file downloaded earlier, put it in the project, set its Property to Content and Copy Always.
using Google.Apis.AnalyticsReporting.v4.Data;
using System;
namespace ConsoleApplication {
class Program {
static void Main(string[] args) {
var credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromFile("serviceAccount.json")
.CreateScoped(new[] { Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService.Scope.AnalyticsReadonly });
using (var analytics = new Google.Apis.AnalyticsReporting.v4.AnalyticsReportingService(new Google.Apis.Services.BaseClientService.Initializer {
HttpClientInitializer = credential
})) {
var request = analytics.Reports.BatchGet(new GetReportsRequest {
ReportRequests = new[] {
new ReportRequest{
DateRanges = new[] { new DateRange{ StartDate = "2019-01-01", EndDate = "2019-01-31" }},
Dimensions = new[] { new Dimension{ Name = "ga:date" }},
Metrics = new[] { new Metric{ Expression = "ga:sessions", Alias = "Sessions"}},
ViewId = "99999999"
}
}
});
var response = request.Execute();
foreach (var row in response.Reports[0].Data.Rows) {
Console.Write(string.Join(",", row.Dimensions) + ": ");
foreach (var metric in row.Metrics) Console.WriteLine(string.Join(",", metric.Values));
}
}
Console.WriteLine("Done");
Console.ReadKey(true);
}
}
}
I had the same experience: Google's documentation is pretty in-depth but is pretty terrible at giving clear examples of how to connect with .NET.
One key thing I finally realized is that you can either connect using an OAuth2 credential or a service account credential. If you own your Analytics account, use a service account. If you're needing to connect to other users' Analytics accounts, use OAuth2.
There seem to be quite a few examples online of how to get Analytics API data using an OAuth2 credential, but I own my Analytics account and just wanted to pull data from it. I figured out how to connect to the Analytics Reporting API v4 using a ServiceAccountCredential, and I wrote an answer on a similar Stack Overflow question with all the details.
Here Is the code you actually looking for-
protected void Page_Load(object sender, EventArgs e)
{
IRestRequest request = new RestRequest("", Method.POST, DataFormat.Json);
string url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet";
RestClient restClient = new RestClient();
RestRequest Tokenrequest = new RestRequest();
Tokenrequest.AddQueryParameter("client_id", "<CLIENTID>");
Tokenrequest.AddQueryParameter("client_secret", "<CLIENTSECRET>");
Tokenrequest.AddQueryParameter("grant_type", "refresh_token");
Tokenrequest.AddQueryParameter("refresh_token", "<REFRESH_TOKEN>");
restClient.BaseUrl = new System.Uri("https://oauth2.googleapis.com/token");
restClient.Post(Tokenrequest);
var responseToken = restClient.Execute(Tokenrequest);
//Response.Write(responseToken);
dynamic Tokendata = JObject.Parse(responseToken.Content);
var newToken = Tokendata.access_token.Value;
request.AddHeader("authorization", string.Concat("Bearer "+newToken));
string jsonString = "{" +
"\"reportRequests\": [{" +
"\"dateRanges\" : [{\"" +
"startDate\" :'2021-07-01' ," +
"\"endDate\" : '2021-07-07'" +
"}]," +
"\"metrics\":["+
"{\"expression\":'ga:totalEvents'},"+
"{\"expression\": 'ga:pageviews'}"+
"]," +
"\"dimensions\": ["+
"{\"name\": 'ga:eventCategory'}" +
",{" +
"\"name\": 'ga:eventAction'"+
"},"+
//"{\"name\": 'ga:deviceCategory'}"+
"]," +
"\"dimensionFilterClauses\": [{"+
"\"filters\": [{"+
"\"dimensionName\": 'ga:eventCategory',"+
"\"operator\": 'EXACT',"+
"\"expressions\": ["+
"\"Login_Form"+
"\"]}]}],"+
"\"viewId\":'<VIEWID>'" +
"}]" +
"}";
IRestClient client = new RestClient(url);
request.AddHeader("Content-Type", "application/json; CHARSET=UTF-8");
request.Resource = "";
request.AddParameter("application/json", jsonString, ParameterType.RequestBody);
var response = client.Execute(request);
dynamic jdata = JObject.Parse(response.Content);
var Row_data = jdata.reports[0].data.rows;
Response.Write(Row_data);
}
Read The Document To Get access_token through refresh_token.
https://developers.google.com/identity/protocols/oauth2/web-server#offline

Facebook SDK integration in WPF application

I have wpf desktop application and I want Facebook login integration in this application so that users can share images from local machine, moreover I am using "Facebook.7.0.6" sdk. Apparently I am facing following issue on login screen.
Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
And below coding I am using in my application.
private Uri GenerateLoginUrl(string appId, string extendedPermissions)
{
// for .net 3.5
// var parameters = new Dictionary<string,object>
// parameters["client_id"] = appId;
dynamic parameters = new ExpandoObject();
parameters.client_id = appId;
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(extendedPermissions))
parameters.scope = extendedPermissions;
// generate the login url
var fb = new FacebookClient();
return fb.GetLoginUrl(parameters);
}
void facebookBrowser_Navigated(Object sender,NavigationEventArgs e)
{
var fb = new FacebookClient();
FacebookOAuthResult oauthResult;
if (!fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
return;
if (oauthResult.IsSuccess)
LoginSucceeded(oauthResult);
}
Note : Let me know if Facebook have any change in term and condition for desktop application.
Thanks
After some study I got this link and now my application working fine.
Please set below settings on Facebook app first.
Native or desktop app? - Yes
Client OAuth login - Yes
Embedded browser OAuth Login - Yes
read more from this link :-https://www.hackviking.com/2014/11/facebook-api-login-flow-for-desktop-application/
Thanks
This error means you haven't configured well you app on facebook
If you are testing on localhost, you need to add a platform to your app, then configuring the "site url" for the example http://localhost. Then create a test app (a copy of your main app) and use it for your tests.

Evernote AuthToken via OAuth

I have worked with OAuth before (working with Twitter and PHP) and it was simple. I am trying to get OAuth to work with the EverNote API sample https://github.com/evernote/evernote-sdk-csharp (because, as they say, "Real applications authenticate with Evernote using OAuth"). I looked at these:
Simple C# Evernote API OAuth example or guide?
https://github.com/sethhitch/csharp-oauth-sample
http://blog.stevienova.com/2008/04/19/oauth-getting-started-with-oauth-in-c-net/
But, I still don't know how to do this... This is my code:
// Real applications authenticate with Evernote using OAuth, but for the
// purpose of exploring the API, you can get a developer token that allows
// you to access your own Evernote account. To get a developer token, visit
// https://sandbox.evernote.com/api/DeveloperToken.action
String authToken = "myAuthCode";
if (authToken == "your developer token") {
Console.WriteLine("Please fill in your developer token");
Console.WriteLine("To get a developer token, visit https://sandbox.evernote.com/api/DeveloperToken.action");
return;
}
How can I add OAuth to this to get my authToken?
Thank you.
Check this sample project : http://discussion.evernote.com/topic/30584-here-is-a-net-oauth-assembly/ . I think this will help you to understand how oauth works.
For anyone trying to get this to work in MVC, I was playing around with Evernote, OpenAuth and C# this morning and managed to get it all working. I have put together a blog post / library explaining the experience and outlining how to do it with MVC here - http://www.shaunmccarthy.com/evernote-oauth-csharp/ - it uses the AsyncOAuth library: https://github.com/neuecc/AsyncOAuth
I wrote a wrapper around AsyncOAuth that you might find useful here: https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
One prickly thing to be aware of - the Evernote Endpoints (/oauth and /OAuth.action) are case sensitive
// Download the library from https://github.com/shaunmccarthy/AsyncOAuth.Evernote.Simple
// Configure the Authorizer with the URL of the Evernote service,
// your key, and your secret.
var EvernoteAuthorizer = new EvernoteAuthorizer(
"https://sandbox.evernote.com",
"slyrp-1234", // Not my real id / secret :)
"7acafe123456badb123");
// First of all, get a request token from Evernote - this causes a
// webrequest from your server to Evernote.
// The callBackUrl is the URL you want the user to return to once
// they validate the app
var requestToken = EvernoteAuthorizer.GetRequestToken(callBackUrl);
// Persist this token, as we are going to redirect the user to
// Evernote to Authorize this app
Session["RequestToken"] = requestToken;
// Generate the Evernote URL that we will redirect the user to in
// order to
var callForwardUrl = EvernoteAuthorizer.BuildAuthorizeUrl(requestToken);
// Redirect the user (e.g. MVC)
return Redirect(callForwardUrl);
// ... Once the user authroizes the app, they get redirected to callBackUrl
// where we parse the request parameter oauth_validator and finally get
// our credentials
// null = they didn't authorize us
var credentials = EvernoteAuthorizer.ParseAccessToken(
Request.QueryString["oauth_verifier"],
Session["RequestToken"] as RequestToken);
// Example of how to use the credential with Evernote SDK
var noteStoreUrl = EvernoteCredentials.NotebookUrl;
var noteStoreTransport = new THttpClient(new Uri(noteStoreUrl));
var noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
var noteStore = new NoteStore.Client(noteStoreProtocol);
List<Notebook> notebooks = client.listNotebooks(EvernoteCredentials.AuthToken);
You can also try the OAuth library found here : https://code.google.com/p/devdefined-tools/wiki/OAuth and follow the steps mentioned here.
The simple code to add is:
EvernoteOAuth oauth = new EvernoteOAuth(EvernoteOAuth.HostService.Sandbox, myConsumerKey, myConsumerSecret);
string errResponse = oauth.Authorize();
if (errResponse.Length == 0)
{
Console.WriteLine(string.Format("Token: {0}\r\n\r\nExpires: {1}\r\n\r\nNoteStoreUrl: {2}\r\n\r\nUserId: {3}\r\n\r\nWebApiUrlPrefix: {4}", oauth.Token, oauth.Expires, oauth.NoteStoreUrl, oauth.UserId, oauth.WebApiUrlPrefix));
}
else
{
Console.WriteLine("A problem has occurred in attempting to authorize the use of your Evernote account: " + errResponse);
}
You will need to use this assembly:
using EvernoteOAuthNet;
Available here:
http://www32.zippyshare.com/v/98249023/file.html

Signing-in to use Live SDK, Windows Store app

I am developing an application (Windows Store) to access SkyDrive content. To login to Live I am using the below code snippet.
try
{
var uri = "https://login.live.com/oauth20_authorize.srf";
var authorizeUri = new StringBuilder(uri);
authorizeUri.AppendFormat("?client_id={0}&", "000000004C0DE9B7"); //This is my Client ID
authorizeUri.AppendFormat("scope={0}&", "wl.signin");
authorizeUri.AppendFormat("response_type={0}&", "code");
authorizeUri.AppendFormat("redirect_uri={0}", ("")); //I don't have redirect URL.
LiveAuthClient auth = new LiveAuthClient(authorizeUri.ToString());
LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
if (loginResult != null)
{
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
this.txtStatus.Text = "Signed in";
}
}
}
catch (LiveAuthException exception)
{
this.txtStatus.Text = exception.Message+ " Error";
}
}
With this I am always getting the below exception:
"The app is not configured correctly to use Live Connect services. ..."
I tried to get Package identity for my Windows Store app. Since, it is taking me to paid registration page, I have not done that. [ https://appdev.microsoft.com/StorePortals/en-us/account/signup/start ]
I am not sure if that is the cause for the problem.
I have also tried this link to register my app. This too is not working.
https://manage.dev.live.com/build?wa=wsignin1.0
I appreciate if someone could help me in resolving this issue.
For a Windows Store app to use Live Connect APIs, it needs to have a Package Identity which you can only get my registering as a Windows Store Developer.
Windows Phone, iOS and Android apps need only the Client ID. All other apps need Client ID, Client Secret and Redirect Domain.
That is why it's not working. For more information, see: http://msdn.microsoft.com/en-us/library/live/hh826541.aspx
Hope that helps.

How to get friends list from facebook? (Desktop application)

As per this link code from stack overflow i have try this code for getting
friendslist but after login i got this error "requires valid signature"
string APIKey = ConfigurationManager.AppSettings["API_Key"];
string APISecret = ConfigurationManager.AppSettings["API_Secret"];
Facebook.Session.ConnectSession connectsession = new Facebook.Session.ConnectSession(APIKey, APISecret);
Facebook.Rest.Api api = new Facebook.Rest.Api(connectsession);
var friends = api.Friends.GetLists();
foreach (var friend in friends)
{
System.Console.WriteLine(friend.name);
}
guide me to find out the solution
Thanks
ash
If you are starting with a new application, you should definitely use the Graph API and not the old Rest API. The Rest API has been deprecated for quite a while now and there is no guarantee how much longer Facebook will support it.
For an example on using the Graph API try http://csharpsdk.org/docs/web/getting-started
You can obtain the friends list by making a request to me/friends
You can test other requests using the Graph API explorer.

Categories

Resources