Retreiving upcoming calendar events from a Google Calendar

Posted by brian_ritchie on ASP.net Weblogs See other posts from ASP.net Weblogs or by brian_ritchie
Published on Fri, 04 Mar 2011 03:19:00 GMT Indexed on 2011/03/04 7:25 UTC
Read the original article Hit count: 398

Filed under:
|
|
|

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.

© ASP.net Weblogs or respective owner

Related posts about c#

Related posts about google