Get And Create Google Calendar Events In .NET

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

Google configuration

We won't go into details of how to create a service account or grant a service access role as admin of Gsuite. Below are some reference links.

Please make sure you add scopes to ClientId as mentioned in the domain 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 the Google Admin SDK Nuget package from Visual Studio.

Or you can directly download it from this link, Please check for the latest version from the above URL, you should get an option to Download the package on the right side. Add references to the below DLLs.

For our purpose, we will use the Nuget Package Manager of Visual Studio to download and reference required DLLs.

Go to Tools->NuGet Package Manager->Package Manager Console. Run the below command in the console.

Install-Package Google.Apis.Calendar.v3 -Version 1.40.3.1692

GoogleAPI

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

API

For this demo, I have created a Windows application and it will create a group and display a list of upcoming events in the 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 the method to Create an Event, if you notice below we are converting time to Asia/Calculate by adding +0530 as an offset. This will make sure the 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> attendees = new List<EventAttendee>();
    attendees.Add(a);
    attendees.Add(b);
    body.Attendees = attendees;
    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 the future as we have set the 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 a message box that will be displayed once we click on Create Calendar Event. If you notice here, the time returned is not IST and we will have to convert it explicitly to IST(not done in the above method).

Message box

Go to calendar.google.com or any of the users added as an attendee and we can see the below event added to the calendar. time here displayed is correct as we have set it in the create event method. It will be displayed as per the user's time zone.

Discussion

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 the user's calendar(send meeting invite).
  • We are using a service account to impersonate users, this can be done by normal users also.
  • We can set different parameters like location, summary, date, etc while creating an event.

Hope you enjoyed reading!

Links to previous articles in this series.