SharePoint CSOM (45 SharePoint client object model examples)

If you want to become a SharePoint developer, then you should have a good understanding of SharePoint CSOM, the client object model in sharepoint 2013 (csom sharepoint).

We will try to understand on SharePoint client object model (CSOM), what are various SharePoint client object model techniques available. How to work with the client object model in SharePoint Online/2013/2016? We will also see more than 25+ examples in the SharePoint client object model.

Apart from SharePoint CSOM examples, we will discuss on CRUD operations in CSOM.

Here, we will focus purely on the SharePoint .Net client object model. The same .Net managed object model code will work in almost the same in SharePoint 2010/2013/2016 and SharePoint Online.

client object model in sharepoint 2013
csom sharepoint

Table of Contents

What is SharePoint CSOM (client object model)?

SharePoint client object model (CSOM SharePoint) provides lots of APIs to retrieve, update, and manage data in SharePoint. There are limitations to what can be done client-side compared to server-side, say for example:

  • You cannot access the FARM level properties, you can get/set only the properties at the web application level.
  • We cannot elevate the privilege in COM as we can do in the server object model.
  • No SharePoint installation is required in the development machine. Only the Client DLL’s are required.
  • No Compilation required as required on the server-side, NO IISRESET required.

Different types of SharePoint client object model

There are 4 types of SharePoint client object model available to work with SharePoint 2013/2016/2010 or SharePoint Online.

.Net client object model (C#.Net)

The Managed object model can be used to create .NET applications that run on Windows operating systems that aren’t phones or SharePoint servers. The managed client object model dlls are found inside the ISAPI folder ( %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\ISAPI).

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

JavaScript client object model

JavaScript client object model does not contain any dlls, rather it contains .js files. These .js files are located inside the LAYOUTS folder and mainly functionality exists inside SP.js and SP.Core.js. The JavaScript object model can be used in an inline script or in separate .js files.

Rest API

In SharePoint 2013 now you can interact remotely with SharePoint sites using REST API. You will be able to interact by using any technology that supports REST web requests.

You need to construct a RESTful HTTP request, using the Open Data Protocol (OData) standard. You may like SharePoint Rest API examples:

Silverlight client object model

By using the Silverlight object model, you can build Silverlight applications, Web Parts, Asp.Net applications, apps for SharePoint and Office, and Silverlight applications for phones that use SharePoint data or SharePoint objects.

The Silverlight client object model dlls are presented inside %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS\ClientBin folder.

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

Windows Phone client object model

The Mobile object model can be used to create applications that run on Windows Phones. The Mobile client-side object model contains some functionality that is specific to phones, such as APIs that enable a phone app to register for notifications from the Microsoft Push Notification Service.

The required dlls are found inside %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS\ClientBin folder. The dlls are:

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

Microsoft.sharepoint.dll and SharePoint 2013 client dll location

This SharePoint tutorial explains the location of SharePoint dlls. We will see microsoft.sharepoint.dll location 2013, sharepoint 2013 client dll location and SharePoint 2013 search dll, etc.

microsoft.sharepoint.dll location SharePoint 2013/2016:

Below is the microsoft.sharepoint.dll location in SharePoint 2013/2016.

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI (SharePoint 2016)

or

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\13\ISAPI (SharePoint 2013)

SharePoint 2013 client dll location

We will use two dlls for SharePoint C#.Net development.

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

Below is the SharePoint 2013 client dll location.

E:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI

Search API and their location in SharePoint 2013

SharePoint 2013 provides some API to work with search functionality in custom solutions and applications.

Through these APIs, you can query search results in different ways. Search in SharePoint 2013 provides:

  • Client object model (CSOM)
  • JavaScript object model (JSOM)
  • Representational State Transfer (REST) service

Search API and their location in SharePoint 2013

Below are Search APIs and the path:

.NET CSOM SharePoint

Microsoft.SharePoint.Client.Search.dll
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\ISAPI

Silverlight CSOM SharePoint

Microsoft.SharePoint.Client.Search.Silverlight.dll
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS\ClientBin

JavaScript CSOM SharePoint

SP.search.js
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS

SharePoint REST service endpoints
http://server/_api/search/query
http://server/_api/search/suggest

SharePoint Server object model
Microsoft.Office.Server.Search.dll
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\ISAPI

How SharePoint CSOM works

Let us see how SharePoint CSOM works. When you will use SharePoint client-side APIs to perform certain tasks by calling methods, then the .Net client object model bundles those things to XML and then send them to the server when the ExecuteQuery method is called.

Create a console application to use CSOM SharePoint

If you want to use CSOM SharePoint 2013 or CSOM SharePoint Online, first create a console application, windows form application or an asp.net application using visual studio.

Once you create the application, then you can add the below DLLs from NuGet.

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

Or, if you have installed SharePoint client components SDKs, then you can give references from the following path:

%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS\ClientBin

Once your application is ready, you can write the below code that will give the SharePoint site title and description using SharePoint .Net client object model (CSOM SharePoint).

void GetWebTitle()
{
ClientContext context = new ClientContext(“http://[Site URL]”);
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
string webTitle = web.Title;
string webDescription = web.Description;
}

You may like SharePoint Online console application with csom.

CRUD Operations with SharePoint CSOM

Let us see first a CRUD operations with SharePoint CSOM. Here we will see how to use client object model in SharePoint 2013 with a CRUD operation.

Insert item to SharePoint List

We can easily insert item to SharePoint list using .Net client object model in SharePoint 2013/2016/2010.

Here I have a custom SharePoint list having 3 columns as: Title, Description & TaskStatus.

ClientContext context = new ClientContext(“http://bsahoo3:2500/sites/MyTest/”);
List list = context.Web.Lists.GetByTitle(“MyCustomList”);

ListItemCreationInformation newItem = new ListItemCreationInformation();
Microsoft.SharePoint.Client.ListItem listItem = list.AddItem(newItem);
listItem[“Title”] = “New Item Added”;
listItem[“Description”] = “New Item Description”;
listItem[“TaskStatus”] = “False”;
listItem.Update();
context.ExecuteQuery();

Update SharePoint list items using CSOM

Now, we will see how we can update all list items using SharePoint .Net client object model code in SharePoint.

ClientContext context = new ClientContext("http://bsahoo3:2500/sites/MyTest/");
List list = context.Web.Lists.GetByTitle("MyCustomList");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query);

context.Load(list);
context.Load(items);
context.ExecuteQuery();

foreach (Microsoft.SharePoint.Client.ListItem item in items)
{
item["Title"] = item["Title"] + " Modified";
item.Update();
}
context.ExecuteQuery();

The above code will update each SharePoint list item and will add Modified with the existing title.

Delete SharePoint List item

Now, we will discuss how we can delete a list item programmatically using the SharePoint client object model. The below CSOM SharePoint code will delete an item whose title is “New Task”.

ClientContext context = new ClientContext(“http://bsahoo3:2500/sites/MyTest/”);
List list = context.Web.Lists.GetByTitle(“MyCustomList”);
CamlQuery query = new CamlQuery();
query.ViewXml = “<View/>”;
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query);

context.Load(list);
context.Load(items);
context.ExecuteQuery();

foreach (Microsoft.SharePoint.Client.ListItem item in items)
{
if (item[“Title”].ToString() == "New Task")
item.DeleteObject();
break;
}

Here, we saw how to use client object model in SharePoint.

43 SharePoint CSOM Examples

Here are a few examples of SharePoint csom (.Net client object model) examples.

1. Create SharePoint list programmatically using .Net Client object model (CSOM)

Let us see how to create a SharePoint list programmatically using .Net client object model (CSOM SharePoint) in SharePoint 2010/2013/2016. The below code will create an announcement list in SharePoint using csom.

Here I have used the Announcements list template, you can also use other list template ids.

using (ClientContext context = new ClientContext(“http://bsahoo3:8787/sites/Training”))
{
//Create a new list
ListCreationInformation listCreationInformation = new ListCreationInformation();
listCreationInformation.Title = "My Announcements List";
listCreationInformation.Description += "Here is my list created by client object midel";
listCreationInformation.TemplateType = (int)ListTemplateType.Announcements;
listCreationInformation.QuickLaunchOption = Microsoft.SharePoint.Client.QuickLaunchOptions.On;
List list = context.Web.Lists.Add(listCreationInformation);
context.ExecuteQuery();
}

Once you execute the csom SharePoint 2013 code, it will create a list name as “My Announcements List”.

2. Create a custom list and add an item to a custom list programmatically using the SharePoint client object model

We can create list and add item to a SharePoint 2013 list using managed client object model.

string webUrl =”http://WebURL”;
using (ClientContext ctx = new ClientContext(webUrl))
{
//Below is the code to create a list
ListCreationInformation listInfo = new ListCreationInformation();
listInfo.Title = “My Test List”;
listInfo.Description += “This is a test description for a test list.”;
listInfo.TemplateType = (int)ListTemplateType.GenericList;
listInfo.QuickLaunchOption = Microsoft.SharePoint.Client.QuickLaunchOptions.On;
List list = ctx.Web.Lists.Add(listInfo);
ctx.ExecuteQuery();

//Below is the code to add an item to the list:

ListItemCreationInformation newlistitem = new ListItemCreationInformation();
ListItem item = list.AddItem(newlistitem);
item[“Title”] = “New Test Item”;
item.Update();
ctx.ExecuteQuery();
}

3. Update SharePoint list programmatically using CSOM

Now, we will see how we can update list title and description using SharePoint .Net managed client object model (CSOM).

ClientContext context = new ClientContext(“http://WebSiteUrl”);
Web web = context.Web;
List myList = web.Lists.GetByTitle("My New List");
myList.Title = "My New List Modified";
myList.Description="This is modified list description!";
list.Update();
context.ExecuteQuery();

Once you execute the SharePoint client side object model code, the list title will be changed from My New List to My New List Modified.

See also  How to Customize SharePoint Modern list form using JSON

4. Delete SharePoint list programmatically using CSOM

Below is the SharePoint client object model code to delete SharePoint list programmatically using CSOM.

ClientContext context = new ClientContext(“http://WebSiteUrl”);
Web web = context.Web;
List list = web.Lists.GetByTitle("My New List");
list.DeleteObject();
context.ExecuteQuery();

This csom sharepoint 2013 example helps to delete the SharePoint list programmatically from the SharePoint site.

5. Get SharePoint List Title using .Net Client object model (CSOM)

Now, we will see how to get the list title using CSOM SharePoint in SharePoint 2010/2013/2016.

ClientContext context = new ClientContext(“http://bsahoo3:2500/sites/MyTest/”);
List list = context.Web.Lists.GetByTitle(“MyCustomList”);
context.Load(list);
context.ExecuteQuery();
Label1.Text = list.Title;

6. Get SharePoint list items and display in Gridview using CSOM

Now we will see how we can get list items and display in a gridview using the SharePoint .Net client object model in SharePoint 2010/2013/2016.

ClientContext context = new ClientContext(“http://bsahoo3:2500/sites/MyTest/”);
List list = context.Web.Lists.GetByTitle(“MyCustomList”);
CamlQuery query = new CamlQuery();
query.ViewXml = “<View/>”;
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query);
context.Load(list);
context.Load(items);
context.ExecuteQuery();
DataTable table = new DataTable();
table.Columns.Add(“Id”);
table.Columns.Add(“Title”);
foreach (Microsoft.SharePoint.Client.ListItem item in items)
table.Rows.Add(item.Id, item[“Title”]);
GridView1.DataSource = table;
GridView1.DataBind();

The above csom sharepoint 2013 code will read all list items and will show the list data in a gridview.

7. Check if list exists SharePoint 2013 c# csom

Let us see how to check if list exists SharePoint 2013 c# csom.

In CSOM SharePoint, there is no direct method that will return whether the list is presented or not. If the list does not exist then when we run the context.ExecuteQuery(); it will go to the exception block and it will return a message like below:

List ‘MyListName’ does not exist at site with URL ‘https://onlysharepoint2013.sharepoint.com/sites/Bhawana’.

So from the exception, we have to catch that the list does not exist. Full code is like below:

private void btnClick_Click(object sender, EventArgs e)
{
bool isListExists = IsListExist();
}

private bool IsListExist()
{
bool isExists = false;
using (ClientContext context = new ClientContext(“https://onlysharepoint2013.sharepoint.com/sites/Bhawana/”))
{
string username = "********@onlysharepoint2013.onmicrosoft.com";
context.AuthenticationMode = ClientAuthenticationMode.Default;
var secureString = new SecureString();
foreach (char c in “********”)
{
secureString.AppendChar(c);
}
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(username, secureString);
try
{
List lst = context.Web.Lists.GetByTitle("MyListName");
context.Load(lst);
context.ExecuteQuery();
if (lst != null)
{
if (lst.ItemCount >= 0)
{
isExists = true;
}
}
}

catch (Exception ex)
{
isExists = false;
}
}
return isExists;
}

This way, we can check if list exists SharePoint 2013 c#.

8. Get column names of SharePoint list using CSOM

Learn how to get column names of a SharePoint list using the SharePoint client object model. The code will work in SharePoint 2010/2013/2016.

ClientContext context = new ClientContext(“http://URL of the Site”);
Web web = context.Web;
List list = site.Lists.GetByTitle(“ListName”);
context.Load(list);
context.ExecuteQuery();
FieldCollection fieldCollection = list.Fields;
context.Load(fieldCollection);
context.ExecuteQuery();
foreach (Field field in fieldCollection)
{
Console.WriteLine(“Name: ” + field.InternalName.ToString());
}
Console.ReadLine();

The above csom code will display all columns from SharePoint list.

9. Update web part Title using SharePoint Client object model

Below is the SharePoint CSOM code to update web part title using the SharePoint client object model (csom).

ClientContext ctx = new ClientContext(“http://URL of the site”);
Web oWeb = ctx.Web;
File file = oWeb.GetFileByServerRelativeUrl(“/default.aspx”);
LimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
ctx.Load(limitedWebPartManager.WebParts,wps => wps.Include(wp => wp.WebPart.Title));
ctx.ExecuteQuery();
if (limitedWebPartManager.WebParts.Count > 0)
WebPartDefinition oWebPartDef = limitedWebPartManager.WebParts[0];
oWebPartDef.WebPart.Title = “New webpar Title”;
oWebPartDef.SaveWebPartChanges();
ctx.ExecuteQuery();
}

10. Delete a SharePoint online list using CSOM SharePoint

We will see how to delete a SharePoint online list using the csom c#.net managed object model in SharePoint online. We are going to do this inside a console application.

Here we are retrieving the SharePoint list using the GetByTitle method. And we are deleting the list by calling the DeleteObject() method.

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 csom sharepoint online helps you to delete a list using the client object model in SharePoint.

11. Check if current site is root site using .net managed object model code csom in SharePoint online

Now we will discuss how we can check if the current site is a root site using .Net managed client object model code in SharePoint online. Here I have a site URL and I want to check if the site is a root site using csom (.net managed object model code).

Below is the full code to get the result. Here we are retrieving the credentials by using GetSPOAccountName(),

GetSPOSecureStringPassword() to connect to SharePoint online site which has been explained in the console application.

public static string CheckRootweb()
{
var isRootWeb = false;

using (ClientContext context = new ClientContext(“https://onlysharepoint2013.sharepoint.com/sites/Bhawana/subsite1”))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
context.Load(context.Site.RootWeb, rw => rw.Id);
context.Load(context.Web, w => w.Id);
context.ExecuteQuery();
isRootWeb = (context.Site.RootWeb.Id == context.Web.Id) ? true : false;
}

return isRootWeb.ToString();

If you will run the code, you can see the isRootWeb value like below:

SharePoint .Net Client Object Model Examples
SharePoint .Net Client Object Model Examples

12. SharePoint online csom create list, list item and add columns

In this microsoft.sharepoint online.csom examples, we will see how to use SharePoint Online CSOM to create a list, add columns to the SharePoint list. And also we will see how to create a list item in sharepoint online csom.

Below is the full code to create a custom list using client object model in SharePoint Online:

using System;
using Microsoft.SharePoint.Client;
class Program
{
static void Main()
{
ClientContext clientContext =new ClientContext(“http://intranet.contoso.com”);
Web site = clientContext.Web;
// Create a list.

ListCreationInformation listCreationInfo =new ListCreationInformation();
listCreationInfo.Title = “Client API Test List”;
listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;
List list = site.Lists.Add(listCreationInfo);

// Add fields to the list.
Field field1 = list.Fields.AddFieldAsXml(
@”<Field Type=’Choice’
DisplayName=’Category’
Format=’Dropdown’>
<Default>Specification</Default>
<CHOICES>
<CHOICE>Specification</CHOICE>
<CHOICE>Development</CHOICE>
<CHOICE>Test</CHOICE>
<CHOICE>Documentation</CHOICE>
</CHOICES>
</Field>”,true, AddFieldOptions.DefaultValue);

Field field2 = list.Fields.AddFieldAsXml(
@”<Field Type=’Number’ DisplayName=’Estimate’/>”,true, AddFieldOptions.DefaultValue);

// Add some data.

ListItemCreationInformation itemCreateInfo =new ListItemCreationInformation();
ListItem listItem = list.AddItem(itemCreateInfo);
listItem[“Title”] = “Write specs for user interface.”;
listItem[“Category”] = “Specification”;
listItem[“Estimate”] = “20”;
listItem.Update();
listItem = list.AddItem(itemCreateInfo);
listItem[“Title”] = “Develop proof-of-concept.”;
listItem[“Category”] = “Development”;
listItem[“Estimate”] = “42”;
listItem.Update();
listItem = list.AddItem(itemCreateInfo);
listItem[“Title”] = “Write test plan for user interface.”;
listItem[“Category”] = “Test”;
listItem[“Estimate”] = “16”;
listItem.Update();
listItem = list.AddItem(itemCreateInfo);
listItem[“Title”] = “Validate SharePoint interaction.”;
listItem[“Category”] = “Test”;
listItem[“Estimate”] = “18”;
listItem.Update();
listItem = list.AddItem(itemCreateInfo);
listItem[“Title”] = “Develop user interface.”;
listItem[“Category”] = “Development”;
listItem[“Estimate”] = “18”;
listItem.Update();
clientContext.ExecuteQuery();
}
}

13. Follow or UnFollow people by using SharePoint client object model

Now in this SharePoint client object model tutorial, we will discuss how we can follow or unfollow people by using the SharePoint 2013 client object model. Programmatically we can follow or unfollow people in SharePoint 2013/2016.

Remember the logged in user should have Full Control permission to the user profile service application. Here we will use SocialFollowingManager class.

ClientContext clientContext = new ClientContext(“http://ServerURL”);
SocialFollowingManager followingManager = new SocialFollowingManager(clientContext);
SocialActorInfo actorInfo = new SocialActorInfo();
actorInfo.AccountName = “domain\\username”;
ClientResult<bool> isFollowed = followingManager.IsFollowed(actorInfo);
clientContext.ExecuteQuery();
if (isFollowed == true)
{
//If the user already following you can stop following by calling the StopFollowing() method.
followingManager.StopFollowing(actorInfo);
clientContext.ExecuteQuery();
}
else
{
//If the user is not follwing then you can follow by using the Follow() method.
followingManager.Follow(actorInfo);
clientContext.ExecuteQuery();
}

14. Query Search with SharePoint 2013/2016 Client Object Model

Now, will discuss how to query search with SharePoint 2013 client object model.

To work with SharePoint 2013 Search Client Object Model, we need to add below assemblies which are located inside ISAPI folder of the 15 hive directory.

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

Then in the code write the corresponding using statements:

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Search;
using Microsoft.SharePoint.Client.Search.Query;

using (ClientContext clientContext = new ClientContext(“http://ServerName”))
{
KeywordQuery keywordQuery = new KeywordQuery(clientContext);
keywordQuery.QueryText = “SharePoint 2013”;
SearchExecutor searchExecutor = new SearchExecutor(clientContext);
ClientResult<ResultTableCollection> results = searchExecutor.ExecuteQuery(keywordQuery);
clientContext.ExecuteQuery();
}

After that you can iterate through the ResultTableCollection like below:

foreach (var resultRow in results.Value[0].ResultRows)
{
string Title = resultRow[“Title”];
string Path = resultRow[“Path”];
}

15. Get followers by using SharePoint 2013 .Net client object model

In this SharePoint csom example, we will discuss how to get followers as well as followed by people by using.Net client object model in SharePoint 2013/2016.

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social;
ClientContext clientContext = new ClientContext(“http://URL”);
SocialFollowingManager followingManager = new SocialFollowingManager(clientContext);
SocialActorInfo actorInfo = new SocialActorInfo();
actorInfo.AccountName = “domain\\username”;
//By using the GetFollowed method you can get the people who the current user is following.
ClientResult<SocialActor[]> followedResult = followingManager.GetFollowed(SocialActorTypes.Users);
//By using the GetFollowers() method you can get the people who are following the current user.
ClientResult<SocialActor[]> followersResult = followingManager.GetFollowers();
clientContext.ExecuteQuery();
Once you get the resultset you can iterate like below:
foreach (SocialActor actor in followedResult)
{
string name = actor.Name;
string imageURL = actor.ImageUri;
}

16. Get SharePoint column display name and internal name using SharePoint client object model

This SharePoint client object model example explains, how to get display and internal name for columns or fields in SharePoint using the SharePoint client object model

Below is the SharePoint client object model code to get SharePoint column display name and internal name using the SharePoint client object model.

string url = "http://SiteURL";
ClientContext context = new ClientContext(url);
Web web = context.Web;
var list = web.Lists.GetByTitle("Announcements");
context.Load(list.Fields);
context.ExecuteQuery();
string title = string.Empty;
string internalName = = string.Empty;
foreach (Field f in list.Fields)
{
title += field.Title + " ";
internalName += field.InternalName + " ";
}

17. Get selected properties of website using CSOM SharePoint

This SharePoint client object model example explains, how to retrieve selected properties of a website using the SharePoint 2013 object model.

If you follow this article to retrieve the website title using SharePoint 2013 object model, then here context.Load(web); will load all the properties of the website.

But suppose we need only two properties like Title and Description then it is unnecessary to bring all the properties from the server to the client. So client object model provides anonymous methods which use lambda expressions, to specifically request property names.

The client library will query only for those properties on the server, and the server will send only those properties to the client. This technique reduces unnecessary data transfer between the client and the server.

Below is the full code:

To work with SharePoint 2013 client object model, we need to give reference to the below dlls:

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

These dlls are located in %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\ISAPI.

Below is the full code to retrieve the title of a SharePoint site using client object model code.

using Microsoft.SharePoint.Client;

ClientContext context = new ClientContext("http://URL of the Site");
Web web = context.Web;
context.Load(web, w => w.Title, w => w.Description);
context.ExecuteQuery();
string Title = web.Title;
string Description = = web. Description;

18. Add a user to a SharePoint group using CSOM SharePoint

In this SharePoint client object model example, we will discuss how to add a user to a SharePoint group using the SharePoint 2013 client object model.

ClientContext context = new ClientContext(“http://SiteURL”);
GroupCollection siteGroups = context.Web.SiteGroups;
// Here it will retrieve the group whose ID=1
Group myGroup = siteGroups.GetById(1);
UserCreationInformation userInfo = new UserCreationInformation();
userInfo.Email = “[email protected]”;
userInfo.LoginName = “enjoysharepoint\\User1”;
userInfo.Title = “Admin EnjoySharePoint”;
User newUser = membersGroup.Users.Add(userInfo);
context.ExecuteQuery();

Once you execute the csom sharepoint code, it will add the above user to the SharePoint group (myGroup) using the SharePoint client object model code.

19. Get all users from sharepoint group programmatically csom

In this csom sharepoint 2013 example we will see how to get all the users from SharePoint group using CSOM SharePoint.

Below is the SharePoint CSOM code to get all users from sharepoint group programmatically csom.

ClientContext context = new ClientContext(“http://SiteURL”);
GroupCollection siteGroups = context.Web.SiteGroups;
// Here it will retrieve the group whose ID=1
Group myGroup = siteGroups.GetById(1);
context.Load(myGroup.Users);
context.ExecuteQuery();
foreach (User member in myGroup.Users)
{
lblUsers.Text = lblUsers.Text + “, ” + member.Title;
}

20. Get site level content types using CSOM

We will discuss here how to get site-level content types using the SharePoint client object model.

using Microsoft.SharePoint.Client;

ClientContext context = new ClientContext("http://URL of the Site");
Web web = context.Web;
context.Load(site);
context.ExecuteQuery();
ContentTypeCollection contentTypeCollection = site.ContentTypes;
context.Load(contentTypeCollection);
context.ExecuteQuery();
foreach (ContentType contentType in contentTypeCollection)
{
Console.WriteLine(contentType.Name);
}
Console.ReadLine();

21. Get root web site URL from site collection URL in SharePoint online using CSOM

Now, we will see how to get the root website URL and title from the site collection URL using.Net managed object model (csom) code in SharePoint online. We will do this inside a console application using.Net managed object model code (CSOM).

Here we need to load context.Site.RootsWeb, then we can retrieve the RootsWeb properties like Url or Title etc.

Below is the full code:

public static string GetRootweb()
{
string rootweb = string.Empty;
using (ClientContext context = new ClientContext(“https://onlysharepoint2013.sharepoint.com/sites/Bhawana/subsite1”))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
context.Load(context.Site.RootWeb, w => w.Url, w => w.Title);
context.ExecuteQuery();
rootweb =”Root Web URL:: “+ context.Site.RootWeb.Url +” Title:: “+ context.Site.RootWeb.Title;
}
return rootweb;
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<[email protected]>";
            }
            catch
            {
                throw;
            }
        }

Once you run, you can see the rootweb URL and title like below:

Get root web site url from site collection url in SharePoint online using CSOM

22. Retrieve ModerationStatus of a document using CSOM SharePoint Online

In this SharePoint CSOM tutorial, we will see how to retrieve ModerationStatus of a document using csom (.Net managed object model) code in SharePoint Online. The same code also will work to retrieve _moderationstatus SharePoint 2013.

Here I have a SharePoint document library and I want to retrieve the ModerationStatus for a particular document. 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.

See also  LepideMigrator for Documents Product Review (Kernel Migrator for SharePoint)
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.

Below is the full code to retrieve ModerationStatus of document using csom (.Net managed object model) code in SharePoint Online

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 SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<[email protected]>";
            }
            catch
            {
                throw;
            }
        }

This code will return the ModerationStatus of a document using csom in SharePoint Online.

23. Set the Bing Maps key at the web and farm level in SharePoint 2013

Now, we will see how to set Bing Maps key at the farm level in SharePoint 2013 using Client object model code.

Below is the full code to Set the Bing Maps key in SharePoint 2013 using client object model.

ClientContext context = new ClientContext(“http://Site URL”);
Web web = context.Web;
web.AllProperties[“BING_MAPS_KEY”] = “Enter valid bing map key here”
web.Update();
context.ExecuteQuery();

24. Add a Geolocation column to a list programmatically in SharePoint 2013

Now, we will see how to add a Geolocation column to a SharePoint 2013 list using SharePoint 2013 client object model.

SharePoint 2013 introduces a new field type named Geolocation that enables you to annotate SharePoint lists with location information. In columns of type Geolocation, you can enter location information as a pair of latitude and longitude coordinates in decimal degrees or retrieve the coordinates of the user’s current location from the browser if it implements the W3C Geolocation API.

First, we need to add the below 2 dlls to work with the SharePoint 2013 client object model.

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

Then we need to write the using statement like below:

using Microsoft.SharePoint.Client;

Below is the full code:

ClientContext context = new ClientContext("http://site url");
List oList = context.Web.Lists.GetByTitle("MyCustomList");
oList.Fields.AddFieldAsXml("<Field Type=’Geolocation’ DisplayName=’Location’/>",true, AddFieldOptions.DefaultValue);
oList.Update();
context.ExecuteQuery();

25. Query Search with SharePoint 2013 CSOM client object model

This SharePoint 2013 tutorial explains, how to query search result by using the Client Object Model (CSOM) in SharePoint 2013.

using Microsoft.SharePoint.Client

var clientContext = new SP.ClientContext("SiteURL");
var contextSite = clientContext.get_site();
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(clientContext);
keywordQuery.set_queryText("SharePoint 2013");
var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(clientContext);
var results = searchExecutor.executeQuery(keywordQuery);

Here the results object will contain the search results.

26. Add lookup column to SharePoint list programmatically using CSOM

Hi folks today we are going to see how to add lookup column programmatically using csom in SharePoint 2016/2013/Online. We will see how to add a lookup column to the SharePoint list programmatically using CSOM (C#).

Add lookup column to SharePoint list programmatically using CSOM

There are two SharePoint lists, where, from one we need to get Title as a lookup field display name and in the second list we need to show the title field as a column value.

Here we have a SharePoint list name as “SourceListName” which has a column as Title. The list looks like below:

Add lookup column to SharePoint list programmatically
Add lookup column to SharePoint list programmatically

And I have another list known as DestinationList which has a Title column. And here we need to add a lookup column to this list.

Below is the full code to add a lookup column to the SharePoint list programmatically using CSOM (c#).

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

namespace SPOnlineConsoleAppDemo
{
class Program
{
static void Main(string[] args)
{
using (ClientContext clientContext = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
List SourceListName = clientContext.Web.Lists.GetByTitle("SourceListName");
List DestinationList = clientContext.Web.Lists.GetByTitle("DestinationList");
clientContext.Load(SourceListName);
clientContext.Load(DestinationList);
clientContext.ExecuteQuery();
Field LookUpField = DestinationList.Fields.AddFieldAsXml(
"<Field Type='Lookup' DisplayName='Employees' Required='FALSE' List='" + SourceListName.Id + "' ShowField = 'Title' StaticName = 'Title' Name = 'Title' /> ", true, AddFieldOptions.DefaultValue);
LookUpField.Update();
clientContext.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 we run the code the lookup column will be added to the SharePoint list like below:

Add lookup column to SharePoint list programmatically using csom
Add lookup column to SharePoint list programmatically using csom

Next time when you will add an item to the list you can see the lookup data like below:

How to Add lookup column to SharePoint list programmatically
How to Add lookup column to SharePoint list programmatically

This is how to add a lookup column to the sharepoint list programmatically using client-side object model (csom).

27. Activate workflows can use app permissions in SharePoint

Let us see, how to activate “Workflows can use app permissions” in SharePoint online site programmatically using client object model code (csom).

We will use C#.net managed object model code (Microsoft.SharePoint.Client.dll) to activate the workflows can use app permissions.

“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.

Even if you have any issues like “workflows can use app permissions error activating“, you can also use CSOM to activate the feature.

Activate workflows can use app permissions

Below is the full code to activate workflows can use app permissions.

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, the workflows can use app permissions feature programmatically using CSOM.

28. csom upload file to document library in SharePoint

Let us see, how to upload a document to the SharePoint document library using CSOM (client-side object model) from the physical location.

Many times there is a requirement to upload a document from a physical path to the document library using Client Side Object Model (csom) in SharePoint 2013.

upload document to SharePoint document library programmatically
csom upload file to document library

Upload document to SharePoint document library using CSOM Programmatically

Below, is the CSOM code to upload a document to the SharePoint document library programmatically using csom in SharePoint 2013/2016.

You can write the code inside the console application or windows application in c#.net.

static void Main(string[] args)
{

try
{
// Starting with ClientContext, the constructor requires a URL to the server running SharePoint.
using(ClientContext client = newClientContext("http://servername146/sites/test/"))
{
//client.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Assume that the web site has a library named "FormLibrary".
var formLib = client.Web.Lists.GetByTitle("Documents");
client.Load(formLib.RootFolder);
client.ExecuteQuery();

// FormTemplate path, The path should be on the local machine/server !
string fileName = @ "C:\File.txt";

var fileUrl = "";

//Craete FormTemplate and save in the library.
using(var fs = newFileStream(fileName, FileMode.Open))
{
var fi = newFileInfo("test.txt"); //file Title
fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
client.ExecuteQuery();
}

// Get library columns collection.
var libFields = formLib.Fields;
client.Load(libFields);
client.ExecuteQuery();

Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl);

ListItem item = newFile.ListItemAllFields;

item["Title"] = "test";
item.Update();
client.ExecuteQuery();
}

} catch (Exception ex)
{

}

}

Final Output:

upload document to SharePoint document library programmatically using CSOM
csom upload file to document library in SharePoint

This is how, we can use CSOM to upload file to document library in SharePoint.

Unable to read data from the transport connection An existing connection was forcibly closed by the remote host

Now, we will 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. 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.

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

29. Read CSV file from SharePoint document library programmatically using CSOM

Let us see, how to read CSV file from a document library using the .Net client object model (csom) in SharePoint Online.

Here we are going to write our csom code in a windows application. So first create a windows application and then add the below ddls in the reference. You can add these two dlls from NuGet package manager.

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

Here we have a csv file which has 3 columns as:

  • SiteName
  • SiteURL
  • SiteDescription

And it has 3 rows of data and the CSV file looks like below:

sharepoint read csv file programmatically
read file from sharepoint document library using c#

And we have uploaded the CSV file to a SharePoint document library (MyDocLib) like below:

sharepoint read csv file programmatically c#
read file from sharepoint document library using c#

Read CSV file from SharePoint document library using CSOM

Below is the full code to read the CSV file from the SharePoint document library using csom.

private void btnSubmit_Click(object sender, EventArgs e)
{
using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
string username = "********@onlysharepoint2013.onmicrosoft.com";
context.AuthenticationMode = ClientAuthenticationMode.Default;
var secureString = new SecureString();
foreach (char c in ""********")
{
secureString.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials(username, secureString);
try
{
DataTable dt= ImportSiteList(context);
}
catch (Exception ex)
{
throw;
}
}
}

private DataTable ImportSiteList(ClientContext context)
{
try
{
List list = context.Web.Lists.GetByTitle("MyDocLib");
context.Load(list);
context.ExecuteQuery();
Folder folder = list.RootFolder;
FileCollection files = folder.Files;
context.Load(files);
context.ExecuteQuery();
DataTable dt = new DataTable("tblSiteLists");
foreach (Microsoft.SharePoint.Client.File f in files)
{
FileInformation fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, (string)f.ServerRelativeUrl);
if((string)f.ServerRelativeUrl == "/sites/Bhawana/MyDocLib/Sites.csv")
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
{
String line = sr.ReadToEnd();
string dataformat = line.Replace("\r\n", ",");
string[] strArray = dataformat.Split(‘,’);
dt.Columns.Add("SiteName", typeof(string));
dt.Columns.Add("SiteURL", typeof(string));
dt.Columns.Add("SiteDescription", typeof(string));
int j = 0;
DataRow dr = dt.NewRow();
for (int i = 3; i < strArray.Length – 1; i++)
{
dr[j] = strArray[i];
j++;
if (j == 3)
{
j = 0;
dt.Rows.Add(dr);
dr = dt.NewRow();
}
}
}
}
}
return dt;
}
catch (Exception ex)
{
throw ex;
}
}

The above code will return a data table which looks like below:

sharepoint read csv file programmatically csom
read file from sharepoint document library using csom

This is how to read CSV file from the SharePoint document library programmatically using CSOM..

30. Get SharePoint term store data programmatically using csom

Let us see, how to get term store data programmatically using csom in SharePoint Online. We will retrieve term store group, term set name and terms from term store using .Net managed object model in SharePoint Online Office 365.

Also, we will see, how to retrieve term store data including Labels using csom (.Net managed object model) in SharePoint Online.

Retrieve term store data programmatically using csom in SharePoint

Here we have a term store in Office 365 and it has a group, term set, and a few term sets in SharePoint. The structure looks like below:

programmatically get terms label from term store
Get SharePoint term store data programmatically

Now we will see how we can retrieve groups, term sets and terms using csom (.Net managed client object model). Here we have taken a windows application. To work with SharePoint objects we need to add the below details:

  • Microsoft.SharePoint.Client
  • Microsoft.SharePoint.Client.Runtime
  • Microsoft.SharePoint.Client.Taxonomy

Below is the full code to retrieve the term store group, term set name, and terms from the SharePoint term store.

private void button1_Click(object sender, EventArgs e)
{
using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
// Use default authentication mode.
context.AuthenticationMode = ClientAuthenticationMode.Default;
var secureString = new SecureString();
foreach (char c in "********")
{
secureString.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials("*******@onlysharepoint2013.onmicrosoft.com", secureString);
try
{
getTerms(context);
}
catch (Exception ex)
{
throw;
}
}
}

public void getTerms(ClientContext cc)
{
TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(cc);
TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
cc.Load(termStore,
store => store.Name,
store => store.Groups.Include(
group => group.Name,
group => group.TermSets.Include(
termSet => termSet.Name,
termSet => termSet.Terms.Include(
term => term.Name
)
)
)
);

cc.ExecuteQuery();
string s = string.Empty;
if (taxonomySession != null)
{
if (termStore != null)
{
foreach (TermGroup group in termStore.Groups)
{
if (group.Name == "Company Term Store")
{
lblTermGroupName.Text ="Term Store Group Name: "+ group.Name;
foreach (TermSet termSet in group.TermSets)
{
lblTermSets.Text = "Term Sets Name: " + termSet.Name;
foreach (Term term in termSet.Terms)
{
s += term.Name +"\n";
}
lblTerms.Text = s;
}
}
}
}
}
}

Once we run the code and click on the button click, we can see the details like below:

sharepoint get term store programmatically using csom
taxonomy sharepoint online csom example

31. Get term store data including Labels using csom in SharePoint

Now, we will see how to get term store data including labels using .Net managed object model in SharePoint Online.

In SharePoint online term store I have made the structure like below. Here also I have added the data in Other Labels. Here we will see how to retrieve groups, term sets, terms and labels using csom (.Net managed client object model). The term store looks like below:

programmatically retrieve terms from term store
sharepoint term set examples

Here we are going to write our code in a windows application. So first create a windows application and then add the below ddls in the reference.

  • Microsoft.SharePoint.Client
  • Microsoft.SharePoint.Client.Runtime
  • Microsoft.SharePoint.Client.Taxonomy

Below is the full code to retrieve term store data including Labels using csom in SharePoint Online programmatically.

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Taxonomy;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ClientOMDemo
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
using (ClientContext context = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
// Use default authentication mode.
context.AuthenticationMode = ClientAuthenticationMode.Default;
var secureString = new SecureString();
foreach (char c in "*******")
{
secureString.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials("*****@onlysharepoint2013.onmicrosoft.com", secureString);
try
{
getTerms(context);
}
catch (Exception ex)
{
throw;
}
}
}

public void getTerms(ClientContext clientContext)
{
TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
TermStore termStore = taxonomySession.GetDefaultSiteCollectionTermStore();
clientContext.Load(termStore,
store => store.Name,
store => store.Groups.Include(
group => group.Name,
group => group.TermSets.Include(
termSet => termSet.Name,
termSet => termSet.Terms.Include(
term => term.Name
)
)
)
);
clientContext.ExecuteQuery();
string s = string.Empty;
string lblCol= string.Empty;
if (taxonomySession != null)
{
if (termStore != null)
{
foreach (TermGroup group in termStore.Groups)
{
if (group.Name == "Company Term Store")
{
lblTermGroupName.Text ="Term Store Group Name: "+ group.Name;
foreach (TermSet termSet in group.TermSets)
{
lblTermSets.Text = "Term Sets Name: " + termSet.Name;
foreach (Term term in termSet.Terms)
{
s += term.Name + "\n";
clientContext.Load(term.Labels);
clientContext.ExecuteQuery();
LabelCollection lblCollection= term.Labels;
lblCol +="Default Label:: "+ lblCollection[0].Value.ToString() + " Other Label:: " + lblCollection[1].Value.ToString() + "\n";
}
lblTerms.Text = s;
lblLabel.Text = lblCol;
}
}
}
}
}
}
}
}

Once you run the code, you can see the term store details like below:

sharepoint get term store programmatically
sharepoint term set examples

This is how to get term store data including Labels programmatically using csom (.Net managed object model) in SharePoint Online Office 365.

See also  SharePoint Online Planner Web Part

32. SharePoint get site url using CSOM

SharePoint get site url using CSOM?

Now, we will see how to get SharePoint site URL based on site name using .Net managed object model (csom) code in SharePoint Online Office 365. Here we will work in a console application and we will try to connect to the SharePoint Online site.

Here in this example, we are checking with one title as “Bhawana” and if the SharePoint site title is “Bhawana” then it will return the URL. In the method, we are loading the Title and URL property of the web. Before that, we using the SharePoint clientcontext.

Below is the full csom code to get sites URL SharePoint based on site title using csom in SharePoint Online.

private static string GetSiteURLFromSiteTitle()
{
string siteURL = string.Empty;
string siteTitle = "Bhawana";
using (ClientContext clientContext = new ClientContext("https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
Web web = clientContext.Web;
clientContext.Load(web, w => w.Title, w => w.Url);
clientContext.ExecuteQuery();
if (web.Title == siteTitle)
{
siteURL = web.Url;
}
}
return siteURL;
}

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 code, you can see it will return the SharePoint site URL like below:

get sharepoint site url csom
get sharepoint site url

33. Retrieve exact SharePoint site URL from SharePoint ServerRelativeUrl

Let us see an serverrelativeurl sharepoint example in c#.

Now, we will see how to get the exact SharePoint site URL from the ServerRelativeUrl in SharePoint online using .Net managed object model code (C#.Net). Here we are doing a console application and we are trying to connect to the SharePoint Online site.

Here my requirement is if the site URL is:

https://onlysharepoint2013.sharepoint.com/sites/Bhawana

It should return me only “Bhwana”

If the site URL is:

https://onlysharepoint2013.sharepoint.com/sites/Bhawana/SubSite1

It should return me only “SubSite1”

Here in the GetSiteURL function we are taking the context and splitting the ServerRelativeUrl with “/” and returning the last element from the array.

Below is the full code (First we are using the SharePoint clientcontext)

using (ClientContext context = new ClientContext(URL))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
string siteTitle = GetSiteURL(context);
}

private static string GetSiteURL(ClientContext context)
{
string siteTitle;
string[] strArray = context.Web.ServerRelativeUrl.Split('/');
int j = strArray.Length;
siteTitle = strArray[j – 1].ToString();
return siteTitle;
}

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 is how we can get SharePoint site URL from SharePoint serverrelativeurl.

34. Create List Item using Client Object Model (CSOM) in SharePoint

Below is the code to create a list item using the client object model (csom).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
namespace CreateListItem
{
class Program
{
static void Main(string[] args)
{
string siteUrl = "http://servername:2525/";
ClientContext clientContext = new ClientContext(siteUrl);
List oList = clientContext.Web.Lists.GetByTitle("TestList");
ListItemCreationInformation listCreationInformation = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(listCreationInformation);
oListItem["Title"] = "Hello World";
oListItem.Update();
clientContext.ExecuteQuery();
}
}
}

35. Update List Item using Client Object Model CSOM

Below is the code to update a list item using the client object model (csom) in SharePoint 2013/2016.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;

namespace UpdateListItem
{
class Program
{
static void Main(string[] args)
{
string siteUrl = "http://servername:2525/";
ClientContext clientContext = new ClientContext(siteUrl);
List oList = clientContext.Web.Lists.GetByTitle("TestList");
ListItem oListItem = oList.GetItemById(5);
oListItem["Title"] = "Hello World Updated!!!";
oListItem.Update();
clientContext.ExecuteQuery();
}
}
}

36. Delete List Item using Client Object Model CSOM

The below code, we can use to delete a list item using client object model (CSOM) in SharePoint 2013/2016.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;

namespace UpdateListItem
{
class Program
{
static void Main(string[] args)
{
string siteUrl = "http://servername:2525/";
ClientContext clientContext = new ClientContext(siteUrl);
List oList = clientContext.Web.Lists.GetByTitle("TestList");
ListItem oListItem = oList.GetItemById();
oListItem.DeleteObject();
clientContext.ExecuteQuery();
}
}
}

37. Get content type Id from content type name using CSOM

First, we will see, how we to retrieve content type name from content type id using.Net managed object model code (csom) in SharePoint Online.

Here in the below csom code, we are passing the content type name as “Document Set” and it will return the content type id of “Document Set” from the SharePoint Online site.

I have added a button in my windows application and call the below method.

private static string GetContentTypeIDFromName()
{
string contentTypeId = string.Empty;
using (ClientContext clientContext = new ClientContext("https://<tenantname>.sharepoint.com/sites/Bhawana/"))
{
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
clientContext.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
Web web = clientContext.Web;
ContentTypeCollection contentTypeColl = web.ContentTypes;
clientContext.Load(contentTypeColl);
clientContext.ExecuteQuery();
foreach (ContentType ct in contentTypeColl)
{
if (ct.Name.Equals("Document Set"))
{
contentTypeId = ct.Id.ToString();
break;
}
}
}
return contentTypeId;
}

private static SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname>@onmicrosoft.com";
            }
            catch
            {
                throw;
            }
        }

If you run the code, you can see it will return the content type id like below:

Retrieve content type Id from content type name using CSOM

This way we can retrieve content type id from content type name csom in SharePoint Online.

38. Retrieve Content type Name by Id using csom in SharePoint Online

Now, we will discuss how to retrieve content type name by content type id using csom (.Net client object model c#) code in SharePoint Online or SharePoint 2013/2016.

Here in this example I have used the “Workflow Task (SharePoint 2013)” whose Id is “0x0108003365C4474CAE8C42BCE396314E88E51F”.

Once I will run the below code, it will give me the content type name

Below is the full csom code to retrieve the content type name from content type id in SharePoint using csom.

public static void GetContentTypeByID()
{
string contentTypeName = string.Empty;
using (ClientContext context = new ClientContext("https://<tenant name>.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 SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname>@onmicrosoft.com";
            }
            catch
            {
                throw;
            }
        }

Once you run the above code, you can see the result like below:

Retrieve Content type Name by Id using csom in SharePoint

39. Get list content types using csom in SharePoint

Now, we will see how to retrieve content types associated with a list using csom in SharePoint Online or SharePoint 2013/2016.

First, we can retrieve the SharePoint list using GetByTitle method and then we can retrieve all the content types by using the below code:

ContentTypeCollection contentTypeColl = lst.ContentTypes;

Below is the full csom code to retrieve all list content types in SharePoint.

public static void RetrieveListContentType()
{
string contentTypes = string.Empty;
using (ClientContext context = new ClientContext("https://<tenantname>.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 SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname>@onmicrosoft.com";
            }
            catch
            {
                throw;
            }
        }

Once you run the above code, it will retrieve all content types associated with MyTestList list in SharePoint Online/2013/2016.

40. Get content type id by content type name using SharePoint CSOM

Now, we will see how to retrieve content type id by content type name using the client object model in SharePoint Online.

The below method will take two parameters as 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.

This we are doing in a console application and we are connecting to a SharePoint online site.

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 "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname>@onmicrosoft.com";
            }
            catch
            {
                throw;
            }
        }

41. Delete content type from SharePoint Online list using CSOM

In this CSOM example, we will discuss how to delete a content type attached to a list using csom in SharePoint Online.

Here I have a list name as “MyTestList” which is a SharePoint custom list and 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.

Below is the full code to delete a content type from the SharePoint list using csom.

public static void DeleteContentType()
{
using (ClientContext contextURL = new ClientContext("https://<tenantname>.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 SecureString GetSPOSecureStringPassword()
        {
            try
            {
                var secureString = new SecureString();
                foreach (char c in "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname>@onmicrosoft.com";
            }
            catch
            {
                throw;
            }
        }

The above code will delete the content type from the SharePoint Online list.

42. Get list item content type name or id using csom in SharePoint

Now we will discuss how to retrieve list item’s associated content type name or id using csom (.Net managed object model) code in SharePoint online.

Here we have a list that has few content type’s associated with it and we have created a few items using those content types. Now as per the requirement we have to check which is content type associated with particular items.

The below method will take the ItemID as an input parameter and return the content type name.

First, we are retrieving the list item by Id and then we are getting the content type associated with the item from item.ContentType;

public static string GetContentTypeNameForItem(int ItemID)
{
string contentTypeName = string.Empty;
using (ClientContext contextURL = new ClientContext("https://<tenantname>.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 "MyPassword")
                {
                    secureString.AppendChar(c);
                }
                return secureString;
            }
            catch
            {
                throw;
            }
        }

        private static string GetSPOAccountName()
        {
            try
            {
                return "bijay@<tenantname>@onmicrosoft.com";
            }
            catch
            {
                throw;
            }
        }

43. How to get all content types using csom in SharePoint

Below is the source code which can call to SharePoint online site to get the all content type.

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security;
using Microsoft.SharePoint.Client;
using System.Data;

public partial class getDataFromSharePointOnline : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        using (ClientContext clientcontext = new ClientContext("https://pikasha12.sharepoint.com/sites/DLH"))
        {
            string pwd = "xyz";
            SecureString passWord = new SecureString();

            foreach (char c in pwd.ToCharArray()) passWord.AppendChar(c);

            clientcontext.Credentials = new SharePointOnlineCredentials("[email protected]", passWord);
            ContentTypeCollection displayContentTypes = clientcontext.Web.ContentTypes;
            clientcontext.Load(displayContentTypes);
            clientcontext.ExecuteQuery();
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Name", typeof(string)));
            dt.Columns.Add(new DataColumn("Description", typeof(string)));

            foreach (ContentType ContentTypes in displayContentTypes)
            {
                dt.Rows.Add(ContentTypes.Name, ContentTypes.Description);
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }
}

On this page, I have added a GridView to show all content type Name with Descriptions.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4">
                <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                <RowStyle BackColor="White" ForeColor="#330099" />
                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                <SortedAscendingCellStyle BackColor="#FEFCEB" />
                <SortedAscendingHeaderStyle BackColor="#AF0101" />
                <SortedDescendingCellStyle BackColor="#F6F0C0" />
                <SortedDescendingHeaderStyle BackColor="#7E0000" />
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Here is the O/P of this code.

sharepoint csom get all content types

If you want to delete content types, then you have to use ContentTypes.DeleteObject() .

foreach (ContentType ContentTypes in displayContentTypes
{
Console.WriteLine(ContentTypes.Name);
ContentTypes.DeleteObject();
clientcontext.ExecuteQuery();
}

Issue 1: The “SharePointOnlineCredentials” is marked as type or namespace not found.

using (var context = new ClientContext(webUrl))
{
context.Credentials = new SharePointOnlineCredentials(userName, password);

Solution: According to this article, that should be a member of Microsoft.SharePoint.Client namespace.

In Visual Studio Nuget Packages, search “Microsoft.SharePointOnline.CSOM” and install the latest CSOM API for SharePoint Online.

44. Get all users from SharePoint group programmatically using csom

This SharePoint csom tutorial explains, how to get all users from the SharePoint group programmatically using csom (.Net managed object model) code in SharePoint Online.

We have a SharePoint group that has few users in it, the below code will display all the user’s email id in a comma-separated string.

We are doing everything inside a console application. We are trying to connect to a SharePoint online site from the console application. For this, we have stored the Email Address and Password inside the App. Config file.

That information we are retrieving using the below methods.

  • GetSPOAccountName()
  • GetSPOSecureStringPassword()

And then passing as a credentials inside the code.

public static string GetPortalOwnerEmail(string URL)
{
string ownerEmail = string.Empty;
using (ClientContext context = new ClientContext(URL))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(), GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
Microsoft.SharePoint.Client.Group group = context.Web.SiteGroups.GetByName(“My Custom SharePoint Group”);

context.Load(context.Web, w => w.Title);
context.Load(group, grp => grp.Title, grp => grp.Users, grp => grp.Owner);
context.ExecuteQuery();
foreach (User usr in group.Users)
{
ownerEmail += usr.Email+”,”;
}

}
return ownerEmail;
}

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;
}
}

The above SharePoint csom code will give all the users email address as a string separated by comma from a SharePoint group in SharePoint.

45. Check if user belongs to SharePoint group using CSOM

This SharePoint CSOM tutorial explains, how to check if a particular user belongs to a SharePoint group or not using.Net managed object model code (csom). Here we will pass the email id of the user and the function will return if the user is presented in the group or not.

The code we are writing inside a console application where we have added the SharePoint client object model dlls and we are connecting to a SharePoint Online site.

Below is the full code, the method will take the Site URL, Group name and Email of the user. Here we are retrieving the credentials by using GetSPOAccountName(), GetSPOSecureStringPassword() to connect to SharePoint online site which has been explained in the console application.

public static bool IsUserBelongsToSharePointGroup(string siteURL, string groupName, string email)
{
bool isUserExistInGroup = false;

using (ClientContext context = new ClientContext(siteURL))
{
context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = new SharePointOnlineCredentials(GetSPOAccountName(),GetSPOSecureStringPassword());
context.Load(context.Web, w => w.ServerRelativeUrl);
context.Load(context.Web, w => w.Title, w => w.Url);
context.ExecuteQuery();

Microsoft.SharePoint.Client.Group group = context.Web.SiteGroups.GetByName(groupName);

context.Load(context.Web, w => w.Title);
context.Load(group, grp => grp.Title, grp => grp.Users, grp => grp.Owner);
context.ExecuteQuery();
foreach (User usr in group.Users)
{
if (email == usr.Email)
{
isUserExistInGroup = true;
break;
}
}

}
return isUserExistInGroup;
}

We can call the function like below:

bool isUserBelongsToGroup = IsUserBelongsToSharePointGroup(“https://onlysharepoint2013.sharepoint.com/sites/Bhawana/”, “Bhawana Owners”, “[email protected]”);

Once you run the code it will return if the user belongs to group or not. It will give results like the below:

Check if user belongs to SharePoint group using CSOM
Check if user belongs to SharePoint group using CSOM

This is how to check if the user belongs to the SharePoint group using CSOM in SharePoint Online Office 365.

46. The remote server returned an error: (403) forbidden – CSOM SharePoint

Let us see, how to fix The remote server returned an error 403 forbidden error which comes in CSOM SharePoint Online.

Recently while working with SharePoint Online using.Net managed object model code I got the below error which says:

An unhandled exception of type ‘System.Net.WebException’ occurred in Microsoft.SharePoint.Client.dll
Additional information: The remote server returned an error: (403) Forbidden.

The remote server returned an error 403 forbidden
The remote server returned an error 403 forbidden

Here I was trying to write code like below:

ClientContext clientContext = new ClientContext(“https://onlysharepoint2013.sharepoint.com/”);
Web web = clientContext.Web;

try
{
file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
clientContext.Load(file);
clientContext.ExecuteQuery();
}

catch (ServerException ex)
{

}

The remote server returned an error 403 forbidden

Here we need to write handle authentication using SharePointOnlineCredentials like below:

SecureString passWord = new SecureString();
foreach (char c in “*******”.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(“[email protected]”, passWord);

So the full code will look like below:

ClientContext clientContext = new ClientContext(“https://onlysharepoint2013.sharepoint.com/”);
SecureString passWord = new SecureString();
foreach (char c in “YourPasword”.ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(“[email protected]”, passWord);
Web web = clientContext.Web;

try
{
file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
clientContext.Load(file);
clientContext.ExecuteQuery();
}

catch (ServerException ex)
{
}

Now you will not receive any error.

This is how to fix the error, “The remote server returned an error 403 forbidden” error in SharePoint.

You may like the following SharePoint tutorials:

Conclusion

I hope this SharePoint tutorial, we learned SharePoint CSOM (Client-side object model). I have explained how CSOM works and various SharePoint CSOM examples and csom sharepoint 2013 examples.

  • >