Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (149).NET Core  (24)Angular  (42)ASP.NET  (48)ASP.NET Core  (56)ASP.NET MVC  (84)Azure  (28)Blazor  (68)DocIO  (18)Essential JS 2  (67)Essential Studio  (161)Flutter  (78)JavaScript  (140)Microsoft  (101)PDF  (54)React  (31)Succinctly series  (120)Syncfusion  (457)TypeScript  (30)Uno Platform  (2)UWP  (4)Vue  (26)Webinar  (16)Windows Forms  (54)WPF  (106)Xamarin  (117)XlsIO  (22)Other CategoriesBarcode  (4)BI  (29)Bold BI  (3)Build conference  (6)Business intelligence  (53)Button  (4)C#  (104)Chart  (43)Cloud  (9)Company  (445)Dashboard  (6)Data Science  (3)Data Validation  (3)DataGrid  (36)Development  (244)Doc  (7)DockingManager  (1)eBook  (91)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (16)Extensions  (9)File Manager  (3)Gantt  (7)Gauge  (5)Git  (3)Grid  (25)HTML  (9)Installer  (2)Knockout  (2)LINQPad  (1)Linux  (1)M-Commerce  (1)Metro Studio  (11)Mobile  (179)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (18)Performance  (2)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (5)Road Map  (9)Scheduler  (18)SfDataGrid  (8)Silverlight  (21)Sneak Peek  (14)Solution Services  (2)Spreadsheet  (4)SQL  (5)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (9)Tips and Tricks  (41)UI  (101)Uncategorized  (68)Unix  (2)User interface  (66)Visual State Manager  (1)Visual Studio  (15)Visual Studio Code  (8)Web  (154)What's new  (99)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
How to Synchronize Google Calendar with Syncfusion Blazor Scheduler

How to Synchronize Google Calendar with Syncfusion Blazor Scheduler

Syncfusion Blazor Scheduler lets you synchronize and manage calendars like Google calendar and Outlook calendar in one place. This will help you avoid conflicts among the multiple calendars (like personal and professional appointments) and manage time efficiently. In this article, we will walk you through the steps to implement two-way synchronization between Syncfusion Blazor Scheduler and Google Calendar. This means that if we make changes in either calendar, it will be reflected in both the places. Google Calendar provides flexible APIs for synchronization.

Let’s get started!

Project setup

Refer to the Getting Started with Blazor Scheduler Component UG documentation to create a simple Blazor Scheduler in a Blazor server-side application.

Configuring Google service

To add the required NuGet packages to the project, right-click on Dependencies and select Manage NuGet Packages.
Right-click on Dependencies and select Manage NuGet Packages.

In the Browse tab, find and install the Google.Apis.Calendar.v3 NuGet package.
Install the Google.Apis.Calendar.v3 NuGet package

Enable Google Calendar API

Refer to the Quick Start documentation to turn on the Google Calendar API, download the credentials.json, and place it in the application root directory.

Initialize service

 Add the GoogleService class in the Data folder and add the following code to initialize Google Calendar service.

public class GoogleService
{
    string[] Scopes = { CalendarService.Scope.Calendar };
    string ApplicationName = "Google Calendar Sync with Blazor Scheduler";
    CalendarService Service;
    public GoogleService()
    {
       UserCredential credential;
       using (FileStream stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
       {
          credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "admin", CancellationToken.None, new FileDataStore("token.json", true)).Result;
       }
       Service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName });
    }
}

In the StartUp.cs file, register GoogleService as AddSingleton in the ConfigureServices method. Refer to the following code.

public void ConfigureServices(IServiceCollection services)
{
    …
    services.AddSingleton<GoogleService>();
}

Blazor Scheduler fields

Create an Appointment class in the Data folder and add in the following code. This Appointment class will serve as the model class.

public class Appointment
{
    public string Id { get; set; }
    public string Subject { get; set; }
    public string Location { get; set; }
    public string Description { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public string StartTimezone { get; set; }
    public string EndTimezone { get; set; }
    public bool IsAllDay { get; set; }
    public bool IsBlock { get; set; }
    public bool IsReadonly { get; set; }
    public string RecurrenceID { get; set; }
    public string FollowingID { get; set; }
    public string RecurrenceRule { get; set; }
    public string RecurrenceException { get; set; }
}

Add Syncfusion Blazor Scheduler component

Now add the Blazor Scheduler component to the Index.razor page and set Tvalue to the Appointment model type.

<SfSchedule TValue="Appointment">
</SfSchedule>

Getting events from Google Calendar

In previous steps, we initialized the Google Calendar service and added an empty Scheduler without appointments. In the following method, we will make an API request to read Google Calendar events. Then, we will convert them to the Appointment model type for the Blazor Scheduler.

public List<Appointment> GetEvents(DateTime date)
{
    try
    {
        EventsResource.ListRequest request = Service.Events.List("primary");
        request.TimeMin = date;
        request.MaxResults = 2500;
        Events events = request.Execute();
        List<Appointment> eventDatas = new List<Appointment>();
        if (events.Items != null && events.Items.Count > 0)
        {
            foreach (Event eventItem in events.Items)
            {
                if (eventItem.Start == null && eventItem.Status == "cancelled")
                {
                    continue;
                }
                DateTime start;
                DateTime end;
                if (string.IsNullOrEmpty(eventItem.Start.Date))
                {
                    start = (DateTime)eventItem.Start.DateTime;
                    end = (DateTime)eventItem.End.DateTime;
                }
                else
                {
                    start = Convert.ToDateTime(eventItem.Start.Date);
                    end = Convert.ToDateTime(eventItem.End.Date);
                }
                Appointment eventData = new Appointment()
                {
                    Id = eventItem.Id,
                    Subject = eventItem.Summary,
                    StartTime = start,
                    EndTime = end,
                    Location = eventItem.Location,
                    Description = eventItem.Description,
                    IsAllDay = !string.IsNullOrEmpty(eventItem.Start.Date)
                };
                eventDatas.Add(eventData);
            }
        }
        return eventDatas;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return new List<Appointment>();
    }
}

Refer to the Google Calendar event fields to learn more about  it.

Refer to the Syncfusion UG documentation to learn more about the Blazor Scheduler fields.

Binding events to Blazor Scheduler

Inject the GoogleService in the Index.razor file to get Google Calendar events from that service. Assign the resultant value as the DataSource in the Syncfusion Blazor Scheduler.

Refer to the following code example.

@inject GoogleService GoogleService

<SfSchedule TValue="Appointment" Width="100%" Height="650px" @bind-SelectedDate="SelectedDate">
    <ScheduleEventSettings DataSource="@DataSource"></ScheduleEventSettings>
</SfSchedule>

@code{
    private DateTime SelectedDate;
    private List<Appointment> DataSource;

    protected async override Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        SelectedDate = new DateTime(2020, 11, 1);
        DataSource = GoogleService.GetEvents(SelectedDate);
    }
}

Perform CRUD actions in Blazor Scheduler

Use the ActionCompleted event to capture the insert, update, and delete actions in the Blazor Scheduler. This event will provide the complete details of the changes made in the Calendar during any operation. Using this information, we can perform CRUD actions in Google Calendar via GoogleService.

Refer to the following code.

@inject GoogleService GoogleService

<SfSchedule TValue="Appointment" Width="100%" Height="650px" @bind-SelectedDate="SelectedDate">
    <ScheduleEventSettings DataSource="@DataSource"></ScheduleEventSettings>
    <ScheduleEvents TValue="Appointment" ActionCompleted="OnActionCompleted"></ScheduleEvents>
</SfSchedule>

@code{
    private DateTime SelectedDate;
    private List<Appointment> DataSource;

    protected async override Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        SelectedDate = new DateTime(2020, 11, 1);
        DataSource = GoogleService.GetEvents(SelectedDate);
    }

    private void OnActionCompleted(ActionEventArgs<Appointment> args)
    {
        if (args.ActionType == ActionType.EventCreate || args.ActionType == ActionType.EventChange || args.ActionType == ActionType.EventRemove)
        {
            if (args.AddedRecords != null && args.AddedRecords.Count > 0)
            {
                foreach (Appointment eventData in args.AddedRecords)
                {
                    GoogleService.InsertEvent(eventData);
                }
            }
            if (args.ChangedRecords != null && args.ChangedRecords.Count > 0)
            {
                foreach (Appointment eventData in args.ChangedRecords)
                {
                    GoogleService.UpdateEvent(eventData);
                }
            }
            if (args.DeletedRecords != null && args.DeletedRecords.Count > 0)
            {
                foreach (Appointment eventData in args.DeletedRecords)
                {
                    GoogleService.RemoveEvent(eventData.Id);
                }
            }
            this.DataSource = GoogleService.GetEvents(SelectedDate);
        }
    }
}

Inserting Blazor Scheduler events in Google Calendar

Add the following method in the GoogleService class to convert a Scheduler event to a Google Calendar event and insert it in the Google Calendar.

public void InsertEvent(Appointment eventData)
{
    try
    {
        EventDateTime start;
        EventDateTime end;
        if (eventData.IsAllDay)
        {
            start = new EventDateTime() { Date = eventData.StartTime.ToString("yyyy-MM-dd") };
            end = new EventDateTime() { Date = eventData.EndTime.ToString("yyyy-MM-dd") };
        }
        else
        {
            start = new EventDateTime() { DateTime = eventData.StartTime, TimeZone = "UTC" };
            end = new EventDateTime() { DateTime = eventData.EndTime, TimeZone = "UTC" };
        }
        Event eventItem = new Event()
        {
            Summary = eventData.Subject,
            Start = start,
            End = end,
            Location = eventData.Location,
            Description = eventData.Description,
            Created = DateTime.Now.ToUniversalTime()
        };
        EventsResource.InsertRequest addEvent = Service.Events.Insert(eventItem, "primary");
        addEvent.Execute();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Updating Blazor Scheduler events in Google Calendar

Refer to the following code to do updates in Google Calendar.

public void UpdateEvent(Appointment eventData)
{
    try
    {
        var editedEvent = Service.Events.Get("primary", eventData.Id).Execute();
        editedEvent.Summary = eventData.Subject;
        editedEvent.Location = eventData.Location;
        editedEvent.Description = eventData.Description;
        editedEvent.Updated = DateTime.Now.ToUniversalTime();
        if (eventData.IsAllDay)
        {
            editedEvent.Start = new EventDateTime() { Date = eventData.StartTime.ToString("yyyy-MM-dd") };
            editedEvent.End = new EventDateTime() { Date = eventData.EndTime.ToString("yyyy-MM-dd") };
        }
        else
        {
            editedEvent.Start = new EventDateTime() { DateTime = eventData.StartTime };
            editedEvent.End = new EventDateTime() { DateTime = eventData.EndTime };
        }
        var updatedEvent = Service.Events.Update(editedEvent, "primary", editedEvent.Id);
        updatedEvent.Execute();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Removing Blazor Scheduler events in Google Calendar

Refer to the following code to remove events in Google Calendar.

public void RemoveEvent(string id)
{
    try
    {
        EventsResource.DeleteRequest deleteEvent = Service.Events.Delete("primary", id);
        deleteEvent.Execute();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

Output

Google Calendar Synchronized with Syncfusion Blazor Scheduler
Synchronize Google Calendar with Syncfusion Blazor Scheduler

GitHub reference

For more information, you can check out Synchronize Google Calendar with Syncfusion Blazor Scheduler demo.

Summary

This blog explained in detail how to synchronize Google Calendar with Syncfusion Blazor Scheduler. Try this yourselves and leave your feedback in the comments section below.

Syncfusion Blazor offers 65+ high-performance, lightweight, and responsive UI components for the web, including file-format libraries, in a single package. Please take a look at our live demos in our sample browser for a hands-on experience.

For existing customers, the latest version is available for download from the License and Downloads page. If you are not yet a Syncfusion customer, you can try our 30-day free trial to check out the available features. You can try our samples from this GitHub location.

You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

If you like this post, we think you will also like the following:

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin

Leave a comment

Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top