Get And Create Google Calendar Events In .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.
https://www.googleapis.com/auth/calendar,  
https://www.googleapis.com/auth/calendar.events,
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.
Install-Package Google.Apis.Calendar.v3 -Version 1.40.3.1692

 

All below highlighted dll references will be added. Ignore Other google API dlls(Directory, Drive, and Sheets), this is required for other samples.

For this demo, I have created a windows application and it will create group and display list of upcoming events in message box.
private void button8_Click(object sender, EventArgs e)  
{  
    CalendarService _service = this.GetCalendarService("PATHTOJSONFILE\gsuite-migration-123456-a4556s8df.json");  
    CreateEvent(_service);  
    GetEvents(_service);  
}

 

First method to get CalendarService object.

private CalendarService GetCalendarService(string keyfilepath) {  
 try {  
  string[] Scopes = {  
   CalendarService.Scope.Calendar,  
   CalendarService.Scope.CalendarEvents,  
   CalendarService.Scope.CalendarEventsReadonly  
  };  
  
  GoogleCredential credential;  
  using(var stream = new FileStream(keyfilepath, FileMode.Open, FileAccess.Read)) {  
   // As we are using admin SDK, we need to still impersonate user who has admin access    
   //  https://developers.google.com/admin-sdk/directory/v1/guides/delegation    
   credential = GoogleCredential.FromStream(stream)  
    .CreateScoped(Scopes).CreateWithUser("[email protected]");  
  }  
  
  // Create Calendar API service.    
  var service = new CalendarService(new BaseClientService.Initializer() {  
   HttpClientInitializer = credential,  
    ApplicationName = "Calendar Sample",  
  });  
  return service;  
 } catch (Exception ex) {  
  throw;  
 }  
}

 

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.

private void CreateEvent(CalendarService _service) {  
 Event body = new Event();  
 EventAttendee a = new EventAttendee();  
 a.Email = "[email protected]";  
 EventAttendee b = new EventAttendee();  
 b.Email = "[email protected]";  
 List < EventAttendee > attendes = new List < EventAttendee > ();  
 attendes.Add(a);  
 attendes.Add(b);  
 body.Attendees = attendes;  
 EventDateTime start = new EventDateTime();  
 start.DateTime = Convert.ToDateTime("2019-08-28T09:00:00+0530");  
 EventDateTime end = new EventDateTime();  
 end.DateTime = Convert.ToDateTime("2019-08-28T11:00:00+0530");  
 body.Start = start;  
 body.End = end;  
 body.Location = "Avengers Mansion";  
 body.Summary = "Discussion about new Spidey suit";  
 EventsResource.InsertRequest request = new EventsResource.InsertRequest(_service, body, "[email protected]");  
 Event response = request.Execute();  
}

 

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.

private void GetEvents(CalendarService _service) {  
 // 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;  
  
 string eventsValue = "";  
 // List events.    
 Events events = request.Execute();  
 eventsValue = "Upcoming events:\n";  
 if (events.Items != null && events.Items.Count > 0) {  
  foreach(var eventItem in events.Items) {  
   string when = eventItem.Start.DateTime.ToString();  
   if (String.IsNullOrEmpty(when)) {  
    when = eventItem.Start.Date;  
   }  
   eventsValue += string.Format("{0} ({1})", eventItem.Summary, when) + "\n";  
  }  
  MessageBox.Show(eventsValue);  
 } else {  
  MessageBox.Show("No upcoming events found.");  
 }  
}

 

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)

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.

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…!!

Note – This article was originally published at this link.

(Visited 264 times, 1 visits today)