Have you been trying to connect your website or application to Google+? Do you want to show a list of your most recent posts on Google plus? Are you looking for a list of people someone has in there circles on Google Plus? Are you trying to get back a list of all of the comments on a post? If you are you trying to work with the Google+ api in C# .net I might be able to help. Lets have a look all 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
Activities
An Activity on Google+ is basically a post. In order to get a list of all of the posts back you need to know who’s posts it is you want to get back. There is a little trick if you want to get all of the posts for the user that authenticated your application you can use the command “me”. If you want to list someone else you will need to either use search or send the personId for the person who’s Google+ activities you would like to see.
When you request Google+ activities on a person you can max return 100 Google+ posts at a time. If you want to see more then 100 Google+ activities from the API, you must get the next batch in the list until you have fetched all of the Google+ posts available for a person. It can take some time to get all of the activities returned to you, it is best to really only return the most resent ones unless for some reason you want to see everything they have posted.
//List all of the activities in the specified collection for the current user. // Documentation: https://developers.google.com/+/api/latest/activities/list ActivitiesResource.ListRequest listActivities = service.Activities.List("me", ActivitiesResource.ListRequest.CollectionEnum.Public); listActivities.MaxResults = 100; ActivityFeed activitesFeed = listActivities.Execute(); IList Activites = new List(); //// Loop through until we arrive at an empty page while (activitesFeed.Items != null) { // Adding each person to the list. foreach (Activity item in activitesFeed.Items) { Activites.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (activitesFeed.NextPageToken == null) { break; } // Prepare the next page of results listActivities.PageToken = activitesFeed.NextPageToken; // Execute and process the next page request activitesFeed = listActivities.Execute(); }
Activities now contains a full list of all the activities for the user, go ahead try it out.
foreach (Activity item in _Activities) { Console.WriteLine(item.Actor.DisplayName + " Plus 1s: " + item.Object.Plusoners.TotalItems + " comments: " + item.Object.Replies.TotalItems); }
People
Now people are basically just that people with accounts on Google plus. A person could post an activity, plus1 an Activity leave a comment to an Activity. Basically everything is wrapped around the person who takes the action. Lets keep things easy lets just get a list of the people our current authenticated user has in there circles.
Like when you request Google+ activities on a person you can max return 100 Google+ people at a time. If you want to see more then 100 Google+ people from the API, you must get the next batch in the list until you have fetched all of the Google+ people available for a person.
PeopleResource.ListRequest listPeople = service.People.List(_userId, PeopleResource.ListRequest.CollectionEnum.Visible); listPeople.MaxResults = 10; PeopleFeed peopleFeed = listPeople.Execute(); IList people = new List(); //// Loop through until we arrive at an empty page while (peopleFeed.Items != null) { // Adding each item to the list. foreach (Person item in peopleFeed.Items) { people.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (peopleFeed.NextPageToken == null) { break; } // Prepare the next page of results listPeople.PageToken = peopleFeed.NextPageToken; // Execute and process the next page request peopleFeed = listPeople.Execute(); }
Now people contains a list of all of the people.
Comments
Comments are slightly different, to get a list of comments we need to send the activity for which we want to see the comment.
//List all of the activities in the specified collection for the current user. // Documentation: https://developers.google.com/+/api/latest/activities/list CommentsResource.ListRequest listComments = service.Comments.List(_activityId); listComments.MaxResults = 100; CommentFeed commentsFeed = listComments.Execute(); IList Comments = new List(); //// Loop through until we arrive at an empty page while (commentsFeed.Items != null) { // Adding each item to the list. foreach (Comment item in commentsFeed.Items) { Comments.Add(item); } // We will know we are on the last page when the next page token is // null. // If this is the case, break. if (commentsFeed.NextPageToken == null) { break; } // Prepare the next page of results listComments.PageToken = commentsFeed.NextPageToken; // Execute and process the next page request commentsFeed = listComments.Execute(); }
Concision
You should now understand how to access the Google+ API with an authenticated user. You should also understand the idea behind using NextPageToken to get the next set of results back. 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, you just need to wait for part 3.
I am trying this example but every time after signing in I am getting error 400 uri mismatch although I have provided proper client id,client secret and also provided correct urls in google plus.Plzzzz helpp.
Have you tried the sample project?
If I call Execute() method in listActivities object (in above example) than I get all activities which is shared by a specific user. e.g. If I specify “me” as userId than I get all activities for the authenticated user otherwise for the specified user. But in this I get all activities “shared by” a user. That is fine if I want to list activities “shared by” a particular user.
But how can I get all activities which are “shared with” a user. e.g. any activities which is shared by other users with authenticated user or activities which are shared publicly by other users.
More specifically, what I want to achieve is, while we open google+ app, say for android, we see posts shared by different users. How can I achieve the same behavior?