Retrieving upcoming calendar events from a Google Calendar

Google has a great cloud-based calendar service that is part of their Gmail product.  Besides using it as a personal calendar, you can use it to store events for display on your web site.  The calendar is accessible through Google's GData API for which they provide a C# SDK.

Here's some code to retrieve the upcoming entries from the calendar: 

   1:      public class CalendarEvent
   2:      {
   3:          public string Title { get; set; }
   4:          public DateTime StartTime { get; set; }
   5:      }
   6:   
   7:      public class CalendarHelper
   8:      {
   9:          public static CalendarEvent[] GetUpcomingCalendarEvents
  10:               (int numberofEvents)
  11:          {
  12:              CalendarService service = new CalendarService("youraccount");
  13:              EventQuery query = new EventQuery();
  14:              query.Uri = new Uri(
  15:                 "http://www.google.com/calendar/feeds/userid/public/full");
  16:              query.FutureEvents = true;
  17:              query.SingleEvents = true;
  18:              query.SortOrder = CalendarSortOrder.ascending;
  19:              query.NumberToRetrieve = numberofEvents;
  20:              query.ExtraParameters = "orderby=starttime";
  21:              var events = service.Query(query);
  22:              return (from e in events.Entries select new CalendarEvent() 
  23:          { StartTime=(e as EventEntry).Times[0].StartTime, 
  24:          Title = e.Title.Text }).ToArray();
  25:           }          
  26:       }

There are a few special "tricks" to make this work:

  • "SingleEvents" flag will flatten out reoccurring events
  • "FutureEvents", "SortOrder", and the "orderby" parameters will get the upcoming events.
  • "NumberToRetrieve" will limit the amount coming back 
I then using Linq to Objects to put the results into my own DTO for use by my model.  It is always a good idea to place data into your own DTO for use within your MVC model.  This protects the rest of your code from changes to the underlying calendar source or API.

1 Comment

  • Thanks for this. I've spent an extraordinary amount of time trying to retrieve the next event from my calendar.

    The line below was the one I needed.

    query.ExtraParameters = "orderby=starttime";

    The documentation for the Google Data API is pretty poor.

Comments have been disabled for this content.