Interfacing with the Google Calendar API using C#

I needed to script something with Google Calendar, so naturally I headed over to their API page. I found a quick start document and it is a creative commons license, so I can re-post it here:

See my tips after you read this document! See my previous post: Tips for using the Google Calendar API with C#

—————-
Complete the steps described in the rest of this page, and in about five minutes you’ll have a simple .NET console application that makes requests to the Google Calendar API.

Prerequisites

To run this quickstart you’ll need:

  • Visual Studio 2013 or later.
  • Access to the internet and a web browser.
  • A Google account with Google Calendar enabled.

Step 1: Enable the Calendar API

  1. Use this wizard
    to create or select a project in the Google Developers Console and
    automatically enable the API.
  2. In the sidebar on the left, select Consent screen. Select an
    EMAIL ADDRESS and enter a PRODUCT NAME if not already set and click
    the Save button.
  3. In the sidebar on the left, select Credentials and click Create new
    Client ID
    .
  4. Select the application type Installed application, the installed
    application type Other, and click the Create Client ID button.
  5. Click the Download JSON button under your new client ID. Rename it
    to client_secret.json.

Step 2: Install the Google Client Library

  1. Create a new Visual C# Console Application project in Visual Studio.
  2. From the Package Manager Console, with package source set to “nuget.org”
    run the following command:
PM> Install-Package Google.Apis.Calendar.v3

Step 3: Set up the sample

  1. Copy client_secret.json (downloaded in Step 1) into your project directory.
  2. Refresh the Solution Explorer to show the client_secret.json that was
    copied in.
  3. From Solution Explorer right click on client_secret.json and select
    the Include In Project option.
  4. With client_secret.json still selected go to the Properties window and set
    the Copy to Output Directory field to Copy always.
  5. Replace the contents of Program.cs with the following code.
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CalendarQuickstart
{
  /// <summary>
  /// Google Calendar API quickstart application that retrieves the next ten
  /// events of the authenticated user's primary calendar and prints the
  /// summary and start datetime/date of each.
  /// </summary>
  class Program
  {
    static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
    static string ApplicationName = "Calendar API Quickstart";


    static void Main(string[] args)
    {
      UserCredential credential;

      using (var stream = new FileStream("client_secret.json", FileMode.Open,
          FileAccess.Read))
      {
        string credPath = System.Environment.GetFolderPath(System.Environment
          .SpecialFolder.Personal);
        credPath = Path.Combine(credPath, ".credentials");

        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
           GoogleClientSecrets.Load(stream).Secrets,
          Scopes,
          "user",
          CancellationToken.None,
          new FileDataStore(credPath, true)).Result;

        Console.WriteLine("Credential file saved to: " + credPath);
      }

      // Create Calendar Service.
      var service = new CalendarService(new BaseClientService.Initializer()
      {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
      });

      // Define parameters of request.
      EventsResource.ListRequest request = service.Events.List("primary");
      request.TimeMin = DateTime.Now;
      request.ShowDeleted = false;
      request.SingleEvents = true;
      request.MaxResults = 10;
      request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

      Console.WriteLine("Upcoming events:");
      Events events = request.Execute();
      if (events.Items.Count > 0)
      {
        foreach (var eventItem in events.Items)
        {
          string when = eventItem.Start.DateTime.ToString();
          if (String.IsNullOrEmpty(when))
          {
            when = eventItem.Start.Date;
          }
          Console.WriteLine("{0} ({1})", eventItem.Summary, when);
        }
      }
      else
      {
        Console.WriteLine("No upcoming events found.");
      }
      Console.Read();
    }
  }
}

Step 4: Run the sample

Run the sample by clicking Start in the Visual Studio toolbar.

The first time you run the sample it will prompt you to authorize access.

  1. A browser window will open prompting you to login if you are not already
    logged into your Google account. If you are logged into multiple Google
    accounts, you will be asked to select one account to use for the authorization.
  2. Click the Accept button.

Authorization information is stored on the file system, so subsequent
executions will not prompt for authorization.

Further reading

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the Apache 2.0 License. For details, see our Site Policies.

2 Comments

  1. Ragavan says:

    how to get email address from calendar service? Please any one help me.

  2. Rafail says:

    I have a problem on the code line 32-33 gets me this error : "System.IO.FileNotFoundException: 'Could not find file'c:\users\rafail\documents\visualstudio2017\Projects\test\test\bin\Debug\client_secret.json'.'" What should i do ? Please help me ;/

Leave a Reply to Ragavan

How to post code in comments?