How to Synchronize Google Calendar with Syncfusion Blazor Scheduler
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (203)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (65)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (81)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (897)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (39)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (501)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (381)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (323)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
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:

Comments (1)

I tried to run the GitHub solution (SyncfusionExamples/google-calendar-synchronization-with-blazor-scheduler) after updating to the latest NuGet packages. I have Enabled Google Calendar API and added https://127.0.0.1:5001/ and https://localhost:5001/ as redirect_uris. I keep getting the error………

Error 400: redirect_uri_mismatch

You can’t sign in to this app because it doesn’t comply with Google’s OAuth 2.0 policy.

If you’re the app developer, register the redirect URI in the Google Cloud Console.
Request details: redirect_uri=http://127.0.0.1:55669/authorize/

Do you have any ideas on how to make this work?

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed