What is Client Object Model – CSOM


Client Object Model is a subset of the SharePoint Server Object Model and consists of rich set of libraries for client side data access.

Why Client Object Model?
1) Prior to SharePoint 2010 only the out of box SharePoint web services could be used for client side data access.
2) Web services uses soap and difficult to manage using client scripts.
3) Client Object Model API is more closer to Server Object Model.

4) Most of the methods and properties in Server Object Model exists in Client Object Model too.
Client Object Model – Implementation 

There are 3 different ways to implement client object model.

1) The .NET Client Side Object Model (CSOM) :- Based on .Net managed assemblies mainly Microsoft.SharePoint.client.dll and  Microsoft.SharePoint.client.Runtime.dll which are located in 15\ISAPI
2) Silverlight Client Object Model :- Used to integrate Silverlight applications with SharePoint. The assemblies Microsoft.SharePoint.Silverlight.client.dll and  Microsoft.SharePoint.client.Silverlight.Runtime.dllthat support Silverlight object model are located in 15\TEMPLATE\LAYOUTS\ClientBin
3) JavaScript Object Model (JSOM) :- Consists of set of JS files for enabling client side access using ECMAScript (JavaScript, JScript). The main JS files SP.js, SP.Core.js and SP.Runtime.js are located in 15\TEMPLATE\LAYOUTS\ and downloaded when the referring pages are opened in browser.
Client Object Model – Architecture
The Client Object Model supports multiple platforms like .NET, JavaScript and Silverlight. All these platforms consume a WCF service named Client.svc which is published under the /_vti_bin/ folder of the current site. The client object model accepts REST requests as well as XML requests and responds with JSON or XML Atom responses.Following picture will give you a complete overview of the the Client Object Model architecture.

Client Object Model – Advantages
1) Silverlight and ECMAScript applications can access the SharePoint data from the client side browser itself.
2) Web parts with rich user interface can be developed with the help of Silverlight and jQuery.
3) JSOM can be implemented with just a Content Editor Web part within the browser or from the SharePoint designer without opening the Visual Studio.
4) When we save your site as a template. The application developed with ECMAScript or Silverlight application implemented with Client Object Model would come along with the template which would be very helpful during migrations though we need to take care of any hard coded values.
5) No IISREST is required while deploying a Silverlight or an ECMAScript application implemented with COM.
6) We can have SharePoint accessed from the client desktop using Windows forms or WPF applications implemented with COM.
7) No SharePoint installation is required in the development machine. Only the dll’s are required if you are going to develop Silverlight applications.
Client Object Model – Limitations
1) Admin Tasks Restrictions:- Client Object Model cannot be used for admin tasks like working with web applications and farms. It can only be used with sites, sub-sites, list, libraries and web parts.
2) No Elevated privileges or Impersonation:- Elevated privileges or Impersonate are not applicable in client object model since the data retrieved is already security trimmed by default.
3) Some Classes Missing:- There is also a constraint on classes available for data access. For instance, there are no classes for accessing user profile data, though it is available in web services.
4) Data access across multiple site collections prohibited:- The objects in another site collection cannot be access while implementing in Silverlight or in an ECMAScript (to avoid client side scripting). If we try, an error will be thrown stating “The security validation for this page is invalid.”
5) Recurring events fails in Calender list:- Recurring events cannot be retrieved from a SharePoint calendar list using Client Object Model.

SharePoint 2013 – The .Net Client-Side Object Model (CSOM)

Classes in Microsoft.SharePoint.Client
As compared to server object model, the client side object model has a lot of identical classes with a suffix in the namespace and no SP prefix in the class name.

Client Object Model Server Object Model
ClientContext SPContext
Site SPSite
Web SPWeb
List SPList


Locate the assemblies required for implementing .Net CSOM
Set of managed assemblies for CSOM reside in SharePoint15_Root\ISAPI. The following 2 assemblies are the minimumrequired assemblies for CSOM.
(i) Microsoft.SharePoint.Client.dll
(ii) Microsoft.SharePoint.Client.Runtime.dll

The ClientContext instance
An instance of the ClientContext class in Microsoft.SharePoint.Client namespace should be created to refer to the target Site Collection. ClientContext class is equivalent to SPContext class in object model and stands as proxy to the SharePoint server that you are targeting
ClientContext ctx = new ClientContext(“http://SiteCollectionUrl/”);

Authenticating the ClientContext instance
By default, the CSOM uses Windows integrated authentication. The ClientContext class, through its ClientRuntimeContext base class, provides an AuthenticationMode property and a FormsAuthenticationLoginInfo property, which are useful to configure a set of forms-based authentication credentials.
NetworkCredential credentials = new NetworkCredential(“username”, “password”, “domain”)
ctx.Credentials = credentials;

Loading the objects using Load<T> method
Whenever we need to access an object, we have to first request to load that object using Load<T> method of the ClientContextinstance. The following example shows how to load the site, web and list objects.
Site site = ctx.Site;
Web web = site.RootWeb;
List list = web.Lists.GetByTitle(“Products”);

The ExecuteQuery Method
Once all the objects are loaded, the ExecuteQuery method should be invoked to complete the action on the site, web or list. There is also an asynchronous version of this method, called ExecuteQueryAsync, for invoking the service asynchronously.


Adding CAML Query
To improve performance and reduce network traffic, the data retrieval engine of the Client Object Model by default does not retrieve all of the properties of the items you load. You can use the CAML query definition to specify the fields to retrieve, setting the ViewFields property.
CamlQuery query = new CamlQuery();
query.ViewXml = “<View/>”;
ListItemCollection allItems = list.GetItems(query);

SharePoint 2013 – Retrieve all items from a SharePoint list using .Net Client-Side Object Model (CSOM)

Create a custom list for retrieving data from client side
Create a custom list named Products as shown in the figure below. We will create a windows console application to retrieve data from this list using CSOM.

Locate the assemblies required for implementing .Net CSOM

Set of managed assemblies for CSOM reside in SharePoint15_Root\ISAPI. The following 2 assemblies are the minimum required assemblies for CSOM.
(i) Microsoft.SharePoint.Client.dll
(ii) Microsoft.SharePoint.Client.Runtime.dll

Add the CSOM assembly reference
Create a windows console application in Visual studio and add  the Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll as reference.

Modify the Main Method with following code
//Create the ClientContext instance
ClientContext ctx = new ClientContext(“http://SiteCollectionUrl/&#8221;);

//Authenticate the ClientContext instance
NetworkCredential credentials = new NetworkCredential(“username”, “password”, “domain”)
ctx.Credentials = credentials;

//Load the objects using Load<T> method
Site site = ctx.Site;
Web web = site.RootWeb;
List list = web.Lists.GetByTitle(“Products”);

//Add CAML Query
CamlQuery query = new CamlQuery();
query.ViewXml = “<View/>”;
ListItemCollection allItems = list.GetItems(query);

//Execute the Query

Following is the complete code for our console application using CSOM.

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Microsoft.SharePoint.Client;
  7. using System.Net;
  8. namespace CSOMDemo
  9. {
  10.     class Program
  11.     {
  12.         static void Main(string[] args)
  13.         {
  14.             // Enter your network credentials
  15.             NetworkCredential credentials = new NetworkCredential(“username”, “password”, “domain”);
  16.             // Load the site collection using ClientContext
  17.             ClientContext ctx = new ClientContext(“http://SiteCollectionUrl/&#8221;);
  18.             ctx.Credentials = credentials;
  19.             Site site = ctx.Site;
  20.             ctx.Load(site);
  21.             // Load the “Products” list
  22.             Web web = site.RootWeb; ctx.Load(web);
  23.             List list = web.Lists.GetByTitle(“Products”);
  24.             ctx.Load(list);
  25.             // List load is completed only when ExecuteQuery() or ExecuteQueryAsnc() is called
  26.             ctx.ExecuteQuery();
  27.             // Display the name of list
  28.             Console.WriteLine(list.Title+”\n”);
  29.             // Following query returns all items in the list
  30.             CamlQuery query = new CamlQuery();
  31.             query.ViewXml = “<View/>”;
  32.             ListItemCollection allItems = list.GetItems(query);
  33.             ctx.Load(allItems);
  34.             ctx.ExecuteQuery();
  35.             // Display List Item column names (Title, Description and Price)
  36.             Console.WriteLine(“Title” + “\t\t” + “Description” + “\t\t” + “Price”);
  37.             // Loop through all items and display the list items (Title, Description and Price)
  38.             foreach (ListItem listItem in allItems)
  39.             {
  40.                 Console.WriteLine(listItem[“Title”].ToString() + “\t” + listItem[“Description”].ToString() + “\t” + listItem[“Price”].ToString());
  41.             }
  42.             Console.Read();
  43.         }
  44.     }
  45. }

Displaying the data
Run the console application. Data will be retrieved from the Products list and displayed in the console.

SharePoint 2013 – The JavaScript Object Model (JSOM)

JSOM Objects
Objects in JSOM are pretty much similar to the classes in SharePoint server object model. Following are some of the commonly used JSOM counter parts.

.NET Server type JSOM object
SPSite SP.Site object (sp.js)
SPWeb SP.Web object (sp.js)
SPWebCollection SP.WebCollection object (sp.js)
SPList SP.List object (sp.js)
SPListItem SP.ListItem object (sp.js)
SPListItemCollection SP.ListItemCollection object (sp.js)
Client context not available SP.ClientContext object (sp.js)
SPContentType SP.ContentType object (sp.js)
SPContext SP.RequestContext object (sp.js)

JSOM Implementation
Following are the main steps for implementing JSOM.
1) Add reference to the JavaScript libraries that support JSOM.
2) Get an instance of Client Context and load the JSOM objects
3) Specify Callback functions and Execute the query.

Now lets see each of the above mentioned steps in detail. After that we will see a demo for getting the items from a SharePoint list using JSOM.

1) Adding reference to the JS libraries for supporting JSOM
For implementing JSOM, a reference to the following JS files should added inside the page.
<script type=”text/javascript” src=”//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js”></script>
<script type=”text/javascript” src=”_layouts/15/sp.runtime.js”></script>
<script type=”text/javascript” src=”_layouts/15/sp.js”></script>

Note:- In case we have customized or utilized a new master page for our sites, we should ensure that JSOM is loaded before we start accessing it. There are 2 methods for doing in it.
(i) ScriptLink : Use the server side ScriptLink class to declaratively register a script. The class provides properties and methods for registering scripts so that they can be requested when the page is being rendered.

<SharePoint:ScriptLink ID=”registerSP” runat=”server” OnDemand=”true” LoadAfterUI=”true” Name=”SP.js”>

(ii) ExecuteOrDelayUntilScriptLoaded : The SOD framework provides methods to ensure that the client scripts are loaded before any execution takes place on the dependent methods. Calling the following method before the executing method ensures that the function provided in the first parameter is not executed until the script file name mentioned is not loaded or has not been loaded.

ExecuteOrDelayUntilScriptLoaded(GetProducts, “sp.js”);

2) Get an instance of client context and load the JSOM objects
First of all, an instance of the client context must be created to access the objects in the JSOM. The current context can be get by using the get_current() method in SP.ClientContext as shown below.
var clientContext = new SP.ClientContext.get_current();

Using the Client Context object all the other SharePoint objects should be loaded as follows. In the following example we are loading all the items from the list named “Products”.
var oList = clientContext.get_web().get_lists().getByTitle(‘Products’);

this.collListItem = oList.getItems(“”);
Note: You can further add a CAML query to the above code as follows 

var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘<View><Query><Where><Geq><FieldRef Name=\’ID\’/>’ +'<Value  type=\’Number\’>1</Value></Geq></Where></Query>’ + ‘<RowLimit>10</RowLimit></View>’);
this.collListItem = oList.getItems(camlQuery);

3) Specify the callback functions and execute the query
Once all the necessary objects are loaded, we must specify the callback functions and execute the query as follows.
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));

Specify the Callback function if query execution succeeded
function onQuerySucceeded(sender, args) {
Specify the Callback function if query execution failed
function onQueryFailed(sender, args) {

SharePoint 2013 – Retrieve all items from a SharePoint list using JavaScript Object Model (JSOM)

Create a custom list for retrieving data from client side
Create a custom list named “Products” with three columns TitleDescription and Price.

Code for retrieving all items from a SharePoint list
In the previous post we have already discussed about the objects and methods used in JSOM. Following is complete code for implementing JSOM for retrieving all items from a SharePoint list.

Code Snippet
  1. <script type=”text/javascript” src=”//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js”></script>
  2. <script type=”text/javascript” src=”_layouts/15/sp.runtime.js”></script>
  3. <script type=”text/javascript” src=”_layouts/15/sp.js”></script>
  4. <script type=”text/javascript”>
  5.     function GetProducts() {
  6.         var clientContext = new SP.ClientContext.get_current();
  7.         var oList = clientContext.get_web().get_lists().getByTitle(‘Products’);
  8.         this.collListItem = oList.getItems(“”);
  9.         clientContext.load(collListItem);
  10.         clientContext.executeQueryAsync(
  11.             Function.createDelegate(this, this.onQuerySucceeded),
  12.             Function.createDelegate(this, this.onQueryFailed)
  13.         );
  14.     }
  15.     function onQuerySucceeded(sender, args) {
  16.         var ProductInfo = ”;
  17.         var listItemEnum = collListItem.getEnumerator();
  18.         while (listItemEnum.moveNext()) {
  19.             var oListItem = listItemEnum.get_current();
  20.             ProductInfo += ‘\n\nID: ‘ + oListItem.get_id() +
  21.                 ‘\nTitle: ‘ + oListItem.get_item(‘Title’) +
  22.                 ‘\nDesc: ‘ + oListItem.get_item(‘Description’) +
  23.                 ‘\nPrice: ‘ + oListItem.get_item(‘Price’);
  24.         }
  25.         alert(ProductInfo.toString());
  26.     }
  27.     function onQueryFailed(sender, args) {
  28.         alert(‘Request failed. ‘ + args.get_message() +
  29.             ‘\n’ + args.get_stackTrace());
  30.     }
  31. </script>​
  32. <input type=”button” value=”Get Products” onclick=”GetProducts()”/>

Copy the above code in a Content editor web part
Go to the SharePoint site and add a content editor web part.

Choose the Edit Source option and the HTML source window will pop up.

Copy the code mentioned in the previous step and paste it inside the HTML source window as follows. Click OK button and save the page.

Displaying the data
Click on the “Get Products” button and all the list items in the Products list will be displayed as an alert.


2 thoughts on “What is Client Object Model – CSOM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s