Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Handling events in google calendar using google API v3

0.00/5 (No votes)
27 Jan 2015 2  
This article will help you to create, update and delete events/ appointment in google calendar from your web application.

Introduction

This article will help you to create, update and delete events/ appointment in google calendar from your web application. After analyzing so many confusing ideas i came in a conclusion, that i wish to share through this article.

It includes step by step instructions for

  1. Creating a Project in the Google Developer Console
  2. Creating Client Information in the Developer Console
  3. Creating Project using Visual Studio 2010
  4. Installing NuGet Package
  5. Authenticating Client using OAuth 2.0
  6. creating calendar Event
  7. Edit /Update the event
  8. Deleting the Calendar Event

Background

Step 1 : Creating a Project in the Google Developer Console

  • Log in to Developer Console by giving a valid google Id and password.
  • It will show you a page with a button 'Create project' ( if you don't have a project else you can see list of projects you have created) . clicking on it will show you a pop up where you can choose your Project name
  • As next step click on the project name and You have to Enable API for calendar.
  • Great, now our project is allowed to use the Google calendar API but we still need to create those API Keys i mentioned at the beginning. In order to do that we first need to set up the consent screen, this is a pop up which every user of our app will see where he will allow(or disallow) our application to access his account.
  • On the right menu select APIs & auth and then – you guessed it – Consent screen. Here it’s important to select the Email Address and to specify a Product Name. These values will later be shown to the user on the consent screen, so make sure the user recognizes your application by this values.

Step 2 : Creating Client Information in the Developer Console

  • Now let’s generate an API-Key. Select APIs & auth and then Credentials on the menu on the right. Then click on Create new Client ID.
  • Now a Pop up will show, in that select Web Application and then, give homepage URL and Redirect URL( to which the authenticated information ware passed) click  Create new Client ID. these details can be edited.

  •  The code you’ll need to write later will differ based on the type of application you select now. To keep things simple select Installed application as the application type and since we’re going to create a Windows app other as the installed application type

Now you can see your Credentials like :

Quote:

Client ID  : 241150xxxxxxx-lbffjiuxxxxxxxxxxxxxxxxxxxx45.apps.googleusercontent.com

Email address : 241150xxxxxxx-lbffjiuxxxxxxxxxxxxxxxxxxxx45@developer.gserviceaccount.com

Client secret  : 1MXXi5g_gxxxxxx8zDK1
Redirect URIs : http://localhost:60730/home.aspx

Step 3: Now you have to create a Project in visual studio 2010 

  1. Open Visual Studio 2010
  2. On the File menu, click New and then click Project. (This opens the New Project dialog box.)
  3. In the left pane, select Installed, and select a category of project types from the expanded list. If you have recently created a project of the same type, select Recent instead for faster navigation.

  4. Select one of the project Templates from the middle pane. A description of the selected template appears in the right pane.

  5. In the Name box, type a name for the new project (say : googleintegration)

  6. In the Location box, select a save location.

  7. If available, in the Solution list, specify whether to create a solution or add the project to the solution that is open in Solution Explorer.

  8. In the Solution name box, type a name for the solution.

  9. Click OK.

Setp 4 : Installing NuGet Package

  • In this step you have to download NuGet Package and install it in your system.
  • Then Restart the Visual Studio to setup it. open the project which you have created.
  • Open Package manager Console from the Tools menu. (Will Open a new window)
  • Let’s use NuGet to get those libraries into our project. Open the Packet Manager console (Extras > NuGet-Packet-Manager > NuGet-Packet-Manager-Console) and type:

Install-Package Google.Apis.Calendar.v3

  • A few seconds later you should see the needed libraries added to your references in Project explorer.
    Now we should have all needed libararies to authenticate at Google and use the calendar API.

Using the code

Now you have to design your ASP.Net page (Home.aspx)

  <form id="form1" runat="server"><br />
    <div><br />
        <center><br />
            <asp:Button Text="Create Event" runat="server" ID="btnCreate" /><br />
            <asp:Button Text="Edit Event" runat="server" ID="btnEdit" /><br />
            <asp:Button Text="Delete Event" runat="server" ID="btnDelete" /><br />
            <asp:TextBox runat="server" ID="txtEventId" /><br />
        </center><br />
    </div><br />
    </form>

Step 5 : Authenticating the client

        clientId = ConfigurationManager.AppSettings("client_id").ToString<br />
        clientSecret = ConfigurationManager.AppSettings("client_secret").ToString<br />
        redirecturi = ConfigurationManager.AppSettings("redirect").ToString<br />
        mainUser = ConfigurationManager.AppSettings("mainuser").ToString

' These details are generated in the developer console. and are stored in the web.config

For authentication Call the function authorize which is defined bellow:

Public Sub authorize()<br />
        Dim Uri As String = "https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=" & clientId & "&redirect_uri=" & redirecturi & "&scope=https://www.googleapis.com/auth/calendar&login_hint=" & mainUser & "&include_granted_scopes=true"<br />
        Response.Redirect(Uri)<br />
End Sub

  • This will redirect you to the Google login page where you can login to your account. these informations are passed to the google and necessory informations will be redirected back from the google in the query string. which we can use later.
  • code for receiving the informations from the google after the successfull authentication.

     

  Dim datafolder As String = Server.MapPath("App_Data/CalendarService.api.auth.store")<br />
        Dim scopes = New String() {CalendarService.Scope.Calendar} 'initialising the calendar scope<br />
        Dim UserId As String = mainUser.Trim() ' login user<br />
        Dim flow As GoogleAuthorizationCodeFlow = Nothing ' declaring the authorization code flow<br />
        If Request.QueryString("code") = Nothing Then<br />
            authorize() ' if not authenticated then call the authorize function<br />
        Else<br />
            secrets = New ClientSecrets() With { _<br />
          .ClientId = clientId, _<br />
          .ClientSecret = clientSecret _<br />
          } ' here we initialize the client secrets which are stored in the web config<br />
            Try<br />
                flow = New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer() With { _<br />
                  .DataStore = New FileDataStore(datafolder), _<br />
                  .ClientSecrets = secrets, _<br />
                  .Scopes = scopes<br />
               }) 'Initialize the flow<br />
                Dim code As String = Request.QueryString("code")<br />
                Dim uri As String = redirecturi<br />
                Dim token = flow.ExchangeCodeForTokenAsync(UserId, code, Uri, CancellationToken.None).Result<br />
                GoogleTokenModelObj.Access_Token = token.AccessToken 'Retriving the access token<br />
                If token.RefreshToken IsNot Nothing Then<br />
                    GoogleTokenModelObj.Refresh_Token = token.RefreshToken 'Getting the refresh token<br />
                End If<br />
                Dim calendarConnection As CalendarService = Nothing ' For creating editing and deleting events we need a calendar connection which is declared here<br />
                Dim credential As New UserCredential(flow, UserId, token)<br />
                Dim initializer = New BaseClientService.Initializer()<br />
                initializer.HttpClientInitializer = credential<br />
                initializer.ApplicationName = "chromatic-idea-811"<br />
                calendarConnection = New CalendarService(initializer) ' initialize calendar connection

 

Step 6 : creating calendar event

 Public Function createCalendarEvent(ByVal inCalendar As Google.Apis.Calendar.v3.Data.EventAttendee,<br />
                                       ByVal summary As String, ByVal description As String, ByVal startDate As Date, ByVal endDate As Date,<br />
                                       ByVal calendarConnection As CalendarService, ByVal mailId As String, ByVal eventId As String) As String<br />
        Try<br />
            Dim googleCalendarEvent As New [Event]()<br />
            googleCalendarEvent.Attendees = New List(Of EventAttendee)()<br />
            googleCalendarEvent.Attendees.Add(inCalendar)<br />
            googleCalendarEvent.Id = LCase(eventId)<br />
            googleCalendarEvent.Start = New EventDateTime()<br />
            googleCalendarEvent.[End] = New EventDateTime()<br />
            googleCalendarEvent.Start.DateTime = startDate<br />
            googleCalendarEvent.[End].DateTime = endDate<br />
            googleCalendarEvent.Summary = summary<br />
            googleCalendarEvent.Description = description<br />
            googleCalendarEvent.Reminders = New [Event].RemindersData()<br />
            googleCalendarEvent.Reminders.UseDefault = True<br />
            Dim reminder As New EventReminder()<br />
            reminder.Method = "popup"<br />
            reminder.Minutes = 60<br />
            googleCalendarEvent.Reminders.[Overrides] = New List(Of EventReminder)<br />
            googleCalendarEvent.Reminders.[Overrides].Add(reminder)<br />
            googleCalendarEvent.Reminders = New [Event].RemindersData()<br />
            googleCalendarEvent.Reminders.UseDefault = False<br />
            calendarConnection.Events.Insert(googleCalendarEvent, mainUser).Execute()<br />
        Catch ex As Exception<br />
            createCalendarEvent = "False"<br />
            Exit Function<br />
        End Try<br />
        createCalendarEvent = "true"<br />
    End Function

step 7 : edit/update calendar event

 Public Function updateCalendarEvent(ByVal user_name As String, ByVal from_date As DateTime, ByVal to_date As DateTime, _<br />
                                       ByVal subject As String, ByVal calendarConnection As CalendarService, ByVal calId As String, ByVal calOwner As String) As String<br />
        Try<br />
            '<------ v3 Update appoinment code starts here<br />
            Dim x As New Google.Apis.Calendar.v3.Data.EventAttendee<br />
            x.Email = user_name '<--- calendar owner<br />
            x.DisplayName = user_name<br />
            x.ResponseStatus = "accepted"<br />
            Dim googleCalendarEvent As New [Event]()<br />
            googleCalendarEvent.Attendees = New List(Of EventAttendee)()<br />
            googleCalendarEvent.Attendees.Add(x)<br />
            googleCalendarEvent.Start = New EventDateTime()<br />
            googleCalendarEvent.[End] = New EventDateTime()<br />
            googleCalendarEvent.Id = calId<br />
            googleCalendarEvent.Start.DateTime = from_date<br />
            googleCalendarEvent.[End].DateTime = to_date<br />
            googleCalendarEvent.Summary = subject<br />
            googleCalendarEvent.Description = subject<br />
            googleCalendarEvent.Reminders = New [Event].RemindersData()<br />
            googleCalendarEvent.Reminders.UseDefault = True<br />
            Dim reminder As New EventReminder()<br />
            reminder.Method = "popup"<br />
            reminder.Minutes = 60<br />
            googleCalendarEvent.Reminders.[Overrides] = New List(Of EventReminder)<br />
            googleCalendarEvent.Reminders.[Overrides].Add(reminder)<br />
            googleCalendarEvent.Reminders = New [Event].RemindersData()<br />
            googleCalendarEvent.Reminders.UseDefault = False<br />
            calendarConnection.Events.Update(googleCalendarEvent, calOwner, calId).Execute()<br />
        Catch ex As Exception<br />
            updateCalendarEvent = "E"<br />
        End Try<br />
        updateCalendarEvent = ""<br />
    End Function

            Step 8 : Delete event based on event id

 calendarConnection.Events.Delete(user_name, e.Appointment.ID).Execute()

 

Points to be Noticed

 

  • Event ID nust contains only Lower case letters and, numbers
  • Event attendee can be a list of email ids

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here