Friday, June 15, 2012

Working with SharePoint Client Object Model

In this article we will see some sample codes to work with websites using SharePoint client object model. You can aslo see my last article on how to create list using object model in SharePoint.

To communicate with a SharePoint 2010 website using client object model we need to use the class ClientContext. This class takes the site url as a parameter to the constructor.

In the below demo we will see how to retrieve website properties like Title, Descritpion etc using client object model.

To use client object model we have to write the using statement.
using Microsoft.SharePoint.Client;
Example-1:
ClientContext clientContext = new ClientContext("http://[SharePoint Site URL]");

Web website = clientContext.Web;

clientContext.Load(website); //This will load the web site.

clientContext.ExecuteQuery();

string Title = website.Title;

string Description = website.Description;

Here in the above ExecuteQuery() will load all the properties of the web. But If you want to load any specified properties then you can write like below:
clientContext.Load(
                website ,
                website => website.Title,
                website => website.Description);

Example-2:
Below code sample we will see how to update the Title of a web site using client object model.

           ClientContext clientContext = new ClientContext("http://[SharePoint 2010 Site URL]");

            Web website = context.Web;
            website.Title = "My New Title";          

            website.Update();

            clientContext.ExecuteQuery(); //This method will save the updated details.

Example-3:
In the last code sample we will discuss how to delete a custom list using SharePoint 2010 client object model.

           ClientContext clientContext = new ClientContext("http://[SharePoint 2010 Site URL]");

            Web website = clientContext.Web;

            List objList = website.Lists.GetByTitle("My Custom List");

            objList.DeleteObject();

            clientContext.ExecuteQuery();