Click here to Skip to main content
Click here to Skip to main content
Go to top

How to Read the Google Calendar in C#

, 24 Mar 2010
Rate this:
Please Sign up or sign in to vote.
This article will describe how to read the Google calendar using C#

Introduction

This article describes how to use Google data APIs to read your Google Calendar using C#. It will allow developers to write applications which interact with Google services that will have a number of services such as Calendar, Google Documents, and Contacts, etc.

Synchronization, import, and export of calendars are possible by using APIs. By using Google Calendar service, you can create new events, edit or delete existing events and query for events that match particular criteria.

Note: This article describes only the Google Calendar Service. But in the same manner, you will be able to use other services which Google has provided. Please get the source code for more information.

Calendar.jpg

How to Use Google Data APIs

You have to download the Google data APIs from the below link and install in your machine:

Google data APIs link :http://code.google.com/p/google-gdata/downloads/detail?name=Google%20Data%20API%20Setup%281.4.0.2%29.msi&can=2&q=

Followings are the references to use Google calendar service:

  1. Google.GData.AccessControl
  2. Google.GData.Client
  3. Google.GData.Extensions

The below three namespaces are required.

  • Google.GData.Calendar namespace has view and update calendar events.
  • Google.GData.Extensions namespace contains common extension elements.
  • Google.GData.Client namespace contains service implementation.
using Google.GData.Calendar;
using Google.GData.Extensions;
using Google.GData.Client;

Background

Since Google Application has become more popular, I decided to write an article about Google application which will be useful for many people.

Sample Application Contains Six Projects

Projects.JPG

Google Helpers Project

This project has a helper class for Google calendar which has GetService, GetAllEvents and AddEvents methods.

CalendarHelper class has three properties that are used to get service from Google applications. ApplicationName can be anything like "AAA". UserName is your GMail user Id and Password is your GMail password.

public class CalendarHelper
{
    public string ApplicationName { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }  
} 
  • GetService method will be accessed by the Google Calendar data API and return the service object:
    public class CalendarHelper
    {
        public static CalendarService GetService(string applicationName, 
    				string userName, string password)
        {
            CalendarService service = new CalendarService(applicationName);
            service.setUserCredentials(userName, password);
            return service;
        }  
    } 
  • GetAllEvents method reads the calendar data from the Google calendar by using query object. This will require two parameters. CalendarService is the service object that you created in the previous step. startDate is the actual query which you need to query from Google calendar. EventQuery object holds the query.
    public static IEnumerable<EventEntry> GetAllEvents
    		(CalendarService service, DateTime? startData)
    {
          // Create the query object:
          EventQuery query = new EventQuery();
          query.Uri = new Uri("http://www.google.com/calendar/feeds/" + 
    			service.Credentials.Username + "/private/full");
          if (startData != null)
              query.StartTime = startData.Value;
    
          // Tell the service to query:
          EventFeed calFeed = service.Query(query);
          return calFeed.Entries.Cast<EventEntry>();
    } 
  • AddEvent method will add new calendar data into Google calendar. Event title, content, location, start time and end time have to be provided.
    • Event title is your new calendar title
    • Content is the description
    • Location is event location
    • Start time is when you plan to start the event
    • End time is when you plan to finish the event
    public static void AddEvent(CalendarService service, string title, 
    	string contents, string location, DateTime startTime, DateTime endTime)
    {
        EventEntry entry = new EventEntry();
    
        // Set the title and content of the entry.
        entry.Title.Text = title;
        entry.Content.Content = contents;
    
        // Set a location for the event.
        Where eventLocation = new Where();
        eventLocation.ValueString = location;
        entry.Locations.Add(eventLocation);
    
        When eventTime = new When(startTime, endTime);
        entry.Times.Add(eventTime);
    
        Uri postUri = new Uri
    	("http://www.google.com/calendar/feeds/default/private/full");
    
        // Send the request and receive the response:
        AtomEntry insertedEntry = service.Insert(postUri, entry);
    }   

Google Adapter Project

This project has GoogleEventsSyncDataSource class which will handle all operations for Helper class which we described above. ISyncDataSource interface is inherited into GoogleEventsSyncDataSource class and these interface signatures such as GetItemHeaders which has type IEnumerable<T> and has one parameter which is lastSyncTime that you need to provide date and time. LoadItemContents has not been used in this sample but you can implement it if you need. WriteItems has IEnumerable<T> type parameter which you need to provide when you write events to Google.

GoogleEventsSyncDataSource.JPG

GoogleEventsSyncDataSource contractor will create a service object which you will need later.
Note: You have to change user name and password as required.

namespace GoogleAdapter
{
    public class GoogleEventsSyncDataSource : ISyncDataSource<GenericEvent>
    {
        CalendarService service;

        public GoogleEventsSyncDataSource()
        {
            service = CalendarHelper.GetService("AAA", "mygmail@gmail.com", "mypassword");
        }

        #region ISyncDataSource<GenericEvent> Members

        public string Id
        {
            get { return "Google Calander Sync Data Source"; }
        }

        public IEnumerable<GenericEvent> GetItemHeaders(DateTime? lastSyncTime)
        {
            var googleEvents = CalendarHelper.GetAllEvents(service, lastSyncTime);
            List<GenericEvent> genericEvents = new List<GenericEvent>();
            foreach (var googleEvent in googleEvents)
            {
                GenericEvent genericEvent = new GenericEvent();
                genericEvent.Title = googleEvent.Title.Text;
                genericEvent.Contents = googleEvent.Content.Content;
                genericEvent.Location = googleEvent.Locations.First().ValueString;
                genericEvent.StartTime = googleEvent.Times.First().StartTime;
                genericEvent.EndTime = googleEvent.Times.First().EndTime;
                genericEvents.Add(genericEvent);
            }
            return genericEvents;
        }

        public void LoadItemContents(IEnumerable<GenericEvent> items)
        {
            //Nothing to load here
        }

        public void WriteItems(IEnumerable<GenericEvent> items)
        {
            foreach (var item in items)
            {
                CalendarHelper.AddEvent(service, item.Title, 
		item.Contents, item.Location, item.StartTime, item.EndTime);
            }
        }

        #endregion
    }
}

Generic Entities Project

This project has generic event (calendar) which is used to create event collection.

GenericEvent.JPG

IEquatable interface has been implemented for the comparison of event data if required.

namespace GenericEntities
{
    public class GenericEvent : IEquatable<GenericEvent>
    {
        public string Title { get; set; }
        public string Contents { get; set; }
        public string Location { get; set; }
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }

        #region IEquatable<GenericEvent> Members

        public bool Equals(GenericEvent other)
        {
            //Compare all fields to check equality
            if (this.Title == other.Title &&
                this.Contents == other.Contents &&
                this.Location == other.Location &&
                this.StartTime == other.StartTime &&
                this.EndTime == other.EndTime)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion
    }
} 

DataSynchronizer Project

SyncManager.cs will return a list of calendars from Google.

namespace DataSynchronizer
{
    public class SyncManager<T> where T:IEquatable<T>
    {
        public string Name { get; set; }
        public ISyncDataSource<T> Source1 { get; set; }

        public IEnumerable<T> Synchronize(DateTime? lastSyncTime)
        {
            try
            {
                IEnumerable<T> list = Source1.GetItemHeaders(lastSyncTime).ToList();
                return list;
               
            }
            catch (Exception ex)
            {
                throw ex;
            }
           
        }
    }
}

ISyncDataSource.cs interface:

namespace DataSynchronizer
{
    public interface ISyncDataSource<T> where T : IEquatable<T>
    {
        string Id { get; }
        IEnumerable<T> GetItemHeaders(DateTime? lastSyncTime);
        void LoadItemContents(IEnumerable<T> items);
        void WriteItems(IEnumerable<T> items);
    }
} 

DataSynchronizationService Project

This is a high level service which will be invoked by your application. Here eventManager is generic type of GenericEvent. You will be able to add other Google services by creating helper and generic types.

namespace DataSynchronizer
{
    public class SyncService
    {
        SyncManager<GenericEvent> eventManager = new SyncManager<GenericEvent>();
        public string LastUpdateDate;
        public SyncService()
        {
            //Initialize Event Manager
            eventManager.Name = "..Event Synchronizer";
            eventManager.Source1 = new GoogleEventsSyncDataSource();
        }

        public IList  SynchronizeEvents()
        {
            IList list = eventManager.Synchronize(DateTime.Now).ToList();
            return list;
        }
    }
} 

How to Test this Application: TestApplication Project

Service instance is a type of SyncService under DataSynchronizationService:

namespace TestApplication
{
    public partial class Form1 : Form
    {
        SyncService service = new SyncService();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IList  list = service.SynchronizeEvents();
            dataGridView1.DataSource = list;
        }
    }    
} 

License

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

Share

About the Author

Pubudu Kasakara
Architect
Singapore Singapore
Pubudu Kasakara is working as Solution Architect in Singapore. He has more than 11 years of professional involvement in the IT industry. Worked in successful projects involving mainly the Service Oriented Application by contributing to all requirements gathering, design and implementation phases. He is having experience with SOA applications development, Microsoft .NET, BizTalk, He is member of Charted It professional in UK.
 
Solution Architect
http://www.kasakara.com

Comments and Discussions

 
QuestionVersion 3 API - possible? PinmemberAndrew Truckle26-Jun-14 7:45 
AnswerRe: Version 3 API - possible? PinmemberPubudu Kasakara19-Aug-14 22:56 
QuestionEvent color problem PinmemberMember 1025784111-Sep-13 1:53 
QuestionPassword... PinmemberToddHileHoffer28-May-13 16:42 
QuestionHas this API been deprecated? PinmemberMember 986221725-Feb-13 0:25 
QuestionThank you Pinmemberiosuntrichard11-Jan-13 2:53 
QuestionRead all the calendars PinmemberChindaara19-Dec-12 15:08 
GeneralMy vote of 5 Pinmemberravithejag13-Nov-12 19:55 
QuestionCan you use the API to write to the calendar too? PinmemberJohn Pettersson27-Aug-12 3:22 
QuestionEvent Colors Pinmemberaxsys35620-Mar-12 1:10 

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.140926.1 | Last Updated 25 Mar 2010
Article Copyright 2010 by Pubudu Kasakara
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid