Click here to Skip to main content
15,885,366 members
Articles / Programming Languages / C#

How to Create Google Calendar Events Using .NET

Rate me:
Please Sign up or sign in to vote.
3.57/5 (19 votes)
18 May 2009CPOL1 min read 103.2K   5.8K   41   17
.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.).

C#
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)



Comments and Discussions

 
QuestionExecution of authentication request returned unexpected result: 404 Pin
OceanLuo20-Mar-20 1:12
OceanLuo20-Mar-20 1:12 
QuestionExecution of authentication request returned unexpected result: 404 Pin
Member 133218295-Feb-18 1:41
Member 133218295-Feb-18 1:41 
QuestionExecution of authentication request returned unexpected result: 404 Pin
Nidhin Radhakrishnan10-Jan-18 19:54
Nidhin Radhakrishnan10-Jan-18 19:54 
QuestionCompiled but I can't get in... Pin
ancich11-Sep-14 11:18
ancich11-Sep-14 11:18 
GeneralMy vote of 5 Pin
Nour Lababidi1-Aug-13 10:22
Nour Lababidi1-Aug-13 10:22 
Questionhow do we deleted the Events and update the Existing Events ,,(Specific Ones) Pin
nikitasomaiya8-Feb-13 0:33
nikitasomaiya8-Feb-13 0:33 
Question5 from me Pin
johnnyTray28-Aug-12 20:58
johnnyTray28-Aug-12 20:58 
GeneralMy vote of 1 Pin
prat mandav30-Sep-11 19:18
prat mandav30-Sep-11 19:18 
GeneralNice one Pin
MuhammadAdeel18-Sep-10 20:53
MuhammadAdeel18-Sep-10 20:53 
QuestionHow will I add the event for the particular calendar ? Pin
ksureshhpk17-Aug-10 0:49
ksureshhpk17-Aug-10 0:49 
GeneralThough not clearly written, It helped me, my 4 Pin
Rajesh Naik Ponda Goa2-Mar-10 8:20
Rajesh Naik Ponda Goa2-Mar-10 8:20 
Question[My vote of 1] Where did you define "service" ? Pin
Member 454919928-Aug-09 23:15
Member 454919928-Aug-09 23:15 
AnswerRe: [My vote of 1] Where did you define "service" ? Pin
anubisrwml12-Jan-11 11:57
anubisrwml12-Jan-11 11:57 
GeneralMy vote of 1 Pin
Simon P Stevens24-Jun-09 1:50
Simon P Stevens24-Jun-09 1:50 
Generalquestion concerning vc++/Google api Pin
ziad benslimane18-Jun-09 18:48
ziad benslimane18-Jun-09 18:48 
Generalcool Pin
nørdic20-May-09 6:27
nørdic20-May-09 6:27 
GeneralVery interesting Pin
Jeff Circeo18-May-09 8:43
Jeff Circeo18-May-09 8:43 

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

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