Using the Google .NET client library with Google+

Overview

 

 

IMPORTANT NOTE: This post covers old information on the client libraries. Please read this post for updated information.

 

 

 

 

The first time you use Google+ and .NET, it can be a little tricky to get things working.  This article will cover a few of the basic steps to save you some time. I have uploaded a sample implementation that includes a few minor changes like fixing the cut/paste requirement used to demonstrate that the key is extracted from the page.  Download the C#/Google+ app.

Prerequisites

You will need a Google+ API for client applications generated from the Google API Console.  Most important in this flow are the Client Secret and Client ID.

Next, you will need to download the service generator and generate the library. The following command generates the Google+ class:

ServiceGenerator.exe url https://www.googleapis.com/discovery/v1/apis/plus/v1/rest

You will then have a class, Plus.v1.cs, and a DLL, Plus.v1.dll, that can be included in a project to enable access to Google+. Note You should not use both the DLL and the static generated class.

Before the project will work, you will need to add references to the requisite DLLs from the service generator as well as from .NET.  The easiest way to get all of the libraries for .NET is to clone the Mercurial repo. First, download Mercurial for Windows, next, run the following command:

hg clone https://code.google.com/p/google-api-dotnet-client.samples/

You now have the latest set of samples from Google for .NET, an API key, the Google+ library, and are ready to create a project in Visual Studio.

Creating the project

For this project, just create a basic WPF app using the wizard from Visual Studio.  Next, add a few references to the project by right clicking the references section of the solution explorer and using the browse function for adding references. It can be easier to do this by copying the DLLs to a separate folder than referencing the DLLs from the samples directory for your mercurial clone.

The following list shows the libraries that I am adding:

DotNetOpenAuth
Google.Apis
Google.Apis.Authentication.OAuth2
Google.Apis.Oauth2.v2
Newtonsoft.Json.Net35

Note I am using Plus.v1.cs as opposed to using the library to make debugging easier.

Now you should add the DLL or generated class that was created in the first step and your prereqs are satisfied.

Basic setup for OAUTH2 using the libraries

Now it’s time to add a few includes for our libraries:

// Added for auth flow
// Microsoft
using System.Diagnostics;
using System.Threading;
using System.Windows.Threading;
// DotNetOpenAuth
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth2;
//Google
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Util;
using System.Web;
// The generated plus class
using Plus.v1;

Inside of your WPF project, add a few declarations and a simple class for storing your app credentials:

protected PlusService ps1;
        Plus.v1.Data.Person me;
        private IAuthorizationState _authstate;

        public MainWindow()
        {
            InitializeComponent();
            me = null;
            _authstate = null;
        }

        private static class ClientCredentials
        {
            static public string ClientID = "324659692565.apps.googleusercontent.com";
            static public string ClientSecret = "PC0uBYO4hpQD-MPOwXEgRmDB";
        }

Next, add a button to the app with a text box to store status updates. The following code shows the click handler for the button:

        private void authBtn_Click(object sender, RoutedEventArgs e)
        {            
            authenticate();
        }

this simply calls an Authenticate method that is described in the next section.

The heavy lifting: getting authenticated

The following example is simplified to illustrate the basics but the general steps are to authenticate your users and then make RESTful calls that require authentication are to:

  • Setup the authentication provider
  • Get the auth code
  • Store the auth code and generate tokens for API calls
  • Call the API with the token

The library abstracts away some of this but the following code shows how the calls are formed.

Setup the authentication provider

The following code shows how authentication is configured:

        private OAuth2Authenticator<NativeApplicationClient> CreateAuthenticator()
        {
            // Register the authenticator.
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
            provider.ClientIdentifier = ClientCredentials.ClientID;
            provider.ClientSecret = ClientCredentials.ClientSecret;

            var authenticator =
                new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization) { NoCaching = true };            
            return authenticator;
        }

 

Get the auth code

The following code forks a separate process and blocks the app until the auth code is copied from the web site to the app.

        private IAuthorizationState GetAuthorization(NativeApplicationClient client)
        {
            String[] reqAuthScopes = new[] { "https://www.googleapis.com/auth/plus.me"};            

            // Generate the authstate
            if (_authstate == null)
            {
                // need an authorization state
                _authstate = new AuthorizationState(reqAuthScopes);

                // Create the Url                
                Uri requestURL = client.RequestUserAuthorization(reqAuthScopes);

                Uri url = client.RequestUserAuthorization(reqAuthScopes);

                // Show the dialog.
                Process.Start(url.ToString());

                MessageBox.Show("Please click OK after you have copied the token from the web site.");

                String authCode = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();

                if (string.IsNullOrEmpty(authCode))
                {
                    throw new Exception("The authentication request was cancelled by the user.");                
                }

At this point you will have the auth code that you need to set up the client.

Store the auth code and generate tokens for API calls

The following code uses the library to store the auth state and generate tokens:

IAuthorizationState state = client.ProcessUserAuthorization(new Uri("http://localhost"), _authstate);
                return client.ProcessUserAuthorization(authCode, state);                
            }

            // Now perform auth flow
            return null;
        }        

        public void authenticate(){
            // Register the authenticator.                        
            var auth = CreateAuthenticator();

At this point, you have an authenticated client and are ready to perform API calls.

Use the API

Now that you’re all setup to access Google+ functionality, you can use the Plus.v1 class to access user data and the API.  The following code will retrieve the user who auths the client app and set it in my text area:

            // Create the service.            
            ps1 = new PlusService(auth);
            if (ps1 != null)
            {
                PeopleResource.GetRequest grrrr = ps1.People.Get("me");

                Plus.v1.Data.Person me = grrrr.Fetch();

                if (me != null)
                {
                    textBlock1.Text = "You successfully Authenticated!";                    
                    textBlock2.Text = "UserName: " + me.DisplayName + "nURL: " + me.Url + "nProfile id: " + me.Id;
                }
            }
        }

The following image shows the application, after authentication, displaying user data:

 

 

 

 

 

 

Conclusions

This example is a little hacky but is enough to get you started with the .NET library. This is exciting because you can take advantage of the Windows platform and can integrate things lie Google+ functionality into your apps if you’re targeting Windows.

See Also