How to Synchronize Outlook Calendar Events with Syncfusion WinUI Scheduler
Tags: winui, development, scheduler, outlook
Published: 2023-03-07 06:01:35

---
title: How to Synchronize Outlook Calendar Events with Syncfusion WinUI Scheduler
published: true
date: 2023-03-06 12:18:33 UTC
tags: winui, development, scheduler, outlook
canonical_url: https://www.syncfusion.com/blogs/post/synchronize-outlook-calendar-events-with-syncfusion-winui-scheduler.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vjspzchyfj2j46f792xy.png
---
Maintaining more than one calendar is chaos if the appointments aren’t synchronized. With multiple calendars, the probability of scheduling different appointments in the same time solt is quite high. That’s why it’s always better synchronize appointments across calendars. In this blog, I will explain how to synchronize events in the [Syncfusion WinUI Scheduler](https://www.syncfusion.com/winui-controls/scheduler "Syncfusion WinUI Scheduler") with [Microsoft Outlook Calendar](https://support.microsoft.com/en-us/office/introduction-to-the-outlook-calendar-d94c5203-77c7-48ec-90a5-2e2bc10bd6f8 "Microsoft Outlook Calendar").

To do this, we will be using [Microsoft Graph](https://learn.microsoft.com/en-us/graph/overview "Microsoft Graph"), which is the gateway to access the Microsoft APIs and allows developers to integrate their application with Microsoft products like Outlook Calendar.

Let’s get started!

## Create a WinUI Scheduler application

1. Create a [WinUI 3 desktop application](https://docs.microsoft.com/en-us/windows/apps/winui/winui3/get-started-winui3-for-desktop "Create a WinUI 3 desktop application").
2. Add a reference to the [Syncfusion.Scheduler.WinUI](https://www.nuget.org/packages/Syncfusion.Scheduler.WinUI "Syncfusion.Scheduler.WinUI NuGet Package")NuGet package.
3. Import the control namespace **Syncfusion.UI.Xaml.Scheduler** in XAML.
4. Finally, initialize the WinUI Scheduler control.
```xml
xmlns:scheduler="using:Syncfusion.UI.Xaml.Scheduler"
<scheduler:SfScheduler x:Name="Scheduler"/>
```

### Create an event for the Scheduler

The [WinUI Scheduler](https://www.syncfusion.com/winui-controls/scheduler "Syncfusion WinUI Scheduler") supports loading any data object to create appointments using the [AppointmentMapping](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.Scheduler.AppointmentMapping.html "AppointmentMapping Class of WinUI Scheduler") property.

Follow these steps to create custom appointments in the Scheduler.

1.Create an event model with required fields such as event name, start and end time, etc.
```csharp
public class Meeting
{
   public string EventName { get; set; }
   public DateTime From { get; set; }
   public DateTime To { get; set; }
   public bool IsAllDay { get; set; }
   public Brush Background { get; set; }
   public Brush Foreground { get; set; }
   public string RRule { get; set; }
}
```
2.Create events to schedule in the viewmodel class.
```csharp
public class SchedulerViewModel
{
    public ObservableCollection<Meeting> Meetings { get; set; }
    
    public SchedulerViewModel()
    {
        Meetings = new ObservableCollection<Meeting>();
        this.AddSchedulerEvents();
    }
    /// <summary>
    /// Method to add events to scheduler.
    /// </summary>
    private void AddSchedulerEvents()
    {
       var colors = new List<SolidColorBrush>
       {
          new SolidColorBrush(Color.FromArgb(255, 133, 81, 242)),
          new SolidColorBrush(Color.FromArgb(255, 140, 245, 219)),
          new SolidColorBrush(Color.FromArgb(255, 83, 99, 250)),
          new SolidColorBrush(Color.FromArgb(255, 255, 222, 133)),
          new SolidColorBrush(Color.FromArgb(255, 45, 153, 255)),
          new SolidColorBrush(Color.FromArgb(255, 253, 183, 165)),
          new SolidColorBrush(Color.FromArgb(255, 198, 237, 115)),
          new SolidColorBrush(Color.FromArgb(255, 253, 185, 222)),
          new SolidColorBrush(Color.FromArgb(255, 83, 99, 250))
       };
       
       var subjects = new List<string>
       {
           "Business Meeting",
           "Conference",
           "Medical check up",
           "Performance Check",
           "Consulting",
           "Project Status Discussion",
           "Client Meeting",
           "General Meeting",
           "Yoga Therapy",
           "GoToMeeting",
           "Plan Execution",
           "Project Plan"
       };
       
       Random ran = new Random();
       for (int startdate = -10; startdate < 10; startdate++)
       {
           var meeting = new Meeting();
           meeting.EventName = subjects[ran.Next(0, subjects.Count)];
           meeting.From = DateTime.Now.Date.AddDays(startdate).AddHours(9);
           meeting.To = meeting.From.AddHours(10);
           meeting.Background = colors[ran.Next(0, colors.Count)];
           meeting.Foreground = GetAppointmentForeground(meeting.Background);
           this.Meetings.Add(meeting);
       }
   }
        
   private Brush GetAppointmentForeground(Brush backgroundColor)
   {
      var brush = backgroundColor as SolidColorBrush;
            
      if (brush.Color.ToString().Equals("#FF8551F2") || brush.Color.ToString().Equals("#FF5363FA") || brush.Color.ToString().Equals("#FF2D99FF"))
          return new SolidColorBrush(Microsoft.UI.Colors.White);
       else
          return new SolidColorBrush(Color.FromArgb(255, 51, 51, 51));
    }
}
```
3.Map the custom event data object properties to the Scheduler by configuring the [AppointmentMapping](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.Scheduler.SfScheduler.html#Syncfusion_UI_Xaml_Scheduler_SfScheduler_AppointmentMapping "AppointmentMapping property of WinUI Scheduler") property. Then assign the events from the viewmodel class to the [ItemsSource](https://help.syncfusion.com/cr/winui/Syncfusion.UI.Xaml.Scheduler.SfScheduler.html#Syncfusion_UI_Xaml_Scheduler_SfScheduler_ItemsSource "ItemsSource property of WinUI Scheduler")property.
```xml
<Grid>
  <Grid.DataContext>
     <local:SchedulerViewModel/>
  </Grid.DataContext>
  <scheduler:SfScheduler x:Name="Scheduler" ItemsSource="{Binding Meetings}">
            
    <scheduler:SfScheduler.AppointmentMapping>
      <scheduler:AppointmentMapping
            Subject="EventName"
            StartTime="From"
            EndTime="To"
            AppointmentBackground="Background"
            Foreground="Foreground"
            RecurrenceRule="RRule"
            IsAllDay="IsAllDay"/>
    </scheduler:SfScheduler.AppointmentMapping>
  </scheduler:SfScheduler>
```

We are done creating a [WinUI Scheduler](https://www.syncfusion.com/winui-controls/scheduler "Syncfusion WinUI Scheduler") application with custom appointments.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/WinUI-Scheduler-with-Custom-Appointments.png" alt="WinUI Scheduler with Custom Appointments" style="width:100%">

  <figcaption>WinUI Scheduler with Custom Appointments</figcaption>

</figure>

## Configure Microsoft Azure AD service

Now let’s look at the steps to configure the settings to read and write calendar data from an Office 365 account. We will connect the WinUI Scheduler application with Microsoft Azure to import and export Syncfusion WinUI Scheduler and Microsoft Calendar events.

Follow these steps to configure the Microsoft Azure AD service.

1.Log in to [Microsoft Azure](https://portal.azure.com/#home "Microsoft Azure") and select [App registrations](https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade "Microsoft Azure App Registrations").
2.In the [App registration](https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade "Microsoft Azure App Registrations") page, select the **New registration** option, fill in the **Application Name** (e.g., Outlook Calendar), and click **Register**.  
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Register-Application-in-Microsoft-Azure.png" alt="Register Application in Microsoft Azure" style="width:100%">

  <figcaption>Register Application in Microsoft Azure</figcaption>

</figure>

3.Once the application is registered, go to the registered Outlook Calendar Application page, select **Authentication** > **Add Platform** , and then select **Mobile and desktop applications** on the **Configure platforms** panel.  
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Add-Platform-for-Application-Registered.png" alt="Add Platform for Application Registered" style="width:100%">

  <figcaption>Add Platform for Application Registered</figcaption>

</figure>

4.After clicking the platform configuration, select the Redirect URI option and then click **Configure**.  
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Configure-Platform-for-Application-Registered.png" alt="Configure Platform for Application Registered" style="width:100%">

  <figcaption>Configure Platform for Application Registered</figcaption>

</figure>

5.Next, change the Outlook Calendar application and API permission to synchronize the Office 365 Calendar events in your application. To do that, go to **API permissions** , select **Add a permission** , then select **Microsoft Graph**.  
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Request-API-Permission-for-Application-Registered.png" alt="Request API Permission for Application Registered" style="width:100%">

  <figcaption>Request API Permission for Application Registered</figcaption>

</figure>

6.Click **Delegated permissions** on the Microsoft Graph page.  
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Delegated-Permission-for-Application-Registered.png" alt="Delegated Permission for Application Registered" style="width:100%">

  <figcaption>Delegated Permission for Application Registered</figcaption>

</figure>

7.Search for **Calendar** and change the Calendar API permission to **ReadWrite** , and then click **Add permissions**.  
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Request-Outlook-Calendar-API-Permission.png" alt="Request Outlook Calendar API Permission" style="width:100%">

  <figcaption>Request Outlook Calendar API Permission</figcaption>

</figure>

8.Now we have configured the Microsoft Azure service to access the Calendar API. You can use the application ID and tenant ID of the registered Outlook Calendar application to connect Microsoft Azure with the application.  
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Registered-Application-Overview-1.png" alt="Registered Application Overview" style="width:100%">

  <figcaption>Registered Application Overview</figcaption>

</figure>

9.Install the Microsoft Graph package in Visual Studio to connect the Syncfusion WinUI Scheduler application and Microsoft Azure. Install the NuGet package by selecting **Manage NuGet packages** for the solution, and then add the following references to access the Microsoft Calendar API:
```csharp
using Microsoft.Graph;
using Microsoft.Identity.Client;
```
10.Create the **authority** using the **tenant ID** and register the **client ID** , **authority** , and **Redirecturi** using the [IPublicClientApplication](https://learn.microsoft.com/en-us/dotnet/api/microsoft.identity.client.ipublicclientapplication?view=azure-dotnet "IPublicClientApplication Interface"). Refer to the following code to create a client application.
```csharp
internal static IPublicClientApplication ClientApplication;
private string clientID, tenantID, authority;
        
public App()
{
   this.InitializeComponent();
            
   //// You need to replace this with your application or client ID.
   clientID = "--Client ID goes here--";
            
   //// You need to replace this with your tenant ID.
   tenantID = "--Tenant ID goes here--";
            
   authority = "https://login.microsoftonline.com/" + tenantID;
            
   ClientApplication = PublicClientApplicationBuilder.Create(clientID)
   .WithAuthority(authority)            
   .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
   .Build();
        
}
```

**Note:** Use the **Application (client) ID** and **tenant ID** from the registered application overview in Microsoft Azure. Refer to the previous figure.

## Connect the Microsoft Graph service client by using the GraphServiceClient

The user token information can be obtained using the [AcquireTokenInteractive](https://learn.microsoft.com/en-us/dotnet/api/microsoft.identity.client.ipublicclientapplication.acquiretokeninteractive?view=azure-dotnet#microsoft-identity-client-ipublicclientapplication-acquiretokeninteractive(system-collections-generic-ienumerable((system-string))) "IPublicClientApplication.AcquireTokenInteractive method") and [AcquireTokenSilent](https://learn.microsoft.com/en-us/dotnet/api/microsoft.identity.client.iclientapplicationbase.acquiretokensilent?view=azure-dotnet#microsoft-identity-client-iclientapplicationbase-acquiretokensilent(system-collections-generic-ienumerable((system-string))-microsoft-identity-client-iaccount) "AcquireTokenSilent method") methods of [IPublicClientApplication](https://learn.microsoft.com/en-us/dotnet/api/microsoft.identity.client.ipublicclientapplication?view=azure-dotnet "IPublicClientApplication Interface"). The [GraphServiceClient](https://learn.microsoft.com/en-us/graph/sdks/create-client?tabs=CS "Create a Microsoft Graph client") is used to get user information from the [endpoint](https://graph.microsoft.com/v1.0/ "Endpoint") by registering the user token information of the IPublicClientApplication.

Refer to the following code.

```csharp
using Microsoft.Graph;
using Microsoft.Identity.Client;
 
private GraphServiceClient Client;

//// Scopes to access the Microsoft API permission.
private static string[] scopes = { "User.Read", "Calendars.Read", "Calendars.ReadWrite" };

private async void Authenticate()
{
    AuthenticationResult tokenRequest;

    //// Register the user token.
    var accounts = await App.ClientApplication.GetAccountsAsync();
    if (accounts.Count() > 0)
    {
        tokenRequest = await App.ClientApplication.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
          .ExecuteAsync();
    }
    else
    {
        tokenRequest = await App.ClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync();
    }
    //// Connect the client information. 
    Client = new GraphServiceClient("https://graph.microsoft.com/v1.0/",
             new DelegateAuthenticationProvider(async (requestMessage) =>
             {
                 requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", tokenRequest.AccessToken);
             }));
}
```

We have finished the necessary code for connecting the WinUI application with Microsoft Azure. Once you run the application, you will see a login page like the one shown in the following image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Office365-Login.png" alt="Office365 Login" style="width:100%">

  <figcaption>Office365 Login</figcaption>

</figure>

Once logged in, you will be prompted with a Permission requested dialog. Read the terms and click the **Accept** button.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Application-Permission.png" alt="Application Permission" style="width:100%">

  <figcaption>Application Permission</figcaption>

</figure>

**Note:** If any details are mismatched, like application (client) ID, tenant ID, or redirect URI, then you will receive a connection error.

## Export Syncfusion WinUI Scheduler events to Outlook Calendar

Once the Microsoft Azure client services are added to the application, you can add the Outlook Calendar [events](https://learn.microsoft.com/en-us/graph/api/resources/event?view=graph-rest-1.0 "Event resource type") by requesting the event builder of the [GraphServiceClient](https://learn.microsoft.com/en-us/graph/sdks/create-client?tabs=CS "Create a Microsoft Graph client") from the application.

Refer to the following code to convert the Syncfusion WinUI Scheduler appointments to Outlook Calendar events.

```csharp
/// <summary>
/// Method to add event to Outlook Calendar.
/// </summary>
private void AddEventToOutlookCalendar()
{
    foreach (Meeting meeting in this.Meetings)
    {
       var calEvent = new Event
       {
           Subject = meeting.EventName,
                    
           Start = new DateTimeTimeZone
           {
              DateTime = meeting.From.ToString(),
              TimeZone = "GMT Standard Time"
           },
           End = new DateTimeTimeZone()
           {
              DateTime = meeting.To.ToString(),
              TimeZone = "GMT Standard Time"
           },
       };
       //// Request to add Syncfusion WinUI Scheduler events to Outlook Calendar events.
       Client.Me.Events.Request().AddAsync(calEvent);
   }
} 
```

## Import Outlook Calendar events to Syncfusion WinUI Scheduler

Likewise, refer to the following code example to convert the Outlook Calendar events to Syncfusion WinUI Scheduler events.

```csharp
private void GetOutlookCalendarEvents()
{
   //// Request to get the Outlook Calendar events.
   var events = Client.Me.Events.Request().GetAsync().Result.ToList();
   if (events != null && events.Count > 0)
   {
       foreach (Event appointment in events)
       {
          Meeting meeting = new Meeting()
          {
              EventName = appointment.Subject,
              From = Convert.ToDateTime(appointment.Start.DateTime),
              To = Convert.ToDateTime(appointment.End.DateTime),
              IsAllDay = (bool)appointment.IsAllDay,
           };
           
           if (appointment.Recurrence != null)
           {
               AddRecurrenceRule(appointment, meeting);
           }
           this.Meetings.Add(meeting);
       }
    }
}
```

Refer to the following code example to convert [Microsoft Outlook recurring events](https://learn.microsoft.com/en-us/graph/outlook-schedule-recurring-events "Schedule Repeating Appointments as Recurring Events in Outlook") to [Syncfusion WinUI Scheduler recurring events.](https://help.syncfusion.com/winui/scheduler/appointments#recurrence-pattern-exceptions "Syncfusion WinUI Scheduler Recurring Events")

Here, I added the code to create daily and weekly recurrence appointment types from Outlook Calendar.

```csharp
private static void AddRecurrenceRule(Event appointment, Meeting meeting)
{
   // Creating recurrence rule.
   RecurrenceProperties recurrenceProperties = new RecurrenceProperties();
   if (appointment.Recurrence.Pattern.Type == RecurrencePatternType.Daily)
   {
      recurrenceProperties.RecurrenceType = SchedulerRecurrenceType.Daily;
   }
   else if (appointment.Recurrence.Pattern.Type == RecurrencePatternType.Weekly)
   {
      recurrenceProperties.RecurrenceType = SchedulerRecurrenceType.Weekly;
      foreach (var weekDay in appointment.Recurrence.Pattern.DaysOfWeek)
      {
         if (weekDay == MicrosoftDayOfWeek.Sunday)
         {
             recurrenceProperties.WeekDays = WeekDays.Sunday;
         }
         if (weekDay == MicrosoftDayOfWeek.Monday)
         {
             recurrenceProperties.WeekDays = recurrenceProperties.WeekDays | WeekDays.Monday;
         }
         if (weekDay == MicrosoftDayOfWeek.Tuesday)
         {
             recurrenceProperties.WeekDays = recurrenceProperties.WeekDays | WeekDays.Tuesday;
         }
         if (weekDay == MicrosoftDayOfWeek.Wednesday)
         {
             recurrenceProperties.WeekDays = recurrenceProperties.WeekDays | WeekDays.Wednesday;
         }
         if (weekDay == MicrosoftDayOfWeek.Thursday)
         {
             recurrenceProperties.WeekDays = recurrenceProperties.WeekDays | WeekDays.Thursday;
         }
         if (weekDay == MicrosoftDayOfWeek.Friday)
         {
             recurrenceProperties.WeekDays = recurrenceProperties.WeekDays | WeekDays.Friday;
         }
         if (weekDay == MicrosoftDayOfWeek.Saturday)
         {
              recurrenceProperties.WeekDays = recurrenceProperties.WeekDays | WeekDays.Saturday;
         }
      }
   }
   recurrenceProperties.Interval = (int)appointment.Recurrence.Pattern.Interval;
   recurrenceProperties.RecurrenceRange = SchedulerRecurrenceRange.Count;
   recurrenceProperties.RecurrenceCount = 10;
   meeting.RRule = RecurrenceHelper.CreateRRule(recurrenceProperties, meeting.From, meeting.To);
}
```

## Synchronize Syncfusion WinUI Scheduler events with Outlook Calendar

In this application, I have added buttons to import and export Outlook Calendar events to and from Syncfusion WinUI Scheduler.

When the export button is clicked, Microsoft Azure connects and exports Syncfusion WinUI Scheduler events to Outlook Calendar.

```csharp
public ICommand ImportButtonCommand { get; set; }

public void ExecuteImportCommand(object parameter)
{
   this.Authenticate(true);
}
```

When the import button is clicked, Microsoft Azure connects and imports Outlook Calendar events to the Syncfusion WinUI Scheduler.

```csharp
public ICommand ExportButtonCommand { get; set; }

public void ExecuteExportCommand(object parameter)
{
    this.Authenticate(false);
}
```

Refer to the following code to add import and export buttons.

```xml
<Grid>
   <Grid.DataContext>
      <local:SchedulerViewModel/>
   </Grid.DataContext>
     
   <StackPanel Orientation="Horizontal" >
      <Button Content="Import Outlook Calendar Events to Syncfusion WinUI Scheduler" Background="#DEECF9" Command="{Binding ImportButtonCommand}" Margin="5"/>
      <Button Content="Export Syncfusion WinUI Scheduler Events to Outlook Calendar" Background="#DEECF9" Command="{Binding ExportButtonCommand}" Margin="5" />
   </StackPanel>
```
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/03/Events-Imported-from-Outlook-Calendar.png" alt="Events Imported from Outlook Calendar" style="width:100%">

  <figcaption>Events Imported from Outlook Calendar</figcaption>

</figure>

## GitHub reference

Refer to the complete app code to [Synchronize Outlook Calendar and WinUI Scheduler on GitHub](https://github.com/SyncfusionExamples/Sync-outlook-calendar-with-syncfusion-winui-scheduler "Synchronize Outlook calendar with Syncfusion WinUI Scheduler demo on GitHub").

## Conclusion

Thanks for reading! In this blog, we saw a quick overview of how to synchronize [WinUI Scheduler](https://www.syncfusion.com/winui-controls/scheduler "Syncfusion WinUI Scheduler") events with Outlook Calendar events.

For current customers, the newest version of our WinUI controls is available for download from the [License and Downloads](https://www.syncfusion.com/account/downloads "License and downloads page of Essential Studio") page. If you are not yet a Syncfusion customer, you can try our 30-day [free trial](https://www.syncfusion.com/downloads "Free evaluation of the Syncfusion Essential Studio") to see how our components can enhance your projects.

You can also contact us through our [support forum](https://www.syncfusion.com/forums "Syncfusion Support Forum"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback/home "Syncfusion Feedback Portal"). We are happy to assist you!

## Related blogs

- [Implement Fuzzy Search in Syncfusion WinUI AutoComplete](https://www.syncfusion.com/blogs/post/fuzzy-search-in-winui-autocomplete.aspx "Blog: Implement Fuzzy Search in Syncfusion WinUI AutoComplete")
- [Experience Seamless Excel-Like Filtering in WinUI DataGrid](https://www.syncfusion.com/blogs/post/excel-like-filtering-in-winui-datagrid.aspx "Blog: Experience Seamless Excel-Like Filtering in WinUI DataGrid")
- [Design a Temperature Monitor Like a Pro Using WinUI Radial Gauge](https://www.syncfusion.com/blogs/post/temperature-monitor-winui-radial-gauge.aspx "Blog: Design a Temperature Monitor Like a Pro Using WinUI Radial Gauge")
- [Achieve Google-Like Autosuggestions with the WinUI AutoComplete Control](https://www.syncfusion.com/blogs/post/achieve-google-like-autosuggestions-with-the-winui-autocomplete-control.aspx "Blog: Achieve Google-Like Autosuggestions with the WinUI AutoComplete Control")