Introduction:
We implemented the intranet solution for a consulting firm based out of Alpharetta, GA, USA. One of the requirements was to store events from Shared Outlook Calendar (Office 365) to SharePoint List for easier accessibility for the users. In this blog, we will learn how to get events from a Shared Outlook Calendar
using Microsoft Exchange web service and store in SharePoint Online List with CSOM
using C# console application.
So, now Let’s get started with the procedure to build the custom
console application.
Step 1: Create Solution
- Open Visual Studio 2019, Click on Create
New Project and then Choose Console App (.NET Framework).
- Give it a meaningful Project Name and in Framework select .NET
Framework 4 and click "Create".
Step 2: Establish Connectivity with Microsoft Exchange Webservice
- Install "Microsoft.Exchange.WebServices" NuGet package.
- Add namespace “using Microsoft.Exchange.WebServices.Data;”
- We will be using Exchange Service class to connect the Shared Calendar.
- We can use the below piece of code to create the instance of ExchangeService and define the credentials & endpoint URL.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); service.Credentials = new WebCredentials("userEmailAddress", "userPassword"); service.Url = new Uri("https://outlook.office365.com/ews/exchange.asmx");
Step 3: Get Calendar Events
- The calendar can contain some
folder, with the use of the "FolderView" class we can retrieve the same. Constructor FolderView(100) Initializes a new instance of the FolderView class with the maximum number of returned folders specified.
FolderView view = new FolderView(100);
- Initialize a new instance of the FolderId class with the
specified folder name and mailbox.
Use this constructor to link this folder ID to a well-known folder (for example, Inbox, Calendar or Contacts) in a specific mailbox.FolderId folderToAccess = new FolderId(WellKnownFolderName.Calendar, "shared Email"); FolderId(WellKnownFolderName, Mailbox)
- FindFoldersResults Represents the results of a folder search
operation.
FindFolders Obtains a list of folders by searching the subfolders of the specified folder.FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.Root, view);
- CalendarFolder Represents a folder that contains
appointments.
CalendarFolder.Bind(service,folderToAccess) binds to an existing calendar folder and loads its first-class properties. Calling this method results in a call to Exchange Web Services (EWS).var calendar2 = CalendarFolder.Bind(service,folderToAccess);
- Define a date range view of appointments in the calendar folder
search operations.
CalendarView cv = new CalendarView(StartDate, EndDate);
- FindAppointments obtains a list of appointments by searching
the contents of a specified folder.
FindItemsResults<Appointment> a collection of appointments that represents the contents of the specified folder.FindItemsResults<Appointment> fapts = service.FindAppointments(folderToAccess, cv);
Now with the use of appointment class property, we can retrieve Event Subject, Organizer, and other property. - Here, we will get the Event Title and Organizer.
Step 4: Store in SharePoint List.
- Once we get data, we can store it in SharePoint List with CSOM. We will add the Event subject and Organizer Name, for that we create one Single Line of Text and one Person column in a SharePoint List.
- Add namespace “using Microsoft.SharePoint.Client;” and “using System.Security;”.
- Represents the context for SharePoint objects and
operations.
ClientContext clientContext = new ClientContext(siteUrl);
- Give Email and Password, Gets or sets the authentication
information for the client context
clientContext.Credentials = new SharePointOnlineCredentials("username", "password");
- Connect List.
List appointmentsList = clientContext.Web.Lists.GetByTitle("Appointments");
- ListItemCreationInformation specifies the properties of the new
list item.
ListItem represents an item or row in a list.ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
- List.AddItem method returns a ListItem instance representing
the creation of a new list item in the list.
ListItem newItem = appointmentsList.AddItem(itemCreateInfo);
- As we know to add items in Person columns into the list, we need to
provide Id, below code, will get Id of the organizer.
var demo = Appoint.Organizer; string testName = demo.ToString(); var demo2 = testName.Substring(0, testName.IndexOf("<") - 1); User userTest = clientContext.Web.EnsureUser(demo2); clientContext.Load(userTest); clientContext.ExecuteQuery();
- Now, the final step to insert a record into the SharePoint list.
newItem["Title"] = Appoint.Subject; newItem["Users"] = userTest.Id; newItem.Update(); clientContext.ExecuteQuery();
Complete Code
using System; using Microsoft.Exchange.WebServices.Data; using Microsoft.SharePoint.Client; using System.Security; using Folder = Microsoft.Exchange.WebServices.Data.Folder; namespace SharedCalender { class Program { static void Main(string[] args) { ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010); service.Credentials = new WebCredentials("userEmailAddress", "userPassword"); service.Url = new Uri("https://outlook.office365.com/ews/exchange.asmx"); FolderView view = new FolderView(100); FolderId folderToAccess = new FolderId(WellKnownFolderName.Calendar, "shared Email"); FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.Root, view); foreach (Folder f in findFolderResults) { var calendar2 = CalendarFolder.Bind(service,folderToAccess); DateTime StartDate = DateTime.Today.AddMonths(-1); DateTime EndDate = DateTime.Today.AddMonths(1); CalendarView cv = new CalendarView(StartDate, EndDate); FindItemsResults<Appointment> fapts = service.FindAppointments(folderToAccess, cv); if (fapts.Items.Count > 0) { foreach (Appointment Appoint in fapts) { string siteUrl = "https://constoso.sharepoint.com/sites/SiteName"; ClientContext clientContext = new ClientContext(siteUrl); SecureString passWord = new SecureString(); foreach (char c in "Password".ToCharArray()) passWord.AppendChar(c); clientContext.Credentials = new SharePointOnlineCredentials("userEmailAddress", passWord); List appointmentsList = clientContext.Web.Lists.GetByTitle("TestList");
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); ListItem newItem = appointmentsList.AddItem(itemCreateInfo);
//get user id var demo = Appoint.Organizer; string testName = demo.ToString(); var demo2 = testName.Substring(0, testName.IndexOf("<") - 1); User userTest = clientContext.Web.EnsureUser(demo2); clientContext.Load(userTest); clientContext.ExecuteQuery(); newItem["Title"] = Appoint.Subject; newItem["Users"] = userTest.Id; newItem.Update(); clientContext.ExecuteQuery() } } Console.ReadLine(); } } } }
Conclusion:
This is how we can access Events from Shared Calendar using Exchange web service and store data to SharePoint list.
If you have any questions you can reach out our
SharePoint Consulting team
here.
No comments:
Post a Comment