Click here to Skip to main content
Licence CPOL
First Posted 17 May 2009
Views 25,974
Downloads 933
Bookmarked 41 times

How to Create Google Calendar Events Using .NET

By Abdul_Qayyum | 18 May 2009
.NET code for Google Calendar.
3 votes, 18.8%
1

2
2 votes, 12.5%
3
5 votes, 31.3%
4
6 votes, 37.5%
5
3.39/5 - 16 votes
μ 3.41, σa 2.55 [?]

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)

About the Author

Abdul_Qayyum

Software Developer
Intagleo Pvt Limited
Pakistan Pakistan

Member
I have over 3 years of experience in the following Microsoft Technologies and tools.
Vb.Net
C#.net
Asp.Net
SilverLight
WPF
WCF
SQL Server 2005
Expression Blend
My mail address is abdulqayyum998@hotmail.com. Feel free to contact me at any time.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 Pinmemberprat mandav20:18 30 Sep '11  
GeneralNice one PinmemberMuhammadAdeel21:53 18 Sep '10  
QuestionHow will I add the event for the particular calendar ? Pinmemberksureshhpk1:49 17 Aug '10  
GeneralThough not clearly written, It helped me, my 4 PinmemberRajesh Naik Ponda Goa9:20 2 Mar '10  
Question[My vote of 1] Where did you define "service" ? PinmemberMember 45491990:15 29 Aug '09  
AnswerRe: [My vote of 1] Where did you define "service" ? Pinmemberanubisrwml12:57 12 Jan '11  
GeneralMy vote of 1 PinmvpSimon Stevens2:50 24 Jun '09  
Generalquestion concerning vc++/Google api Pinmemberziad benslimane19:48 18 Jun '09  
Generalcool PinmemberSavara7:27 20 May '09  
GeneralVery interesting PinmemberJeffCirceo9:43 18 May '09  

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.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120209.1 | Last Updated 19 May 2009
Article Copyright 2009 by Abdul_Qayyum
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid