Google+ API Get with C# 17


Please Share

GooglePlusLarge
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

  1. Google+ API List with C# –  List (Articles, People, comments)
  2. Google+ API Get with C#  – Get (Article, Person, comment)
  3. Google+ API Search with C#  – Search (Articles and People)
  4. 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

Please Share


Linda Lawton

About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as a developer and a database expert. I have been working with several of the Google APIs, since 2012. I helping others in the On-Line community to develop with the Google APIs, by creating my own blog www.daimto.com. This and my presence on a number of On-Line developer forums lead me to be noticed by the Google Analytics API development team. I was nominated for and recently became one of the first Google Developer Experts for Google Analytics.


Leave a comment

Your email address will not be published. Required fields are marked *

17 thoughts on “Google+ API Get with C#

  • ragia

    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

  • P.Rajesh

    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.

  • Vinh

    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.

    • Administrator
      Linda Lawton

      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.

  • Arnie Gonzalez

    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();

  • Arnie Gonzalez

    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!

  • Jarvis

    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?