SharePoint list and library operations using csom

This SharePoint csom tutorial, we will discuss few csom examples to work with SharePoint list, library, columns, users, etc. These are the examples to know how to work with csom in SharePoint 2010/2013 or SharePoint Online.

Create a list using SharePoint 2013 client object model

Now, let us see how to create a list using the SharePoint 2013 client object model in SharePoint provider-hosted add-in or apps.

var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
ListCreationInformation createinfo = new ListCreationInformation();
createinfo.Title = "Thought_Of_The_Day";
createinfo.Description = "Thought of the day list creted using CSOM";
createinfo.TemplateType = (int)ListTemplateType.GenericList;
List newList = clientContext.Web.Lists.Add(createinfo);
clientContext.Load(newList);
clientContext.ExecuteQuery();
string FieldAsXML = "<Field Name='AuthorName' DisplayName='AuthorName' Type='Text' Hidden='False'/>";
Field fld = newList.Fields.AddFieldAsXml(FieldAsXML, true, AddFieldOptions.DefaultValue);
newList.Update();
clientContext.ExecuteQuery();
}

The above code will create a SharePoint list using csom.

Check if list already exists or not using sharepoint 2013 client object model

Now, we will see how to check if a list already exists or not use the SharePoint 2013 client object model.

Below is the full code to check if the SharePoint list already exists or not.

var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
/*——————–Check the list if aalready Exist———————*/
ListCollection listCollection = clientContext.Web.Lists;
clientContext.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == “Thought_Of_The_Day”));
clientContext.ExecuteQuery();
if (listCollection.Count > 0)
{
Response.Write(“List all ready exist…”);
}
else
{
Response.Write(“List not exist”);
}
}

This is how we can check if the SharePoint list exists or not using csom in SharePoint 2013/2016 or SharePoint Online.

Change column name using SharePoint 2013 list using client object model

Now, we will see how to change the column name of a list using the SharePoint 2013 client object model.

var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
Web web = clientContext.Web;
List ListName = web.Lists.GetByTitle("Yours List Name");
FieldCollection collField = ListName.Fields;
Field oneField = collField.GetByInternalNameOrTitle("Title");
oneField.Title = "Thought"; //new column name replace of Title
oneField.Update();
clientContext.Load(collField);
clientContext.Load(oneField);
clientContext.ExecuteQuery();
Response.Write("Column updated succesfully…");
}

This is how we can change the SharePoint list column name using the client object model (csom) in SharePoint 2013/2016 or SharePoint Online.

Display SharePoint List collection using CSOM

Now, we will see how to display SharePoint list collection using the client-side object model (csom) in SharePoint 2013/2016/Online.

Here all lists are added by Feature using a visual studio in provider-hosted apps.

string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
SharePointContextToken contextToken =
TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
Uri sharepointUrl = new Uri(Request.QueryString[“SPAppWebUrl”]);
string accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
Web web = clientContext.Web;
ListCollection listcoll = web.Lists;
clientContext.Load(listcoll,lists => lists.Include(list => list.Title,list => list.Hidden).Where(list => !list.Hidden));
clientContext.ExecuteQuery();
foreach (var list in listcoll)
{
Response.Write(list.Title);
}

This is how we can display the SharePoint List collection using CSOM (client object model).

Create a SharePoint list using an auto hosted app

Now, we will see how to create a list based on auto hosted app in SharePoint 2013.

Follow the below steps:

Open Visual Studio 2012, Go to File -> New Project. Then in the New Project dialog box, go to Office/SharePoint under Visual C#.

Then select App for SharePoint 2013 template as shown in the fig below:

Create a SharePoint list using auto hosted app

Then in the next dialog box Give a name for the App, local debugging URL and then Choose the Autohosted hosting option as shown in the fig below:

Create a SharePoint list using provider hosted app

On the Project menu, choose Add New Item. When the Add New Item dialog box opens with the Office/SharePoint templates, choose List.

Specify the name of the list, and choose Add.

After you add the list to the solution, you can add a column to the list using the user interface.

Add the following code inside the body of the default.aspx page.

<div>
<p>Click on TOD List for adding the thought in that list</p>
<asp:HyperLink ID="HyperLink1″ runat="server" Target="_blank">TOD</asp:HyperLink>
</div>

Add the following code in code behind under Page_load method in default.aspx.cs

string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);
SharePointContextToken contextToken =
TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);
Uri sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
HyperLink1.NavigateUrl = sharepointUrl.AbsoluteUri + "/Lists/TOD";

Where TOD is a list name.

Now you deploy the apps and click that link then you able to show the list of auto hosted apps.

Fetch all user using csom in SharePoint Online 2013

Here, we will display how to fetch all users using provider-hosted apps or add-ins using in SharePoint Online or SharePoint 2013/2016.

Here I have added the code in the default.aspx page.

<asp:Label ID="UserName" runat="server"></asp:Label>

Now I added the following code under Default.aspx.cs (code behind code)

using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
List UserInformationList = clientContext.Web.Lists.GetByTitle("User Information List");
CamlQuery query = CamlQuery.CreateAllItemsQuery(100);
Microsoft.SharePoint.Client.ListItemCollection items = UserInformationList.GetItems(query);
clientContext.Load(items);
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem listItem in items)
{
UserName.Text = UserName.Text + ", " + listItem["Title"];
}
}
Fetch all user using csom in SharePoint

Now I Save and deploy this app in my SharePoint Online site.

Retrieve all lists in SharePoint using CSOM (Windows Form Application)

Now, we will see how to retrieve all the available lists in Windows form in SharePoint 2010.

Let us first create a windows application to connect to our SharePoint site.

Open the Visual Studio and create the new project. On the Start page, in the Projects section, click New Project.

In the Installed Templates section, in the Visual C# group, click Windows, and then click Windows Forms Application. Ensure that the .NET Framework version has been set to 3.5. See in fig.

Retrieve all lists in SharePoint

Give the name of your windows application form and give the location and click on OK.

In the Solution Explorer window, right-click and then click Add Reference. Click the Browse tab, and then browse to the following location: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI.

Click Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll. See in fig

Retrieve all lists in SharePoint using CSOM

Click OK. Now the references are added to the Solution Explorer window under References.

Click the Toolbox to the left of the editor pane and click the pin icon. Expand Common Controls, then click and drag a TextBox control onto Form1. This control will be used to enter a web address.

Click the Toolbox to the left of the editor pane and expand Common Controls, then click and drag a ListBox control onto Form1. Place the ListBox below the TextBox you have already added. This control will show lists available in the site specified in the TextBox.

Click the Toolbox to the left of the editor pane and expand Common Controls, then click and drag a Button control onto Form1.

In the right-hand properties, window changes the Text property from Button1 to Show Lists. Your form should look similar to the following example: See in fig

Retrieve all lists in SharePoint 2010 using CSOM

Adding code to the Windows Form application

In this task, you will add code to the Windows Form Application. You will add code for the button control.

Double-click the Button control to open the code window. Enter the following namespace.

using ClientOM = Microsoft.SharePoint.Client;

Add the following code between the braces in the button1_Click event.

listBox1.Items.Clear();
using (ClientOM.ClientContext ctx = new ClientOM.ClientContext(textBox1.Text))
{
ClientOM.Web site = ctx.Web;
ctx.Load(site);
ctx.Load(site.Lists);
ctx.Load(site, x => x.Lists.Where(l => l.Title != null));
ctx.ExecuteQuery();
foreach (ClientOM.List list in site.Lists)
{
listBox1.Items.Add(list.Title);
}
}

Press [CTRL] + [F5]. The application builds and the form appears. In the TextBox control, type URL and then press the Show Lists button. Now you see the whole list in that URL. Show in fig.

Retrieve all lists in SharePoint 2013 using CSOM

Here we saw how to retrieve all lists and libraries using csom in SharePoint 2010.

Set formula for a calculated field in SharePoint list using the Client Side Object Model

Now, we will discuss how to set formula for a calculated field in the SharePoint list using the Client-Side Object Model.

Under the Page load method write the following code:

var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
Web web = clientContext.Web;
// Get the list by title
List list = web.Lists.GetByTitle(“ListA”);
// Get the calculated field by title
Field field = list.Fields.GetByTitle(“Calculated”);
// Cast the field
FieldCalculated calculatedField =
clientContext.CastTo<FieldCalculated>(field);
// Set the formula for the calculated field
calculatedField.Formula = “=UPPER([Title])”;
// Update the field
calculatedField.Update();
// Execute the query to the server
clientContext.ExecuteQuery();
}

This is how we can set formula for a calculated field in the SharePoint list using the Client-Side Object Model.

You may like following SharePoint csom tutorials:

This SharePoint tutorial, we learned how to create a SharePoint list using the client object model (csom), then we saw, how to check if a SharePoint list already exists or not using the SharePoint client object model.

Also, we saw how to change the column name using SharePoint 2013 list using the client object model, how to display all SharePoint lists using csom. We also learned how to create a SharePoint list using provider-hosted apps, and how to fetch all user from SharePoint list using csom, how to retrieve all lists in SharePoint using CSOM in Windows Form Application. And finally, we discussed how to set formula for a calculated field in SharePoint list using the Client Side Object Model./

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

Navneet Singh

I am Navneet Singh, Working at C3it software solutions pvt. ltd. in Pune. My core skills are SharePoint 2013, Office 365, SharePoint 2010, SharePoint Designer, SharePoint Designer Workflow, Nintex Workflow, Infopath, Webpart, CSOM/SSOM, Power-shell, C#, ASP.NET and SQL Server.

>