Friday, 4 July 2014

Client Object Model is a new feature of SharePoint 2010

Client Object Model is a new feature of SharePoint 2010
.Net Managed Code
SilverLight
JavaScript
Advantages
Less Deployment Hassles: Using the Client OM, you do not need to install the components required by Server Object Model. Thus the Client OM provides significant conveniences for the end user.
Language Flexibility: We can use the following languages to work with the Client OM:
a. Microsoft .Net
b. Silverlight
c. ECMA Script (JavaScript / Jscript)
Query Speed Optimizations: In the Client OM, reduced network traffic is attained using Query Optimizations. Thus the user will feel reduced round trips and other advantages like paged results etc.
How it works?
The Client OM works by sending an XML Request. The server will be returning a JSON response which is converted to the appropriate Object Model.
Supported Languages
The following are the programming languages/platforms supported for the Client Object Model:
.Net Languages (C#, VB.Net etc.)
Silverlight
Scripting Languages (JavaScript, Jscript)
Core Assemblies
There are 2 assemblies to be referrenxws for working with the Client Object Model:
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
These assemblies can be found in the 14 Hive folder:
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\ISAPI
Classes inside Client Object Model
In C#, when comparing with the classes of Server Object Model we can see that Client Object Model has similar classes with a suffix in the namespace and no SP prefix in the class name.
For example: An SPSite in the Server Object Model is represented in the Client OM as Site in the namespace Microsoft.SharePoint.Client.
Client Object ModelServer Object Model
Microsoft.SharePoint.Client.ClientContextSPContext
Microsoft.SharePoint.Client.SiteSPSite
Microsoft.SharePoint.Client.WebSPWeb
Microsoft.SharePoint.Client.ListSPList

Server.NET Managed and SilverlightJavaScript
Microsoft.SharePoint.SPContextMicrosoft.SharePoint.Client.ClientContextSP.ClientContext
Microsoft.SharePoint.SPSiteMicrosoft.SharePoint.Client.SiteSP.Site
Microsoft.SharePoint.SPWebMicrosoft.SharePoint.Client.WebSP.Web
Microsoft.SharePoint.SPListMicrosoft.SharePoint.Client.ListSP.List
Microsoft.SharePoint.SPListItemMicrosoft.SharePoint.Client.ListItemSP.ListItem
Microsoft.SharePoint.SPField (including major derived classes)Microsoft.SharePoint.Client.FieldSP.Field
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManagerMicrosoft.SharePoint.Client.WebParts.LimitedWebPartManagerSP.WebParts.LimitedWebPartManager
Example

The following is an example of retrieving a list from a server using the Client OM:
ClientContext context = new ClientContext("http://hp");
List list = context.Web.Lists.GetByTitle("Tasks");
context.Load(list);
context.ExecuteQuery();
Console.WriteLine(list.Title);
Console.ReadKey(false);
  • Even though there are multiple calls, they are sent to the server until ExecuteQuery() is called
  • Network round trips between client and server are reduced by combining multiple calls into one
  • Object Identity is used to set up the queries. Object Identities are those which refer to the Server Object Model. Object Identities are valid only for the current client context
More Examples with Client Object Model
Here I would like to list some of the examples using the Client Object Model. For starting with the examples, please do the following:
  1. Create a Windows Application
  2. Change the Target Framework to .Net 4.0
  3. Add reference to Microsoft.SharePoint.Client, Microsoft.SharePoint.Client.Runtime
Before continuing with the examples please ensure the site has valid data items in the Tasks list. We will be changing the data items during our session.
1. Get List Items
Here we are querying the list items of the Tasks list.
ClientContext context = new ClientContext(ServerText.Text);
List list = context.Web.Lists.GetByTitle("Tasks");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
ListItemCollection items = list.GetItems(query);
context.Load(list);
context.Load(items);
context.ExecuteQuery();
After executing the code, the result can be stored into a DataTable as shown below:
DataTable table = new DataTable();
table.Columns.Add("Id");
table.Columns.Add("Title");
foreach (ListItem item in items)
table.Rows.Add(item.Id, item["Title"]);
datagrid.DataSource = table;
2. Update List Items
Here I would like to show the modification code. All the Titles are appended with two asterisks whose Id are an even number.
ClientContext context = new ClientContext(ServerText.Text);
List list = context.Web.Lists.GetByTitle("Tasks");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
ListItemCollection items = list.GetItems(query);
context.Load(items);
context.ExecuteQuery();
foreach(ListItem item in items)
if ((item.Id % 2) == 0)
{
item["Title"] += "**";
item.Update();
}
context.ExecuteQuery();
3. Get By Row Limit
Here we can experiment with the Row Limit tag inside CAML queries. You can note that while accessing the list we are actually using a CAMLQuery class instance. Inside the query it is possible to set the RowLimit tag as well.
The RowLimit tag restricts the number of items retrieved from the server. Thus we can save a lot of bandwidth by reducing the volume of rows returned from the search.
ClientContext context = new ClientContext(ServerText.Text);
Web web = context.Web;
List list = web.Lists.GetByTitle("Tasks");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View><RowLimit>3</RowLimit></View>";
ListItemCollection listItems = list.GetItems(query);
context.Load(listItems);
context.ExecuteQuery();
4. Get By Search Criteria
Now we can try selecting the list items using search criteria. Here we are trying to get the items of the Status as "In Progress".
ClientContext context = new ClientContext(ServerText.Text);
List list = context.Web.Lists.GetByTitle("Tasks");
CamlQuery query = new CamlQuery();
query.ViewXml = @"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Status'/>
<Value Type='Text'>In Progress</Value>
</Eq>
</Where>
</Query>
</View>";
ListItemCollection listItems = list.GetItems(query);
context.Load(listItems, items => items.Include(
item => item["Id"],
item => item["Title"],
item => item["Status"]
));
context.ExecuteQuery();
5. Insert an Item
Here we can try inserting a new item into the Tasks list.
ClientContext context = new ClientContext(ServerText.Text);
Web web = context.Web;
List list = web.Lists.GetByTitle("Tasks");
ListItemCreationInformation newItem = new ListItemCreationInformation();
ListItem listItem = list.AddItem(newItem);
listItem["Title"] = "New Item Created through C#";
listItem.Update();
context.ExecuteQuery();
You can see that we are using a new class named ListItemCreationInformation along with the ListItem class. This information will be recorded and passed to the server once the ExecuteQuery() method is called.
6. Update an Item
The Update operation is next in the series of the CRUD pattern. Already we have seen updating the Title. Here you will see updating the Status.
ClientContext context = new ClientContext(ServerText.Text);
List list = context.Web.Lists.GetByTitle("Tasks");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
ListItemCollection listItems = list.GetItems(query);
context.Load(listItems);
context.ExecuteQuery();
ListItem item = listItems[listItems.Count - 1];
item["Status"] = "In Progress";
item.Update();
context.ExecuteQuery();
7. Delete an Item
Now we can try deleting an item from the List. Here is the code to achieve that.
ClientContext context = new ClientContext(ServerText.Text);
List list = context.Web.Lists.GetByTitle("Tasks");
ListItemCollection listItems = list.GetItems(new CamlQuery() { ViewXml = "<View/>" });
context.Load(listItems);
context.ExecuteQuery();
listItems[listItems.Count - 1].DeleteObject();
context.ExecuteQuery();
We need to call the DeleteObject() method of the item followed by the ExecuteQuery().
8. Reducing the Result Size by Specifying Properties
So what if you wanted only 1 property value for an item with 10 properties. There will be an unwanted transference of 9 columns. Here we can see how to specify only the necessary columns for an item.
ClientContext context = new ClientContext(ServerText.Text);
Web web = context.Web;
context.Load(web, w => w.Title);
context.ExecuteQuery();
MessageBox.Show("The title is: " + web.Title);
MessageBox.Show("Now trying to access a field not in Result Set (expect exception)");
try
{
MessageBox.Show(web.Description); // You will get Error here
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Here we can see that only the Title property has been specified for retrieval. Accessing the Description column throws an exception.
9. Reducing the Result Size in List
In the case of the list the problem is worse since there are n number of columns for the list. The result will be multiplied n times. So if we need only 1 column and retrieve 10 columns for a list of 1000 items, we end up getting 9 x 1000 unwanted column values.
So to specify the list columns in the Result Set the syntax will be slightly different.
ClientContext context = new ClientContext(ServerText.Text);
List list = context.Web.Lists.GetByTitle("Tasks");
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
ListItemCollection listItems = list.GetItems(query);
context.Load(listItems, items => items.Include(item => item["Id"]));
context.ExecuteQuery();
Please note the way Id is specified. While filling the results you should take care that only the Id column value is
accessed.
DataTable table = new DataTable();
table.Columns.Add("Id");
foreach (ListItem item in listItems)
table.Rows.Add(item.Id);
datagrid.DataSource = table;
10. Specifying Credentials
You can specify user Credentials while accessing the SharePoint server. The property Credentials is for this purpose.
ClientContext context = new ClientContext(ServerText.Text);
context.Credentials = new NetworkCredential("User", "Password");
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
MessageBox.Show(web.Title);
Please specify the correct user name and password of your site otherwise a Unauthorized Exception will be thrown.
So this concludes the article with Client Object Model examples for the most common scenarios. In the real world you will need much more complicated steps and I believe these will provide a base to achieve it.
When to use Server Object Model?
We can use it on the SharePoint server where the Server Object Model binaries are available. A typical example would be inside Web Parts / Workflows.
It will work only where sharepoint has installed. Mean sharepoint servers only. If you want to develop any custom code using server object model you have to install SharePoint in that System.
When to use Client Object Model?
We can use it from client machines where the entire SharePoint binaries are not available. A typical example would be from a Windows Form application in a client machine.
And when you want to get SharePoint data in your normal Asp.net application, you can use client object model.
If you have .Net application, you want to read/Update/Delete some data in SharePoint Site which is located in another system using .net application. Now you will use client object model.
Ref: http://www.c-sharpcorner.com/UploadFile/40e97e/sharepoint-2010-client-object-model-C-Sharp-silverlight-jav/
http://rajsharma-sharepoint2010.blogspot.com/2012/05/working-with-sharepoint-data-access.html