Have you been trying to connect your website or application to Google+? Do you want to get a User, Post or Comment? Are you trying to work with the Google+ api in C# .net? Lets have a look at that now?
Three part Tutorial Series
- Google+ API List with C# – List (Articles, People, comments)
- Google+ API Get with C# – Get (Article, Person, comment)
- Google+ API Search with C# – Search (Articles and People)
- Google Plus API with C# .net – Sample project
Restringing your application.
Like with most of the Google APIs you need to be authenticated in order to connect to them. To do that you must first register your application on Google Developer console. Under APIs be sure to enable the Google+ API, as always don’t forget to add a product name and email address on the consent screen form.
Project Setup
Make sure your project is at least set to .net 4.0.
Add the following NuGet Package
PM> Install-Package Google.Apis.Plus.v1
You will probably need most of these using’s
using System; using Google.Apis.Auth.OAuth2; using Google.Apis.Plus.v1; using System.Threading; using Google.Apis.Util.Store; using Google.Apis.Services; using Google.Apis.Plus.v1.Data; using System.Collections.Generic; using System.Linq;
Authentication
Authentication is the key to everything here. If you want to be able to access data you will need to be authenticated. The code for authentication simply displays a webpage for your user asking them to give you permission to access there data. If the user gives you permission a file is then stored on the machine in the %AppData% directory containing all the information you will need in the future to access there data.
That’s just fine but how does Google know what kind of permission you want to ask the user for? That’s where scopes come in, with scopes you define what permissions you need.
In the code below we ask the user to give us access to some basic information about there user-profile, there email address and the standard stuff for login.
string[] scopes = new string[] {PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail, PlusService.Scope.UserinfoProfile}; // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData% UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets {ClientId = _client_id, ClientSecret = _client_secret }, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("Daimto.GooglePlus.Auth.Store") ).Result;
Assuming the user clicks Accept and gives you permission you will then have a valid user credential you can build upon.
Google plus Service
The service is where all of the magic is. It is though the service that all of the calls will be made to the Google plus API.
// Now we create a Google service. All of our requests will be run though this. PlusService service = new PlusService(new BaseClientService.Initializer(){ HttpClientInitializer = credential, ApplicationName = "Google Plus Sample", });
Notice how we pass our credential to it.
Requesting Data
Activity
An Activity on Google+ is basically a post. In order to get a the post back you need to know the id of the post. One of the ways to get an Id of a post would be to get the list of all of the activities for a user. But this would also return the activity so it is probably a bad example.
ActivitiesResource.GetRequest activityRequest = service.Activities.Get(_activityId); Activity post = activityRequest.Execute();
Person
Now people are basically just that people with accounts on Google plus. A person could post an activity, plus 1 an Activity leave a comment to an Activity. Basically everything is wrapped around the person who takes the action. with person you must either know the user id of the person you would like to get or you can just use me, me is the current authenticated user.
PeopleResource.GetRequest personRequest = service.People.Get(_userId); Person _me = personRequest.Execute();
Comment
A comment is just that a comment on a post. In order to get a comment you must know the id of the comment you would like to get.
CommentsResource.GetRequest Request = service.Comments.Get(_commentId); Comment aComment = Request.Execute();
Concision
You should now understand how to access the Google+ API with an authenticated user. You should also understand the difference between a post, activity, comment and a person is. I hope you will also agree that working with the Google APIs is quite easy once you get the authentication down.
Blog authors who like to make people happy and help them enjoy working with the Google APIs, release the code to go along with this tutorial on GitHub
Hi Linda Thanks so mush for your effort, I need your help in problem i faced when run your google plus app on my device always i got this exception ‘An unhandled exception of type ‘System.AccessViolationException’ occurred in mscorlib.dll ‘
Do you have any recommendations to solve and make it run I need C# desktop application let me post on google+ account
Thanks
I have seen several people post this error, I have been unable to recreate it myself. Sorry i cant be of any help.
Hi Linda, I’ve downloaded your “Diamto-Google-plus-sample” project and when i’m trying to run this I got an error like “Error: redirect_uri_mismatch”. Please help me out this, I’ve tried so many times to solve this but i can’t.
redirect_uri must match exactly what is in the developer console. The problem is that when running C# in dev it can change the port. Try and figure out how to get it to stop using a port.
How to i am post the image in Google plus page using c# windows forms
You cant, the Google+ API is extremely limited it does not allow you to post to pages, or timelines.
how to share image on google using c# winforms
You cant the API doesn’t allow that.
Are u sure we cant post test, image and video to google+ in C#, If there any other way maybe because this person be able to post something.. https://www.surinderbhomra.com/blog/post/2013/01/29/Beginners-Guide-To-Using-Google-Plus-NET-API-Part-2-User-Posts.aspx#.UXifsNiwpes
Unless you can get him to tell you what GooglePlusPost() i would suggest that that link is just click bait it does not work. You cant post to the Google+ social media website.
Hi Linda,
I create an example project to login Google. I use Google+ Api. It work. But something happened, in first time I login, I login by Google account and nothing happen. But when I logout my google account, I run my project again and it alway show my infomation Google account, even I did logout. I can’t login with other account.
This is the nature of Open Authentication you are never really “logged out” you never loose access until a user revokes your access. The trick to changing users will be to change the Environment.UserName, this is what is used to identify different users.
Hello:
I’m developing an app for this but using a manual flow. The app is in C# and I’ve hit a brick wall on the profile GET request. I’m already able to log in the user, send the authorization code request and handle the response, send the access token request and handle the response, but while trying to send the GET request with the access token to receive the server’s response with the user’s profile information, the server keeps responding with a 401 unauthorized response.
Here’s what that particular request looks like:
string RequestString = “https://www.googleapis.com/plus/v1/people/me?access_token=” + AccessToken;
WebRequest GGLRequest = WebRequest.Create(RequestString);
GGLRequest.Method = “GET”;
GGLRequest.ContentLength = 0;
GGLRequest.ContentType = “application/json”;
GGLRequest.Headers.Add(“Authorization”, “Bearer”);
GGLRequest.UseDefaultCredentials = false;
WebResponse GGLResponse = GGLRequest.GetResponse();
You should probably ask this question on stackoverflow.com this tutorial is about using the Google .net client library not doing it manually.
Hello:
I’m developing an app for this but using a manual flow. The app is in C# and I’ve hit a brick wall on the profile GET request. I’m already able to log in the user, send the authorization code request and handle the response, send the access token request and handle the response, but while trying to send the GET request with the access token to receive the server’s response, that includes the user’s profile information, the server keeps responding with a 401 unauthorized response.
Here’s what that particular request looks like:
string RequestString = “https://www.googleapis.com/plus/v1/people/me?access_token=” + AccessToken;
WebRequest GGLRequest = WebRequest.Create(RequestString);
GGLRequest.Method = “GET”;
// I’ve already tried alternating the use of the following 3 lines (all possible combinations)
// with no luck:
GGLRequest.ContentLength = 0;
GGLRequest.ContentType = “application/json”;
GGLRequest.Headers.Add(“Authorization”, “Bearer”);
GGLRequest.UseDefaultCredentials = true;
WebResponse GGLResponse = GGLRequest.GetResponse();
The code explodes on that last line when trying to get the response. Naturally, the code following that line doesn’t execute.
Now, I’ve been thinking that maybe the problem might lie in using the wrong scope specification in the initial authentication URL string. If that is in fact the problem (using a wrong set of scopes on that string) then maybe the access token sent by the server doesn’t match the Google API URL I’m using in the GET request, hence the 401 unauthorized answer. Just in case that may be the problem, here’s what that URL string looks like:
https://account.google.com/o/oauth2/auth?scope=profile%20email&redirect_uri={myuri}&response_type=code&client_id={myclientid}&approval_prompt=force&access_type=offline”
So, (1) Maybe I’m using the wrong set of scopes in the string OR (2) I’m sending the GET profile request to the wrong URL for that set of scopes defined in the initial Authentication string.
Thank you so much for your time!
people.get doesn’t require authentication any reason you aren’t just using a public API key?
Hi Linda. In my project, 2 users need to sign up at one time but after the first user authorizes successfully and sign out, the second user can not authorize. It doesn’t show any popup for the second user to accept. Do you have any idea to solve?
credential.RevokeTokenAsync(CancellationToken.None) is my solution. Thanks for all your tutorials so much. Have a nice day
Change Environment.UserName to be different for each user authenticating. This tutorial will explain the problem you are having. Google .net – FileDatastore demystified
Hi Linda,
I wan’t to create simple app with 2 winforms (main menu) with button that show the second winform (that contains webbrowser) , and i want that the user connect to his google + account to get some informations like ( name, email, birthday date) , can you help me please , i don’t find solution please.
I am assuming this is your question? Google+ login Winform using C#
I have create a blank web application in visual studio 2012 using 4.5 framework, and try to install “Install-Package Google.Apis.Plus.v1”, I am getting a error,
PM> Install-Package Google.Apis.Plus.v1
Attempting to resolve dependency ‘Google.Apis (≥ 1.32.0)’.
Attempting to resolve dependency ‘Google.Apis.Core (≥ 1.32.0)’.
Attempting to resolve dependency ‘System.Net.Http (≥ 4.3.1)’.
Install-Package : ‘System.Net.Http’ already has a dependency defined for ‘System.IO’.
At line:1 char:16
+ Install-Package <<<< Google.Apis.Plus.v1
+ CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
please advice me what should I do,
Want to try again there was an issue with the NuGet packages over the holidays. It should be fixed now.
Hi Linda how are you? I wonder u can do step by step instruction on how to post/activity on Google+ based on the code u post. I wonder u can do this in WPF or webform in C#.
The Google+ social media website api is read only you can not post to it.