Click here to Skip to main content
Click here to Skip to main content

How to Create Google Calendar Events Using .NET

, 18 May 2009
Rate this:
Please Sign up or sign in to vote.
.NET code for Google Calendar.

Introduction

This article will provide you information about how Google Calendar events can be manipulated in .NET. I have performed only two functionalities: total calendar retrievals and then populating events against a selected calendar. Finally, creating events for a selected Google Calendar.

Using the code

You will have to add references to the following DLLs:

  • Google.Google.GData.AccessControl.dll
  • Google.GData.Calendar.dll
  • Google.GData.Client.dll
  • Google.GData.Extensions.dll

First of all, we will get all the calendars owned by the user having the Google Calendar. For this, we will create a CalendarService object as shown below. Here, UserName and Password will be your Google credentials. After that, we will create a CalendarQuery object and will use the CalendarService object to get the Calendars against the given query.

Now, for getting events against a selected calendar, first, we will have to create CalendarURI for the particular calendar. Then, we will create a RequestFactory to create a request for the particular query (select, update, delete etc.) and the proxy object if required. At last, we will provide the final query to the CalendarService object to get the EventFeed array (events) from the selected calendar. The functionality for creating events in the Google Calendar is much similar except for the fact that there will be a change in the query (this time, we will be requesting for insertion along with setting different values for events, e.g., Name, Description, Location etc.).

CalendarQuery query = new CalendarQuery();

query.Uri = new Uri("http://www.google.com/calendar" + 
                    "/feeds/default/owncalendars/full");
CalendarFeed resultFeed = myService.Query(query);

if (cmbGoogleCalendar.SelectedIndex >= 0)
{
    //Get the selected calendar whose events you want to retrieve
    this.CalendarURI.Text = "http://www.google.com/calendar/feeds/" + 
      ((CalendarEntry)(cmbGoogleCalendar.SelectedItem)).SelfUri.ToString(
      ).Substring(((CalendarEntry)
      (cmbGoogleCalendar.SelectedItem)).SelfUri.ToString().LastIndexOf("/") 
      + 1) + "/private/full"; 
}

string calendarURI = this.CalendarURI.Text;
userName = this.UserName.Text;
passWord = this.Password.Text;
this.entryList = new ArrayList(50); 
ArrayList dates = new ArrayList(50); 
EventQuery query = new EventQuery();
GDataGAuthRequestFactory requestFactory = 
   (GDataGAuthRequestFactory)service.RequestFactory;
IWebProxy iProxy = WebRequest.GetSystemWebProxy();
WebProxy myProxy = new WebProxy();

// potentially, setup credentials on the proxy here
myProxy.Credentials = CredentialCache.DefaultCredentials;
myProxy.UseDefaultCredentials = false;

if (ProxyAddress.Text.Trim() != "" && ProxyPort.Text.Trim() != "")
{
    myProxy.Address = new Uri("http://" + ProxyAddress.Text.Trim() + 
                              ":" + ProxyPort.Text.Trim());
}

if (userName != null && userName.Length > 0)
{
    service.setUserCredentials(userName, passWord);
}

// only get event's for today - 1 month until today + 1 year
query.Uri = new Uri(calendarURI);
requestFactory.CreateRequest(GDataRequestType.Query, query.Uri);// = myProxy;

if (calendarControl.SelectionRange != null)
{
    query.StartTime = calendarControl.SelectionRange.Start.AddDays(-1) ;
    query.EndTime = calendarControl.SelectionRange.End.AddDays(1) ;
}
else
{
    query.StartTime = DateTime.Now.AddDays(-12);
    query.EndTime = DateTime.Now.AddMonths(0);
}

EventFeed calFeed = service.Query(query) as EventFeed;

// now populate the calendar
if (calFeed != null && calFeed.Entries.Count == 0)
{
    MessageBox.Show("No Event found");
}
else
{
    while (calFeed != null && calFeed.Entries.Count > 0)
    {
        // look for the one with dinner time...
        foreach (EventEntry entry in calFeed.Entries)
        {
            this.entryList.Add(entry);

            if (entry.Times.Count > 0)
            {
                foreach (When w in entry.Times)
                {
                    dates.Add(w.StartTime);
                }
            }
        }

        // just query the same query again.
        if (calFeed.NextChunk != null)
        {
            query.Uri = new Uri(calFeed.NextChunk);
            calFeed = service.Query(query) as EventFeed;
        }
        else
            calFeed = null;
    }
    DateTime[] aDates = new DateTime[dates.Count];

    int i = 0;
    foreach (DateTime d in dates)
    {
        aDates[i++] = d;
    }

    this.calendarControl.BoldedDates = aDates;
    // this.calendarControl.SelectionRange = 
    //         new SelectionRange(DateTime.Now, DateTime.Now);
    if (aDates.Length >0)
    {
        MessageBox.Show("Please select the Dates marked " + 
                        "bold in the calendar to see events");
    }
    else
    {
        MessageBox.Show("No Event found against selected dates rage and calendar");
    }
}

try
{
    EventEntry entry = new EventEntry();
    // Set the title and content of the entry.
    entry.Title.Text = EventName.Text;
    entry.Content.Content = Description.Text;
    // Set a location for the event.
    Where eventLocation = new Where();
    eventLocation.ValueString = location.Text;
    entry.Locations.Add(eventLocation);
    DateTime dtstartdatetime = calStartDate.Value;
    DateTime dtenddatetime = CalEndDate.Value;
    string[] str = new string[1];
    str[0] = ":";

    double dblHour = Convert.ToDouble(cmbStartTime.SelectedItem.ToString().Split(
                     str, StringSplitOptions.RemoveEmptyEntries)[0]);
    double dblMinutes = Convert.ToDouble(cmbStartTime.SelectedItem.ToString().Split(
                        str, StringSplitOptions.RemoveEmptyEntries)[1]);
    dtstartdatetime.AddHours(dblHour);
    dtstartdatetime.AddMinutes(dblMinutes);

    dblHour = Convert.ToDouble(cmbEndTime.SelectedItem.ToString().Split(
              str, StringSplitOptions.RemoveEmptyEntries)[0]);
    dblMinutes = Convert.ToDouble(cmbEndTime.SelectedItem.ToString().Split(
                 str, StringSplitOptions.RemoveEmptyEntries)[1]);
    dtenddatetime.AddHours(dblHour);
    dtenddatetime.AddMinutes(dblMinutes);
    When eventTime = new When(dtstartdatetime, dtenddatetime);
    entry.Times.Add(eventTime);
    userName = UserName.Text;
    passWord = Password.Text;

    if (userName != null && userName.Length > 0)
    {
        service.setUserCredentials(userName, passWord);
    }

    Uri postUri;
    postUri = new Uri("http://www.google.com/calendar" + 
                      "/feeds/default/private/full");

    if (GoogleCalendar.SelectedIndex >= 0)
    {
        postUri = new Uri("http://www.google.com/calendar/feeds/" + 
          ((CalendarEntry)(GoogleCalendar.SelectedItem)).SelfUri.ToString(
          ).Substring(((CalendarEntry)(
          GoogleCalendar.SelectedItem)).SelfUri.ToString(
          ).LastIndexOf("/") + 1) + "/private/full" );
    }
    GDataGAuthRequestFactory requestFactory = 
        (GDataGAuthRequestFactory)service.RequestFactory;
    IWebProxy iProxy = WebRequest.GetSystemWebProxy();
    WebProxy myProxy = new WebProxy();

    // potentially, setup credentials on the proxy here
    myProxy.Credentials = CredentialCache.DefaultCredentials;
    myProxy.UseDefaultCredentials = false;

    if (ProxyAddress.Text.Trim() != "" && ProxyPort.Text.Trim() != "")
    {
        myProxy.Address = new Uri("http://" + ProxyAddress.Text.Trim() + 
                                  ":" + ProxyPort.Text.Trim());
    }

    requestFactory.CreateRequest(GDataRequestType.Insert, postUri);// = myProxy;
    // Send the request and receive the response:
    AtomEntry insertedEntry = service.Insert(postUri, entry);

    MessageBox.Show("Event Successfully Added");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message.ToString());
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


Comments and Discussions

 
GeneralMy vote of 5 PinmemberNour Lababidi1-Aug-13 10:22 
Questionhow do we deleted the Events and update the Existing Events ,,(Specific Ones) Pinmembernikitasomaiya8-Feb-13 0:33 
Question5 from me PinmemberjohnnyTray28-Aug-12 20:58 
GeneralMy vote of 1 Pinmemberprat mandav30-Sep-11 19:18 
GeneralNice one PinmemberMuhammadAdeel18-Sep-10 20:53 
QuestionHow will I add the event for the particular calendar ? Pinmemberksureshhpk17-Aug-10 0:49 
GeneralThough not clearly written, It helped me, my 4 PinmemberRajesh Naik Ponda Goa2-Mar-10 8:20 
Question[My vote of 1] Where did you define "service" ? PinmemberMember 454919928-Aug-09 23:15 
AnswerRe: [My vote of 1] Where did you define "service" ? Pinmemberanubisrwml12-Jan-11 11:57 
GeneralMy vote of 1 PinmvpSimon Stevens24-Jun-09 1:50 
Generalquestion concerning vc++/Google api Pinmemberziad benslimane18-Jun-09 18:48 
Generalcool PinmemberSavara20-May-09 6:27 
GeneralVery interesting PinmemberJeffCirceo18-May-09 8:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140827.1 | Last Updated 19 May 2009
Article Copyright 2009 by Abdul_Qayyum
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid