Office 365 / SharePoint Online - Connecting Office 365 / SharePoint Online Site Using CSOM (Client Object Model)

While working with SharePoint online, most of the time, we need to perform some one-time batch operations like - associating content types to multiple lists, associating content type to list items, setting default content type for multiple lists, giving the permissions to multiple lists/sites, deleting the list items in list having some condition and this list is very large.

Also, there were no timer jobs available in SharePoint Online. So, the only option that remains is hosting the job in Azure but then it requires the extra cost of an Azure subscription. SharePoint Designer Workflow is another option but there are limitations, for some scenarios workflows doesn’t work either.

So in all those scenarios, CSOM is very helpful. We could easily write any kind of tool/application using CSOM and very easily perform such types of batch operations.

Here, I’ll be covering the first initial basic step - to connect the Office 365 / SharePoint online using CSOM.

Tools required

  1. Visual Studio (Here, I am using Visual Studio 2017) – We will create console application.
  2. SharePoint Client Object Model (CSOM) SDK– Microsoft.SharePointOnline.CSOM
  3. Office 365 details,

    1. SharePoint site URL to which we need to connect
    2. UserName and Password to connect the Office 365 / SharePoint online

Detailed Steps

  1. Open Visual Studio. 
  2. Create new project of type “Console App (.NET Framework)” say “CSOM-ConnectToO365”.
  3. To connect to SharePoint Online, we will require SharePoint Client Object Model (CSOM) SDK. With the help of NuGet Manager, we will add SharePoint Client Object Model SDK to our solution.

    • Right click on Project in “Solution Explorer” and click on “Manage NuGet Packages…” as shown in below figure 1.

      Note

      In Visual Studio 2017, NuGet Package Manager is automatically installed. For more details on NuGet please have a look at NuGet Documentation.

      SharePoint
      Figure 1: NuGet manager option in Visual Studio
    • Once you've clicked on the above link “NuGet UI” opens, by default “Installed” tab is selected and shows the currently referenced packages in the solution.

    • To install SharePoint online client SDK first time, click on “Browse” tab and in search box put the text like “SharePoint online client sdk 2016”, here we will get result as

      SharePoint
      Figure 2: Installing SharePoint online SDK - Version 16
    • Install the package as shown in above figure 2. Make sure you selected version 16 since there is version 15 also available for SharePoint on premises environment.

    • Once installation started press “OK” button for “Preview” dialog box as

      SharePoint
      Figure 3: Preview dialog while installing NuGet package - SharePoint online CSOM SDK
    • And accept the License on “License Accept” dialog as

      SharePoint
      Figure 4: License Acceptance dialog while installing NuGet package - SharePoint Online CSOM SDK
    • Once this package is installed successfully, in references we will see the  following new libraries are getting added

      SharePoint
      Figure 5: New SharePoint online libraries are getting added after installing SharePoint online CSOM SDK
    • In solution “packages.config” file get added with following details
      1. <packages>    
      2.    <package id="Microsoft.SharePointOnline.CSOM" version="16.1.6621.1200" targetFramework="net452" />    
      3. </packages>    
    • Also, in folder structure parallel to our project file “packages” folder gets created (if no other package previously installed) and under which there is a folder with the name =>packagename + version is getting created, so in this case it is “Microsoft.SharePointOnline.CSOM.16.1.6621.1200” and underneath in lib folder, folders with specific frameworks are getting created and in these folders all dlls or respective files get copied.

      So here folder structure is as follows,

      \visual studio 2017\Projects\CSOM-ConnectToO365\packages\Microsoft.SharePointOnline.CSOM.16.1.6621.1200\lib\ and under lib folder, respective framework folders as

      SharePoint
      Figure 6: Folder structure for NuGet files under \visual studio 2017\Projects\CSOM-ConnectToO365\packages\Microsoft.SharePointOnline.CSOM.16.1.6621.1200\lib\

  1. Once we have references to client libraries, we can now use API and connect to the SharePoint Online site. For connecting to SharePoint online site we will require “Site URL, UserName and Password”. Here we are storing these details in App.Config file as
    1. <appSettings>  
    2.    <add key="siteURL" value="sharepointonlinesiteurl"/>  
    3.    <add key="userName" value="username"/>  
    4.    <add key="password" value="password"/>  
    5. </appSettings>  

  1. In Main method of our console application , read the above settings as,
    1. #region Site Details - Read the details from config file  
    2. string siteURL = ConfigurationManager.AppSettings["siteURL"];  
    3. string userName = ConfigurationManager.AppSettings["userName"];  
    4. string password = ConfigurationManager.AppSettings["password"];  
    5. #endregion  

  1. From site URL , we will create ClientContext object and assign the credentials as
    1. //Create the client context object and set the credentials  
    2. ClientContext clientContext = new ClientContext(siteURL);  
    3. SecureString securePassword = new SecureString();  
    4. foreach(char c in password.ToCharArray())  
    5. securePassword.AppendChar(c);  
    6. clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);  

In above example, SharePointOnlineCredentials class requires secured string. For more details on SecureString class please have a look once here.

Complete Code

  1. using Microsoft.SharePoint.Client;  
  2. using System;  
  3. using System.Configuration;  
  4. using System.Security;  
  5. namespace ConnectingToO365 {  
  6.     /// <summary>  
  7.     ///  
  8.     /// </summary>  
  9.     public class Program {  
  10.         static void Main(string[] args) {#region Site Details - Read the details from config file  
  11.             string siteURL = ConfigurationManager.AppSettings["siteURL"];  
  12.             string userName = ConfigurationManager.AppSettings["userName"];  
  13.             string password = ConfigurationManager.AppSettings["password"];  
  14.             #endregion  
  15.             #region ConnectTo O365  
  16.             //Create the client context object and set the credentials  
  17.             ClientContext clientContext = new ClientContext(siteURL);  
  18.             SecureString securePassword = new SecureString();  
  19.             foreach(char c in password.ToCharArray()) securePassword.AppendChar(c);  
  20.             clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);  
  21.             //Load the web  
  22.             Web web = clientContext.Web;  
  23.             clientContext.Load(web);  
  24.             clientContext.ExecuteQuery();  
  25.             Console.WriteLine(web.Title);  
  26.             Console.ReadKey();  
  27.             #endregion  
  28.         } //Main  
  29.     } //cs  
  30. //ns  

Thanks!

Enjoy Reading :)

As usual, any feedback / query / suggestions are most welcome!!!