Click here to Skip to main content
Click here to Skip to main content

Using Google Calendar in ASP.NET Website

, 27 May 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
How to use Google Calendar in ASP.NET website
Calendar

Problem

Google Calendar is used to store concert dates of some famous Russian DJs. The task is to display these dates with titles on the ASP.NET website.

What is Google Calendar?

Google calendar is a free Google service for planning of meetings, events, affairs with a binding to a calendar. It is possible to set a time for a meeting, repetition, a reminder, to invite other participants (service sends the invitation by e-mail). It is possible to create several calendars, each with its own name.

Possible Ways to Solve the Problem

Google has Calendar Data API that allows you to view and update calendar events from your application.

The following Calendar Data API libraries are there:

  1. .NET
  2. Java
  3. JavaScript
  4. PHP
  5. Python

We will use .NET library for our task, because we have ASP.NET application where we need to work with Google Calendar service.

Meaningful Statement of the Problem

  1. Get an array of events from the Google Calendar, using the following information: "Google calendar name", "Google account name", "Google account password".
  2. Display these events on the site.

Solution of the Problem

(1) Get an array of events from the Google Calendar, using the following information: "Google calendar name", "Google account name", "Google account password".

Consider the solution to this problem step by step:

Step 1: Download .NET library for Google data API

You can download the .NET library for Google data API from Google_Data_API_Setup_1.8.0.0.msi. Then, run the installer. The library will be installed into the following folder: C:\Program Files\Google\Google Data API SDK\Redist\.

Step 2: Copy the necessary files to the Web site

Copy the following files from C:\Program Files\Google\Google Data API SDK\Redist\ into Bin folder of the website: Google.GData.AccessControl.dll, Google.GData.Calendar.dll, Google.GData.Client.dll, Google.GData.Extensions.dll.

Next, add the References to these files in the website project.

Go to References-Add Reference-Browse, choose files and press OK.

Step 3: Create class to interact with Google Calendar service, using the ASP.NET Google API library.

Our task is to create a class which will return an array of events (array of CalendarEventObject objects) from Google Calendar using information that we will provide: "Google calendar name", "Google account name", "Google account password". CalendarEventObject class is defined by us as follows:

public class CalendarEventObject
{
    public DateTime Date { get; set; }
    public string Title { get; set; }
}

The problem is solved as follows:

public class GoogleCalendar
    {
        private const string CALENDARS_URL = 
	"https://www.Google.com/calendar/feeds/default/owncalendars/full";
        private const string CALENDAR_TEMPLATE = 
	"https://www.Google.com/calendar/feeds/{0}/private/full";
        private string m_CalendarUrl = null;
        private string m_CalendarId = null;
        private readonly CalendarService m_Service = null;
        private readonly string m_CalendarName;
        private readonly string m_UserName;
        private readonly string m_Password;
    public GoogleCalendar(string calendarName, string username, string password)
        {
            m_CalendarName = calendarName;
            m_UserName = username;
            m_Password = password;
            m_Service = new CalendarService("Calendar");
        }
        public CalendarEventObject[] GetEvents()
        {
            try
            {
                if (Authenticate())
                {
                    EventQuery query = new EventQuery(m_CalendarUrl);
                    EventFeed feed = m_Service.Query(query);
                    return (from EventEntry entry in feed.Entries
                            select new CalendarEventObject()
                            {Date = entry.Times[0].StartTime, 
				Title = entry.Title.Text}).ToArray();
                }
                else
                {
                    return new CalendarEventObject[0];
                }
            }
            catch (Exception)
            {
                return new CalendarEventObject[0];
            }
        }

      private bool Authenticate()
        {
            m_Service.setUserCredentials(m_UserName, m_Password);
            return SaveCalendarIdAndUrl();
        }

        private bool SaveCalendarIdAndUrl()
        {
            CalendarQuery query = new CalendarQuery();
            query.Uri = new Uri(CALENDARS_URL);
            CalendarFeed resultFeed = (CalendarFeed)m_Service.Query(query);

            foreach (CalendarEntry entry in resultFeed.Entries)
            {
                if (entry.Title.Text == m_CalendarName)
                {
                    m_CalendarId = entry.Id.AbsoluteUri.Substring(63);
                    m_CalendarUrl = string.Format(CALENDAR_TEMPLATE, m_CalendarId);
                    return true;
                }
            }
            return false;
        }

   public string GetCalendarId()
    {
          return m_CalendarId;
    }
}

Description of Variables and Constants

  • CALENDARS_URL - URL where you can get an array of all calendars that the specified account has
  • CALENDAR_TEMPLATE - URL to specific calendar without specifying Id of calendar so far
  • m_CalendarUrl - URL to specific calendar
  • m_CalendarId - Id of specific calendar
  • m_Service - Represents a client connection to a Calendar service
  • m_CalendarName - Represents Google Calendar name
  • m_UserName - Represents Google account name
  • m_Password - Represent Google account password

Description of Constructor and Methods

Constructor

Here is the creation of CalendarService. When you create CalendarService, you provide the name of your application, that is, in fact, any string.

m_Service=new CalendarService("Calendar"); 
Authenticate()

The .NET client library can be used to work with either public or private calendars. Public calendars are read-only and do not require authentication. When you work with private calendars, you need to be authenticated. To authenticate, invoke the setUserCredentials method of CalendarService, specifying the user name and password of Google account:

m_Service.setUserCredentials(m_UserName, m_Password);

Also Authenticate() method invokes SaveCalendarIdAndUrl() helper method to save target Calendar Id and Calendar URL.

SaveCalendarIdAndUrl()

Here is searching for the appropriate calendar in the account's calendars and saving the found Id and URL of Calendar in internal variables.

To request all calendars in account, we create object of CalendarQuery class, set its Uri property, and ask for calendars using Query method of CalendarService:

CalendarQuery query = new CalendarQuery();
query.Uri = new Uri(CALENDARS_URL);
CalendarFeed resultFeed = (CalendarFeed)m_Service.Query(query); 

Then we iterate through account's calendars and search by name for calendar that we need. If we found calendar, then we save Calendar Id and Calendar URL:

 foreach (CalendarEntry entry in resultFeed.Entries)
            {
                if (entry.Title.Text == m_CalendarName)
                {
                    m_CalendarId = entry.Id.AbsoluteUri.Substring(63);
                    m_CalendarUrl = string.Format(CALENDAR_TEMPLATE, m_CalendarId);
                    return true;
                }
            }

One tricky moment may be noted:

m_CalendarId = entry.Id.AbsoluteUri.Substring(63);

Thus, Id rips out from the full Calendar URL. Why so tricky? Often Calendar Id equals Calendar Name. But it is not always true. So this is the most reliable way for me to get Calendar Id for all cases. And it works nice.

GetEvents()

The method returns an array of CalendarEventObject objects(array of events, read from the Google Calendar).

To request events from a specific calendar (this calendar has URL saved before in m_CalendarUrl variable), we create object of EventQuery class and then ask for calendar events using Query method of CalendarService. Then we get custom array of CalendarEventObject objects from Google EventEntry array, and return it:

EventQuery query = new EventQuery(m_CalendarUrl);
EventFeed feed = m_Service.Query(query);
return (from EventEntry entry in feed.Entries
       select new CalendarEventObject()
          {Date = entry.Times[0].StartTime, 
           Title = entry.Title.Text}).ToArray(); 
GetCalendarId()

This method returns Calendar Id saved before in m_CalendarId variable.

(2) Display these events on the site

There are two possible ways for us to display Calendar events:

a) Get array of Calendar events and display it
GoogleCallendar calendar = new GoogleCalendar
	("Google calendar name", "Google account name", "Google account password");
CalendarEventObject[] events= calendar.GetEvents()

So, we have an array of events (CalendarEventObject[]). Now we can go through array and display events on the page as we like. The result may be, for example, as follows:

Calendar
b)Display Google Calendar on the site using Google Calendar iframe

In order to display Google Calendar on your site, paste the following code in aspx page:

<iframe src="https://www.Google.com/calendar/embed?src=<%=
GetCalendarID()%>&ctz=Europe%2FMoscow" style="border: 0" width="800"
height="600" frameborder="0" scrolling="no"></iframe>

After that, define GetCalendarID() method in the Code-behind file of this page. This method returns Id of Calendar:

public string GetCalendarId()
{
     GoogleCalendar calendar = new GoogleCalendar
	("Google calendar name", "Google account name", "Google account password");
     return calendar.GetCalendarId();
}

The result may be, for example, as follows:

Calendar

License

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

Share

About the Author

Igor Alekseev
Technical Lead UBS
Russian Federation Russian Federation
Currently Technical Lead at UBS. MCTS, MCPD.

Comments and Discussions

 
QuestionUsing Access_Token Instead Of Credentails PinmemberSaddam Khan Ranjhani28-Sep-14 3:42 
QuestionCalender does not show without gmail login PinmemberDebapriya Sahoo17-Jul-14 3:16 
AnswerRe: Calender does not show without gmail login Pinmemberharishrulz26-Jul-14 3:21 
QuestionIt doesn't display anything. :( PinmemberJBobby15-Jul-14 2:47 
GeneralMy vote of 2 PinmemberJBobby15-Jul-14 1:03 
QuestionHow to solve system.Linq namespace in vs 2005 Pinmemberwinmart31-Mar-14 22:15 
Questionwhy the iframe not content the data PinmemberRishi Dahikar15-Nov-13 1:30 
QuestionCalendarId was null PinmemberJacquiline Jameson30-Oct-13 20:57 
AnswerRe: CalendarId was null PinmemberMember 1039493312-Dec-13 11:13 
AnswerRe: CalendarId was null Pinmemberharishrulz26-Jul-14 4:25 
QuestionDisplaying events? PinmemberJonathan Cassell23-Sep-13 18:26 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun25-Aug-13 21:21 
QuestionDisplying Blank Page Pinmemberbandushri158-May-13 22:58 
QuestionHelp : sort the result based on the date of the events in the Google Calendar PinmemberReesha Santhosh25-Mar-13 9:06 
GeneralMy vote of 3 PinmemberYogesh Modi12-Jan-13 21:35 
GeneralMy vote of 5 Pinmembermanoj kumar choubey9-Jul-12 23:42 
Questionnull return PinmemberPeter Pfude8-Jul-12 4:17 
QuestionHelp - Invalid calendar ID - Parameter Error PinmemberMember 904753930-May-12 14:37 
AnswerRe: Help - Invalid calendar ID - Parameter Error Pinmemberm.daveiga1-Jun-12 7:10 
GeneralRe: Help - Invalid calendar ID - Parameter Error PinmemberControlAltDelete25-Sep-12 0:44 
GeneralRe: Help - Invalid calendar ID - Parameter Error PinmemberControlAltDelete27-Sep-12 0:32 
GeneralMy vote of 5 PinmemberMircea Puiu13-Feb-12 22:56 
Beautiful, thanks Smile | :)
QuestionTime shows based on server time zone PinmemberKirk Quinbar12-Feb-12 18:27 
GeneralMy vote of 5 Pinmemberwayvirgo1-Jan-12 16:55 
QuestionGetCalendarId() method return null PinmemberHarish Chandra Patel20-Dec-11 0:02 

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
Web03 | 2.8.141030.1 | Last Updated 27 May 2011
Article Copyright 2011 by Igor Alekseev
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid