C# application - Read Google Contacts
Asked Answered
S

2

5

Since Google stopped support for their older Auth, and now we have to use oAuth 2, our simple desktop application can no longer read contacts from my google account.

Fine - i understand this, however this new oAuth 2 is extraordinarily complicated... and im not talking about from a developer perspective. From what i am reading online. We now have to make our customers jump over a multitude of hoops in order for our simple application to read contacts stored in their Google mail/Contacts.

My iPhone seems to be able to sync contacts just fine with just the typical email and password that i entered about a year ago. How do they get it to work? and yet with my simple desktop application, the client has to be rummaging around in Google Developer sites and with API settings etc. I'm a developer and im confused!! - could you imagine what my customer is going to go through... it cant be this complicated.

Is there anyone who can give me the simple 1,2,3 to get a C# desktop application to go off and get the contacts (read-only) from a particular Gmail account... with the least amount of fiddling around (for the owner of the Gmail account).

Ill do all the hard work in the application - i just don't want to client to have to spend an hour authorizing and creating API's and clicking around in a developer site (he/she is NOT a developer).

Syd answered 27/10, 2015 at 8:21 Comment(6)
You understand they are going to have to authenticate your application right?Maize
github.com/google/google-gdata/blob/…Maize
I fully understand there must be some "tick" or "enable" or something that the client must do - i totally get that. But from what i see now... there is way to much "stop" actions, my clients would just give up and not bother. They would blame us for making it complicated.Syd
All they should have to do is accept it once. Once they have done that you will get a refresh token that you can store someplace and then they wont need to do it again. Your application should have access to there data for as long as they don't revoke the authentication.Maize
What type of application do you have?Maize
We are making our own application in c#Syd
M
8

The main problem you have here is that contacts is an old Gdata API. It is possible to use Oauth2 with the Gdata library but its not pretty. Personally I like to hack things a little. I use the Current .net client library with the old Gdata client library.

Nuget New client library for authentication:

not 100% sure this is the only one you need let me know if it doesn't work we can find it. You basically need Google.apis.auth.oauth2 and google apis.util.store.

Install-Package Google.Apis.Auth

Nuget old client library for contacts:

Install-Package Google.GData.Contacts

Code

 using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using Google.Contacts;
using Google.GData.Client;
using System;
using System.Threading;

public static void auth()
{

    string clientId = "xxxxxx.apps.googleusercontent.com";
    string clientSecret = "xxxxx";


    string[] scopes = new string[] { "https://www.googleapis.com/auth/contacts.readonly" };     // view your basic profile info.
    try
    {
        // Use the current Google .net client library to get the Oauth2 stuff.
        UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                     , scopes
                                                                                     , "test"
                                                                                     , CancellationToken.None
                                                                                     , new FileDataStore("test")).Result;

        // Translate the Oauth permissions to something the old client libray can read
        OAuth2Parameters parameters = new OAuth2Parameters();
        parameters.AccessToken = credential.Token.AccessToken;
        parameters.RefreshToken = credential.Token.RefreshToken;
        RunContactsSample(parameters);
        Console.ReadLine();
    }
    catch (Exception ex)
    {

        Console.ReadLine();

    }
    Console.ReadLine();


}

/// <summary> 
/// Send authorized queries to a Request-based library 
/// </summary> 
/// <param name="service"></param> 
private static void RunContactsSample(OAuth2Parameters parameters)
{
    try
    {
        RequestSettings settings = new RequestSettings("Google contacts tutorial", parameters);
        ContactsRequest cr = new ContactsRequest(settings);
        Feed<Contact> f = cr.GetContacts();
        foreach (Contact c in f.Entries)
        {
            Console.WriteLine(c.Name.FullName);
        }
    }
    catch (Exception a)
    {
        Console.WriteLine("A Google Apps error occurred.");
        Console.WriteLine();
    }
}

Tutorial can be found here

Google developers console

All applications accessing google apis must be registered on Google developers console. It is the application accessing Google that is registered users running the code do not need to do this step. Its you as a developer who has to register it.

From this you get the client id and client secret used in the code above.

Maize answered 27/10, 2015 at 9:44 Comment(14)
Yes, that's all very nice and all, and i have seen a bunch of code like this... but the clientId and secret is what? some thing that i had to go into the developer section to go and generate. I'm going to repeat this... my client is NOT a developer! or am i totally misunderstanding this?Syd
You as a developer need to create the client id and client secret. This is not something your users need to do. It is application specific. There is no way around this step all applications accessing google apis must be registered on Google developers console. This might help daimto.com/registering-a-project-with-googleMaize
So i make a project in Google API and get the clientid etc. We do this once off as developers. Great. Now my customer comes along, where does he specify his details, how do we get HIS contacts as against another persons contacts?Syd
When the application runs the first time It will pop up a consent screen. They approve it. filedatastore will store the users authentication information for you on the machine. If more then one user is going to run your code on the same machine you will need to change the "test" variable to differentiate between users.Maize
When ever user "test" runs the application you will only be getting data back for user "test".Maize
Ah, ok, so we will replace the "test" with a text box field for the email address. Then what about the clients password?Syd
"When the application runs the first time It will pop up a consent screen"... really? We are writing the application tho. Does the Google.API.Auth DLL handle this?Syd
Yup the client library handles it all for you.Maize
Success!! Thanks for your help guys, we got it working now. The confusing part was that generally you are logged in to google because you have just setup the API stuff - so of course the test code it wasn't asking for credentials. Tip... Go setup the API, get the client id etc and then LOG OUT OF GOOGLE... or it will be helluva confusing, because you are given the oAuth consent page (directly without longing in or selecting an account), so you get your access token, and as a result your own contacts only.Syd
Once you understand Oauth2 its really not that bad. Its just very confusing in the beginning I am happy that I could help, and that you got it working.Maize
I got error in the opened in browser page: The redirect URI in the request, http://localhost:35310/authorize/, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/309207651634-06ooi078hv12hrnggrr8c38ikqdp87it.apps.googleusercontent.com?project=309207651634 to update the authorized redirect URIs. What redirect url I shoud specify and where? I don't understand why http://localhost:35310/authorize/ is pointed in error message. Can you help me please?Jacqualinejacquard
For starters get visual Studio to stop adding port numbers I can't remember how you will either need to open a new question or Google itMaize
Nuget NEW client library for contacts:?Fennelflower
When I ran this code it did not worked because I was missing to enable the contacts api under APIs & Services search for contacts and enable it!Emmie
L
0

I have done this but its all a bit of a blur from like you say, a lot of fiddling.

I think you can sign up and setup a project in google developer console and generate a service account. Then the client will need to sign in to HERE as the google app admin and fill out the clientID field with the name of your service account generated by the developer console and the API scope you need access to.

In the end I just logged in as the client to their admin panel and set it up for them. There is no easy way about it without the client also engaging a google apps re-seller to assist. I managed to figure it out as a developer with a lot of googling.

Lorient answered 27/10, 2015 at 8:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.