CSOM SharePoint Online – Detailed Guide

This is a complete tutorial on CSOM SharePoint Online and we will also discuss a few more csom SharePoint online examples. In details we will discuss:

  • What is csom in SharePoint Online?
  • Create csom SharePoint Online console application
  • Authenticate csom SharePoint online
  • SharePoint Online csom clientcontext credentials
  • csom SharePoint online nuget
  • SharePoint online csom download
  • CSOM SharePoint Online example
  • SharePoint Online csom create site collection
  • SharePoint online csom create communication site
  • SharePoint online csom get all site collections
  • SharePoint online csom site collection created date
  • Create SharePoint Online Subsite using CSOM

What is csom in SharePoint Online

Now, let us first understand what is CSOM in SharePoint Online.

CSOM stands for SharePoint client object model, and is used to insert, update, delete and retrieve data in SharePoint.

Microsoft provides various client object models like:

Apart from the about popular 3 csom models, below are the two CSOM models which are deprecated:

  • Windows Phone assemblies
  • Silverlight redistributable assemblies

In this tutorial, we will focus on SharePoint .NET client object model.

.Net client object model is used with mostly the .net applications or asp.net applications. Apart from this also, we can use .Net client object model with SharePoint provider hosted apps or add-ins.

For on premise SharePoint version, Microsoft provides SharePoint server object model to work with SharePoint objects programmatically.

Microsoft provides C#.net client object model or csom sharepoint online to work with SharePoint sites from .Net applications.

For example, let us see you have an asp.net web application and you want to display data from a SharePoint Online list. What options you have? We can not use the server object model here. So Microsoft provides .NET client object model to work with SharePoint sites from the Asp.Net application.

We can use the csom sharepoint or .Net client object model with windows application, web application, console applications.

csom sharepoint online
csom sharepoint online

SharePoint Online csom download

To work with .Net client object model, we need the below two dlls.

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll

So in the Asp.Net application or windows or console application, we need to add these two dlls.

Based on the functionalities you will use, you will have to add the other dlls like:

  • Microsoft.SharePoint.Client.DocumentManagement.dll
  • Microsoft.SharePoint.Client.Publishing.dll
  • Microsoft.SharePoint.Client.Taxonomy.dll
  • Microsoft.SharePoint.Client.UserProfiles.dll
  • Microsoft.SharePoint.WorkflowServices.Client.dll

By default, since there will not SharePoint installed in the system, there are other ways to get or add these two dlls to the .net application.

We can download and install SharePoint client components sdk in the system. Based on the SharePoint version, you can download SharePoint client components SDK.

Once you download and install SharePoint Online client components sdk, you can see all the client side dlls, in the below directory.

C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI
sharepoint online csom download
sharepoint online csom download

CSOM SharePoint Online console application

Now let us see how to create a console application using visual studio 2019 for CSOM SharePoint Online.

Open visual studio 2019 and then click on Create a new project. Then in the Create a new project, search for console and then choose Console App (.NET Framework). Then click on Next.

what is csom in sharepoint online
csom sharepoint online console application

Then in the Configure your new project, provide the details like:

  • Project name
  • Location (You can choose the default location)
  • Solution name
  • Framework – Select the .NET Framework.
csom sharepoint online console application
csom sharepoint online console application

Then click on the Create button.

Then it will create the console application and you can see the solution explorer like below. Here we can write the code in the Program.cs file.

create console application for csom sharepoint
create console application for csom sharepoint

Here, first thing we need to do is to add the below two dlls into the solution.

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll

As I have explained above, if you have already installed SharePoint Online client component sdk, then you can give a reference from the ISAPI folder.

Right click on the References folder and then click on Add Reference… Then browse to the ISAPI folder and then select the above two dlls.

create console application for csom sharepoint online
create console application for csom sharepoint online

If you have not installed SharePoint online client sdks, then you can also add the dlls from Nuget package manager.

CSOM SharePoint Online nuget

Now, let us see how to add the client dlls from Nuget.

Right click on the References folder then click on Manage NuGet Packages…

csom sharepoint online nuget
csom sharepoint online nuget

Then go to the Browse tab and then search for Microsoft.SharePointOnline.CSOM and you will see the dll from Microsoft, select it and then click on Install.

add csom sharepoint client dll from nuget
add csom sharepoint client dll from nuget

Accept the license agreement and then it will install all the client dlls. You can see below all the references.

sharepoint online csom nuget package
sharepoint online csom nuget package

You can also install SharePoint Online CSOM nuget package from the command prompt.

Install-Package Microsoft.SharePointOnline.CSOM -Version 16.1.20720.12000

Now we can write the code using CSOM SharePoint online.

SharePoint online csom clientcontext credentials

To connect with a SharePoint Online site from the console application using CSOM SharePoint, we need to add the username and password to the SharePointOnlineCredentials.

Here, the password will be a secure password, you can pass like a string.

First thing, you need to do is two add the below using statements:

using System.Security;
using Microsoft.SharePoint.Client;

To get sharepoint online site context using csom, we can use the ClientContext class like:

ClientContext ctx = new ClientContext("https://tsinfo.sharepoint.com/sites/SPGuides/")

ctx.AuthenticationMode = ClientAuthenticationMode.Default;

The complete code looks like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;

namespace CSOM_SharePoint
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ClientContext ctx = new ClientContext("https://tsinfo.sharepoint.com/sites/SPGuides/"))
            {
                ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                SecureString securePassword = new SecureString();
                foreach (char c in "YourPassword")
                    securePassword.AppendChar(c);
                ctx.Credentials = new SharePointOnlineCredentials("bijay@tsinfo.onmicrosoft.com", securePassword);
            }
        }
    }
}

This is how we can authenticate csom sharepoint online console application. This is how the csom sharepoint online authentication works.

Here I have added a simple csom sharepoint online example to get the SharePoint web site properties. Here I have retrieved the website title.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;

namespace CSOM_SharePoint
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ClientContext ctx = new ClientContext("https://tsinfo.sharepoint.com/sites/SPGuides/"))
            {
                ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                SecureString securePassword = new SecureString();
                foreach (char c in "YourPassword")
                    securePassword.AppendChar(c);
                ctx.Credentials = new SharePointOnlineCredentials("bijay@tsinfo.onmicrosoft.com", securePassword);
                Web web = ctx.Web;
                ctx.Load(web);
                ctx.ExecuteQuery();
                Console.WriteLine("The web site title: "+web.Title);
                Console.Read();
            }
        }
    }
}

Once you run the csom sharepoint online console application, you can see the output like below:

authenticate csom sharepoint online
csom sharepoint online console application

Here, we learned, how to get sharepoint online site context using csom and how the csom sharepoint online authentication works.

Here we need to understand the below two important methods of CSOM SharePoint Online.

Load() method

The SharePoint CSOM Load() method does not actually retrieve anything, it just loads the properties only when the ExecuteQuery() method is called does it provide notification that these are the property values that should be loaded for the object.

ExecuteQuery() method

The SharePoint CSOM ExecuteQuery() method sends the request to the server. There is no network traffic until the application calls this method. Until the ExecuteQuery() method is called only the requests are registered by the application.

Before looking out other csom sharepoint online examples, let us check out the difference between SharePoint Online CSOM vs JSOM.

SharePoint Online csom vs jsom

  • SharePoint Online CSOM uses Microsoft.SharePoint.dll while JSOM uses sp.js library. Before you execute the jsom code, make sure the sp.js library loaded in the page.
  • Similar to the Managed CSOM, the JS also is built to batch requests to ensure performance.
  • Another fundamental differences between JSOM and CSOM is that JSOM is designed with asynchronous calls and call-backs in mind. This ensures that transactions that take some time to complete don’t potentially block the calling thread, possibly impacting the UI of your application.
  • C#.net SharePoint CSOM can be used to develop applications that run on the client computer or on windows web server not running SharePoint.
  • JSOM allows JavaScript code to run within the context of SharePoint so it can be used to develop SharePoint hosted add-ins.

CSOM vs REST

Differences:

  • CSOM developers can use Object-oriented programming while REST does not provide this feature.
  • CSOM provides request batching while REST doesn’t. So, REST is chattier & JSOM not.
  • In CSOM we use CAML query while REST uses standard OData vocabularies.
  • SharePoint CSOM Supports Batching which make a lesser number of service call between the client and SharePoint.
  • But Rest API is easier to debug and troubleshoot. By putting the Rest endpoint URL in the browser, we can see the results.

CSOM vs SSOM

  • One of the major disadvantages of SharePoint server object model code is that you need downtime while deploying the solution.
  • The SharePoint server-side code run in the SharePoint server itself. And that is the reason, the server code is not supported in Office 365 SharePoint Online. Because Microsoft does not allow anything deployed to the Office 365 SharePoint Online server.
  • But the CSOM code does not run in the SharePoint server, it always runs outside of the SharePoint farm.

CSOM SharePoint Online example

Now, we will see a few csom sharepoint online examples. We will see how to work with SharePoint site collection, lists etc.

SharePoint Online csom create site collection

Let us see how to create a site collection using SharePoint Online CSOM. Below is the complete code to create a SharePoint Online collection using CSOM SharePoint Online.

To create a site collection in SharePoint Online using CSOM, we need to get the tenant context rather than using the client context.

Here, we can pass the SharePoint Online admin center URL to the ClientContext.

Check out the below code to create SharePoint site collection using CSOM SharePoint Online.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;

namespace CSOM_SharePoint
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ClientContext ctx = new ClientContext("https://tsinfo-admin.sharepoint.com/"))
            {
                ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                SecureString securePassword = new SecureString();
                foreach (char c in "MyPassword")
                    securePassword.AppendChar(c);
                ctx.Credentials = new SharePointOnlineCredentials("bijay@tsinfo.onmicrosoft.com", securePassword);
                var tenant = new Tenant(ctx);
                var siteCollectionProperties = new SiteCreationProperties();
                siteCollectionProperties.Url = "https://tsinfo.sharepoint.com/sites/NewSPGuideSite";
                siteCollectionProperties.Title = "New SPGuides Site";
                siteCollectionProperties.Owner = "bijay@tsinfo.onmicrosoft.com";
                siteCollectionProperties.Template = "STS#3";
                SpoOperation spo = tenant.CreateSite(siteCollectionProperties);
                ctx.Load(tenant);
                ctx.ExecuteQuery();
                Console.WriteLine("SharePoint site collection created successfully!");
                Console.Read();
            }
        }
    }
}

Now, when you open the SharePoint Online admin center, you can see the newly created site collection under Active sites like below:

sharepoint online csom create site collection
sharepoint online csom create site collection

This is how we can create a site collection using CSOM in SharePoint Online.

SharePoint online csom create communication site

Now, let us see how to create a communication site collection in SharePoint Online using CSOM. The steps to create a communication site is similar to create a team site in SharePoint Online. Only difference is the site template id.

The SharePoint Online communication site template id is: SITEPAGEPUBLISHING#0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;

namespace CSOM_SharePoint
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ClientContext ctx = new ClientContext("https://tsinfo-admin.sharepoint.com/"))
            {
                ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                SecureString securePassword = new SecureString();
                foreach (char c in "YourPassword")
                    securePassword.AppendChar(c);
                ctx.Credentials = new SharePointOnlineCredentials("bijay@tsinfo.onmicrosoft.com", securePassword);
                var tenant = new Tenant(ctx);
                var siteCollectionProperties = new SiteCreationProperties();
                siteCollectionProperties.Url = "https://tsinfo.sharepoint.com/sites/NewCommunicationSite";
                siteCollectionProperties.Title = "New Communication Site";
                siteCollectionProperties.Owner = "bijay@tsinfo.onmicrosoft.com";
                siteCollectionProperties.Template = "SITEPAGEPUBLISHING#0";
                SpoOperation spo = tenant.CreateSite(siteCollectionProperties);
                ctx.Load(tenant);
                ctx.ExecuteQuery();
                Console.WriteLine("SharePoint Communication site collection created successfully!");
                Console.Read();
            }
        }
    }
}

Once you execute the code, the SharePoint communication site created successfully using CSOM SharePoint Online.

sharepoint online csom create communication site
sharepoint online csom create communication site

SharePoint online csom get all site collections

Now, let us see how to get all site collections using SharePoint Online CSOM. Below is the complete code for sharepoint online csom list all site collections.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.SharePoint.Client;

namespace CSOM_SharePoint
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ClientContext ctx = new ClientContext("https://tsinfo-admin.sharepoint.com/"))
            {
                ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                SecureString securePassword = new SecureString();
                foreach (char c in "YourPassword")
                    securePassword.AppendChar(c);
                ctx.Credentials = new SharePointOnlineCredentials("bijay@tsinfo.onmicrosoft.com", securePassword);
                var tenant = new Tenant(ctx);
                
                SPOSitePropertiesEnumerable siteProps = tenant.GetSitePropertiesFromSharePoint("0", true);
                ctx.Load(siteProps);
                ctx.ExecuteQuery();
                Console.WriteLine("Total Site Collections: " + siteProps.Count.ToString());
                foreach (var site in siteProps)
                {
                    Console.WriteLine(site.Title + "\t" + site.Template.ToString());
                }
                Console.ReadLine();
            }
        }
    }
}
sharepoint online csom list all site collections
sharepoint online csom list all site collections

This is how we can get all the site collections from the Office 365 tenant or from SharePoint Online admin center.

SharePoint online csom site collection created date

Now, let us see how to know the SharePoint Online site collection created date using CSOM SharePoint Online.

Below is the full code to get the site collection created date using CSOM SharePoint Online.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;

using Microsoft.SharePoint.Client;

namespace CSOM_SharePoint
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ClientContext ctx = new ClientContext("https://tsinfo.sharepoint.com/sites/SPGuides/"))
            {
                ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                SecureString securePassword = new SecureString();
                foreach (char c in "YourPassword")
                    securePassword.AppendChar(c);
                ctx.Credentials = new SharePointOnlineCredentials("bijay@tsinfo.onmicrosoft.com", securePassword);
                Web web = ctx.Web;
                ctx.Load(web);
                ctx.ExecuteQuery();
                Console.WriteLine("The web site title: " + web.Title +" Created Date " + web.Created.ToShortDateString());
                Console.Read();

            }
        }
    }
}
sharepoint online csom site collection created date
sharepoint online csom site collection created date

This is how to get SharePoint Online site collection created date.

Create SharePoint Online Subsite using CSOM

Now, let us see how to create a subsite under a site collection using CSOM SharePoint Online.

Here I have used STS#3, which will create a team site without Office 365 group. You can check out various SharePoint Online site templates.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;

namespace CSOM_SharePoint
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ClientContext ctx = new ClientContext("https://tsinfo.sharepoint.com/sites/SPGuides/"))
            {
                ctx.AuthenticationMode = ClientAuthenticationMode.Default;
                SecureString securePassword = new SecureString();
                foreach (char c in "YourPassword")
                    securePassword.AppendChar(c);
                ctx.Credentials = new SharePointOnlineCredentials("bijay@tsinfo.onmicrosoft.com", securePassword);
                WebCreationInformation creation = new WebCreationInformation();
                creation.Url = "SPGuidesNewSite";
                creation.Title = "SPGuides New Sub Site";
                creation.WebTemplate = "STS#3";
                Web newWeb = ctx.Web.Webs.Add(creation);
                ctx.ExecuteQuery();
                Console.WriteLine("SharePoint site collection created successfully!");
                Console.Read();
            }
        }
    }
}

You can see the subsite created under the SharePoint site collection like below:

sharepoint online csom create sub site
sharepoint online csom create sub site

This is how we can create a subsite under a site collection in SharePoint Online using CSOM.

You cannot change moderation status and set other item properties at that same time SharePoint Online csom

Recently we were trying to update the Approval status column as well as some properties of the list item in SharePoint online using csom (.Net managed object model code). But I got an error which says: You cannot change moderation status and set other item properties at that same time.

To work with SharePoint online using csom (.Net managed object model code) using visual studio 2015, we need to add the below dlls which we can add from Nuget package.

  • Microsoft.SharePoint.client.dll
  • Microsoft.SharePoint.client.runtime.dll

I am using a console application to connect to SharePoint Online site and to work with CSOM.

Recently we were working on a SharePoint project where we need to update item properties of a list item where we also need to update the approval status of the item using csom (.Net managed object model code). We were trying the below code:

if (item != null)
{
item["Columnname"] = "Column Value";
item["Columnname 1"] = "Column 1 Value";
item["Columnname 2"] = "Column 2 Value";
item["_ModerationStatus"] = "0";
item.Update();
context.ExecuteQuery();
}

In the ExecuteQuery() method it gave the below error:

You cannot change moderation status and set other item properties at that same time.

You cannot change moderation status and set other item properties at that same time

We changed the code like below. Basically, we change first update the item custom column properties and then we change the _ModerationStatus properties value.

if (item != null)
{
item["Columnname"] = "Column Value";
item["Columnname 1"] = "Column 1 Value";
item["Columnname 2"] = "Column 2 Value";
item.Update();
context.ExecuteQuery();
item["_ModerationStatus"] = "0";
item.Update();
context.ExecuteQuery();
}

After this the error “You cannot change moderation status and set other item properties at that same time” will not come.

You may like the following SharePoint CSOM tutorials:

In this SharePoint tutorial, we learn everything about CSOM SharePoint Online, how to use CSOM in SharePoint Online to do various operations. And we cover the below topics:

  • What is csom in SharePoint Online?
  • SharePoint Online csom download
  • CSOM SharePoint Online console application
  • CSOM SharePoint Online nuget
  • SharePoint online csom clientcontext credentials
  • SharePoint Online csom vs jsom
  • CSOM vs REST
  • CSOM vs SSOM
  • CSOM SharePoint Online example
  • SharePoint Online csom create a site collection
  • SharePoint online csom create a communication site
  • SharePoint online csom get all site collections
  • SharePoint online csom site collection created date
  • Create SharePoint Online Subsite using CSOM
  • You cannot change moderation status and set other item properties at that same time
  • >