Beginner’s Guide To Using Google Plus .NET API Part 2: User Posts

Ok I’ll admit Part 2 to my “Beginner’s Guide To Using Google Plus .NET API” has been on the back-burner for some time (or maybe it’s because I completely forgot). After getting quite a few email recently on the subject, I thought now would be the best time to continue with Part 2.

It’s recommended you take a gander at Part 1 before proceeding to this post.

As the title suggests, I will be showing how to output user’s publicly view posts. The final output of what my code will produce can be seen on my homepage under the “Google+ Posts” section.

Create Class Object

We will create a class called “GooglePlusPost" to allow us to easily store each item of post data within a Generic List.

public class GooglePlusPost
{
    public string Title { get; set; }
    public string Text { get; set; }
    public string PostType { get; set; }
    public string Url { get; set; }
}

 

Let’s Get The Posts!

I have created a method called “GetPosts” that accepts a parameter to select the number of posts of your choice.

public class GooglePlus
{
    private static string ProfileID = ConfigurationManager.AppSettings["googleplus.profileid"].ToString();
    
    public static List<GooglePlusPost> GetPosts(int max)
    {
        try
        {
            var service = new PlusService();
            service.Key = GoogleKey;
            var profile = service.People.Get(ProfileID).Fetch();

            var posts = service.Activities.List(ProfileID, ActivitiesResource.Collection.Public);
            posts.MaxResults = max;

            List<GooglePlusPost> postList = new List<GooglePlusPost>();

            foreach (Activity a in posts.Fetch().Items)
            {
                GooglePlusPost gp = new GooglePlusPost();

                //If the post contains your own text, use this otherwise look for
                //text contained in the post attachment.
                if (!String.IsNullOrEmpty(a.Title))
                {
                    gp.Title = a.Title;
                }
                else
                {
                    //Check if post contains an attachment
                    if (a.Object.Attachments != null)
                    {
                        gp.Title = a.Object.Attachments[0].DisplayName;
                    }
                }

                gp.PostType = a.Object.ObjectType; //Type of post
                gp.Text = a.Verb;
                gp.Url = a.Url; //Post URL

                postList.Add(gp);
            }

            return postList;
        }
        catch
        {
            return new List<GooglePlusPost>();
        }
    }
}

By default, I have ensured that my own post comment takes precedence over the contents of the attachment (see lines 24-35). If I decided to just share an attachment without a comment, the display text from the attachment will be used instead.

There are quite a few facets of information an attachment contains and this only becomes apparent when you add a breakpoint and debug line 33. For example, if the attachment had an object of type “video”, you will get a wealth of information to embed a YouTube video along with its thumbnails and description.

Attachment Debug View

So there is room to make your Google+ feed much more intelligent. You just have to make sure you cater for every event to ensure your feed displays something useful without breaking. I’m in the process myself of displaying redoing my own Google+ feed to allow full access to content directly from my site.

Recommendation

It is recommended that you cache your collection of posts so you are not making constantly making request to Google+. You don’t want to exceed your daily request limit now do you.

I’ve set my cache duration to refresh every three hours.

Beginner’s Guide To Using Google Plus .NET API Part 1: Profile Data

Google has always impressed me with the quality of their API libraries allowing us to interface with their products in a somewhat straight-forward manner. In the past, I’ve used a couple of Google’s API’s for implementing YouTube video’s or Checkout merchant within my own sites. What makes life even easier is that the API’s are available in my native programming framework - .NET.

Google were quite slow in launching an official API upon Google Plus’s initial release and even though unofficial API’s were available, I thought it would be best to wait until an official release was made. I’ve been playing around with Google’s .NET API for a couple weeks now and only just had the time to blog about it.

I am hoping to make this beginners guide a three part series:

  1. Profile Data
  2. User Posts
  3. User’s +1’s

So let’s get to it!

Today, I shall be showing you the basic API principles to get you started in retrieving data from your own Google+ profile.

Prerequisites

Before we can start thinking about coding our page to retrieve profile information, it’s a requirement to register your application by going to: https://code.google.com/apis/console. Providing you already have an account with Google (and who hasn’t?), this shouldn’t be a problem. If you don’t see the page (below), a new API Project needs to be created.

Google Plus API - Console

Only the Client ID, Client Secret and API Key will be used in our code allowing us to carry our API requests from our custom application.

Next, download the Google Plus .NET Client. My own preference is to use the Binary release containing compiled .NET Google Client API and all dll's for all supported services.

Building A Custom Profile Page

1) Create a new Visual Studio Web Application.

2) Unzip the Binary Zip file containing all Google service DLL’s. Find and reference the following DLL’s in your project:

  • Google.Apis.dll
  • Google.Apis.Authentication.OAuth2.dll
  • Google.Apis.Plus.v1.dll

3) Copy and paste the following front-end HTML code:

<h2>
    About Me
</h2>
<br />
<table>
    <tr>
        <td valign="top">
            <asp:Image ID="ProfileImage" runat="server"></asp:Image>
        </td>
        <td valign="top">
            <strong>Name:</strong> <asp:Label ID="DisplayName" runat="server"></asp:Label>
            <br /><br />
            <strong>About Me:</strong> <asp:Label ID="AboutMe" runat="server"></asp:Label>
            <br />
            <strong>Gender:</strong> <asp:Label ID="Gender" runat="server"></asp:Label>
            <br /><br />
            <strong>Education/Employment:</strong> <asp:Literal ID="Work" runat="server"></asp:Literal>
        </td>
    </tr>
    <tr>
        <td colspan="2" valign="middle">
            <asp:HyperLink ID="GotoProfileButton" runat="server">Go to my Google+ profile</asp:HyperLink>
        </td>
    </tr>
</table>

4) Copy and paste the following C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Plus.v1;
using Google.Apis.Plus.v1.Data;

namespace GooglePlusAPITest
{
    public partial class About : System.Web.UI.Page
    {
        private string ProfileID = "100405991313749888253"; // My public Profile ID
        private string GoogleIdentifier = "<GoogleIdentifier>";
        private string GoogleSecret = "<GoogleSecret>";
        private string GoogleKey = "<GoogleKey>";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                GetGooglePlusProfile();
        }

        private void GetGooglePlusProfile()
        {
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = GoogleIdentifier;
            provider.ClientSecret = GoogleSecret;

            var service = new PlusService();
            service.Key = GoogleKey;

            var profile = service.People.Get(ProfileID).Fetch();

            // Profile Name
            DisplayName.Text = profile.DisplayName;

            //About me
            AboutMe.Text = profile.AboutMe;

            //Gender
            Gender.Text = profile.Gender;

            // Profile Image
            ProfileImage.ImageUrl = profile.Image.Url;

            // Education/Employment
            StringBuilder workHTML = new StringBuilder();

            workHTML.Append("<ul>");

            foreach (Person.OrganizationsData work in profile.Organizations.ToList())
            {
                workHTML.AppendFormat("<li>{0} ({1})", work.Title, work.Name);
            }

            workHTML.Append("</ul>");

            Work.Text = workHTML.ToString();

            //Link to Google+ profile
            GotoProfileButton.NavigateUrl = profile.Url;            
        }
    }
}

Once completed, the page should resemble something like this:

Google Plus Profile Page

I think you can all agree this example was pretty straight-forward. We are simply using the people.get method which translates into the following HTTP request:

https://www.googleapis.com/plus/v1/people/100405991313749888253?key=APIKey

Unless you really want to display my profile information on your site (who wouldn’t!), you can keep the code as it is. But you have the flexibility to change the “ProfileID” variable to an ID of your own choice. To find your Profile ID, read: How Do I Find My Google Plus User ID?.

Finally! Google Shows My Profile Information In Search Results

Ever since Google+ came along, I noticed website authors were getting their picture displayed next to article’s they’ve written in Google searches. Not to be left out of this trend, I decided I would attempt to get my ugly-mug displayed next to all my authored content as well.

Having carried out almost all of Google’s requirements through minor HTML modifications and verifying my Google+ account is linked to this blog, it’s finally happened!

Author information in search results

You may find that it can take some time for authorship information to appear in search results. I carried out all necessary steps back in January 2012. So it’s taken a good 3 months to get picked up. I am sure times will vary depending on the popularity of your site and the number of authored content it contains.

Here are the four basic things I did to get my mug-shot in Google’s search results:

  1. Make sure your Google+ profile has a recognisable headshot photo of high quality.
  2. Link your site to your Google+ account by adding a badge.
  3. Verify your Google+ account with an email address containing your domain address.
  4. Add a link to your site in the “Contributor” box in your Google+ profile.

Integrating Into Google Plus - Is it worth it?

Google PlusWhen I first heard Google were introducing their own social-networking platform, I was intrigued to say the least on what they could offer compared to the other social sites I use: Facebook and Twitter.

As I stated in one of my earlier posts, I am more of a tweeter since I can share my blog posts easily along with my random ramblings. I think Facebook will have a problem competing alongside Twitter or Google+. Facebook is seen to be more of a personal social network rather than a open professional network and that’s its biggest downfall. It’s quite difficult to cross the boundaries between posting professional/business content alongside personal posts. Thankfully, this is something Google Plus does quite well through its new “circle’s” feature allowing complete control on who see’s what.

I jumped at the chance of using Google Plus when I was offered an invite during the initial release. I was very impressed. Simple and straight-forward. My posts looked really beautiful within its minimalist user interface. Well what else would you expect from Google? Don’t get me started on the eye-sore that is Facebook’s new interface – I’ll leave that for another blog post.

For me, Google Plus is like an extension of Twitter with some added benefits such as:

  • Ability to make posts private/public.
  • Follow people by adding them to a circle.
  • No character limit on the length of posts.
  • Nice interoperability with the search-daddy that is Google.

For a new social networking site, I get a higher click-through-rate to my blog than I ever got compared to tweeting on Twitter. In the process, I managed to get more people adding me to their circle. So take any remarks regarding the inactivity of Google+ with a pinch of salt. I don’t buy it. Google encompasses a big community that you feel part of.

I briefly touched upon the interoperability factor with Google search. People underestimate the power of having the backing of Google search. For example, what if you wrote an article and linked it to your Google+ profile? This information will be displayed as author information within search results to help users discover great content and learn more about the person who wrote the article.

One thing that did surprise me is the fact that at this point in time there’s no advertisement. Unlike its predecessors (yes I that’s how confident I am in Google Plus), you always manage to find advertisement in some form or another. I can view my profile page without constantly having an advert rubbing my single relationship status to my face – something Facebook does far too often.

I trust Google more with my data over Facebook any day. I know Google can’t exactly be trusted either but unlike Facebook they’re not always in the the news on a monthly basis regarding some type of data scandal. At time of writing, it is being reported Facebook is now facing a privacy suit over internet tracking.

In conclusion, integrating ones self into Google Plus is definitely worth it. I only recently started to make more of an effort on Google+ and I find myself posting my content here over other social-networking sites. The key to making a good start is to make some of your posts public to show others your interests and even connect to these type of people either by adding them to a circle or joining a hangout.

On a final note, if you have a Google Plus account and like what I post then why not circle me. :-)