Authenticate to Yammer in c# console application - c#

I am using the NuGet Yammer API and I am trying to simply authenticate and display the token as a test.
Unfortunately I can't seem to get it working. I am new to this but there is no documentation on the NuGet Yammer API and it will be a console application. All the examples and documentation on the Yammer developers page show doing this from a web based appication.
My code so far:
static void Main(string[] args)
{
var myConfig = new ClientConfigurationContainer
{
ClientCode = null,
ClientId = "CODEHERE",
ClientSecret = "CODEHERE"
};
var myYammer = new YammerClient(myConfig);
var test = myYammer.GetToken();
Console.WriteLine("Token" + test);
Console.ReadLine();
}

It's an OAuth authentication, you must interact with Yammer OAuth webpage to obtain a token.
You should look in the asp.net mvc example in sources on Github.
In the HomeController.cs :
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
if (ModelState.IsValid)
{
var myConfig = new ClientConfigurationContainer
{
ClientCode = null,
ClientId = model.ClientId,
ClientSecret = model.ClientSecret,
RedirectUri = Request.Url.AbsoluteUri + Url.Action("AuthCode")
};
var myYammer = new YammerClient(myConfig);
// Obtain the URL of Yammer Authorisation Page
var url = myYammer.GetLoginLinkUri();
this.TempData["YammerConfig"] = myConfig;
// Jump to the url page
return Redirect(url);
}
return View(model);
}
And Yammer redirect you here:
public ActionResult AuthCode(String code)
{
if (!String.IsNullOrWhiteSpace(code))
{
var myConfig = this.TempData["YammerConfig"] as ClientConfigurationContainer;
myConfig.ClientCode = code;
var myYammer = new YammerClient(myConfig);
// var yammerToken = myYammer.GetToken();
// var l = myYammer.GetUsers();
// var t= myYammer.GetImpersonateTokens();
// var i = myYammer.SendInvitation("test#test.fr");
// var m = myYammer.PostMessage("A test from here", 0, "Event");
return View(myYammer.GetUserInfo());
}
return null;
}

The person who wrote the API also wrote an article on how to use it, which is here:
http://fullsaas.blogspot.fr/2013/05/a-simple-net-wrapper-of-yammer-api.html
This may also be useful:
https://blogs.technet.com/b/speschka/archive/2013/10/05/using-the-yammer-api-in-a-net-client-application.aspx

Related

Aweber API .NET SDK 401 unauthorized exception

I've followed the documentation steps and everything went smooth until step 5.
After successful authorization I've tried to access account data, like in step 5
var api = new API(ConsumerKey, ConsumerSecret);
api.OAuthToken = "My OAuthToken"; // That I've received on step 4
Account account = api.getAccount();
and I've got 401 exception on api.getAccount();
Please tell me what am I missing? What am I doing wrong?
Thanks
I've found a solution. In order someone else has the same issue, here is fully functional code example
public class AWeber
{
public void Authorize()
{
var Session = HttpContext.Current.Session;
var api = new API(AppSettings.AWebberConsumerKey, AppSettings.AWebberConsumerSecret);
api.CallbackUrl = "http://localhost:61006/test.aspx";
api.get_request_token();
Session["OAuthToken"] = api.OAuthToken;
Session["OAuthTokenSecret"] = api.OAuthTokenSecret;
api.authorize();
}
public void InitAccessToken(string OAuthVerifier)
{
var Session = HttpContext.Current.Session;
var api = new API(AppSettings.AWebberConsumerKey, AppSettings.AWebberConsumerSecret);
api.OAuthToken = (string)Session["OAuthToken"];
api.OAuthTokenSecret = (string)Session["OAuthTokenSecret"];
api.OAuthVerifier = OAuthVerifier;
// These two are final token that are needed
Session["OAuthToken"] = api.get_access_token();
Session["OAuthTokenSecret"] = api.adapter.OAuthTokenSecret;
}
public void GetData()
{
var Session = HttpContext.Current.Session;
var api = new API(AppSettings.AWebberConsumerKey, AppSettings.AWebberConsumerSecret);
api.adapter.OAuthToken = (string)Session["OAuthToken"];
api.adapter.OAuthTokenSecret = (string)Session["OAuthTokenSecret"];
Account account = api.getAccount();
}
}

ASP.Net MVC5, Google OAuth 2.0 and Youtube API

I need some help regarding mvc 5 using the google login provider and getting some youtube data. right now i think i get things a little mixed up. i'm not new to mvc but to version 5's owin middleware features. well, and not experienced in implementing oauth 2.0.
What i want:
Login to my MVC5 Application via Google.
Read some Youtube information from the logged in user.
What i have done so far:
Followed this Google OAuth 2.0 tutorial: Web applications (ASP.NET MVC).
Installed Google.Apis.Auth.MVC via NuGet.
Implemented AppFlowMetadata and AuthCallbackController as described.
Configured the redirect uri to "/AuthCallback/IndexAsync" as described.
Implemented a YoutubeController with the following action just to dump out some data:
public async Task<ActionResult> IndexAsync()
{
var result =
await new AuthorizationCodeMvcApp(this, new AppFlowMetadata())
.AuthorizeAsync(cancellationToken);
if (result.Credential == null)
{
return new RedirectResult(result.RedirectUri);
}
else
{
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "MyYoutubeApplication"
});
var playlists = service.Playlists.List("contentDetails, snippet");
playlists.Mine = true;
var list = await playlists.ExecuteAsync();
var json = new JavaScriptSerializer().Serialize(list);
ViewBag.Message = json;
return View();
}
}
So what this does, when trying to access /Youtube/IndexAsync is redirecting me to google, asking for my credentials.
when entered, i'm asked if i'm ok with the permission asked by the application. after confirming, i get redirected to my page, showing my /Youtube/IndexAsync page with the requested data. so far so good, but that's not quite what i want.
what (i think) i have done here is that i completely bypassed the asp.net identity system. the user is not logged in to my application let alone registered.
i want the user to log in with google, register in my application and provide access to his youtube data. then, when on a specific page, retrieve data from the user's youtube account.
What i also have tried:
Following this ASP.Net MVC5 Tutorial
This tutorial does not mention the NuGet package "Google.Apis.Auth.MVC" and talks something about a magic "/signin-google" redirect uri".
This also works, but breaks the solution above, complaining about a wrong redirect uri.
When using this approach, it seems not right to me call AuthorizeAsync in YoutubeController again, since i should already be authorized.
So i'm looking for some light in the dark, telling me what i'm mixing all together :) I hope the question is not as confused as i am right now.
I managed to do this using GooglePlus, haven't tried Google. Here's what I did:
Install the nugets:
> Install-Package Owin.Security.Providers
> Install-Package Google.Apis.Youtube.v3
Add this to Startup.auth.cs:
var g = new GooglePlusAuthenticationOptions();
g.ClientId = Constants.GoogleClientId;
g.ClientSecret = Constants.GoogleClientSecret;
g.RequestOfflineAccess = true; // for refresh token
g.Provider = new GooglePlusAuthenticationProvider
{
OnAuthenticated = context =>
{
context.Identity.AddClaim(new Claim(Constants.GoogleAccessToken, context.AccessToken));
if (!String.IsNullOrEmpty(context.RefreshToken))
{
context.Identity.AddClaim(new Claim(Constants.GoogleRefreshToken, context.RefreshToken));
}
return Task.FromResult<object>(null);
}
};
g.Scope.Add(Google.Apis.YouTube.v3.YouTubeService.Scope.YoutubeReadonly);
g.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
app.UseGooglePlusAuthentication(g);
The above code does two things:
Enable authentication via. Google+
Requests for the access token and the refresh token. The tokens are then added as a claim in the GooglePlus middleware.
Create a method that will store the claims containing the token to the database. I have this in the AccountController.cs file
private async Task StoreGooglePlusAuthToken(ApplicationUser user)
{
var claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
if (claimsIdentity != null)
{
// Retrieve the existing claims for the user and add the google plus access token
var currentClaims = await UserManager.GetClaimsAsync(user.Id);
var ci = claimsIdentity.FindAll(Constants.GoogleAccessToken);
if (ci != null && ci.Count() != 0)
{
var accessToken = ci.First();
if (currentClaims.Count() <= 0)
{
await UserManager.AddClaimAsync(user.Id, accessToken);
}
}
ci = claimsIdentity.FindAll(Constants.GoogleRefreshToken);
if (ci != null && ci.Count() != 0)
{
var refreshToken = ci.First();
if (currentClaims.Count() <= 1)
{
await UserManager.AddClaimAsync(user.Id, refreshToken);
}
}
}
You'll need to call it in 2 places in the AccountController.cs: Once in ExternalLoginCallback:
case SignInStatus.Success:
var currentUser = await UserManager.FindAsync(loginInfo.Login);
if (currentUser != null)
{
await StoreGooglePlusAuthToken(currentUser);
}
return RedirectToLocal(returnUrl);
and once in ExternalLoginConfirmation:
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await StoreGooglePlusAuthToken(user);
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
Now that we've got the users access token and refresh token we can use this to authenticate the user.
I tried a simple search I saw in the examples and it worked:
private async Task<Models.YouTubeViewModel> Search(string searchTerm)
{
var user = (ClaimsPrincipal)Thread.CurrentPrincipal;
var at = user.Claims.FirstOrDefault(x => x.Type == Constants.GoogleAccessToken);
var rt = user.Claims.FirstOrDefault(x => x.Type == Constants.GoogleRefreshToken);
if (at == null || rt == null)
throw new HttpUnhandledException("Access / Refresh Token missing");
TokenResponse token = new TokenResponse
{
AccessToken = at.Value,
RefreshToken = rt.Value
};
var cred = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer()
{
ClientSecrets = new ClientSecrets()
{
ClientId = Constants.GoogleClientId,
ClientSecret = Constants.GoogleClientSecret
}
}
),
User.Identity.GetApplicationUser().UserName,
token
);
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApplicationName = this.GetType().ToString(),
HttpClientInitializer = cred,
});
var searchListRequest = youtubeService.Search.List("snippet");
searchListRequest.Q = searchTerm;
searchListRequest.MaxResults = 50;
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = await searchListRequest.ExecuteAsync();
Models.YouTubeViewModel vm = new Models.YouTubeViewModel(searchTerm);
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
vm.Videos.Add(new Models.Result(searchResult.Snippet.Title, searchResult.Id.VideoId));
break;
case "youtube#channel":
vm.Channels.Add(new Models.Result(searchResult.Snippet.Title, searchResult.Id.ChannelId));
break;
case "youtube#playlist":
vm.Playlists.Add(new Models.Result(searchResult.Snippet.Title, searchResult.Id.PlaylistId));
break;
}
}
return vm;
}
Model Classes
public class Result
{
public string Title { get; set; }
public string Id { get; set; }
public Result() { }
public Result(string title, string id)
{
this.Title = title;
this.Id = id;
}
}
public class YouTubeViewModel
{
public string SearchTerm { get; set; }
public List<Result> Videos { get; set; }
public List<Result> Playlists { get; set; }
public List<Result> Channels { get; set; }
public YouTubeViewModel()
{
Videos = new List<Result>();
Playlists = new List<Result>();
Channels = new List<Result>();
}
public YouTubeViewModel(string searchTerm)
:this()
{
SearchTerm = searchTerm;
}
}
Reference: http://blogs.msdn.com/b/webdev/archive/2013/10/16/get-more-information-from-social-providers-used-in-the-vs-2013-project-templates.aspx

Can't register application on Instagram

I am writing C# client for Instagram. I've registered my application and filled the fields: Application Name, Description, Website, OAuth redirect_uri. But I receive this error message in my C# client:
This client is not xAuth enabled.
I think the problem is in Website, OAuth redirect_uri fields. What values must I put in these fields?
Here is method that have to get access_token (HttpRequest class from xNet library):
private string GetAccessToken()
{
using (var request = new HttpRequest())
{
var urlParams = new RequestParams();
urlParams["client_id"] = "ce3c76b914cb4417b3721406d7fe3456";
urlParams["client_secret"] = "b8ad0c21ce8142d0a8c0fa2d2bd78f53";
urlParams["username"] = this.login;
urlParams["password"] = this.password;
urlParams["grant_type"] = "password";
urlParams["scope"] = "comments likes relationships";
try
{
this.json = request.Post("https://api.instagram.com/oauth/access_token", urlParams).ToString();
var values = JsonConvert.DeserializeObject<InstagramResponse>(this.json);
return values.access_token;
}
catch (Exception)
{
return null;
}
}
}

Use Google Analytics API to show information in C#

I have been looking for a good solution all day, but Google evolves so fast that I can't find something working. What I want to do is that, I have a Web app that has an admin section where user need to be logged in to see the information. In this section I want to show some data from GA, like pageviews for some specific urls. Since it's not the user information that I'm showing but the google analytics'user I want to connect passing information (username/password or APIKey) but I can't find out how. All the sample I found use OAuth2 (witch, if I understand, will ask the visitor to log in using google).
What I found so far :
Google official Client Library for .Net : http://code.google.com/p/google-api-dotnet-client/, no sample for GA
official developers help : https://developers.google.com/analytics/
an other question with code on SO : Google Analytics API - Programmatically fetch page views in server side but I get a 403 when I try to authenticate
some source that access the API : http://www.reimers.dk/jacob-reimers-blog/added-google-analytics-reader-for-net downloaded the source but I can't figure out how it works
this other question on SO : Google Analytics Access with C# but it does not help
while writing this they suggest me this 09 old post Google Analytics API and .Net.
Maybe I'm just tired and that tomorrow it will be easy to find a solution but right now I need help!
Thanks
It requires a bit of setup on the google side but it's actually quite simple. I will list step by step.
First you will need to create an application in the Google cloud console and enable the Analytics API.
Go to http://code.google.com/apis/console
Select the drop down and create a project if you do not already have one
Once the project is created click on services
From here enable the Analytics API
Now that the Analytics API is enabled the next step will be to enable a service account to access your desired analytics profiles/sites. The service account will allow you to log in without having to prompt a user for credentials.
Go to http://code.google.com/apis/console and choose the project you
created from the drop down.
Next go to the "API Access" section and click the "Create another client id" button.
In the Create Client ID window choose service account and click
create client id.
Download the public key for this account if it doesn't start the
download automatically.You will need this later on when you code for
authorization.
Before exiting copy the service accounts auto generated email address as you will need this in the next step. The client email looks like #developer.gserviceaccount.com
Now that we have a service account you will need to allow this service account to access to your profiles/sites in Google Analytics.
Log into Google Analytics.
Once logged in click on the Admin button to the bottem left on the
screen.
In Admin click the account drop down and select the account/site you would like your service account to be able to access then click on "User Management" under the account section.
Enter the email address that was generated for your service account and give it read and analyze permission.
Repeat these steps for any other account/site you would like your service to have access to.
Now that the setup is done for the service account to access Google Analytics through the API we can start to code.
Get this package from NuGet:
Google.Apis.Analytics.v3 Client Library
Add these usings:
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using System.Collections.Generic;
using System.Linq;
Some things to note are.
The keyPath is the path to the key file you downloaded with a .p12 file extention.
The accountEmailAddress is the api email we got earlier.
Scope is an Enum in the Google.Apis.Analytics.v3.AnalyticService class that dictates the url to use in order to authorize (ex: AnalyticsService.Scope.AnalyticsReadonly ).
Application name is a name of your choosing that tells the google api what is accessing it (aka: it can be what ever you choose).
Then the code to do some basic calls is as follows.
public class GoogleAnalyticsAPI
{
public AnalyticsService Service { get; set; }
public GoogleAnalyticsAPI(string keyPath, string accountEmailAddress)
{
var certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);
var credentials = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(accountEmailAddress)
{
Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
}.FromCertificate(certificate));
Service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "WorthlessVariable"
});
}
public AnalyticDataPoint GetAnalyticsData(string profileId, string[] dimensions, string[] metrics, DateTime startDate, DateTime endDate)
{
AnalyticDataPoint data = new AnalyticDataPoint();
if (!profileId.Contains("ga:"))
profileId = string.Format("ga:{0}", profileId);
//Make initial call to service.
//Then check if a next link exists in the response,
//if so parse and call again using start index param.
GaData response = null;
do
{
int startIndex = 1;
if (response != null && !string.IsNullOrEmpty(response.NextLink))
{
Uri uri = new Uri(response.NextLink);
var paramerters = uri.Query.Split('&');
string s = paramerters.First(i => i.Contains("start-index")).Split('=')[1];
startIndex = int.Parse(s);
}
var request = BuildAnalyticRequest(profileId, dimensions, metrics, startDate, endDate, startIndex);
response = request.Execute();
data.ColumnHeaders = response.ColumnHeaders;
data.Rows.AddRange(response.Rows);
} while (!string.IsNullOrEmpty(response.NextLink));
return data;
}
private DataResource.GaResource.GetRequest BuildAnalyticRequest(string profileId, string[] dimensions, string[] metrics,
DateTime startDate, DateTime endDate, int startIndex)
{
DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate.ToString("yyyy-MM-dd"),
endDate.ToString("yyyy-MM-dd"), string.Join(",", metrics));
request.Dimensions = string.Join(",", dimensions);
request.StartIndex = startIndex;
return request;
}
public IList<Profile> GetAvailableProfiles()
{
var response = Service.Management.Profiles.List("~all", "~all").Execute();
return response.Items;
}
public class AnalyticDataPoint
{
public AnalyticDataPoint()
{
Rows = new List<IList<string>>();
}
public IList<GaData.ColumnHeadersData> ColumnHeaders { get; set; }
public List<IList<string>> Rows { get; set; }
}
}
Other Links that will prove helpful:
Analytic API Explorer - Query API From The Web
Analytic API Explorer version 2 - Query API From The Web
Dimensions and Metrics Reference
Hopefully this helps someone trying to do this in the future.
I did a lot of search and finally either looking up code from multiple places and then wrapping my own interface around it i came up with the following solution. Not sure if people paste their whole code here, but i guess why not save everyone else time :)
Pre-requisites, you will need to install Google.GData.Client and google.gdata.analytics package/dll.
This is the main class that does the work.
namespace Utilities.Google
{
public class Analytics
{
private readonly String ClientUserName;
private readonly String ClientPassword;
private readonly String TableID;
private AnalyticsService analyticsService;
public Analytics(string user, string password, string table)
{
this.ClientUserName = user;
this.ClientPassword = password;
this.TableID = table;
// Configure GA API.
analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0");
// Client Login Authorization.
analyticsService.setUserCredentials(ClientUserName, ClientPassword);
}
/// <summary>
/// Get the page views for a particular page path
/// </summary>
/// <param name="pagePath"></param>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <param name="isPathAbsolute">make this false if the pagePath is a regular expression</param>
/// <returns></returns>
public int GetPageViewsForPagePath(string pagePath, DateTime startDate, DateTime endDate, bool isPathAbsolute = true)
{
int output = 0;
// GA Data Feed query uri.
String baseUrl = "https://www.google.com/analytics/feeds/data";
DataQuery query = new DataQuery(baseUrl);
query.Ids = TableID;
//query.Dimensions = "ga:source,ga:medium";
query.Metrics = "ga:pageviews";
//query.Segment = "gaid::-11";
var filterPrefix = isPathAbsolute ? "ga:pagepath==" : "ga:pagepath=~";
query.Filters = filterPrefix + pagePath;
//query.Sort = "-ga:visits";
//query.NumberToRetrieve = 5;
query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
Uri url = query.Uri;
DataFeed feed = analyticsService.Query(query);
output = Int32.Parse(feed.Aggregates.Metrics[0].Value);
return output;
}
public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate)
{
// GA Data Feed query uri.
String baseUrl = "https://www.google.com/analytics/feeds/data";
DataQuery query = new DataQuery(baseUrl);
query.Ids = TableID;
query.Dimensions = "ga:pagePath";
query.Metrics = "ga:pageviews";
//query.Segment = "gaid::-11";
var filterPrefix = "ga:pagepath=~";
query.Filters = filterPrefix + pagePathRegEx;
//query.Sort = "-ga:visits";
//query.NumberToRetrieve = 5;
query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
Uri url = query.Uri;
DataFeed feed = analyticsService.Query(query);
var returnDictionary = new Dictionary<string, int>();
foreach (var entry in feed.Entries)
returnDictionary.Add(((DataEntry)entry).Dimensions[0].Value, Int32.Parse(((DataEntry)entry).Metrics[0].Value));
return returnDictionary;
}
}
}
And this is the interface and implementation that i use to wrap it up with.
namespace Utilities
{
public interface IPageViewCounter
{
int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true);
Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate);
}
public class GooglePageViewCounter : IPageViewCounter
{
private string GoogleUserName
{
get
{
return ConfigurationManager.AppSettings["googleUserName"];
}
}
private string GooglePassword
{
get
{
return ConfigurationManager.AppSettings["googlePassword"];
}
}
private string GoogleAnalyticsTableName
{
get
{
return ConfigurationManager.AppSettings["googleAnalyticsTableName"];
}
}
private Analytics analytics;
public GooglePageViewCounter()
{
analytics = new Analytics(GoogleUserName, GooglePassword, GoogleAnalyticsTableName);
}
#region IPageViewCounter Members
public int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true)
{
int output = 0;
try
{
output = analytics.GetPageViewsForPagePath(relativeUrl, startDate, endDate, isPathAbsolute);
}
catch (Exception ex)
{
Logger.Error(ex);
}
return output;
}
public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate)
{
var input = analytics.PageViewCounts(pagePathRegEx, startDate, endDate);
var output = new Dictionary<string, int>();
foreach (var item in input)
{
if (item.Key.Contains('&'))
{
string[] key = item.Key.Split(new char[] { '?', '&' });
string newKey = key[0] + "?" + key.FirstOrDefault(k => k.StartsWith("p="));
if (output.ContainsKey(newKey))
output[newKey] += item.Value;
else
output[newKey] = item.Value;
}
else
output.Add(item.Key, item.Value);
}
return output;
}
#endregion
}
}
And now the rest is the obvious stuff - you will have to add the web.config values to your application config or webconfig and call IPageViewCounter.GetPageViewCount
This answer is for those of you who want access to your own Analytics account and want to use the new Analytics Reporting API v4.
I recently wrote a blog post about how to get Google Analytics data using C#. Read there for all the details.
You first need to choose between connecting with OAuth2 or a Service Account. I'll assume you own the Analytics account, so you need to create a "Service account key" from the Google APIs Credentials page.
Once you create that, download the JSON file and put it in your project (I put mine in my App_Data folder).
Next, install the Google.Apis.AnalyticsReporting.v4 Nuget package. Also install Newtonsoft's Json.NET.
Include this class somewhere in your project:
public class PersonalServiceAccountCred
{
public string type { get; set; }
public string project_id { get; set; }
public string private_key_id { get; set; }
public string private_key { get; set; }
public string client_email { get; set; }
public string client_id { get; set; }
public string auth_uri { get; set; }
public string token_uri { get; set; }
public string auth_provider_x509_cert_url { get; set; }
public string client_x509_cert_url { get; set; }
}
And here's what you've been waiting for: a full example!
string keyFilePath = Server.MapPath("~/App_Data/Your-API-Key-Filename.json");
string json = System.IO.File.ReadAllText(keyFilePath);
var cr = JsonConvert.DeserializeObject(json);
var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
{
Scopes = new[] {
AnalyticsReportingService.Scope.Analytics
}
}.FromPrivateKey(cr.private_key));
using (var svc = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = xCred,
ApplicationName = "[Your Application Name]"
})
)
{
// Create the DateRange object.
DateRange dateRange = new DateRange() { StartDate = "2017-05-01", EndDate = "2017-05-31" };
// Create the Metrics object.
Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };
//Create the Dimensions object.
Dimension browser = new Dimension { Name = "ga:browser" };
// Create the ReportRequest object.
ReportRequest reportRequest = new ReportRequest
{
ViewId = "[A ViewId in your account]",
DateRanges = new List() { dateRange },
Dimensions = new List() { browser },
Metrics = new List() { sessions }
};
List requests = new List();
requests.Add(reportRequest);
// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };
// Call the batchGet method.
GetReportsResponse response = svc.Reports.BatchGet(getReport).Execute();
}
We start by deserializing the service account key information from the JSON file and convert it to a PersonalServiceAccountCred object. Then, we create the ServiceAccountCredential and connect to Google via the AnalyticsReportingService. Using that service, we then prepare some basic filters to pass to the API and send off the request.
It's probably best to set a breakpoint on the line where the response variable is declared, press F10 once, then hover over the variable, so you can see what data is available for you to use in the response.
I was hoping just to add a comment to the answer for v3 Beta, but rep points prevent that. However, I thought it would be nice for others to have this information so here it is:
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Services;
These name spaces are used throughout the code in that post. I always wish people would post name spaces more often, I seem to spend a good bit of time looking for them. I hope this saves some people a few minutes of work.
I've setup something pretty similar to the above answer in a nuGet package. It does the following:
- connects to a "Service Account" you set up in the API Console
- Pulls any Google Analytics data you would like
- Displays that data using Google's Charts API
and it does all of this in a very easy to modify way. You can see more here: https://www.nuget.org/packages/GoogleAnalytics.GoogleCharts.NET/.
Hope google will provide proper documentation someday. Here I am listing all the steps to integrate google analytics server side authentication in ASP.NET C#.
Step 1: Create a project in google console
Goto the link https://console.developers.google.com/iam-admin/projects and create a project by clicking on "Create Project" button and provide project name in the pop up window and submit it.
Step 2: Create credentials and service account
After creation of the project, you will be redirected to "API Manager" page.
Click on credentials and press "Create Credentials" button. select "service account key" from dropdown you will be redirected to next page.
In the service account drop down, select "New service account". Fill in the service account name and download the p12 key. It will have p12 extension. you will get a popup having a password "notasecret" which is default and your private key will be downloaded.
Step 3: Create 0auth client ID
click on the "create credentials" dropdown and select "0auth client ID" you will be redirected to "0auth consent screen" tab. provide a random name in the project name textbox. select application type as "Web application" and click create button. Copy the generated client ID in a notepad.
Step 4: Enable the APIs
On the left side click on the "Overview" tab and select "Enabled APIs" from the horizontal tab. In the search bar search for "Analytics API" click on the dropdown and press "Enable" button. Now again search for "Analytics Reporting V4" and enable it.
Step 5: Install nuget packages
In visual studio, Go to Tools > Nuget Package Manager > Package Manager Console.
Copy paste the below code in the console to install the nuget packages.
Install-Package Google.Apis.Analytics.v3
Install-Package DotNetOpenAuth.Core -Version 4.3.4.13329
The above two packages are Google analytics and DotNetOpenAuth nuget packages.
Step 6: Provide 'View and Analyze' permission to service account
Go to google analytics account and click on "Admin" tab and select "User Management" from left menus,select a domain of which you want to access analytics data and insert the service account email id under it and select "Read and Analyze" permission from the dropdown. Service account email id looks like ex: googleanalytics#googleanalytics.iam.gserviceaccount.com.
Working Code
FRONT END CODE:
Copy and paste the below analytics embed script in your front end or else you can get this code from google analytics documentation page also.
<script>
(function (w, d, s, g, js, fs) {
g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } };
js = d.createElement(s); fs = d.getElementsByTagName(s)[0];
js.src = 'https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); };
}(window, document, 'script'));</script>
Paste the below code in the body tag of your front end page.
<asp:HiddenField ID="accessToken" runat="server" />
<div id="chart-1-container" style="width:600px;border:1px solid #ccc;"></div>
<script>
var access_token = document.getElementById('<%= accessToken.ClientID%>').value;
gapi.analytics.ready(function () {
/**
* Authorize the user with an access token obtained server side.
*/
gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': access_token
}
});
/**
* Creates a new DataChart instance showing sessions.
* It will be rendered inside an element with the id "chart-1-container".
*/
var dataChart1 = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': 'ga:53861036', // VIEW ID <-- Goto your google analytics account and select the domain whose analytics data you want to display on your webpage. From the URL ex: a507598w53044903p53861036. Copy the digits after "p". It is your view ID
'start-date': '2016-04-01',
'end-date': '2016-04-30',
'metrics': 'ga:sessions',
'dimensions': 'ga:date'
},
chart: {
'container': 'chart-1-container',
'type': 'LINE',
'options': {
'width': '100%'
}
}
});
dataChart1.execute();
/**
* Creates a new DataChart instance showing top 5 most popular demos/tools
* amongst returning users only.
* It will be rendered inside an element with the id "chart-3-container".
*/
});
</script>
You can also get your View ID from https://ga-dev-tools.appspot.com/account-explorer/
BACK END CODE:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.Script.Serialization;
using System.Net;
using System.Text;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util;
using DotNetOpenAuth.OAuth2;
using System.Security.Cryptography;
namespace googleAnalytics
{
public partial class api : System.Web.UI.Page
{
public const string SCOPE_ANALYTICS_READONLY = "https://www.googleapis.com/auth/analytics.readonly";
string ServiceAccountUser = "googleanalytics#googleanalytics.iam.gserviceaccount.com"; //service account email ID
string keyFile = #"D:\key.p12"; //file link to downloaded key with p12 extension
protected void Page_Load(object sender, EventArgs e)
{
string Token = Convert.ToString(GetAccessToken(ServiceAccountUser, keyFile, SCOPE_ANALYTICS_READONLY));
accessToken.Value = Token;
var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable);
var credentials = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(ServiceAccountUser)
{
Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "Google Analytics API"
});
string profileId = "ga:53861036";
string startDate = "2016-04-01";
string endDate = "2016-04-30";
string metrics = "ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:visits";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
GaData data = request.Execute();
List<string> ColumnName = new List<string>();
foreach (var h in data.ColumnHeaders)
{
ColumnName.Add(h.Name);
}
List<double> values = new List<double>();
foreach (var row in data.Rows)
{
foreach (var item in row)
{
values.Add(Convert.ToDouble(item));
}
}
values[3] = Math.Truncate(100 * values[3]) / 100;
txtSession.Text = values[0].ToString();
txtUsers.Text = values[1].ToString();
txtPageViews.Text = values[2].ToString();
txtBounceRate.Text = values[3].ToString();
txtVisits.Text = values[4].ToString();
}
public static dynamic GetAccessToken(string clientIdEMail, string keyFilePath, string scope)
{
// certificate
var certificate = new X509Certificate2(keyFilePath, "notasecret");
// header
var header = new { typ = "JWT", alg = "RS256" };
// claimset
var times = GetExpiryAndIssueDate();
var claimset = new
{
iss = clientIdEMail,
scope = scope,
aud = "https://accounts.google.com/o/oauth2/token",
iat = times[0],
exp = times[1],
};
JavaScriptSerializer ser = new JavaScriptSerializer();
// encoded header
var headerSerialized = ser.Serialize(header);
var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
var headerEncoded = Convert.ToBase64String(headerBytes);
// encoded claimset
var claimsetSerialized = ser.Serialize(claimset);
var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
var claimsetEncoded = Convert.ToBase64String(claimsetBytes);
// input
var input = headerEncoded + "." + claimsetEncoded;
var inputBytes = Encoding.UTF8.GetBytes(input);
// signature
var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
var cspParam = new CspParameters
{
KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName,
KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2
};
var aescsp = new RSACryptoServiceProvider(cspParam) { PersistKeyInCsp = false };
var signatureBytes = aescsp.SignData(inputBytes, "SHA256");
var signatureEncoded = Convert.ToBase64String(signatureBytes);
// jwt
var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded;
var client = new WebClient();
client.Encoding = Encoding.UTF8;
var uri = "https://accounts.google.com/o/oauth2/token";
var content = new NameValueCollection();
content["assertion"] = jwt;
content["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";
string response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", content));
var result = ser.Deserialize<dynamic>(response);
object pulledObject = null;
string token = "access_token";
if (result.ContainsKey(token))
{
pulledObject = result[token];
}
//return result;
return pulledObject;
}
private static int[] GetExpiryAndIssueDate()
{
var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var issueTime = DateTime.UtcNow;
var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;
return new[] { iat, exp };
}
}
}
Another Working Approach
Add below code in the ConfigAuth
var googleApiOptions = new GoogleOAuth2AuthenticationOptions()
{
AccessType = "offline", // can use only if require
ClientId = ClientId,
ClientSecret = ClientSecret,
Provider = new GoogleOAuth2AuthenticationProvider()
{
OnAuthenticated = context =>
{
context.Identity.AddClaim(new Claim("Google_AccessToken", context.AccessToken));
if (context.RefreshToken != null)
{
context.Identity.AddClaim(new Claim("GoogleRefreshToken", context.RefreshToken));
}
context.Identity.AddClaim(new Claim("GoogleUserId", context.Id));
context.Identity.AddClaim(new Claim("GoogleTokenIssuedAt", DateTime.Now.ToBinary().ToString()));
var expiresInSec = 10000;
context.Identity.AddClaim(new Claim("GoogleTokenExpiresIn", expiresInSec.ToString()));
return Task.FromResult(0);
}
},
SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
};
googleApiOptions.Scope.Add("openid"); // Need to add for google+
googleApiOptions.Scope.Add("profile");// Need to add for google+
googleApiOptions.Scope.Add("email");// Need to add for google+
googleApiOptions.Scope.Add("https://www.googleapis.com/auth/analytics.readonly");
app.UseGoogleAuthentication(googleApiOptions);
Add below code, name spaces and relative references
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Services;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
public class HomeController : Controller
{
AnalyticsService service;
public IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
public async Task<ActionResult> AccountList()
{
service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = await GetCredentialForApiAsync(),
ApplicationName = "Analytics API sample",
});
//Account List
ManagementResource.AccountsResource.ListRequest AccountListRequest = service.Management.Accounts.List();
//service.QuotaUser = "MyApplicationProductKey";
Accounts AccountList = AccountListRequest.Execute();
return View();
}
private async Task<UserCredential> GetCredentialForApiAsync()
{
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = ClientId,
ClientSecret = ClientSecret,
},
Scopes = new[] { "https://www.googleapis.com/auth/analytics.readonly" }
};
var flow = new GoogleAuthorizationCodeFlow(initializer);
var identity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ApplicationCookie);
if (identity == null)
{
Redirect("/Account/Login");
}
var userId = identity.FindFirstValue("GoogleUserId");
var token = new TokenResponse()
{
AccessToken = identity.FindFirstValue("Google_AccessToken"),
RefreshToken = identity.FindFirstValue("GoogleRefreshToken"),
Issued = DateTime.FromBinary(long.Parse(identity.FindFirstValue("GoogleTokenIssuedAt"))),
ExpiresInSeconds = long.Parse(identity.FindFirstValue("GoogleTokenExpiresIn")),
};
return new UserCredential(flow, userId, token);
}
}
Add this in the Application_Start() in Global.asax
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

Accessing Google Docs with GData

Working Platform: ASP.NET 4.0 C# ( Framework Agnostic )
Google GData is my dependency
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Documents;
I have two pages Auth and List.
Auth redirects to Google Server like this
public ActionResult Auth()
{
var target = Request.Url.ToString().ToLowerInvariant().Replace("auth", "list");
var scope = "https://docs.google.com/feeds/";
bool secure = false, session = true;
var authSubUrl = AuthSubUtil.getRequestUrl(target, scope, secure, session);
return new RedirectResult(authSubUrl);
}
Now it reaches the List Page if Authentication is successful.
public ActionResult List()
{
if (Request.QueryString["token"] != null)
{
String singleUseToken = Request.QueryString["token"];
string consumerKey = "www.blahblah.net";
string consumerSecret = "my_key";
string sessionToken = AuthSubUtil.exchangeForSessionToken(singleUseToken, null).ToString();
var authFactory = new GOAuthRequestFactory("writely", "qwd-asd-01");
authFactory.Token = sessionToken;
authFactory.ConsumerKey = consumerKey;
authFactory.ConsumerSecret = consumerSecret;
//authFactory.TokenSecret = "";
try
{
var service = new DocumentsService(authFactory.ApplicationName) { RequestFactory = authFactory };
var query = new DocumentsListQuery();
query.Title = "project";
var feed = service.Query(query);
var result = feed.Entries.ToList().ConvertAll(a => a.Title.Text);
return View(result);
}
catch (GDataRequestException gdre)
{
throw;
}
}
}
This fails at the line var feed = service.Query(query); with the error
Execution of request failed: https://docs.google.com/feeds/default/private/full?title=project
The HttpStatusCode recieved on the catch block is HttpStatusCode.Unauthorized
What is wrong with this code? Do I need to get TokenSecret? If so how?
You need to request a token from Google and use it to intialize your DocumentsService instance.
Here's an example using Google's ContactsService. It should be the same for the DocumentsService.
Service service = new ContactsService("My Contacts Application");
service.setUserCredentials("your_email_address_here#gmail.com", "yourpassword");
var token = service.QueryClientLoginToken();
service.SetAuthenticationToken(token);
But as you mentioned, you are using AuthSub. I jumped the gun a bit too fast.
I see that you are requesting a session token. According to the documentation of the API you must use the session token to authenticate requests to the service by placing the token in the Authorization header. After you've set the session token, you can use the Google Data APIs client library.
Here's a complete example (by Google) on how to use AuthSub with the .NET client library:
http://code.google.com/intl/nl-NL/apis/gdata/articles/authsub_dotnet.html
Let me include a shortened example:
GAuthSubRequestFactory authFactory =
new GAuthSubRequestFactory("cl", "TesterApp");
authFactory.Token = (String) Session["token"];
CalendarService service = new CalendarService(authFactory.ApplicationName);
service.RequestFactory = authFactory;
EventQuery query = new EventQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
EventFeed calFeed = service.Query(query);
foreach (Google.GData.Calendar.EventEntry entry in calFeed.Entries)
{
//...
}
And if I see correctly your example code pretty follows the same steps, except that you set the ConsumerKey and ConsumerSecret for the AuthFactory which is not done in the example by Google.
Used the 3-legged OAuth in the Google Data Protocol Client Libraries
Sample Code
string CONSUMER_KEY = "www.bherila.net";
string CONSUMER_SECRET = "RpKF7ykWt8C6At74TR4_wyIb";
string APPLICATION_NAME = "bwh-wssearch-01";
string SCOPE = "https://docs.google.com/feeds/";
public ActionResult Auth()
{
string callbackURL = String.Format("{0}{1}", Request.Url.ToString(), "List");
OAuthParameters parameters = new OAuthParameters()
{
ConsumerKey = CONSUMER_KEY,
ConsumerSecret = CONSUMER_SECRET,
Scope = SCOPE,
Callback = callbackURL,
SignatureMethod = "HMAC-SHA1"
};
OAuthUtil.GetUnauthorizedRequestToken(parameters);
string authorizationUrl = OAuthUtil.CreateUserAuthorizationUrl(parameters);
Session["parameters"] = parameters;
ViewBag.AuthUrl = authorizationUrl;
return View();
}
public ActionResult List()
{
if (Session["parameters"] != null)
{
OAuthParameters parameters = Session["parameters"] as OAuthParameters;
OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query, parameters);
try
{
OAuthUtil.GetAccessToken(parameters);
GOAuthRequestFactory authFactory = new GOAuthRequestFactory("writely", APPLICATION_NAME, parameters);
var service = new DocumentsService(authFactory.ApplicationName);
service.RequestFactory = authFactory;
var query = new DocumentsListQuery();
//query.Title = "recipe";
var feed = service.Query(query);
var docs = new List<string>();
foreach (DocumentEntry entry in feed.Entries)
{
docs.Add(entry.Title.Text);
}
//var result = feed.Entries.ToList().ConvertAll(a => a.Title.Text);
return View(docs);
}
catch (GDataRequestException gdre)
{
HttpWebResponse response = (HttpWebResponse)gdre.Response;
//bad auth token, clear session and refresh the page
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Session.Clear();
Response.Write(gdre.Message);
}
else
{
Response.Write("Error processing request: " + gdre.ToString());
}
throw;
}
}
else
{
return RedirectToAction("Index");
}
}
This 2-legged sample never worked for me for google docs.

Categories

Resources