Get And Create Google Calendar Events In .NET

In this article, we will learn how to create google calendar events using C# and .NET.

In this article, we will learn how to create Google Calender Event from .NET. This is the fifth article in series accessing Google API from .NET. I have added links to other articles in at end of this blog. 
 

Google configuration

 
We won't go into details of how to create a service account, grant service access role as admin of Gsuite. Below is some reference link.
Please make sure you add scopes to ClientId as mentioned in domain wide delegation step. For this sample below scope would be required.
  1. https://www.googleapis.com/auth/calendar,  
  2. https://www.googleapis.com/auth/calendar.events,
  3. https://www.googleapis.com/auth/calendar.events.readonly  

.NET API

 
Get Google Admin Sdk nuget package from Visual Studio.
 
Or you can directly download from this link, Please check for the latest version from the above URL, you should get an option to Download package on right side. Add references to below DLLs. 
 
For our purpose, we will use Nuget Package Manager of Visual Studio to download and reference required DLLs.  
 
Go to Tools->NuGet Package Manager->Package Manager Console. Run below command in the console. 
  1. Install-Package Google.Apis.Calendar.v3 -Version 1.40.3.1692   
Get And Create Google Calendar Events From .NET
 
All below highlighted dll references will be added. Ignore Other google API dlls(Directory, Drive, and Sheets), this is required for other samples.
 
Get And Create Google Calendar Events From .NET
 
For this demo, I have created a windows application and it will create group and display list of upcoming events in message box. 
  1. private void button8_Click(object sender, EventArgs e)  
  2. {  
  3.     CalendarService _service = this.GetCalendarService("PATHTOJSONFILE\gsuite-migration-123456-a4556s8df.json");  
  4.     CreateEvent(_service);  
  5.     GetEvents(_service);  
  6. }  
First method to get CalendarService object.
  1. private CalendarService GetCalendarService(string keyfilepath) {  
  2.  try {  
  3.   string[] Scopes = {  
  4.    CalendarService.Scope.Calendar,  
  5.    CalendarService.Scope.CalendarEvents,  
  6.    CalendarService.Scope.CalendarEventsReadonly  
  7.   };  
  8.   
  9.   GoogleCredential credential;  
  10.   using(var stream = new FileStream(keyfilepath, FileMode.Open, FileAccess.Read)) {  
  11.    // As we are using admin SDK, we need to still impersonate user who has admin access    
  12.    //  https://developers.google.com/admin-sdk/directory/v1/guides/delegation    
  13.    credential = GoogleCredential.FromStream(stream)  
  14.     .CreateScoped(Scopes).CreateWithUser("spidey@avengers.com");  
  15.   }  
  16.   
  17.   // Create Calendar API service.    
  18.   var service = new CalendarService(new BaseClientService.Initializer() {  
  19.    HttpClientInitializer = credential,  
  20.     ApplicationName = "Calendar Sample",  
  21.   });  
  22.   return service;  
  23.  } catch (Exception ex) {  
  24.   throw;  
  25.  }  
  26. }  
Next let us write method to Create Event, if you notice below we are converting time to Asia/Calculate by adding +0530 as offset. This will make sure time is in IST.
  1. private void CreateEvent(CalendarService _service) {  
  2.  Event body = new Event();  
  3.  EventAttendee a = new EventAttendee();  
  4.  a.Email = "spidey@avengers.com";  
  5.  EventAttendee b = new EventAttendee();  
  6.  b.Email = "ironman@avengers.com";  
  7.  List < EventAttendee > attendes = new List < EventAttendee > ();  
  8.  attendes.Add(a);  
  9.  attendes.Add(b);  
  10.  body.Attendees = attendes;  
  11.  EventDateTime start = new EventDateTime();  
  12.  start.DateTime = Convert.ToDateTime("2019-08-28T09:00:00+0530");  
  13.  EventDateTime end = new EventDateTime();  
  14.  end.DateTime = Convert.ToDateTime("2019-08-28T11:00:00+0530");  
  15.  body.Start = start;  
  16.  body.End = end;  
  17.  body.Location = "Avengers Mansion";  
  18.  body.Summary = "Discussion about new Spidey suit";  
  19.  EventsResource.InsertRequest request = new EventsResource.InsertRequest(_service, body, "nickfury@avengers.com");  
  20.  Event response = request.Execute();  
  21. }  
The below method is to get upcoming events(please note that it will only return events in future as we have set TimeMin parameter to Now.
  1. private void GetEvents(CalendarService _service) {  
  2.  // Define parameters of request.    
  3.  EventsResource.ListRequest request = _service.Events.List("primary");  
  4.  request.TimeMin = DateTime.Now;  
  5.  request.ShowDeleted = false;  
  6.  request.SingleEvents = true;  
  7.  request.MaxResults = 10;  
  8.  request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;  
  9.   
  10.  string eventsValue = "";  
  11.  // List events.    
  12.  Events events = request.Execute();  
  13.  eventsValue = "Upcoming events:\n";  
  14.  if (events.Items != null && events.Items.Count > 0) {  
  15.   foreach(var eventItem in events.Items) {  
  16.    string when = eventItem.Start.DateTime.ToString();  
  17.    if (String.IsNullOrEmpty(when)) {  
  18.     when = eventItem.Start.Date;  
  19.    }  
  20.    eventsValue += string.Format("{0} ({1})", eventItem.Summary, when) + "\n";  
  21.   }  
  22.   MessageBox.Show(eventsValue);  
  23.  } else {  
  24.   MessageBox.Show("No upcoming events found.");  
  25.  }  
  26. } 
We have all other methods ready, let us now run the code and see the output. Below is message box which will be displayed once we click on Create Calendar Event. If you notice here, time returned is not IST and we will have to convert it explicitly to IST(not done in above method)
 
Get And Create Google Calendar Events From .NET
 
Go to calendar.google.com or any of user added as an attendee and we can see below event added in calendar. time here displayed is correct as we have set in create event method. It will be displayed as per user's time zone.
 
Get And Create Google Calendar Events From .NET
 
So here it is, a new meeting invite is sent to spiderman and iron man to discuss about new Spiderman suit. :) 
 

Conclusion 

  • We can use Google Calendar API to create events in user's calendar(send meeting invite).
  • We are using service account to and impersonate user, this can be done by normal user also.
  • We can set different parameters like location, summary, date etc while creating event.
Hope you enjoyed reading...!!
 
Links to previous articles in this series,