Click here to Skip to main content
11,565,623 members (42,974 online)
Click here to Skip to main content

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

, 25 Feb 2014 CPOL 52.4K 3.9K 44
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.


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.


  • 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.
    <add key="GoogleCalendarApplicationClientID" value=""/>
    <add key="GoogleCalendarApplicationClientSecret" value=""/>
    <add key="GoogleReturnPageAddress" 

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.,
    • 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{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 '' 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 = 
      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);

      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 = "" + 
      	CalendarID + "/private/full";
      Uri postUri = new Uri(ThisFeedUri);
      EventQuery Query = new EventQuery(ThisFeedUri);
      Query.ExtraParameters = "extq=[EventID:" + 
      	GoogleCalendarAppointmentModelObj.EventID + "]";
      Query.Uri = postUri;
      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)
                result = true;
            //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;
                result = true;
    • 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:


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


About the Author

Software Developer Softech Systems (Pvt) Limited
Pakistan Pakistan
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionPlease do an updated v3 article Pin
Member 116616403-May-15 17:47
memberMember 116616403-May-15 17:47 
QuestionTried but getting error Pin
Schatak17-Mar-15 21:00
professionalSchatak17-Mar-15 21:00 
AnswerRe: Tried but getting error Pin
m.waqasiqbal18-Mar-15 3:18
memberm.waqasiqbal18-Mar-15 3:18 
QuestionGoogle Calender - Application integration Pin
Member 114906241-Mar-15 22:26
memberMember 114906241-Mar-15 22:26 
AnswerRe: Google Calender - Application integration Pin
m.waqasiqbal11-Mar-15 18:52
memberm.waqasiqbal11-Mar-15 18:52 
QuestionThe remote server returned an error: (403) Forbidden. Pin
nisharkaliya26-Feb-15 20:05
membernisharkaliya26-Feb-15 20:05 
Questionimplementation google calendar V3 Pin
Member 1134297729-Dec-14 22:36
memberMember 1134297729-Dec-14 22:36 
QuestionHope this help: V3 version of this. Pin
Hewbert Gabon19-Dec-14 10:03
memberHewbert Gabon19-Dec-14 10:03 
AnswerRe: Hope this help: V3 version of this. Pin
m.waqasiqbal19-Dec-14 22:02
memberm.waqasiqbal19-Dec-14 22:02 
QuestionThis integration V2, but a need integration V3 Pin
Member 1128421810-Dec-14 1:29
memberMember 1128421810-Dec-14 1:29 
QuestionRetrieve ExtendedProperty of Google Calendar v3? Pin
Hewbert Gabon23-Nov-14 2:07
memberHewbert Gabon23-Nov-14 2:07 
AnswerRe: Retrieve ExtendedProperty of Google Calendar v3? Pin
m.waqasiqbal26-Nov-14 17:38
memberm.waqasiqbal26-Nov-14 17:38 
GeneralRe: Retrieve ExtendedProperty of Google Calendar v3? Pin
Hewbert Gabon19-Dec-14 10:10
memberHewbert Gabon19-Dec-14 10:10 
QuestionError (403) when create new event Pin
bitsnbytes20-Nov-14 8:11
memberbitsnbytes20-Nov-14 8:11 
AnswerRe: Error (403) when create new event Pin
m.waqasiqbal20-Nov-14 18:05
memberm.waqasiqbal20-Nov-14 18:05 
GeneralGreat job...but API v2 now deprecated as of 17/11/14 - upgrade to v3, anybody? Pin
Member 1124543418-Nov-14 20:31
memberMember 1124543418-Nov-14 20:31 
GeneralRe: Great job...but API v2 now deprecated as of 17/11/14 - upgrade to v3, anybody? Pin
m.waqasiqbal19-Nov-14 1:57
memberm.waqasiqbal19-Nov-14 1:57 
QuestionCan you provide a V3 variation of this? Pin
Member 233046418-Nov-14 18:49
memberMember 233046418-Nov-14 18:49 
AnswerRe: Can you provide a V3 variation of this? Pin
m.waqasiqbal19-Nov-14 1:52
memberm.waqasiqbal19-Nov-14 1:52 
QuestionFetch google calendar events Pin
Milind Singh11-Oct-14 0:47
memberMilind Singh11-Oct-14 0:47 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun18-Sep-14 4:14
memberHumayun Kabir Mamun18-Sep-14 4:14 
QuestionHow to add event without move Gmail Pin
Debapriya Sahoo17-Jul-14 3:19
memberDebapriya Sahoo17-Jul-14 3:19 
AnswerRe: How to add event without move Gmail Pin
m.waqasiqbal17-Jul-14 6:12
memberm.waqasiqbal17-Jul-14 6:12 
GeneralRe: How to add event without move Gmail Pin
Debapriya Sahoo17-Jul-14 18:33
memberDebapriya Sahoo17-Jul-14 18:33 
GeneralRe: How to add event without move Gmail Pin
m.waqasiqbal18-Jul-14 3:40
memberm.waqasiqbal18-Jul-14 3:40 

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