This is a complete tutorial on CSOM SharePoint Online, and we will also discuss a few more csom SharePoint online examples. In detail 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 a communication site
- SharePoint Online csom get all site collections
- SharePoint Online csom site collection created date
- Create a SharePoint Online Subsite using CSOM
- Delete SharePoint List Programmatically
- GetModerationStatus of a document in SharePoint using CSOM
- Bind SharePoint List items in dropdown list programmatically using CSOM
- How to Check if Column Exists or Not in SharePoint List using CSOM
- How to get content type name by id programmatically using csom in SharePoint
- How to get list content types using the SharePoint client object model code (C#.Net)
- How to get SharePoint content type id by name programmatically using CSOM
- How to delete content type from SharePoint list programmatically using CSOM
- Retrieve list item content type name or id using CSOM in SharePoint Online
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:
- JavaScript object model (JSOM)
- SharePoint Rest API
- SharePoint .NET client object model
Apart from the about popular 3 csom models, below are the two CSOM models that 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 the on-premise SharePoint version, Microsoft provides a 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, you have an ASP.net web application that wants to display data from a SharePoint Online list. What options do you have? We can not use the server object model here. So, Microsoft provides a .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, web, and console applications.

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
Since there will not be SharePoint installed in the system by default, 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.
- Download SharePoint Online client components SDK
- Download SharePoint server 2013 client components SDK
- Download SharePoint server 2016 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

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.

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.

Then click on the Create button.
Then, it will create the console application, and you can see the solution explorer below. Here, we can write the code in the Program.cs file.

Here, the 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.

If you have not installed SharePoint online client sdks, then you can also add the dlls from the 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…

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

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

You can also install the 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 CSOM SharePoint console application, we need to add the username and password to the SharePointOnlineCredentials.
Here, the password will be a secure password; you can pass it like a string.
The 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.
I have added a simple csom sharepoint online example to get the properties of the SharePoint web site. 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:

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 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 on the page.
- Similar to the Managed CSOM, the JS also is built to batch requests to ensure performance.
- Another fundamental difference 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 a 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 is not.
- In CSOM, we use CAML query, while REST uses standard OData vocabularies.
- SharePoint CSOM Supports Batching, which makes fewer service calls between the client and SharePoint.
- But Rest API is easier to debug and troubleshoot. We can see the results by putting the Rest endpoint URL in the browser.
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 runs 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.
- However 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 code below to create a 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:

This is how to create a site collection using CSOM in SharePoint Online.
Create a communication site in SharePoint online using csom
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 is created successfully using CSOM SharePoint Online.

Get all SharePoint Site Collections using CSOM
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();
}
}
}
}

This is how we can get all the site collections from the Office 365 tenant or from SharePoint Online admin center.
Get SharePoint Online site collection created date using CSOM
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();
}
}
}
}

This is how to get the SharePoint Online site collection created date.
Create a 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 an 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 below:

This is how to 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 that 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 a 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.
Delete SharePoint List Programmatically using CSOM
Now, let us see how to delete a SharePoint list programmatically c# (CSOM). In SharePoint Online, we can use only client-side technologies like csom, jsom or Rest API, etc. Here we got one requirement to delete a SharePoint 2013 Online list using csom programmatically.
Delete SharePoint list programmatically C#
We wanted to use the csom c#.net managed object model in SharePoint online. We have created a console application to delete a list using csom. Even if you are working on a SharePoint provider-hosted add-in, you can use the same code for SharePoint 2013 or SharePoint Online.
To work with CSOM (C#.Net managed object model), we have to use the below two DLLs, which can be downloaded from Nuget.
- Microsoft.SharePoint.Client.dll
- Microsoft.SharePoint.Client.Runtime.dll
Since we are trying to connect to a SharePoint online site, we are keeping the credentials in App.config file and retrieving by using the two methods:
- GetSPOAccountName()
- GetSPOSecureStringPassword()
Here we are retrieving the SharePoint list using the GetByTitle method. And we are deleting the list by calling the DeleteObject() method.
Below is the C#.net method to delete the sharepoint list programmatically using c#.
public void DeleteTemporaryList(string URL)
{
using (ClientContext clientContext = new ClientContext(URL))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
List tempList;
try
{
tempList = clientContext.Web.Lists.GetByTitle("MyTempList");
clientContext.Load(tempList);
clientContext.ExecuteQuery();
tempList.DeleteObject();
clientContext.ExecuteQuery();
}
catch (Exception ex)
{
}
}
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings["SPOAccount"];
}
catch
{
throw;
}
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
This is how to delete list programmatically using CSOM C#.Net managed object model code in SharePoint Online or SharePoint 2013/2016/2019.
GetModerationStatus of a document in SharePoint using CSOM
We can retrieve ModerationStatus of a document using .Net managed object model csom code in SharePoint online. The same code also will work to retrieve _moderationstatus SharePoint 2013 and SharePoint 2016.
Here I have a SharePoint Online document library, and I want to retrieve the ModerationStatus for a particular item using the client object model. I am filtering records whose ID is 10.
Moderation Status is a 4-byte integer indicating the moderation approval status of a list item. Configurations can require moderation approval to publish a list item or allow automatic approval. A published list item MUST have a Moderation Status of 0.
The following are all possible valid values for Moderation Status.
Value | Description |
0 | The list item is approved. |
1 | The list item has been denied approval. |
2 | The list item is pending approval. |
3 | The list item is in the draft or checked out state. |
4 | The list item is scheduled for automatic approval at a future date. |
GetModerationStatus of document in SharePoint using CSOM
Below is the full code to retrieve ModerationStatus of a document in a SharePoint Online document library.
public string GetItemApprovalStatus(string URL)
{
string status = string.Empty;
using (ClientContext clientContext = new ClientContext(URL))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(),GetSPOSecureStringPassword());
List oList = clientContext.Web.Lists.GetByTitle("MyTestList");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='ID'/><Value Type = 'Int' > 10 </Value ></Eq></Where></Query></View>";
ListItemCollection collListItem = oList.GetItems(camlQuery);
clientContext.Load(collListItem);
clientContext.ExecuteQuery();
foreach (ListItem oListItem in collListItem)
{
string NodeStatus = oListItem["_ModerationStatus"].ToString();
if (NodeStatus == "0")
{
status = "Approved";
}
else if (NodeStatus == "1")
{
status = "Denied";
}
else if (NodeStatus == "2")
{
status = "Pending";
}
else if (NodeStatus == "3")
{
status = "Draft";
}
else if (NodeStatus == "4")
{
status = "Scheduled";
}
}
}
return status;
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings["SPOAccount"];
}
catch
{
throw;
}
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
I hope this will be helpful in retrieving the ModerationStatus of a document in a SharePoint Online document library.
Activate Workflows can use app permissions Feature programmatically using CSOM in SharePoint
We can activate “Workflows can use app permissions” in SharePoint online site using client object model code (csom). We will use C#.net managed object model code (Microsoft.SharePoint.Client.dll).
“Workflows can use app permissions” is site level feature, and the feature id for this feature is: “ec918931-c874-4033-bd09-4f36b2e31fef”.
You can check out this MSDN article to know more about the feature id for various out-of-the-box features in SharePoint 2013.
Below is the full code to activate workflows. You can use app permissions using csom in SharePoint Online.
public static void ActivateWorkflowFeature(string siteURL)
{
Guid WebFeatureID = Guid.Parse("ec918931-c874-4033-bd09-4f36b2e31fef");
using (ClientContext ctx = new ClientContext(siteURL))
{
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
var web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
var webFeatures = ctx.Web.Features;
ctx.Load(webFeatures);
ctx.ExecuteQuery();
webFeatures.Add(WebFeatureID, true, FeatureDefinitionScope.None);
ctx.ExecuteQuery();
}
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings["SPOAccount"];
}
catch
{
throw;
}
}
Once you run the above code will activate the “Workflows can use app permissions” feature once you run it.
I hope this will be helpful to you to activate workflows can use app permissions in SharePoint Online Office 365.
Bind SharePoint List items in dropdown list programmatically using CSOM
Now, let us see, how to bind SharePoint list items into a dropdown list using the client-side object model (CSOM) in SharePoint Online or SharePoint 2013/2016/2019.
Now, we will see how to bind SharePoint list items to a dropdown list programmatically using csom in SharePoint. Here, we will use an asp.net web application to bind the data to the dropdown list.
We will also see, how we can delete an item from the SharePoint list using csom.
Create a SharePoint list and Bind List items to DropDownList, Next, select an item from the dropdown and click on the delete button. Then, the item from the SharePoint list will be deleted.
Here, bind List items to the Data Table before going to bind items to the Dropdown List.
Now I created a SharePoint list name is MyCompanyEmployeeList as shown below.

For Creating Web Application, Open Visual Studio, Go to ->file->New->Project; it will open New Project Dialogue Box; come to the left side of Templates, expand Installed Templates, Visual C# -> Windows, and then select Asp.Net Web Application like below:
Now add the two required dlls in References to Solution Explorer:
- Microsoft.SharePoint.Client.Runtime.dll
- Microsoft.SharePoint.Client.dll.
Right-click on the Reference folder, click on Add Reference, and then add the dlls from the below folder.
C:\Program Files\Common Files\Microsoft shared\Web Server Extensions\16\ISAPI
Now create a form for that we need to Default.aspx page. Here, copy and paste the below code:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DisplayDataInGridView._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<table class="nav-justified" style="width: 34%; height: 75px">
<tr>
<td>
<asp:Label ID="lblTitle" runat="server" Text="Title"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlTitle" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td> </td>
<td>
<asp:Button ID="btnDelete" runat="server" OnClick="btnDelete_Click" Text="Delete" />
</td>
</tr>
</table>
</asp:Content>
Now go to the Default.aspx.cs page, copy and paste below the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Client;
using System.Security;
using System.Data;
namespace DisplayDataInGridView
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindItemsToDropDownList();
}
}
void BindItemsToDropDownList()
{
using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/DevSite/"))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials("lakshminarayana@onlysharepoint2013.onmicrosoft.com", GetSPOSecureStringPassword());
Web wb = context.Web;
List oList = wb.Lists.GetByTitle("MyCompanyEmployeeList");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query /><ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /></ViewFields><QueryOptions /></View>";
Microsoft.SharePoint.Client.ListItemCollection collListItem = oList.GetItems(camlQuery);
context.Load(collListItem);
context.ExecuteQuery();
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Title", typeof(string));
foreach (Microsoft.SharePoint.Client.ListItem item in collListItem)
{
DataRow dr = dt.NewRow();
dr["ID"] = item["ID"];
dr["Title"] = item["Title"];
dt.Rows.Add(dr);
}
ddlTitle.DataSource = dt;
ddlTitle.DataValueField = "ID";
ddlTitle.DataTextField = "Title";
ddlTitle.DataBind();
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
DeleteListItems();
}
private void DeleteListItems()
{
int itemid = Convert.ToInt32(ddlTitle.SelectedValue);
using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/DevSite/"))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials("lakshminarayana@onlysharepoint2013.onmicrosoft.com", GetSPOSecureStringPassword());
Web wb = context.Web;
List oList = wb.Lists.GetByTitle("MyCompanyEmployeeList");
Microsoft.SharePoint.Client.ListItem listItem = oList.GetItemById(itemid);
listItem.DeleteObject();
context.ExecuteQuery();
}
BindItemsToDropDownList();
}
private SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in "Mypassword")
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
}
}
Here is the Result of the Dropdown List.

Click on Dropdown it will display Titles from the list.
Now select “title=Lakshmi” from the dropdown; the item will be deleted from the drop-down and list.

Now, see the selected “Title=Lakshmi” is deleted from the drop-down.
Now checklist. EmpName(Title) of Lakshmi is deleted from my list.

Here, we checked how to bind SharePoint list items to a dropdown list using client-side object model (csom) in SharePoint Online.
Check if Column Exists or Not in SharePoint List using CSOM
In this SharePoint tutorial, we will discuss how to Check if a Column Exists or Not in SharePoint List using CSOM using the C#.Net client object model.
We will use to develop the demo in a Windows application where we have added the two required client-side dll:
- Micrsoft.SharePoint.Client.dll
- Microsoft.SharePoint.Client.Runtime.dll
We will connect to a SharePoint online site as well as a SharePoint 2016 site.
Check if Column Exists or Not in SharePoint List using CSOM
Here I have a list named as “MyDemoList” in my SharePoint 2016 on-premises site. In that list we will check if a column named as “MyTestColumn” exists or not using the SharePoint 2016 client object model.
The same code will work in SharePoint 2013. Here in the Windows application, we have added a button and the code we wrote on the button click.
Below is the full code:
private void btnOnPremise_Click(object sender, EventArgs e)
{
using (ClientContext context = new ClientContext("http://mypc/sites/MySP2016SiteCollection/"))
{
var list = context.Web.Lists.GetByTitle("MyDemoList");
context.Load(list);
context.Load(list.Fields);
context.ExecuteQuery();
for (int i = 0; i < list.Fields.Count; i++)
{
if (list.Fields[i].Title == "MyTestColumn")
{
label1.Text = "Column Exists";
return;
}
}
}
}
Once you run the code, you can see it will display the column exists like below:

Check If Column exists in SharePoint Online List using (C#.net client object model) CSOM
In the same way, we can also check if the list column exists or not in SharePoint online using csom. Here, we have the same list name as “MyDemoList” presented in SharePoint online. Here also, we will check if a column named “MyTestColumn” is exists or not in the list.
Below is the full code which we wrote on a button click in the Windows application.
private void btnOnline_Click(object sender, EventArgs e)
{
using (ClientContext clientContext = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials("bijay@onlysharepoint2013.onmicrosoft.com", GetSPOSecureStringPassword());
List list = clientContext.Web.Lists.GetByTitle("MyDemoList");
clientContext.Load(list);
clientContext.Load(list.Fields);
clientContext.ExecuteQuery();
for (int i = 0; i < list.Fields.Count; i++)
{
if (list.Fields[i].Title == "MyTestColumn")
{
label1.Text = "Column Exists";
return;
}
}
}
}
private SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in "*********")
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
Once you run the above code, you can see the column exists like below:

Here, we learn how to Check if a Column Exists or Not in SharePoint List using CSOM.
Unable to read data from the transport connection: an existing connection was forcibly closed by the remote host
Let us see, how to fix the below issue, which usually comes when we do some bulk operation in SharePoint Online. Recently we were doing some bulk operations from a console application to a SharePoint Online site using .Net client object model code. The error comes as: unable to read data from the transport connection: an existing connection was forcibly closed by the remote host.
We were working in a console application. But we were getting the below error:
An exception of type ‘System.IO.IOException’ occurred in Microsoft.SharePoint.Client.Runtime.dll but was not handled in user code.
Additional information: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Unable to read data from the transport connection
In SharePoint online, we were trying to upload multiple files to a SharePoint document library. We were trying to upload files inside a single button click, but then we divided and uploaded into multiple button clicks. Then it worked correctly.
I hope this will be helpful in resolving unable to read data from the transport connection: an existing connection was forcibly closed by the remote host.
Microsoft.sharepoint.client.serverexception: list does not exist
We will see how to resolve the SharePoint List does not exist at the site with the URL <SiteURL> error while working with SharePoint client object model to insert an item to the SharePoint list.
Recently I was trying to insert an item from an asp.net application to the SharePoint online list using C#.net but I got an error as “Microsoft.SharePoint.Client.ServerException:”List ‘EmployeeInformation ‘ does not exist at site with URL “Site URL”. The error looks like below:

Microsoft.sharepoint.client.serverexception: list does not exist
In my case, there is a list presented in the SharePoint Online site with a name as “EmployeeInformation,” but still it was given the error. Then I realized I had added one extra space in the code after the list name like “EmployeeInformation “, So to resolve the issue I had to remove the space from the list name.
I hope this helps to solve issue Microsoft.sharepoint.client.serverexception: list does not exist Error in SharePoint Online CSOM.
Get content type name by id programmatically using csom in SharePoint
This SharePoint tutorial explains how to get content type name by id programmatically using csom (client-side object model) in SharePoint Online/2013/2016.
A content type SharePoint 2013 is a reusable collection of metadata (columns), workflow, behavior, and other settings for a category of items or documents in a SharePoint 2013 list or document library. We can retrieve content type name by content type id using csom SharePoint online.
We will use here the C#.Net client object model code using the below dlls inside a console application.
- Microsoft.SharePoint.Client.dll
- Microsoft.SharePoint.Client.RunTime.dll
Below is the code to get content type name by id csom in SharePoint Online.
Here in this example, I have used the “Workflow Task (SharePoint 2013)” whose Id is “0x0108003365C4474CAE8C42BCE396314E88E51F”.
Once I run the code below, it will give me the content type name.
public static void GetContentTypeByID()
{
string contentTypeName = string.Empty;
using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
ContentType ct = context.Web.ContentTypes.GetById("0x0108003365C4474CAE8C42BCE396314E88E51F");
context.Load(ct);
context.ExecuteQuery();
contentTypeName = ct.Name;
}
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings["SPOAccount"];
}
catch
{
throw;
}
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
You can see the result like below:

I hope this will be helpful to get the content type name by id programmatically using csom in SharePoint Online/2016/2013.
Retrieve List Content types using CSOM SharePoint
Now, we will see how to get list content types using the C#.Net client object model (CSOM) in SharePoint Online/2016/2013.
We can retrieve content types associated with the SharePoint online list using client object model code (csom) in SharePoint Online. We will use here .Net managed object model code where we will use the below dlls.
- Microsoft.SharePoint.Client.dll
- Microsoft.SharePoint.Client.RunTime.dll
Here, we connect to a SharePoint online site from a console application in Visual Studio 2015/2017/2019.
First, we can retrieve the list using GetByTitle method, and then we can retrieve all the content types by using the code below:
ContentTypeCollection contentTypeColl = lst.ContentTypes;
Below is the full code to retrieve list content types programmatically using CSOM in SharePoint Online/2016/2013.
public static void RetrieveListContentType()
{
string contentTypes = string.Empty;
using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
List lst = context.Web.Lists.GetByTitle("MyTestList");
ContentTypeCollection contentTypeColl = lst.ContentTypes;
context.Load(contentTypeColl);
context.ExecuteQuery();
foreach (ContentType ct in contentTypeColl)
{
contentTypes += ct.Name;
}
}
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings["SPOAccount"];
}
catch
{
throw;
}
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
Delete content type from SharePoint list programmatically using CSOM
Now, we will see how to delete a content type attached to a list using csom in SharePoint online/2013/2016.
Here we will use C#.Net managed object model code where we will use below dlls:
- Microsoft.SharePoint.Client.Dll
- Microsoft.SharePoint.Client.Runtime.Dll
Here, I have a list named as “MyTestList”, which is a custom list; in that list, I have added the default Announcement content type.
By using csom code, I am trying to retrieve the content type by its id, and then I am deleting the object by calling DeleteObject() method.
Below is the full code to delete the content type from the SharePoint Online list using csom programmatically.
public static void DeleteContentType()
{
using (ClientContext contextURL = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
contextURL.AuthenticationMode = ClientAuthenticationMode.Default;
contextURL.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
List lst = contextURL.Web.Lists.GetByTitle("MyTestList");
ContentType ct = lst.ContentTypes.GetById("0x010400BE88F9D0169DC14194092368A99093F1");
ct.DeleteObject();
contextURL.ExecuteQuery();
}
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings["SPOAccount"];
}
catch
{
throw;
}
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
This is how we can programmatically delete a content type from the SharePoint list using client object model (CSOM) in SharePoint.
Get SharePoint content type id by name programmatically using CSOM
Let us see, how to get content type id by name programmatically using csom in SharePoint Online.
As per one of the requirements, we need to retrieve content type id by content type name using the client object model (csom) in SharePoint online.
We have used C#.net managed object model code by using Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll.
The below method will take two parameters: URL and contentTypeName. Here, URL is the site URL, and contentTypeName is the content type name for which we are trying to retrieve the content type id.
We are doing this in a console application and connecting to a SharePoint online site.
Below is the full code to programmatically get content type id by name using csom in SharePoint.
public static string GetContentTypeIdByName(string URL, string contentTypeName)
{
string contentTypeId = string.Empty;
using (ClientContext clientContext = new ClientContext(URL))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
Web rootWeb = clientContext.Site.RootWeb;
var itemContentType = clientContext.LoadQuery(rootWeb.ContentTypes.Where(ct => ct.Name == contentTypeName));
clientContext.ExecuteQuery();
var sessionContentType = itemContentType.FirstOrDefault();
contentTypeId = sessionContentType.Id.ToString();
}
return contentTypeId;
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings["SPOAccount"];
}
catch
{
throw;
}
}
This way, we can get content type id by content type name using csom in SharePoint Online or SharePoint 2013/2016/2019.
Retrieve list item content type name or id using CSOM in SharePoint Online
Now, we will see how to get content type name or id using csom (.Net client object model) in SharePoint Online.
Once a content type is associated to a SharePoint list, we can retrieve list item’s associated content type name or id using .Net managed object model code in SharePoint online.
We have a list that has a content type associated with it. And we have created a few items using those content types in the list. We have one requirement to check the content type of a particular list item. Suppose I have one item as “Item-1”, we need to retrieve the content type name associated with the list item.
The below method will take the ItemID as an input parameter and return the content type name which we have written inside a console application using Visual Studio.
First, we retrieve the list item by Id, and then we get the content type associated with the item from the item ContentType;
Below is the code to retrieve list item content type name or id using CSOM in SharePoint Online.
public static string GetContentTypeNameForItem(int ItemID)
{
string contentTypeName = string.Empty;
using (ClientContext contextURL = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
contextURL.AuthenticationMode = ClientAuthenticationMode.Default;
contextURL.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
List lst = contextURL.Web.Lists.GetByTitle("MyTestList");
ListItem item = lst.GetItemById(ItemID);
contextURL.Load(item);
contextURL.Load(lst);
contextURL.ExecuteQuery();
ContentType ct = item.ContentType;
contextURL.Load(ct, n => n.Name);
contextURL.ExecuteQuery();
if (ct != null)
{
contentTypeName = ct.Name;
}
}
return contentTypeName;
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["SPOPassword"])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings["SPOAccount"];
}
catch
{
throw;
}
}
We can retrieve list item content type name or id using CSOM in .Net client object model in SharePoint Online.
SharePoint Online copy list items to another list programmatically (C#.net)
In this particular example, we will do this inside a console application, and we will try to connect to the SharePoint Online site.
To work with .Net managed object model code, we need to add below two dlls:
- Microsoft.SharePoint.Client.dll
- Microsoft.SharePoint.Client.Runtime.dll
Copy SharePoint list items to another list
Here I have a list named as SourceList, which has 3 columns like the below:
- Title (Single line text)
- EmailID (Single line text)
- Address (Multiple line text)
It has a few items, and the list looks like below:

Here, we will move these items to another list in the same site, which has the same column names.
Below is the code to copy SharePoint list items to another list programmatically using C#.Net.
public static void CopyItemsFromOneListToAnotherList()
{
using (ClientContext ctx = new ClientContext(“https://onlysharepoint2013.sharepoint.com/sites/Bhawana/”))
{
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
ctx.Load(ctx.Web);
ctx.ExecuteQuery();
List sourceList= ctx.Web.Lists.GetByTitle(“SourceList”);
ctx.Load(sourceList);
ctx.ExecuteQuery();
List destList = ctx.Web.Lists.GetByTitle(“DestinationList”);
ctx.Load(sourceList);
ctx.ExecuteQuery();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = “<View/>”;
ListItemCollection listItems = sourceList.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
foreach (ListItem item in listItems)
{
ListItemCreationInformation newItemInfo = new ListItemCreationInformation();
ListItem newItem = destList.AddItem(newItemInfo);
newItem[“Title”] = item[“Title”];
newItem[“EmailID”] = item[“EmailID”];
newItem[“Address”] = item[“Address”];
newItem.Update();
}
ctx.ExecuteQuery();
}
}
private static string GetSPOAccountName()
{
try
{
return ConfigurationManager.AppSettings[“SPOAccount”];
}
catch
{
throw;
}
}
private static SecureString GetSPOSecureStringPassword()
{
try
{
var secureString = new SecureString();
foreach (char c in ConfigurationManager.AppSettings[“SPOPassword”])
{
secureString.AppendChar(c);
}
return secureString;
}
catch
{
throw;
}
}
Once you run the above code, it will copy the items like below:

In this SharePoint tutorial, we learn everything about CSOM SharePoint Online and how to use CSOM in SharePoint Online to do various operations.
You may like the following tutorials:
- CAML Query Builder SharePoint Online
- PnP CSOM SharePoint Examples
- Delete all items from a SharePoint Online
I am Bijay a Microsoft MVP (8 times – My MVP Profile) in SharePoint and have more than 15 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com
Thanks Bijay. It was very helpful
A Great step-by-step tutorial. Thanks!
But I am getting a problem: Whenever I try to connect, I receive an error 400 from the server:
System.Net.WebException: ‘The remote server returned an error: (400) Bad Request.’
This exception was originally thrown at this call stack:
System.Net.HttpWebRequest.GetResponse()
Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute()
Microsoft.SharePoint.Client.ClientContext.GetFormDigestInfoPrivate()
Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()
Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
CSOM_SharePoint.Program.Main(string[]) in Program.cs
Any idea on how to solve this?
Thank you in advance
I just found out where I got it wrong: I created the project using .NET Core instead of .NET Framework. Once I created a new solution using .NET Framework, it worked correclty.