Download Free Demos

Synchronization with Google Calendar

Introduction

This documentation explains how to implement synchronization of DHTMLX Scheduler .NET with Google Calendar.

It is going to be a two-way synchronization, 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 changes in the same event in both Scheduler .NET calendar and Google Calendar, the events will be synchronized 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 synchronize 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.

Step 1. Getting Started

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

1 . Login to the Google API console;
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 the 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. Then find the EMAIL ADDRESS for those credentials. You need to insert this email instead of the "SERVICE_ACCOUNT_EMAIL" string.

Step 2. 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 the 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 replace the "CERTIFICATE_PATH" string by 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

Step 3. Integrating 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 describe the way that loads events from Google Calendar and displays them in Scheduler .NET calendar. When some event is changed in Scheduler .NET calendar, the same 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; }
}

Step 3.1 Connecting to the Calendar

At first, you need to initialize service credentials and return them, like in the 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 the 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.

Step 3.2 Loading Data in the Scheduler

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

Step 3.2.1 Getting Events from the Google Calendar

After creating a 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

Step 3.2.2 Adding Data from Google Calendar to the Scheduler

In the following code an application gets events from the Google Calendar and displays 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()));

Step 4. Changing Events Data via Scheduler

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

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

Additional fields:

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

4.1 Creating Events

Let's 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 the following format xxxxxxxxxxxxx.apps.googleusercontent.com

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

4.2 Updating Events

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

/// <summary>
/// Updates event in the calendar with the identifier CalendarId
/// for more information 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 the following format xxxxxxxxxxxxx.apps.googleusercontent.com

After successful creation it returns the id of a Google event.

4.3 Deleting Events

Finally, deletion of events via Scheduler .NET. In the following code the delete() method has one parameter that contains the id of the event to delete:

/// <summary>
/// Deletes event by eventId from the calendar with CalendarId
/// 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 the following format xxxxxxxxxxxxx.apps.googleusercontent.com

4.4 Implementing Common CRUD Operations

To save some changes in the Google Calendar, you need to add to your method SaveData 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);
}

Was this article helpful?

Yes No