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

Google Calendar Integration in ASP.NET: Create / edit / delete events

, 25 Feb 2014
Rate this:
Please Sign up or sign in to vote.
How to programmatically create / edit / delete events in the Google calendar of a Gmail user.

Introduction

This article describes how to programmatically create / edit / delete events in the Google calendar of a Gmail user. The developer needs to create a project on Google API Console and use the credentials (ClientID, ClientSecret, and Redirect URL) to sync events on any Gmail user registered with the project.

Using the Code

My intention is to let the user walk through the code so that he may be able to sync events of a web application (event management system, reservation system, etc.) with a user's Google Calendar.

Required IDE

  • Visual Studio: 2010

Description of Files

First, I will give a brief description of the files used in this project.

564282/Working/SolExplorer.jpg

  • App_Code
    • GoogleCalendarAppointmentModel.cs - This file is used to keep the contents that need to be sent on Google Calendar
    • GoogleCalendarManager.cs - This file contains all the functions to interact with Google Calendar i.e., read / write events, access the calendar, etc.
    • GoogleTokenModel.cs - This file's contents are used to get the response from the Google Calendar API, i.e., the AccessToken (will be required for identification, will expire after a certain period of time), Refresh Token (will not expire and is used to get a new AccessToken).
  • App_Data
    • XMLFile.xml - This file server is the DB for this project. To keep it simple, this project works with a single user and single event, i.e.,
      • You register the user with the Google API project so that his Google Calendar can be accessed programmatically
      • You create / edit / delete an event through the Visual Studio project and view the changes on Google Calendar
      • You can change your login credentials. Currently they are set to UserName=Waqas, Pwd = 111
      • When you register with Google calendar, you will get a new AccessToken and RefreshToken which will be saved here
      • When you create / update an event, its details are stored here.
      • When you delete event, these details are removed, as you can see below that there are no values for the event attributes
      • When you revoke rights, your AccessToken and RefreshToken are removed from here
      • You don't need to edit this file manually, except the username, pwd as this may result in exceptions.
  • Bin: Download the Google_Data_API_Setup.msi from here (these files are already present in the Bin folder of the attached project)
    • Install the MSI
    • Get the four DLL files shown in the Bin folder image from C:\Program Files\Google\Google Data API SDK\Samples and paste them in your Visual Studio project's bin.
  • Default.aspx - The main page where you can register, revoke, create / edit / delete events from Google Calendar
  • GoogleCalendarRegistration.aspx - This page is used as the Redirect URL in the Google API project, which means that Google will send you the response at this page after verifying the registering Gmail user
  • Web.Config - Save your ClientID, ClientSecret, RedirectURI contents from Google API project here, e.g.
<appSettings>
    <add key="GoogleCalendarApplicationClientID" value=""/>
    <add key="GoogleCalendarApplicationClientSecret" value=""/>
    <add key="GoogleReturnPageAddress" 
    value="http://localhost:3714/GoogleCalandarDemo/GoogleCalendarRegistration.aspx"/>
</appSettings>

Creating Project on Google API Console

  • Create new project here
  • Activate the calendar API under All services
  • Agree to Google API Terms of service
  • Click the Overview link at right top
    • Click Register link in front of "Project ID".
    • Write any text as the Project ID and Register.
    • Click API Access and click “Create an oAuth 2.0 clientID”.
    • Choose a product name, logo and Home page URL (optional).
    • Choose web application as Application type.
    • Click more options and type the address of the page where you will receive the result of Google calendar registration.
    • For testing purpose, type the address of your Visual Studio assigned port, e.g. http://localhost:58392/GoogleCalandarDemo/Default.aspx.
      • To restrict Visual Studio to assign a specific port to this project (if you don't restrict it, you will have to change the Redirect URL in Google API Console and web.config each time for a different port)
        • Click on project name in Solution Explorer tab.
        • Click F4 to show its properties.
        • Select false for "Use dynamic ports".
      • For deployment, use the appropriate registered address (Google does not allow IP address based address e.g., http://192.168.0.1:58392/GoogleCalandarDemo/Default.aspx
    • Click create client ID.
    • Save the ClientID and ClientSecret values in web.config to be used later.
    • You can change the Redirect URL by clicking the "edit settings" link at left side.

View the images below if you find anything confusing with the text.

API Access

API Access.jpg

API Overview

API Overview.jpg

API Services

API Services.jpg

At this point, you can either download the web site project files that I have included and try to understand the logic yourself OR I can try to describe the process so you can create your own code.

If you have chosen the latter, then I have attached the project files. You just need to:

  • Download the Visual Studio website (This is working code and I assume that the user has basic concepts about Google API. To get more insight, visit the 'Useful Links' section below.)
  • Create the Google API project.
  • Get and replace the ClientID, ClientSecret, RedirectURL in web.config (web.config contains my credentials, so it will work even if you forget to create new project or don't want to create the project).

If you want to get an understanding and build the code yourself, then let's start from here. I will describe the flow and requirement for Google Calendar Events Sync and then show the way I did it (I assume that you have created a new project at Google API Console and replaced the entries in web.config).

I also assume that you have a number of users of your website and you are maintaining/storing their events in your DB. Now you want to keep this data on the respective user's Google Calendar also.

  • You (the developer) need to register the user of your website to register with Google API project. This can be a button click event and you need to redirect the user to Google to verify his credentials. Remember that the control is now shifted to Google and it will provide you with an AccessToken and RefreshToken if it verifies the user. This approach provides 2 benefits:
    • User doesn't need to worry that he is providing his Gmail credentials to you (the developer).
    • You get the rights to add, update, delete events on his Google Calendar.
  • The redirect URL is like this
    https://accounts.google.com/o/oauth2/auth?scope={0}&redirect_uri={1}&response_type={2}&client_id={3}&state={4}&access_type={5}&approval_prompt={6}
    • scope: 'The scope specifies the resources that your application can retrieve, insert, update, or delete when acting as the authenticated user' as described here.
    • redirect_uri: If the user is registered, then Google will return a temporary 'authorization code' as querystring at the page address provided in this variable.
    • response_type: what you require from Google upon successful registration of a user.
    • state: Any string that your application would use to maintain state between the request and redirect response. Your application will receive the same value that it sends for this parameter.
    • access_type: put 'offline' as its value so you can refresh the access tokens when the user is not present / active.
    • approval_prompt: Its default value is 'auto'. so you don't need to prompt the user before an action (after the 1st approval).
  • As a result of redirection, the user will be asked to provide credentials:
    • User will be asked to login using his credentials or if already logged in, shown a screen, where Google will ask him to 'allow access' or reject.
      • If 'no thanks' is clicked, you will be provided by an access_denied querystring.
      • If 'allow access' is clicked, you will be provided by a code in querystring.
    • Assuming that you have successfully given a code in querystring at your redirect_uri page, you need to exchange this temporary authorization code with long term access token and refresh token.
    • To exchange the code:
      • Send a request (HttpWebRequest) at 'https://accounts.google.com/o/oauth2/token' and pass code, client_id, client_secret, redirect_uri, grant_type in request body.
      • If successful, then you will be returned with a JSON object containing access_token,token_type,expires_in,refresh_token.
      • Extract the access and refresh token and save in your db to be used later.
    • Till this point, the user is successfully registered. Now to access a user's Google Calendar, you need to create a calendar service to interact with Google Calendar API:
      Google.GData.Client.GAuthSubRequestFactory authFactory = 
      	new Google.GData.Client.GAuthSubRequestFactory("cl", "API Project");
      authFactory.Token = GoogleTokenModelObj.Access_Token;
      authFactory.KeepAlive = true;
      Google.GData.Calendar.CalendarService service = new CalendarService("cl");
      service.RequestFactory = authFactory
    • Next get Calendar ID by querying to the Calendar Service:
      private static string AllCalendarFeed = 
      	@"http://www.google.com/calendar/feeds/default/allcalendars/full";
      Uri postUri = new Uri(AllCalendarFeed);
      Google.GData.Calendar.CalendarQuery CalendarQuery = 
      		new Google.GData.Calendar.CalendarQuery();
      CalendarQuery.Uri = postUri;
      Google.GData.Calendar.CalendarFeed calFeed = CalService.Query(CalendarQuery)
      string CalendarID = "";
      if (calFeed != null && calFeed.Entries.Count > 0)
      {
          foreach (CalendarEntry CalEntry in calFeed.Entries)
          {
              //Commented to post the new appointments 
              //on the main calendar instead of cleverfox calendar
              //if (CalEntry.Title.Text.Contains("Cleverfox") == true)
              //{
              //CalendarID = CalEntry.Title.Text;
              CalendarID = CalEntry.EditUri.ToString().Substring
              (CalEntry.EditUri.ToString().LastIndexOf("/") + 1);
              break;
              //}
          }
      }

      Now CalendarID contains the ID of gmail user's primary calendar. This will be used to construct the FeedURI where the event will be added / updated / deleted.

    • To create / update / delete use an EventEntry object:
      Google.GData.Calendar.EventEntry Entry = new Google.GData.Calendar.EventEntry()
    • Mark the event with the same EventID in your DB, so that it can be updated / deleted later:
      ExtendedProperty oExtendedProperty = new ExtendedProperty();
      oExtendedProperty.Name = "EventID";
      oExtendedProperty.Value = GoogleCalendarAppointmentModelObj.EventID;
    • To search if Google Calendar contains a specific event, use EventQuery object:
      string ThisFeedUri = "http://www.google.com/calendar/feeds/" + 
      	CalendarID + "/private/full";
      Uri postUri = new Uri(ThisFeedUri);
      EventQuery Query = new EventQuery(ThisFeedUri);
      Query.ExtraParameters = "extq=[EventID:" + 
      	GoogleCalendarAppointmentModelObj.EventID + "]";
      Query.Uri = postUri;
      Entry.ExtensionElements.Add(oExtendedProperty);
      EventFeed calFeed = CalService.Query(Query)
    • If the event is found, CalFeed will contain it.
      • To delete an event from Google Calendar:
        if (calFeed != null && calFeed.Entries.Count > 0)
        {
            foreach (EventEntry SearchedEntry in calFeed.Entries)
            {
                SearchedEntry.Delete();
                result = true;
                break;
            }
            //return null;
        }
      • To update an event:
        if (calFeed != null && calFeed.Entries.Count > 0)
        {
            foreach (EventEntry SearchedEntry in calFeed.Entries)
            {
                SearchedEntry.Content = Entry.Content;
                SearchedEntry.Title = Entry.Title;
                SearchedEntry.Times.RemoveAt(0);
                SearchedEntry.Times.Add(EventTime);
                SearchedEntry.Locations.RemoveAt(0);
                SearchedEntry.Locations.Add(eventLocation);
                CalService.Update(SearchedEntry);
                result = true;
                break;
            }
        } 
    • To create an event:
      CalService.Insert(postUri, Entry);

That's all. I spent almost 2 weeks to figure this out. It would be a great help to you, I believe.

Useful Links

To refresh access token:

To revoke rights access token:

License

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

About the Author

m.waqasiqbal
Software Developer Softech Systems (Pvt) Limited
Pakistan Pakistan
No Biography provided
Follow on   Twitter   LinkedIn

Comments and Discussions

 
QuestionHow to add event without move Gmail PinmemberDebapriya Sahoo17-Jul-14 3:19 
AnswerRe: How to add event without move Gmail Pinmemberm.waqasiqbal17-Jul-14 6:12 
GeneralRe: How to add event without move Gmail PinmemberDebapriya Sahoo17-Jul-14 18:33 
GeneralRe: How to add event without move Gmail Pinmemberm.waqasiqbal18-Jul-14 3:40 
Questioninvalid_client [modified] PinmemberBraneloc12-Jul-14 10:04 
AnswerRe: invalid_client Pinmemberm.waqasiqbal17-Jul-14 6:12 
QuestionThanks fort your reply Pinmemberpiyush201124-Mar-14 4:14 
AnswerRe: Thanks fort your reply Pinmemberm.waqasiqbal24-Mar-14 4:48 
QuestionHow will i use this code for storing multiple users Pinmemberpiyush201124-Mar-14 2:39 
AnswerRe: How will i use this code for storing multiple users Pinmemberm.waqasiqbal24-Mar-14 3:13 
QuestionI want to google calendar access Pinmembersaylibhagwat20-Feb-14 20:00 
AnswerRe: I want to google calendar access Pinmemberm.waqasiqbal22-Feb-14 19:19 
QuestionAccess Token verification PinmemberAhmadFarouq27-Nov-13 1:27 
AnswerRe: Access Token verification Pinmemberm.waqasiqbal27-Nov-13 19:21 
GeneralRe: Access Token verification [modified] PinmemberAhmadFarouq28-Nov-13 0:56 
GeneralRe: Access Token verification Pinmemberm.waqasiqbal2-Dec-13 0:15 
QuestionCalendar colors Pinmemberjasenf6-Jun-13 10:11 
AnswerRe: Calendar colors Pinmemberm.waqasiqbal6-Jun-13 23:57 
GeneralMy vote of 5 PinmemberRenju Vinod21-Mar-13 2:38 
GeneralRe: My vote of 5 Pinmemberm.waqasiqbal21-Mar-13 3:05 
GeneralMy vote of 5 Pinmembermohsinshahbaz21-Mar-13 1:43 
GeneralRe: My vote of 5 Pinmemberm.waqasiqbal21-Mar-13 3:06 
GeneralGreat ! Thanks Pinmembermohsinshahbaz21-Mar-13 1:13 

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
Web01 | 2.8.140721.1 | Last Updated 26 Feb 2014
Article Copyright 2013 by m.waqasiqbal
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid