BigBastis Blog

.NET

Retrieving calendar events using Google Calendar API

Posted on .

Retrieving calendar events using Google Calendar API

Introduction

.NET

Retrieving calendar events using Google Calendar API

Posted on .

Introduction

Calendars are fun and every big player on the market (Google, Microsoft, Yahoo, you name it) provides its own implementation of one, usually for free. And it’s even more fun to integrate those calendars into your own apps and services. Lucky for us, all major calendar providers offer pretty good support and well documented APIs for us to use in our apps.

In this post you will see how easy it is to set up a simple application that uses the google calendar API to access calendar events.

API Setup

Whenever you want to use a third party API ,you need to register your application as a client in order to receive an API-Key. This API-Key will make sure that your application doesn’t access parts of the API its not supposed to and also (in case of Google) that you don’t use the API too much (later more on that).

So create a Google Account if you don’t have one already and navigate your browser to Google’s developer portal. Here you’ll find many useful information including sample applications and different how-tos.

Our next step is to create a new project in the Google Developer Console. When you visit this page for the first time you should see a message telling you to „create a new project to get started“ – and this exactly what we’ll do.

New Project Dialog

New Project Dialog

Enter the name of your app and also a project id, which must be unique between all Google apps, just be a bit creative on this step, nobody will see the project id anyway :). When you’re done hit Create, and a few seconds later you should see your newly created project.

Click on your new project and in the next screen select Enable an API on the right.

Enable APIs

Enable APIs

Now we need to select which APIs should be available to our application. Since we want to access the calendar events, it makes sense to enable the calendar API. Since it’s a pretty long list of different APIs its easier to just enter ‚calendar‘ into the filter-textbox. When you successfully located the Calendar API link, click on it and flip the switch to ‚on‘.

Flipping the switch

Flipping the switch

Great, now our project is allowed to use the Google calendar API but we still need to create those API Keys i mentioned at the beginning. In order to do that we first need to set up the consent screen, this is a popup which every user of our app will see where he will allow(or disallow) our application to access his account. They usually look something like this:

Example consent screen

Example consent screen

On the right menu select APIs & auth and then – you guessed it – Consent screen. Here it’s important to select the Email Address and to specify a Product Name. These values will later be shown to the user on the consent screen, so make sure the user recognizes your application by this values.

Now let’s generate an API-Key. Select APIs & auth and then Credentials on the menu on the right. Then click on Create new Client ID.

Create a new Client ID

Create a new Client ID

Here you need to choose what type of application you are creating. The code you’ll need to write later will differ based on the type of application you select now. To keep things simple select Installed application as the application type and since we’re going to create a Windows app other as the installed application type. After you’re done you should see something like this:

Generated client ID

Generated client ID

This is it, now we have everything wee need to start writing code.

A few words about the Client ID

As a free user you are allowed to create 500k requests/day to the calendar API (differs dependent on the API). This sounds like a lot at first but you may run into this limitation sooner than you think if your app will be used by more than one user, so maybe you will need to think about how to save requests inside your app in the future.

Setting up the Project

So let’s move on to the interesting part and use the API we just configured. As i mentioned above it will be a Windows Desktop Application Project inside of Visual Studio.

First thing we need to take care of is the download of the libraries which will do all the heavy lifting for us. In our case it is the Google Calendar API library.

Let’s use NuGet to get those libraries into our project. Open the Packet Manager console (Extras > NuGet-Packet-Manager > NuGet-Packet-Manager-Console) and type:

Install-Package Google.Apis.Calendar.v3

A few seconds later you should see the needed libraries added to your references in Project explorer.
Now we should have all needed libararies to authenticate at Google and use the calendar API.

Connect to Google

The first thing our application needs to do is, of course, connect to Google and get the permission by the user to use his or her calendar data. This will be handled by Google automatically when our client application connects for the first time.

CalendarService calendarConnection;
public bool connectCalendar()
{
	ClientSecrets secrets = new ClientSecrets 
	{ 
		ClientId = "xxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", 
		ClientSecret = "cmqb8LAJcvyyyyy-sVToGwh" 
	};

	try
	{
		UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
			secrets,
			new string[]
			{ 
				CalendarService.Scope.Calendar
			},
			"user",
			CancellationToken.None)
		.Result;

		var initializer = new BaseClientService.Initializer();
		initializer.HttpClientInitializer = credential;
		initializer.ApplicationName = "MyProject";
		calendarConnection = new CalendarService(initializer);
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.Message);
		return false;
	}
	return true;
}

Lets go step by step through the code. The first step should bring up some memories from the first part of this article, here we’re setting up the API-Key which we generated earlier. We’re creating a ClientSecrets Object to hold this information.

In the next step we’re creating a UserCredential object by calling the AuthorizeAsync method of the GoogleWebAuthorizationBroker class which is provided by the Google API library. We also provide four parameters to this method, the first of which is the ClientSecrets object holding our authentication information.

UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
	secrets,
	new string[]
	{ 
		CalendarService.Scope.Calendar
	},
	"user",
	CancellationToken.None)
.Result;

The second parameter is a string-array containing the permissions we would like the user to give us, in this case we’re only asking for access to the calendar, but we could ask for anything google is offering (as long as we have activated the API in the Project settings on the Google Developer Console).

The third parameter is a simple string containing the word „user“, which could be anything you like since it’s only a reference to the user authorization in the internal DataStore holding the granted permission by the user. This parameter gets important when your application manages more than one Google Account at a time and you need to reference different users in your API requests.

Finally, the fourth parameter specifies a CancellationToken, which makes sense, since the method we call is async, but to keep things simple we don’t provide one here.

When this line of code is executed the Google API library will launch a new browser window and promt the user with the question weather he or she would like to accept your request to access the calendar data. If the user consents, this information will be saved in an internal DataStore under the key you provided („user“ in our example here). If you’re interested, you can have a look inside this store, its located in your AppData directory:

[userfolder]\[yourname]\AppData\Roaming\Google.Apis.Auth

You can of course also use your own store to hold this information, you can provide your own store as a fifth parameter to the AuthorizeAsync method.

The next block of code creates the actual connection to the calendar:

var initializer = new BaseClientService.Initializer();
initializer.HttpClientInitializer = credential;
initializer.ApplicationName = "MyProject";
calendarConnection = new CalendarService(initializer);

With the Initializer which holds our credentials(user permission) and the name of our app we can now create a CalendarService which we will now use to acces the actual calendar data.

List of all Calendars

Before we can read calendar events we first need to know where we want to read them from. Because a user can have unlimited calendars on his account we first need to get a list of those and then select the one we want to access. Lucky for us it’s an one liner:

var calendars = calendarConnection.CalendarList.List().Execute().Items;

After this line has been executed, we will have a complete list of calendars available to the user. Every entry in this list will contain every important information about the calendar including the id, which is important for every other action.

CalendarListEntry expanded
CalendarListEntry

Everything we need is provided here

So let’s print all the calendars we have available:

foreach (CalendarListEntry entry in calendars)
{
    Console.WriteLine(entry.Summary + " - " + entry.Id);
}

This should provide us with something like this:

"BWI 14" - "m3ur6kkk9vo1vdrraphiaa3jj8@group.calendar.google.com"
"Sebastian Gross" - "bigbasti@gmail.com"
"patxxx@googlemail.com" - "patxxx@gmail.com"
"Testkalender" - "d7oegsapgo53pgueicn7kiohk8@group.calendar.google.com"
"Contacts' birthdays and events" - "#contacts@group.v.calendar.google.com"
"Day of the Year" - "#daynum@group.v.calendar.google.com"
"Holidays in Germany" - "en.german#holiday@group.v.calendar.google.com"
"Phases of the Moon" - "ht3jlfaac5lfd6263ulfh4tql8@group.calendar.google.com"
"Weather" - "p#weather@group.v.calendar.google.com"
"Week Numbers" - "p#weeknum@group.v.calendar.google.com"

As you can see you get also the calendars you have subscribed to and also the shared calendars of your friends.

Retrieving calendar entries

Now let’s use one of those calendars to read the entries in a timespan.

Events request = null;
ListRequest lr = calendarConnection.Events.List("calendar id (email)");

lr.TimeMin = DateTime.Now.AddDays(-5); //five days in the past
lr.TimeMax = DateTime.Now.AddDays(5);  //five days in the future

request = lr.Execute();

This is a very straight forward way of retrieving calendar events in a given timespan.

Google Calendar Event
Google Calendar Event

Everything specific to this event

Well basically that’s it, now you have a list of the events from your calendar. Do what ever you want.

Creating new calendar events

As you might imagine creating calendar events is as easy as reading them. Let’s create an Event including some Attendees and their rsvp status:

Event googleCalendarEvent = new Event();

googleCalendarEvent.Start = new EventDateTime();
googleCalendarEvent.End = new EventDateTime();

if (AllDay) 
{
	//If you want to create an all day event you don't need
	//to provide the time, only the date
	googleCalendarEvent.Start.Date = DateTime.Now.ToString("yyyy-MM-dd");
	googleCalendarEvent.End.Date = DateTime.Now.ToString("yyyy-MM-dd");
}
else
{
	googleCalendarEvent.Start.DateTime = DateTime.Now;
	googleCalendarEvent.End.DateTime = DateTime.Now.AddDays(1);
}
googleCalendarEvent.Summary = "Its my birthday";
googleCalendarEvent.Description = "I'm becoming one year older";
googleCalendarEvent.Location = "at home";


//Set Remainder
googleCalendarEvent.Reminders = new Event.RemindersData();
googleCalendarEvent.Reminders.UseDefault = false;
EventReminder reminder = new EventReminder();
reminder.Method = "popup";
reminder.Minutes = 60;
googleCalendarEvent.Reminders.Overrides = new List();
googleCalendarEvent.Reminders.Overrides.Add(reminder);

//Attendees
googleCalendarEvent.Attendees.Add(new EventAttendee()
	{
		DisplayName = "Sebastian",
		Email = "my@email.com",
		ResponseStatus = "accepted"
	});
googleCalendarEvent.Attendees.Add(new EventAttendee()
	{
		DisplayName = "Fiona",
		Email = "fiona@email.com",
		ResponseStatus = "needsAction"
	});	
			
calendarConnection.Events.Insert(googleCalendarEvent , "calendar id (email)").Execute();

Conclusion

Google offers really great libraries to use their APIs, they make it incredibly easy to access and authenticate to Google Services. The rest of the APIs works really similar to the examples you saw here, maybe the hardest part is even to setup the API.

If you need some examples you can actually run, you can have a look at my GitHub repository. The project SyncMyCal is a very basic Outlook to Google calendar synchronisation tool which uses the examples above.

profile

Sebastian Gross

http://www.bigbasti.com

Sebastian Gross arbeitet in Bielefeld als Softwareentwickler für .NET und Java im Bereich Web.Als Fan der .NET-Plattform lässt er sich kein Userguppen Treffen und Community Event im Raum OWL entgehen.Dabei hat er eine besondere Vorliebe für das ASP.NET MVC Framework und für das Test Driven Development (TDD) entwickelt.

There are no comments.

Kommentar verfassen

View Comments (0) ...
Navigation