Synchronization with Google Calendar

Synchronization with Google Calendar

1. Introduction

This documentation explains how to implement synchronization of DHTMLX Scheduler .NET with Google Calendar. It is going to be a two-way syncronization, which means that if you make changes to events either in DHTMLX Scheduler .NET calendar or in Google Calendar, they will be reflected in both calendars.

Implementation of integration with Google Calendar implies the following:

  • If you make amendments to the same event in both Scheduler .NET calendar and Google Calendar, the events will be synced in accordance with the latest update.
  • If you add or delete an event in any of the calendar apps, it will be deleted from both calendar apps.
  • You can’t sync only a part of events. All events in both Scheduler .NET and Google Calendar are synchronized.
  • By default, Scheduler .NET takes the start and end times of calendar events as well as text information from Google Calendar. However, you can get additional info of the event when required.

The following instructions will help you create a functional client using DHTMLX Scheduler .NET and Google Calendar API.

2. Getting started

To start synchronization, you need to follow the steps listed below:

  1. Login to the Google API console link;
  2. Click on the Create new project button. The “Google APIs” screen opens;
  3. Enable Calendar API (APIs&authAPIs) in the left sidebar;
  4. Select Credentials in the sidebar on the left. Create a new Client ID for the service account, if you haven’t created it yet:

OAuth 2.0

  • Under the OAuth heading, select Create New Client ID.
  • When prompted, select Service Account and click Create Client ID.
  • A dialog box appears. To proceed, click Okay, got it.

If you have service account, you can generate new P12 key by clicking on the button beneath the existing service-account credentials table.

Configure your app

  1. Go to the Google Developers Console;
  2. Select a project;
  3. In the sidebar on the left, select APIs&authAPIs. Make sure that the status is ON for the Calendar API;
  4. In the sidebar on the left, select Credentials;
  5. Find the correct of OAuth 2.0 service account credentials in the list, and then find the EMAIL ADDRESS for those credentials. This email you need to insert instead of “SERVICE_ACCOUNT_EMAIL” string.

3. Getting Calendar ID

  1. Go to the Calendars;
  2. In the list of calendars click the down-arrow button next to the appropriate calendar which will be shared, then select Share Calendar;
  3. Enter the Service Email Address and select item of permission (Make changes AND manage sharing)
  4. In the tab Calendar Details get calendar identifier

This identifier will be used instead of “CALENDAR_ID”

calendar id

Also, you need to change “CERTIFICATE_PATH” string to the certificate path file were downloaded.

Set up libraries

Set up libraries via nuget

  • Install-Package Google.Apis.Calendar.v3
  • Install-Package Google.Apis.Core
  • Install-Package Google.Apis.Auth

4. Integration with Google Calendar

In this part we assume, that you have some ready project and below are instructions how to add synchronization in your project.

There are a few ways of synchronization between Scheduler and Google Calendar. We descibe the way that loads events from Google Calendar and displays them in Scheduler .NET calendar. After some event is changed in Scheduler .NET calendar, the event is changed in the Google Calendar.

For synchronization we will use the following model of the scheduler event (SchedulerEvent):

public class SchedulerEvent
    {
        public string id { get; set; }
        public string text { get; set; }
        public string description { get; set; }
        public DateTime start_date { get; set; }
        public DateTime end_date { get; set; }
 
        // Additional fields
 
        public DateTime Created { get; set; }
        public DateTime Updated { get; set; }
}

4.1 Connect to the Calendar

At first, you need to initialize service credentials and return them, like in code below:

 ServiceAccountCredential GetCredential()
 {
     try
     {
         var certificate = new X509Certificate2(
         "CERTIFICATE_PATH",
         "notasecret",
          X509KeyStorageFlags.Exportable);
 
          ServiceAccountCredential credential = new ServiceAccountCredential(
          new ServiceAccountCredential.Initializer("SERVICE_ACCOUNT_EMAIL")
          {
             Scopes = new[] { Google.Apis.Calendar.v3.CalendarService.Scope.Calendar }
          }.FromCertificate(certificate));
 
          return credential;
     }
     catch (Exception)
     {
        return null;
     }
}

Parameters:

  • CERTIFICATE_PATH - physical path of the certificate which was downloaded
  • notasecret - fixed value required by Google Calendar API
  • SERVICE_ACCOUNT_EMAIL- your service account's email address which has a following format xxxxxxxxxxxxx@developer.gserviceaccount.com
Google.Apis.Calendar.v3.CalendarService Get()
{
     try
     {
          var credential = GetCredential();
          var service = new Google.Apis.Calendar.v3.CalendarService(new BaseClientService.Initializer()
          {
              HttpClientInitializer = credential,
              ApplicationName = "Calendar"
          });
 
          return service;
     }
     catch (Exception)
     {
         return null;
     }
}

Parameters:

  • Calendar - the name of the client application accessing the service. Application names should preferably have the format [company-id]-[app-name]-[app-version]. The name will be used by the Google servers to monitor the source of authentication.

4.2 Load Data in the Scheduler

In this section we will load data to Scheduler .NET from Google Calendar.

4.2.1 Get Events from the Google Calendar

After creating calendar service you can get events from the Google Calendar and parse them to the Scheduler Event model:

  IEnumerable<SchedulerEvent> GetEvents()
        {
            try
            {
                using (var service = Get())
                {
                    var evs = service.Events.List("CALENDAR_ID").Execute();
                    return evs.Items.Select(e => new SchedulerEvent
                    {
                        id = e.Id,
                        description = e.Description ?? string.Empty,
                        text = e.Summary,
                        Created = (DateTime)e.Created,
                        Updated = (DateTime)e.Updated,
                        start_date = (DateTime)e.Start.DateTime,
                        end_date = (DateTime)e.End.DateTime
                    });
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

Parameters:

  • Unordered List Item

4.2.2 Load Data to the Scheduler

In the following code an application gets events from the Google Calendar and displaying them in the scheduler:

var events =GetEvents().Select(item =>
              new
                {
                    item.id,
                    item.text,
                    item.description,
                    item.start_date,
                    item.end_date,
                    googleeventid = item.id,
                }).ToList();
 
 
 return (new SchedulerAjaxData(events.ToList()));

5. Changing Events Data via Scheduler

This section contains operations such as create, update and delete event from Google Calendar via Scheduler. The model of the scheduler event (SchedulerEvent) should contain the next fields:

  • id - event id
  • text - topic of event
  • description - description of event
  • start_date - start date of event
  • end_date - end date of event

Additional fields:

  • Created - date of creation of event
  • Updated - date of updating of event

5.1 Create Events

Consider insertion of events in the following code:

/// <summary>
/// Creates a new event 
/// for more information see https://developers.google.com/google-apps/calendar/v3/reference/events/insert
/// </summary>
/// <param name="gEvent">Google event object</param>
/// <returns></returns>
public string CreateEvent(SchedulerEvent gEvent)
{
    try
    {
        using (var service = Get())
        {
            var inserted = service.Events.Insert(new Google.Apis.Calendar.v3.Data.Event
            {
                Id = gEvent.id,
                Description = gEvent.description,
                Summary = gEvent.text,
                Created = gEvent.Created.ToUniversalTime(),
                Updated = gEvent.Updated.ToUniversalTime(),
                Start = new Google.Apis.Calendar.v3.Data.EventDateTime { DateTime = gEvent.start_date.ToUniversalTime() },
                End = new Google.Apis.Calendar.v3.Data.EventDateTime { DateTime = gEvent.end_date.ToUniversalTime() }
            }, "CALENDAR_ID").Execute();
            return inserted.Id;
        }
    }
    catch (Exception)
    {
        return string.Empty;
    }
}

Parameters:

  • CALENDAR_ID - calendar identifier which has a following format xxxxxxxxxxxxx.apps.googleusercontent.com

This method has one parameter SchedulerEvent, which contains information about event created via scheduler. After successful creation it returns id of a new Google event.

5.2 Update Events

In the following code the event updates in the Google Calendar after some changes are made to Scheduler .NET calendar:

/// <summary>
/// Updates event in the calendar with identifier CalendarId
/// for more informatio see https://developers.google.com/google-apps/calendar/v3/reference/events/update
/// </summary>
/// <param name="gEvent">Google event object</param>
/// <returns></returns>
public string UpdateEvent(SchedulerEvent gEvent)
{
    try
    {
        using (var service = Get())
         {
             var toUpdate = service.Events.Get("CALENDAR_ID", gEvent.id).Execute();
 
             toUpdate.Description = gEvent.description;
             toUpdate.Summary = gEvent.text;
             toUpdate.Created = gEvent.Created.ToUniversalTime();
             toUpdate.Updated = gEvent.Updated.ToUniversalTime();
             toUpdate.Start = new Google.Apis.Calendar.v3.Data.EventDateTime
             {
                 DateTime = gEvent.start_date.ToUniversalTime()
             };
             toUpdate.End = new Google.Apis.Calendar.v3.Data.EventDateTime
             {
                 DateTime = gEvent.end_date.ToUniversalTime()
             };
 
             var result = service.Events.Update(toUpdate,"CALENDAR_ID", toUpdate.Id).Execute();
             return result.Id;
         }
     }
     catch (Exception)
     {
         return string.Empty;
     }
}

Parameters:

  • CALENDAR_ID - calendar identifier which has a following format xxxxxxxxxxxxx.apps.googleusercontent.com

After successful creation it returns id of a Google event.

5.3 Delete Event

And finally, deletion of events via Schuduler .NET. In the following code delete method has one parameter that contains an event id to delete:

/// <summary>
/// Delete event by eventId from the calendar with calendaId
/// for more information see https://developers.google.com/google-apps/calendar/v3/reference/events/delete
/// </summary>
/// <param name="eventId">Identifier of the event</param>
public void DeleteEvent(string eventId)
{
    try
    {
       using (var service =  Get())
       {
          service.Events.Delete("CalendarId", eventId).Execute();
        }
     }
     catch (Exception)
     {
     }
}

Parameters:

  • CALENDAR_ID - calendar identifier which has a following format xxxxxxxxxxxxx.apps.googleusercontent.com

5.4 Common CRUD Operation

To save some changes in the Google Calendar, you need to add to your method SaveData to the following code:

public ContentResult SaveData(int? id, FormCollection actionValues){
  var googleEvent = (SchedulerEvent)DHXEventsHelper.Bind(typeof(SchedulerEvent), actionValues);
  googleEvent.Updated = DateTime.Now;
 
  switch (action.Type){
      case DataActionTypes.Insert:
        googleEvent.Created = DateTime.Now;
        var gEventId = service.CreateEvent(googleEvent);
        googleEvent.googleeventid = gEventId;
      break;
      case DataActionTypes.Delete:
        service.DeleteEvent(googleEvent.Id);
      break;
      default:
 	service.UpdateEvent(googleEvent);
      break;
  }
 
  var result = new AjaxSaveResponse(action);
 
  result.UpdateField("googleeventid", googleEvent.googleeventid);
  return (result);
}

comments powered by Disqus