Click here to Skip to main content
11,414,670 members (65,627 online)
Click here to Skip to main content

How to Create Google Calendar Events Using .NET

, 18 May 2009 CPOL
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

 
QuestionCompiled but I can't get in... [modified] Pin
ancich11-Sep-14 12:18
memberancich11-Sep-14 12:18 
GeneralMy vote of 5 Pin
Nour Lababidi1-Aug-13 11:22
memberNour Lababidi1-Aug-13 11:22 
Questionhow do we deleted the Events and update the Existing Events ,,(Specific Ones) Pin
nikitasomaiya8-Feb-13 1:33
membernikitasomaiya8-Feb-13 1:33 
Question5 from me Pin
johnnyTray28-Aug-12 21:58
memberjohnnyTray28-Aug-12 21:58 
GeneralMy vote of 1 Pin
prat mandav30-Sep-11 20:18
memberprat mandav30-Sep-11 20:18 
GeneralNice one Pin
MuhammadAdeel18-Sep-10 21:53
memberMuhammadAdeel18-Sep-10 21:53 
QuestionHow will I add the event for the particular calendar ? Pin
ksureshhpk17-Aug-10 1:49
memberksureshhpk17-Aug-10 1:49 
GeneralThough not clearly written, It helped me, my 4 Pin
Rajesh Naik Ponda Goa2-Mar-10 9:20
memberRajesh Naik Ponda Goa2-Mar-10 9:20 
Question[My vote of 1] Where did you define "service" ? Pin
Member 454919929-Aug-09 0:15
memberMember 454919929-Aug-09 0:15 
AnswerRe: [My vote of 1] Where did you define "service" ? Pin
anubisrwml12-Jan-11 12:57
memberanubisrwml12-Jan-11 12:57 
GeneralMy vote of 1 Pin
Simon Stevens24-Jun-09 2:50
mvpSimon Stevens24-Jun-09 2:50 
Generalquestion concerning vc++/Google api Pin
ziad benslimane18-Jun-09 19:48
memberziad benslimane18-Jun-09 19:48 
Generalcool Pin
Savara20-May-09 7:27
memberSavara20-May-09 7:27 
GeneralVery interesting Pin
JeffCirceo18-May-09 9:43
memberJeffCirceo18-May-09 9: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 | Terms of Use | Mobile
Web02 | 2.8.150427.4 | Last Updated 19 May 2009
Article Copyright 2009 by Abdul_Qayyum
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid