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
  • Delete SharePoint List Programmatically
  • GetModerationStatus of 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

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.

Delete SharePoint List Programmatically using CSOM

This SharePoint tutorial explains, how to delete 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 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 SharePoint provider-hosted add-in, you can also 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 also.

  • 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 below 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 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 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 record 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.

ValueDescription
0The list item is approved.
1The list item has been denied approval.
2The list item is pending approval.
3The list item is in the draft or checked out state.
4The 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 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 to retrieve 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 for know more about the feature id for various out of box features in SharePoint 2013.

Below is the full code to activate workflows 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, it will activate the “Workflows can use app permissions” feature.

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 we can 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 and Next select item from the dropdown and click on 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.

Bind SharePoint List items in dropdown list programmatically
Bind SharePoint List items in dropdown list programmatically

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 and then 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 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>&nbsp;</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.

Delete Items from sharepoint list using CSOM
Delete Items from sharepoint list using CSOM

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.

Delete Items from list using CSOM
Delete Items from list using CSOM

Now see the selected “Title=Lakshmi” is deleted from the drop-down.

Now checklist. EmpName(Title) of Lakshmi is deleted from my list.

Bind SharePoint List items in dropdown list programmatically using CSOM
Bind SharePoint List items in dropdown list programmatically using CSOM

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 name as “MyDemoList” in my SharePoint 2016on-premisee site. In that list we will check if a column name as “MyTestColumn” exists or not using 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:

SharePoint 2016 csom check if column exists in list
SharePoint 2016 csom check if column exists in list

Check If Column exists in SharePoint Online List using (C#.net client object model) CSOM

The same way we can also check if 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 column name as “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:

SharePoint online csom check if column exists in list
SharePoint online csom check if column exists in list

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 operation 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
Unable to read data from the transport connection

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 have divided and uploaded into multiple button clicks. Then it worked correctly.

I hope this will be helpful to resolve 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 SharePoint List does not exist at site with 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 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:

SharePoint List does not exist at site with URL
SharePoint List does not exist at site with URL

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 realize I have 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.

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
  • Delete SharePoint List Programmatically using CSOM
  • 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
  • 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.

  • >