Click here to Skip to main content
15,868,076 members
Articles / Programming Languages / C#

How to Read the Google Calendar in C#

Rate me:
Please Sign up or sign in to vote.
4.82/5 (38 votes)
24 Mar 2010CPOL3 min read 195.9K   9.5K   128   48
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.
C#
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.

C#
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:
    C#
    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.
    C#
    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
    C#
    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.

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

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

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

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

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

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


Written By
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

 
GeneralGreat article Pin
Wrangly31-Aug-11 23:25
Wrangly31-Aug-11 23:25 
GeneralRedirect to google login Pin
Harisri23-Mar-11 0:27
Harisri23-Mar-11 0:27 
GeneralRe: Redirect to google login Pin
vikjo11-May-11 12:14
vikjo11-May-11 12:14 
Generalgreat stuff! Pin
devlynx16-Aug-10 11:33
devlynx16-Aug-10 11:33 
QuestionHow to get data From a Shared Calendar Pin
Britman Branco12-Jul-10 0:57
Britman Branco12-Jul-10 0:57 
AnswerRe: How to get data From a Shared Calendar Pin
CoderJ7-Mar-12 11:26
CoderJ7-Mar-12 11:26 
QuestionCan We Add Access Control to Particular Calandar Pin
Britman Branco9-Jul-10 20:18
Britman Branco9-Jul-10 20:18 
GeneralExcellent one :I need a Help too [modified] Pin
Britman Branco9-Jul-10 0:10
Britman Branco9-Jul-10 0:10 
You used The Following to Retrive a Calendar Events

EventQuery query = new EventQuery();

query.Uri = new Uri("uri string");




EventFeed calFeed = service.Query(query);
return calFeed.Entries.Cast<EventEntry>();

[how Can i get all the uri string for all calendars of Logined user]

modified on Friday, July 9, 2010 6:37 AM

GeneralRe: Excellent one :I need a Help too Pin
Pubudu Kasakara9-Jul-10 0:29
Pubudu Kasakara9-Jul-10 0:29 
GeneralRe: Excellent one :I need a Help too Pin
Britman Branco9-Jul-10 0:44
Britman Branco9-Jul-10 0:44 
Generalvery useful Pin
v# guy30-Apr-10 18:44
v# guy30-Apr-10 18:44 
GeneralRe: very useful Pin
Pubudu Kasakara2-May-10 14:57
Pubudu Kasakara2-May-10 14:57 
GeneralMy vote of 2 Pin
deckerson25-Mar-10 3:03
deckerson25-Mar-10 3:03 
GeneralSource code has been upaded with new features. Pin
Pubudu Kasakara18-Mar-10 18:01
Pubudu Kasakara18-Mar-10 18:01 
GeneralProblem with the GenericEvent type Pin
sferlix11-Mar-10 23:43
sferlix11-Mar-10 23:43 
GeneralRe: Problem with the GenericEvent type Pin
Pubudu Kasakara12-Mar-10 2:29
Pubudu Kasakara12-Mar-10 2:29 
GeneralRe: Problem with the GenericEvent type Pin
Pubudu Kasakara12-Mar-10 2:32
Pubudu Kasakara12-Mar-10 2:32 
GeneralRe: Problem with the GenericEvent type Pin
sferlix12-Mar-10 5:21
sferlix12-Mar-10 5:21 
GeneralRe: Problem with the GenericEvent type Pin
Pubudu Kasakara15-Mar-10 3:08
Pubudu Kasakara15-Mar-10 3:08 
GeneralRe: Problem with the GenericEvent type Pin
DecodedSolutions.co.uk25-May-10 4:38
DecodedSolutions.co.uk25-May-10 4:38 
GeneralRe: Problem with the GenericEvent type Pin
Pubudu Kasakara27-May-10 17:08
Pubudu Kasakara27-May-10 17:08 

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.