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.
SharePoint Tutorial Contents
- What is SharePoint CSOM (client object model)?
- Different types of SharePoint client object model
- How SharePoint CSOM works
- Create a console application to use CSOM SharePoint
- CRUD Operations with SharePoint CSOM
- 25+ SharePoint CSOM Examples
- 1# Create SharePoint list programmatically using .Net Client object model (CSOM)
- 2# Create a custom list and add an item to a custom list programmatically using the SharePoint client object model
- 3# Update SharePoint list programmatically using CSOM
- 4# Delete SharePoint list programmatically using CSOM
- 5# Get SharePoint List Title using .Net Client object model (CSOM)
- 6# Retrieve SharePoint list items and display in Gridview using SharePoint Client object model (csom)
- 7# check if list exists SharePoint 2013 c# csom
- 8# Get column names of SharePoint list using SharePoint client object model (CSOM)
- 9# Update web part Title using SharePoint Client object model
- 10# Delete a SharePoint online list using CSOM SharePoint
- 11# Check if current site is root site using .net managed object model code csom in SharePoint online
- 12# SharePoint online csom create list, list item and add columns
- 13# Follow or UnFollow people by using SharePoint client object model
- 14# Query Search with SharePoint 2013/2016 Client Object Model
- 15# Get followers by using SharePoint 2013 .Net client object model
- 16# Get SharePoint column display name and internal name using SharePoint client object model
- 17# Retrieve selected properties of website using CSOM SharePoint
- 18# Add a user to a SharePoint group using CSOM SharePoint
- 19# get all users from sharepoint group programmatically csom
- 20# Get site level content types using CSOM
- 21# Get root web site URL from site collection URL in SharePoint online using CSOM
- 22# Retrieve ModerationStatus of a document using CSOM SharePoint Online
- 23# Set the Bing Maps key at the web and farm level in SharePoint 2013
- 24# Add a Geolocation column to a list programmatically in SharePoint 2013
- 25# Query Search with SharePoint 2013 CSOM client object model
- #26 Add lookup column to SharePoint list programmatically using CSOM
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.
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)
- JavaScript client object model (jsom)
- Rest API
- Silverlight client object model
- Windows Phone client object model
.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
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.
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
- SharePoint Server 2013 Client Components SDK
- SharePoint Server 2016 Client Components SDK
- SharePoint Online Client Components SDK
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.
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.
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();
Now, we will see how we can update all list items using
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.
Now, we will discuss how we can delete a list item programmatically using the
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.
Here are a few examples of SharePoint csom (.Net client object model) examples.
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”.
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();
}
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.
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.
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;
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.
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#.
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.
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();
}
We will see how we can 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.
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:
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();
}
}
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();
}
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”];
}
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;
}
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 + " ";
}
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;
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.
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();
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 "[email protected]<[email protected]>";
}
catch
{
throw;
}
}
Once you run, you can see the rootweb URL and title like below:
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.
Value | Description |
0 | The list item is approved. |
1 | The list item has been denied approval. |
2 | The list item is pending approval. |
3 | The list item is in the draft or checked out state. |
4 | The list item is scheduled for automatic approval at a future date. |
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 "[email protected]<[email protected]>";
}
catch
{
throw;
}
}
This code will return the ModerationStatus of a document using csom in SharePoint Online.
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();
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();
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.
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:
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:
Next time when you will add an item to the list you can see the lookup data like below:
This is how to add a lookup column to the sharepoint list programmatically using client-side object model (csom).
You may like the following SharePoint tutorials:
- Add user to SharePoint group programmatically
- SharePoint create folder programmatically using CSOM
- How to get sharepoint site URL programmatically
- Get user profile properties in SharePoint programmatically using CSOM (C#)
- How to get all content types using csom in SharePoint
- How to get access token in SharePoint Online using CSOM and use in Postman or Google Rest client
- Get SharePoint List Name and GUID using PowerShell and CSOM
- Create an index in SharePoint Online list using CSOM
- Content type Examples using CSOM in SharePoint
- How to activate SharePoint Publishing Feature Programmatically using CSOM
- Get all lists and document libraries programmatically using CSOM in SharePoint Online
- Copy list items from one site collection to another programmatically using CSOM in SharePoint Online
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.
I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SPGuides.com
[…] SharePoint 2013 client object model supports ExecuteQueryAsync and not synchronous ExecuteQuery. When you call ExecuteQueryAsync in […]
[…] SharePoint CSOM tutorial, we will discuss how to get all subsites from a site collection in SharePoint Online using .net […]
[…] SharePoint csom tutorial we will discuss, how to work with content types using csom (.Net client object model) code in […]
[…] SharePoint csom tutorial, we will discuss, how to copy list items from one list to another list in SharePoint […]
[…] SharePoint CSOM tutorial explains, how to create an index in SharePoint online list using csom .Net managed object model […]