Search code examples
c#.net-coregoogle-contacts-api

How to connect .NET Core to Google contacts


I want to edit google contacts based on a database. I've done all the work, the only thing left is to implement the API, but I just can't wrap my head around how to do so. I've made an application in the Google API dashboard and made an OAuth2.0 client (I'm not even sure if that is what I need).

I've downloaded the Google assemblies and included them in my C# Console Application.

  • How can I connect to google contacts from my Console Application?
  • How can I add and remove entries from the contacts list?

Solution

  • The answer can be found HERE under the "installed applications" section. Here's an excerpt:

    Sample code using the Books API:

    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Books.v1;
    using Google.Apis.Books.v1.Data;
    using Google.Apis.Services;
    using Google.Apis.Util.Store;
    
    namespace Books.ListMyLibrary
    {
        /// <summary>
        /// Sample which demonstrates how to use the Books API.
        /// https://developers.google.com/books/docs/v1/getting_started
        /// <summary>
        internal class Program
        {
            [STAThread]
            static void Main(string[] args)
            {
                Console.WriteLine("Books API Sample: List MyLibrary");
                Console.WriteLine("================================");
                try
                {
                    new Program().Run().Wait();
                }
                catch (AggregateException ex)
                {
                    foreach (var e in ex.InnerExceptions)
                    {
                        Console.WriteLine("ERROR: " + e.Message);
                    }
                }
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }
    
            private async Task Run()
            {
                UserCredential credential;
                using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] { BooksService.Scope.Books },
                        "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
                }
    
                // Create the service.
                var service = new BooksService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Books API Sample",
                    });
    
                var bookshelves = await service.Mylibrary.Bookshelves.List().ExecuteAsync();
                ...
            }
        }
    }
    
    • In this sample code a new UserCredential instance is created by calling the GoogleWebAuthorizationBroker.AuthorizeAsync method. This static method gets the following:

      • The client secret (or a stream to the client secret).
      • The required scopes.
      • The user identifier.
      • The cancellation token for cancelling an operation.
      • An optional data store. If the data store is not specified, the default is a FileDataStore with a default Google.Apis.Auth folder. The folder is created in Environment.SpecialFolder.ApplicationData.
    • The UserCredential that is returned by this method is set as a HttpClientInitializer on the BooksService (using the initializer). As explained above, UserCredential implements an HTTP client initializer.

    • Notice that in the above sample code, the client secret information is loaded from a file, but you can also do the following:


    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        new ClientSecrets
        {
            ClientId = "PUT_CLIENT_ID_HERE",
            ClientSecret = "PUT_CLIENT_SECRETS_HERE"
        },
        new[] { BooksService.Scope.Books },
        "user",
        CancellationToken.None,
        new FileDataStore("Books.ListMyLibrary")
    );