Retreiving upcoming calendar events from a Google Calendar
- by brian_ritchie
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:
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: Consolas, "Courier New", Courier, Monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
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.