Click here to Skip to main content
15,860,861 members
Articles / Web Development / ASP.NET

Using Google Calendar in ASP.NET Website

Rate me:
Please Sign up or sign in to vote.
4.81/5 (23 votes)
27 May 2011CPOL4 min read 172.2K   9.6K   62   36
How to use Google Calendar in ASP.NET website

Calendar

[PLEASE BEWARE] While the overall concepts could be valid some years after the publication, some API details could have changed.

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:

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

The problem is solved as follows:

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

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

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

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

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

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

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

HTML
<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:

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


Written By
Technical Lead UBS
Russian Federation Russian Federation
Currently Technical Lead at UBS

Comments and Discussions

 
QuestionUrl Exception Pin
Rajesh waran29-Sep-16 23:48
professionalRajesh waran29-Sep-16 23:48 
AnswerRe: Url Exception Pin
21joy16-Jul-19 3:15
21joy16-Jul-19 3:15 
QuestionError with authenticate Pin
Member 121524838-Aug-16 1:56
Member 121524838-Aug-16 1:56 
Questionthe code have problem Pin
Mohsen ms8-Nov-15 9:03
Mohsen ms8-Nov-15 9:03 
QuestionDid anyone have successfully convert this code to V3 API? Pin
Member 409542424-Nov-14 13:58
Member 409542424-Nov-14 13:58 
QuestionUsing Access_Token Instead Of Credentails Pin
Saddam Khan Ranjhani28-Sep-14 3:42
Saddam Khan Ranjhani28-Sep-14 3:42 
QuestionCalender does not show without gmail login Pin
Debapriya Sahoo17-Jul-14 3:16
Debapriya Sahoo17-Jul-14 3:16 
AnswerRe: Calender does not show without gmail login Pin
harishrulz26-Jul-14 3:21
harishrulz26-Jul-14 3:21 
QuestionIt doesn't display anything. :( Pin
JBobby15-Jul-14 2:47
JBobby15-Jul-14 2:47 
AnswerRe: It doesn't display anything. :( Pin
Member 121524838-Aug-16 1:59
Member 121524838-Aug-16 1:59 
GeneralMy vote of 2 Pin
JBobby15-Jul-14 1:03
JBobby15-Jul-14 1:03 
QuestionHow to solve system.Linq namespace in vs 2005 Pin
winmart31-Mar-14 22:15
winmart31-Mar-14 22:15 
Questionwhy the iframe not content the data Pin
Rishi Dahikar15-Nov-13 1:30
Rishi Dahikar15-Nov-13 1:30 
QuestionCalendarId was null Pin
Jacquiline Jameson30-Oct-13 20:57
Jacquiline Jameson30-Oct-13 20:57 
AnswerRe: CalendarId was null Pin
Member 1039493312-Dec-13 11:13
Member 1039493312-Dec-13 11:13 
AnswerRe: CalendarId was null Pin
harishrulz26-Jul-14 4:25
harishrulz26-Jul-14 4:25 
QuestionRe: Url Exception Pin
Rajesh waran30-Sep-16 0:05
professionalRajesh waran30-Sep-16 0:05 
QuestionDisplaying events? Pin
Jonathan Cassell23-Sep-13 18:26
Jonathan Cassell23-Sep-13 18:26 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun25-Aug-13 21:21
Humayun Kabir Mamun25-Aug-13 21:21 
QuestionDisplying Blank Page Pin
bandushri158-May-13 22:58
bandushri158-May-13 22:58 
QuestionHelp : sort the result based on the date of the events in the Google Calendar Pin
Reesha Santhosh25-Mar-13 9:06
Reesha Santhosh25-Mar-13 9:06 
GeneralMy vote of 3 Pin
Yogesh Modi12-Jan-13 21:35
Yogesh Modi12-Jan-13 21:35 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey9-Jul-12 23:42
professionalManoj Kumar Choubey9-Jul-12 23:42 
Questionnull return Pin
Peter Pfude8-Jul-12 4:17
Peter Pfude8-Jul-12 4:17 
QuestionHelp - Invalid calendar ID - Parameter Error Pin
Member 904753930-May-12 14:37
Member 904753930-May-12 14:37 

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.