Tuesday, 3 December 2013

SharePoint App Tutorial

 SharePoint App Tutorial
Refhttp://blog.helloitsliam.com/Lists/Posts/Post.aspx?ID=113

So in part 1​ we looked at some basic concepts of creating a SharePoint 2013 Hosted App. In this post we will continue with our demonstration app and look to expand it further. We left off with a custom ribbon action that redirects to a page within the App Web and simply just uses the default code from the "App.js" to render your display name. As a recap the design we are looking for is to allow a user to select items from a list and then when they click the ribbon be redirected to the App Web and render a grid type view of just the selected items, which we learned from the last post we can get by using query string parameters. So to start we need to open the "App.js" file and look at the existing code.
  
This code is very straight forward, as it simple gets a context for SharePoint using the client object model, grabs the current web which in this case is the SharePoint site you clicked the ribbon button from and then gets the "Current User" which would be you right now. When the document is loaded which is checked with the following code:
  
A custom function called "getUserName()" is called which loads the current user and executes an asynchronous query which on success writes out the name that you see on the page.
  
So let's look at changing this to retrieve data about the SharePoint Site using the REST API that is now available in SharePoint 2013. First off we will need to add the following to the "Default.aspx" page markup.
  
Now we need to remove the current code from "App.js and add the following section first.
  
This code declares two variables, then loads them upon document ready from the query strings that are passed in the URL. It then loads a JavaScript files that is used to execute code, and we make a call to a custom method we create called "getSelectedList". The "getSelectedList" method for now is not actually getting a list, it will be retrieving the SharePoint Site Title, confusing I know but easier than changing all the code each time.
  
This method makes a call to the "_api" URL of SharePoint which an endpoint for the web services / WCF for the client object model components of SharePoint 2013. To read more about this, read the details on MSDN here:
In our custom method you will see that we have a success and error call to two methods shown below:
  
These methods simply either render an error or the SharePoint Site Title onto the "Default.aspx" page. We also have a helper method for parsing the query strings so we can use them through the code.
  
Now we have all the plumbing done we should be able to build and deploy our solution and it should render as shown below once we click the ribbon button.
  
If we debug the code by adding a break point in the "App.js" we can see that we are getting an "Access Denied" error.
  
  
This means that the current account is not allowed to access the root web properties. This is by design and this brings me to another consideration when designing a SharePoint 2013 Hosted App. You need to work out the permission level that you want to assign so when it is deployed the right trust level is set ready for use. To set the permission, double click the "AppManifest.xml" file in Visual Studio. Select the "Permissions" tab and you will be presented with the following screen:
  
Set this screen to the following:
  
Rebuild the solution deploy using "F5" as always from Visual Studio. This time when you deploy you get stopped halfway through and are asked to trust it.
  
Select the "Trust It" button and the page will load as shown below:
  
So the key here is that by design the end user who is accessing your application is NOT allowed to perform certain functions unless the trust level has been set in the App and accepted during installation. So now we have it working with SharePoint Site data, now let's change the code a little to retrieve a specific list from the site. First off ensure you have an announcements list with some items within the SharePoint Site you are using.
Modify the "Default.aspx" page to now have the following code, you can remove the last markup we added.
  
We now need to modify the custom function we wrote to now use the following:
  
The success and failure method also need to be changed slightly too.
  
As before now build and deploy using Visual Studio so we can debug if needed. Accept the "Trust" and it should render as shown below:
  
Now that we are able to render the values let's make some changes to the code so it will work for any list that we decide to click the ribbon button from. To do this lets first look at the URL:
If we look in the link above we have the query string from the last post already in there, which is "SelectedList={B6F5FCC8-5102-4F1B-9F24-D8929162CB51}", this means we already have the list ID so if we modify the code a little we should be able to use this dynamic value, instead of hard coding "Announcements". To achieve this firstly add the following to "App.js".
  
This will get us the list ID loaded into a variable we can use throughout the code. Now we need to modify the "getSelectedList" method code to be the following:
  
Once complied and deployed you are then able to click any list and it should render details as shown below.
Announcement List
  
Contacts List
  
So now we have the code working for any list now we need to look at restricting the list of items that is renders to the selected items that are passed in the URL. We need to change the code in the "App.js".
  
Next we need to change the rendering code to be the following:
  
Now build and deploy from Visual Studio so you can debug and you should now be able to select items within the list and when the page renders it will only display the selected items. Of course there are better way of doing this but we will save that for another day.
In the next post we will look at the options available for rendering more than just "Title" and "Body" fields and actually create the grid view we need.

Thursday, 28 November 2013

Sharepoint 2010 Search configuration

In this article I am describing how to configure Search in SharePoint 2010.

1. Go to SharePoint Central Administration.

2. Click on Application management then select Manage Service application.
 
ConSerShare1.gif

3. Click New and select Search Service Application
 
ConSerShare2.gif

4. Give a name for your Service application.

5. Select Search Service account or register new Service account in the drop down.

6. Better create a new application pool for your Search service as shown below.
 
ConSerShare3.gif

7. Once done Click OK.
 
ConSerShare4.gif

8. It will take some time to configure the service.

9. Once configured correctly you will see the service created like below.
 
ConSerShare4.1.gif

10. Click on the Search Service Application 1 that we create now.

11. Select Content Source. 

ConSerShare5.gif

12. Click on the Local SharePoint Site.
 
ConSerShare6.gif

13. Add the Web applications that you need to put in Search Services as shown below.
 
ConSerShare7.gif

14. You have to configure Full and incremental crawl schedules in the preceding screen.

15. Now go back and start a Full crawl.
 
ConSerShare8.gif

16. You will get the following screen.
 
ConSerShare9.gif

17. Even though you have done all these steps you may get some error while searching "The search request was unable to connect to the Search Service".

18. To avoid this you have to perform the following steps.

19. Go to Application management and select Configure Application Association as shown below.
 
ConSerShare10.gif

20. Click on your application.

21. From the "Edit the following group of connections" drop down select Custom.

22. Associate your search service with your web application.

ConSerShare11.gif

23. If you done this step you may have to start the crawl once again.
 

Thursday, 24 October 2013

Creating UserToken in Sharepoint

SPUserToken userToken = SPContext.Current.Web.AllUsers["domain name\\UserLoginId"].UserToken;
                using (SPSite site = new SPSite(SPContext.Current.Site.ID, userToken))
                {
                    SPWeb myweb = site.OpenWeb();
                    Guid docsid=new Guid(hiddenDocumentLibraryName.Value);
                    SPDocumentLibrary myDocLib = (SPDocumentLibrary)myweb.Lists[docsid];
                    SPListItem items=                                               myDocLib.Items.GetItemById(Convert.ToInt32(hiddenDocumentId.Value));
                    myweb.AllowUnsafeUpdates = true;
                    items.File.CheckOut();
                 
                }

Monday, 23 September 2013

Passing filter values on the URL to PerformancePoint Services web parts

Although this pattern’s as old as the web, you asked us to make PerformancePoint dashboards work with it. In SharePoint 2010 it works!
The steps are the same whether you deploy a page that uses only PerformancePoint web parts using Dashboard Designer, or build a more complex page using SharePoint web or SharePoint Designer.
  1. Understand how Query String (URL) Filter works
  2. Build the content & page
  3. Add Query String (URL) Filter web parts for each attribute you want to control on the URL
  4. Connect each filter web part to the web parts you want it to affect
To illustrate we’ll add URL filtering to a simple dashboard that has one PerformancePoint Report web part.
We will specify Geography on the URL:

2

1. Understand how Query String (URL) Filter works

The Query String (URL) Filter accepts the name and value parts, separated by an equals sign, and multiple filters separated by a semi-colon (this is quite common and not unique to SharePoint.)
3
You’ll have full control over the name part. We’ll explain how to specify it in the next step.
The value depends on the web part the value’s passed to. In the case of PerformancePoint Services web parts you’ll need a member unique name for the data source(s) referenced by the content.
Unfortunately a Query String (URL) filter and another filter can’t be synchronized with the same consumer field of a web part. Although you can connect more than one filter web parts to the same consumer field, this won’t result in the multiple filters being synchronized with the field. You will have to choose one mode or the other.

2. Build the content & page

We laid out the analytic chart “Local Sales Report” in Dashboard Designer. The only detail of interest is we put the Geography hierarchy in the Background well so we can connect filters to it in SharePoint.
If you’re going to do URL filtering we recommend you do your page editing outside Dashboard Designer. Dashboard Designer’s web part page deployment is very simplistic and removes all changes not possible within Dashboard Designer, including URL filtering.
For this example we didn’t use Dashboard Designer at all except to create “Local Sales Report.” We started with a blank web part page, added the PerformancePoint Report web part, then configured it to show “Local Sales Report.”

3. Add Query String (URL) Filter web parts for each attribute you want to control on the URL

For each query string parameter you want the page to have:
  1. In SharePoint web put the page in edit mode (Select the Page tab in the ribbon, and click Edit Page.)
  2. Click Add a Web Part in any zone.
  3. In the Categories column, select Filters
  4. Select Query String (URL) Filter and click Add 4
  5. In the new web part’s web part menu, click Edit Web Part:

     5
  6. In the tool pane fill out Query String Parameter Name. You may also want to fill out Default Value, so that when the parameter’s not specified a reasonable default’s used.

     6
  7. Click “OK at the bottom of the tool pane.

4. Connect each filter web part to the web parts you want it to affect

For each web part you want the filter to affect:
  1. From the web part menu on the filter web part select: Connections -> Send Filter Values To –> then the destination web part:
    7
  2. The Choose Connection dialog appears. You’ll have 2 choices for Connection Type; either will work in this case.
  3. Under Configure Connection select the field you’d like to filter. The options vary based on the web part, and in the case of PerformancePoint web parts, on the content. Here we select the Geography hierarchy we added to “Background” in Local Sales Report:
    8
  4. Click Finish.
  5. You can now click “Stop Editing”, and try it out:
9
 

Wednesday, 3 July 2013

Hide Quick Launch using Javascript

Add bellow script in page

<style>

#s4-leftpanel {
DISPLAY: none
}
.s4-ca {
MARGIN-LEFT: 0px
}</style>

Thursday, 16 May 2013

Backup/Restore of SharePoint 2010 site Collection using Power Shell

In this article I am showing you how to perform backup/restore operation using Power Shell 

1. On the Start menu, click All Programs.
2. Click Microsoft SharePoint 2010 Products.
3. Click SharePoint 2010 Management Shell.
4. At the Windows Power Shell command prompt type the following command:
Image1.gif

5. You will get a Power shell command prompt like below
Image2.gif

6. In SharePoint 2010, Power Shell command Backup-SPSite is used for taking backup

7. Please see the screen shot for the backup Power Shell command

8. Backup-SPSite -Identity http://ServerName:port -Path "c:\backup\file.bak"

 Image3.gif

9. If you want to overwrite a previously used backup file, use the Force parameter. You can use the NoSiteLock parameter to keep the read-only lock from being set on the site collection while it is being backed up. However, using this parameter can allow users to change the site collection while it is being backed up and might lead to possible data corruption during backup. 

10. Once this done you will get the backup.

11. Next you have to create site collection then use the below command to restore the backup that we currently taken.

12. Restore-SPSite -Identity http://Servername:port -Path "c:\backup\file.bak" -force

Image4.gif

13. I am using force command because I want to overwrite the existing site collection that I created now.

Friday, 1 February 2013

Using the SharePoint 2010 Client Object Model in JavaScript


  1. Retrieve a ListItem
  2. Create a ListItem
  3. Update a ListItem
  4. Delete a ListeItem

Why use the SharePoint Client Object Model for JavaScript?

Using the COM allows developers to create a web page that can interact with SharePoint without requiring a page refresh. In the background, the page uses JavaScript to communicate with SharePoint via the COM to retrieve or update data in SharePoint. JavaScript can then update the page to reflect the updated data from SharePoint.

Accessing SharePoint

The first thing to note about the COM with JavaScript is that it is disconnected from SharePoint in the sense that in order to retrieve or update data in SharePoint, asynchronous calls to the server must be made. Because of its asynchronous nature, the page can continue to be responsive to the user while the data is being retrieved or updated in the background. This can be both an asset and a liability if not handled properly.
In order to access the COM in a webpage, a reference to the JavaScript file containing the COM code must be included. There are 3 JavaScript files which contain the code for the COM: SP.js, SP.Core.js, and SP.Runtime.js. SharePoint provides the SharePoint:ScriptLink server control tag for referencing JavaScript files. Using the ScriptLink control will:
  • assure that the JavaScript file is loaded only once
  • assure that dependency files are also loaded
In a SharePoint Application page, the ScriptLink tag should be declared within the PlaceHolderAdditionalPageHead Content Placeholder.
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server" />
   <SharePoint:ScriptLink Name="SP.js" LoadAfterUI="true" runat="server" />
</asp:Content>

How to retrieve a ListItem from a SharePoint List

The following code sample shows how to connect to create a connection to SharePoint and access the Root Web.
var ListItem;

function GetListItemById(listName, listItemId)
{
   var SPContext = new SP.ClientContext.get_current();
   var web = SPContext.get_web();

   var list = web.get_lists().getByTitle(listName);
   ListItem = list.getItemById(listItemId);

   SPContext.load(ListItem, "Id", "Title");
   SPContext.executeQueryAsync(GetListItemById_Success, GetListItemById_Fail);
}

function GetListItemById_Success(sender, args)
{
   var id = ListItem.get_id();
   var title = ListItem.get_item("Title");
   alert("Updated List Item: \n Id: " + id + " \n Title: " + title);
}

// Display an appropriate error message
function GetListItemById_Fail(sender, args)
{
   alert("GetListItemById Failed. \n" + args.get_message() + "\n" + args.get_stackTrace());
}
Let's break down the code. First, we declare a global variable which will contain the data returned from SharePoint via the COM. Since we must use asynchronous calls to SharePoint, the data must be stored somewhere that is accessible by the CallBack function that will be called once the data has been retrieved from SharePoint.
var SPContext = new SP.ClientContext.get_current();
Next, the code creates an object which will facilitate the communication between JavaScript and SharePoint. This is done by accessing the current property of the SP.ClientContext object by calling the get_current() method.
Note: In JavaScript, COM properties are access by calling a function which is named "get_" + the name of the property. For example, the id property which all COM objects have is accessed by calling the object's get_id() method.
var web = SPContext.get_web();
var list = web.get_lists().getByTitle(listName);
Next, the Root Web property of the SPClientContext object can be accessed by calling the get_web() method. The Web has a SharePoint Lists collection property which is accessed by calling get_lists() method.
ListItem = list.getItemById(listItemId);
Then to identify the specific List, a call is made to the getByTitle() method passing in the name of the List. Finally, to identify a specific List Item in the List, a call is made to the getItemById() method passing in the List Item's ID value.
At this point, there still has been no data retrieved from SharePoint. The code has simply been identifying which data will be retrieved.
Since it is the List Item data that will be retrieved and accessed in the CallBack function, it must be assigned to a global variable that can be accessed later by the CallBack function.
SPContext.load(ListItem, "Id", "Title");
Now that the specific data to be retrieved has been identified, we need to tell it specifically what data to return. It is the client context object's load() method which specifies which data will be retrieved. The load() method's first parameter is the object to return data for, followed by the names of the List Fields to return.
Note: While it is possible to call the load() method without specifying the List Fields, this will return data for every Field in the List, including hidden fields. Since loading all of the List Fields can add 10 times the amount of data needed, it will always be in your best interest to specify the specific Fields to load.
SPContext.executeQueryAsync(GetListItemById_Success, GetListItemById_Fail);
Finally, a call to the executeQueryAsync() method will initiate the actual call to the server. This method takes the 2 CallBack functions to call. The first will be called if the data is successfully retrieved from SharePoint, while the second will be called in the case there was an error retrieving the data.
function GetListItemById_Success(sender, args)
function GetListItemById_Fail(sender, args)
Each CallBack function can take the sender and args parameters which return additional information about the results of the server call.
var id = ListItem.get_id();
var title = ListItem.get_item("Title");
In the "success" CallBack function, the objects and their properties which were specified in the load() method can now be accessed using the object's get_item() method passing in the name of the field.

How to create a ListItem in a SharePoint List

function CreateListItem(listName, title)
{
   var SPContext = new SP.ClientContext.get_current();
   var web = SPContext.get_web();

   // Create a new List Item

   var SPContext = new SP.ClientContext.get_current();
   var list = web.get_lists().getByTitle(listName);
   ListItem = list.addItem(new SP.ListCreationInformation());
   ListItem.set_item("Title", title);
   ListItem.update();

   SPContext.executeQueryAsync(CreateListItem_Success, CreateListItem_Fail);
}

function CreateListItem_Success(sender, args)
{
   alert("New List Item Created");
}

// Display an appropriate error message
function CreateListItem_Fail(sender, args)
{
   alert("CreateListItem Failed. \n" + args.get_message() + "\n" + args.get_stackTrace());
}
This example is very similar to the previous one, so I will only point out the differences.
ListItem = list.addItem(new SP.ListCreationInformation());
ListItem.set_item("Title", title);
Once the List has been identified, a new List Item is created and added to the List. This is done by creating an instance of the SP.ListCreationInformation class. Then the properties of the new List Item object are set by using the set_item() method passing in the name of the property and the value to set it to.
ListItem.update();
SPContext.executeQueryAsync(CreateListItem_Success, CreateListItem_Fail);
The update() method is called to tell SharePoint to save the changes that were made. Finally the call to executeQueryAsync() method is made to send the request to SharePoint.
Note: In this example, the load() method was not called, and therefore there will not be any SharePoint data accessible in the "success" CallBack function. However, the load() method could have been called. In which case, the newly created List Item would be available.

How to update a ListItem in a SharePoint List

function UpdateListItem(listName, title)
{
   var SPContext = new SP.ClientContext.get_current();
   var web = SPContext.get_web();

   var list = web.get_lists().getByTitle(listName);
   ListItem = list.getItemById(listItemId);

   // Update an existing List Item
   ListItem.set_item("Title", title);
   ListItem.update();
   SPContext.executeQueryAsync(UpdateListItem_Success, UpdateListItem_Fail);
}

function UpdateListItem_Success(sender, args)
{
   alert("List Item Updated");
}

// Display an appropriate error message
function UpdateListItem_Fail(sender, args)
{
   alert("UpdateListItem Failed. \n" + args.get_message() + "\n" + args.get_stackTrace());
}
Updating a List Item is simply a combination of identifying an existing List Item as seen in the first example and then setting the property values of the List Item as seen in the second example.
Again, if we actually want to access the values of the List Item as stored in SharePoint after it is updated, a call to the load() method could be made specifying the objects and their fields to retrieve from SharePoint.

How to delete a ListItem from a SharePoint List

function DeleteListItem(listName, title)
{
   var SPContext = new SP.ClientContext.get_current();
   var web = SPContext.get_web();

   // Retrieve the List Item
   var list = web.get_lists().getByTitle(listName);
   ListItem = list.getItemById(listItemId);

   // Delete the List Item
   ListItem.deleteObject();
   SPContext.executeQueryAsync(DeleteListItem_Success, DeleteListItem_Fail);
}

function DeleteListItem_Success(sender, args)
{
   alert("List Item Deleted");
}

// Display an appropriate error message
function DeleteListItem_Fail(sender, args)
{
   alert("DeleteListItem Failed. \n" + args.get_message() + "\n" + args.get_stackTrace());
}
Again, deleting a List Item is very similar. In order to delete a List Item, the List Item must first be identified as in the first example and then a call made to its deleteObject() method to tell SharePoint to delete the List Item. Finally a call to the executeQueryAsync() method to send the updates to SharePoint.

SharePoint 2010 Client Object Model

Introduction

In this article I would like to discuss about the Client Object Model feature of SharePoint 2010.

Overview

Client Object Model is a new feature of SharePoint 2010. It provides features to program against a SharePoint site using .NET Managed Code or JavaScript.
The Client Object Model provides almost all the programming features of the Server Object Model plus advantages in deployment. The Client OM (Client Object Model) is being used as the core programming aid for SharePoint 2010 and thus widely used in the market.

Advantages

  1. Less Deployment Hassles: Using Client OM, you do not need to install the components required by the Server Object Model. Thus Client OM provides much ease to the end user.
  2. Language Flexibility: We can use the following languages to work with the Client OM:
    1. Microsoft .NET
    2. Silverlight
    3. ECMA Script (JavaScript /JScript)
  3. 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 return a JSON response which is converted to the appropriate Object Model.

Supported Languages

Following are the programming language/platforms supported for Client Object Model:
  • .NET Languages (C#, VB.NET etc.)
  • Silverlight
  • Scripting Languages (JavaScript, Jscript)

Core Assemblies

There are two assemblies to be referred for working with the Client Object Model.
  1. Microsoft.SharePoint.Client.dll
  2. 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#, comparing with classes of the 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: SPSite in the Server Object Model is represented in the Client OM as Site with namespace Microsoft.SharePoint.Client.
Client Object Model
Server Object Model
Microsoft.SharePoint.Client.ClientContext
SPContext
Microsoft.SharePoint.Client.Site
SPSite
Microsoft.SharePoint.Client.Web
SPWeb
Microsoft.SharePoint.Client.List
SPList

Example

Following is an example of retrieving a list from the server using 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);
I should remark something about the above code:
  • Even though there are multiple calls, they are not sent to the server until ExecuteQuery() is called.
  • Network round trips between the client and server are reduced by combining multiple calls into one.
  • Object Identity is used to setup 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 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;
On my machine, the data retrieved is shown below:

2. Update List Items

Here I would like to show the modification code. All the titles are appended with two asterisks whose IDs are 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();
After executing the query, please refresh the data grid using the Get Data button. You can see the following result.

You can see that the Titles are modified for those with even number IDs.

3. Get By Row Limit

Here we can experiment with the RowLimit 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 rows while doing 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();
You can see that the RowLimit is set to 3. On executing the query and displaying the results to a data grid, you can see three items as shown below.

4. Get By Search Criteria

Now we can try selecting the list items using the search criteria. Here we are trying to get the items of 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();
On executing the code above, you will get the results filtered by the Status field.

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.
On executing the above code and retrieving the results, you can see the output as below:

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 can see how to update 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();
On executing the code, you can see that the last item was updated.

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 one property value for an item with 10 properties? There will be unwanted transferring of 9 columns. Here we can see how to specify only the needed 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 as 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 an 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 them.

When to use Server Object Model?

We can use it on the SharePoint server where the Server Object Model binaries are available. Typical example would be inside Web Parts / Workflows.

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 Forms application in a client machine.

http://www.codeproject.com/Articles/399156/SharePoint-2010-Client-Object-Model-Introduction