Managing Google Calendar Events using .Net

By | May 14, 2011

Yesterday I posted an article on how to create events in SalesForce programatically now we will do the same thing for Google Calendar. The processes are nearly the same but it’s not as straightforward as the SalesForce one specially on Event Creation and Custom fields extensions. One good thing though that Google has is a native .Net API that you can add to your project so you do not need to reference to the Google Calendar web service and the dll handles its for you.


First you need to download that API and add it in your .Net Project. You need to install the Google_Data_API_Setup_{CurrentVerion}.msi and to refer to it, you need to browse to “C:Program Files (x86)GoogleGoogle Data API SDKRedist” on 64 bit machines and “C:Program FilesGoogleGoogle Data API SDKRedist” on 32 bit machines by default

You need to reference 4 main items for this scenario and it is the following

Now include that reference in your codes

using Google.GData.Client;
using Google.GData.Calendar;
using Google.GData.Extensions;

Then like what we had done with the SalesForce article we need a method for login and here is the code snippet. Again I provided a proxy setting in case you need


private CalendarService GAuthenticate()
{
    string sGoogleUserName = "username";
    string sGooglePassword = "password";
    Uri oCalendarUri = new Uri("http://www.google.com/calendar/feeds/" + sGoogleUserName + "/private/full");

    //Initialize Calendar Service
    CalendarService oCalendarService = new CalendarService("CalendarSampleApp");
    oCalendarService.setUserCredentials(sGoogleUserName, sGooglePassword);

    //Use Proxy 
    GDataRequestFactory oRequestFactory = (GDataRequestFactory)oCalendarService.RequestFactory;
    WebProxy oWebProxy = new WebProxy(WebRequest.DefaultWebProxy.GetProxy(oCalendarUri));
    oWebProxy.Credentials = CredentialCache.DefaultCredentials;
    oWebProxy.UseDefaultCredentials = true;
    oRequestFactory.Proxy = oWebProxy;

    return oCalendarService;
}

Now lets go to the methods you need, on all of the methods discussed below you will need the GAuthenticate to execute your methods

1. Creating Calendar Entries in Google programatically

Now if you notice we used 4 different object types unlike in SalesForce where we used only 1 object which is the SalesForceService.Event. Here we have to define an Event, Where, When and ExtendedProperty if you need one. ExtendedProperty is a way of adding properties to the objects programatically , so in this case we created a property called SynchronizationID which will hold our Guid that you can use with other apps.
Hint: I use this for my sync application.

//Set Event Entry 
EventEntry oEventEntry = new EventEntry();
oEventEntry.Title.Text = "Test Calendar Entry From .Net";
oEventEntry.Content.Content = "Hurrah!!! I posted my first Google calendar event through .Net";

//Set Event Location 
Where oEventLocation = new Where();
oEventLocation.ValueString = "New Zealand";
oEventEntry.Locations.Add(oEventLocation);

//Set Event Time
When oEventTime = new When(new DateTime(2011, 5, 31, 9, 0, 0), new DateTime(2011, 5, 31, 9, 0, 0).AddHours(1));
oEventEntry.Times.Add(oEventTime);

//Set Additional Properties
ExtendedProperty oExtendedProperty = new ExtendedProperty();
oExtendedProperty.Name = "SynchronizationID";
oExtendedProperty.Value = Guid.NewGuid().ToString();
oEventEntry.ExtensionElements.Add(oExtendedProperty);

CalendarService oCalendarService = GAuthenticate();

//Prevents This Error
//{"The remote server returned an error: (417) Expectation failed."}
System.Net.ServicePointManager.Expect100Continue = false;

//Save Event
oCalendarService.Insert(oCalendarUri, oEventEntry);

You might also notice this line “System.Net.ServicePointManager.Expect100Continue = false”, that takes care of the HTTP 417 Error which is explained here.

2. Searching Calendar Entries in Google programatically

Searching is also straightforward, just use the EventQuery properties to pass to the CalendarService.Query method. Set the EventQuery.Query to the same query you use when you search for the calendar in Google.

You can also fliter by date start and end by using the StartDate and EndDate properties

CalendarService oCalendarService = GAuthenticate();

//Search for Event
EventQuery oEventQuery = new EventQuery(oCalendarUri.ToString());
oEventQuery.Query = "Query String";
oEventQuery.StartDate = new DateTime(2011, 6, 5);
oEventQuery.EndDate = new DateTime(2012, 6, 5);

Google.GData.Calendar.EventFeed oEventFeed = oCalendarService.Query(oEventQuery);

//Delete Related Events
foreach (EventEntry oEventEntry in oEventFeed.Entries)
{
    //Do your stuff here
    string sEventTitle = oEventEntry.Title.ToString();
}

But if you want to search for the ExtendedProperty like the “SynchronizationID” we created on the event creation on step 1 then you need to use the ExtraParameters property and use the extq=[YourCutomProperty:TheValue] to get what you need.

CalendarService oCalendarService = GAuthenticate();

//Search for Event
EventQuery oEventQuery = new EventQuery(oCalendarUri.ToString());
oEventQuery.ExtraParameters = "extq=[SynchronizationID:Your GUID Here]";

Google.GData.Calendar.EventFeed oEventFeed = oCalendarService.Query(oEventQuery);

//Delete Related Events
foreach (EventEntry oEventEntry in oEventFeed.Entries)
{
    //Do your stuff here
    string sEventTitle = oEventEntry.Title.ToString();
}

3. Updating Calendar Entries in Google programatically

Updating is straight forward, just search for the item then use the CalendarService.Update method

CalendarService oCalendarService = GAuthenticate();

//Search for Event
EventQuery oEventQuery = new EventQuery(oCalendarUri.ToString());
oEventQuery.ExtraParameters = "extq=[SynchronizationID:{Your GUID Here}]";

Google.GData.Calendar.EventFeed oEventFeed = oCalendarService.Query(oEventQuery);

//Delete Related Events
foreach (EventEntry oEventEntry in oEventFeed.Entries)
{
    //Update Event
    oEventEntry.Title.Text = "Updated Entry";

    oCalendarService.Update(oEventEntry);
    break;
}

4. Deleting Calendar Entries in Google programatically

Deleting is straight forward, as well, just search for the item then use the CalendarService.Delete method

CalendarService oCalendarService = GAuthenticate();

//Search for Event
EventQuery oEventQuery = new EventQuery(oCalendarUri.ToString());
oEventQuery.ExtraParameters = "extq=[SynchronizationID:{Your GUID Here}]";

Google.GData.Calendar.EventFeed oEventFeed = oCalendarService.Query(oEventQuery);

//Delete Related Events
foreach (EventEntry oEventEntry in oEventFeed.Entries)
{
    oEventEntry.Delete();
    break;
}


13 thoughts on “Managing Google Calendar Events using .Net

  1. Michael Franz

    hi,

    how does one send an appointment to someone else? All the examples I have found on the net are authenticating to a known user. what if I want to send an appointment to someone else

    I have done it with Hotmails calendar no problem

    Reply
  2. naresh

    Hi,
    Please tell me how to do this in windows phone 7 ?
    am unable to add the google dll’s in wp7 please give me reply asap
    thanks in advance

    Reply
    1. Raymund

      For Google do something like this
      foreach (CalendarParticipant oGuest in oCalendarEvent.Guests)
      {
      if (oGuest.Email != "")
      {
      Who oEventParticipant = new Who();
      oEventParticipant.ValueString = oGuest.Name;
      oEventParticipant.Email = oGuest.Email;
      oEventParticipant.Rel = Who.RelType.EVENT_ATTENDEE;
      oEventEntry.Participants.Add(oEventParticipant);
      }
      }

      For SalesForce its something like this
      if (oCalendarEvent.Guests.Count != 0)
      {
      oEvent.EventAttendees = GetContactIDs(oCalendarEvent.Guests);
      }
      public QueryResult GetContactIDs(List oCalendarParticipants)
      {
      string sWhereClause = "";

      foreach (CalendarParticipant oCalendarParticipant in oCalendarParticipants)
      {
      sWhereClause += "'" + oCalendarParticipant.Email + "',";
      }

      sWhereClause = "(" + sWhereClause.Substring(0, sWhereClause.Length - 1) + ")";

      //SforceService oSalesForceService = Authenticate();
      QueryResult oQueryResult = null;
      oSalesForceService.QueryOptionsValue = new QueryOptions();
      oQueryResult = oSalesForceService.query("select Id from Contact where email in " + sWhereClause);

      return oQueryResult;
      }

      Reply
  3. Rit K

    hi !, Nice code with very helpful details , please help me in following:

    1: Want to add some Guests programmatically.
    2: then send invitations to all of them so that they can add this to their Calendar or Accept/Reject (if possible).

    this will help me a lot.

    Thank you for all these code.

    Reply
    1. Raymund

      Hi Rit, please read this on my last comment. It shows how to add guests and if I can remember once this is added they will be sent an email automatically as Gmail does that (still have to confirm though)

      Reply
  4. gopal

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Google.GData.Calendar;
    using Google.GData.Client;
    using Google.GData.Extensions;
    using System.Net;
    public partial class _Default : System.Web.UI.Page
    {

    string sGoogleUserName = “username”;
    string sGooglePassword = “password”;
    Uri oCalendarUri = new Uri(“http://www.google.com/calendar/feeds/” + “username” + “/private/full”);

    protected void Page_Load(object sender, EventArgs e)
    {

    Google.GData.Calendar.EventEntry oEventEntry = new Google.GData.Calendar.EventEntry();
    oEventEntry.Title.Text = “Test Calendar Entry From .Net”;
    oEventEntry.Content.Content = “Hurrah!!! I posted my first Google calendar event through .Net”;

    Where oEventLocation = new Where();
    oEventLocation.ValueString = “India”;
    oEventEntry.Locations.Add(oEventLocation);

    When oEventTime = new When(new DateTime(2015, 1, 15, 9, 0, 0), new DateTime(2015, 1, 15, 9, 0, 0).AddHours(1));
    oEventEntry.Times.Add(oEventTime);

    CalendarService oCalendarService = GAuthenticate();

    System.Net.ServicePointManager.Expect100Continue = false;

    oCalendarService.Insert(oCalendarUri,oEventEntry);

    }
    private CalendarService GAuthenticate()
    {

    //Initialize Calendar Service
    CalendarService oCalendarService = new CalendarService(“CalendarSampleApp”);
    oCalendarService.setUserCredentials(sGoogleUserName, sGooglePassword);

    //Use Proxy
    GDataRequestFactory oRequestFactory = (GDataRequestFactory)oCalendarService.RequestFactory;
    WebProxy oWebProxy = new WebProxy(WebRequest.DefaultWebProxy.GetProxy(oCalendarUri));
    oWebProxy.Credentials = CredentialCache.DefaultCredentials;
    oWebProxy.UseDefaultCredentials = true;
    oRequestFactory.Proxy = oWebProxy;

    return oCalendarService;
    }
    }

    Show Above Code i try and i getting error like:-

    Google.GData.Client.GDataRequestException: Execution of authentication request returned unexpected result: 405

    Reply
  5. gopal

    To use Google calender Api is it Compulsory to Create Project in Google Console? And Further Process to be done?
    if Yes Then Please Tell me All step By step information to use Google Calender API in Asp.net Website.

    Thank you For Replaying…..

    Reply

Leave a Reply