Pages

Feb 4, 2011

SharePoint 2010: Getting Started With Client Object Model

Along with the Server Object Model, SharePoint 2010 introduces new set of API called Client Object Model

Refer to my blog post SharePoint 2010: Introducing the Client Object Model to get to know more about Client Object Model.

The Client Object Model (OM) is a new programming interface for SharePoint 2010 where code runs on a user’s client machine against a local object model and interacts with data on the SharePoint Server.

Lets get started on our ‘Hello Word’ Client Object Model console application.

Step 1 – Reference the Client Object Model

You need to reference two dlls which are available at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI

1. Microsoft.SharePoint.Client

2. Microsoft.SharePoint.Client.Runtime

image

Add the using namespace for Microsoft.SharePoint.Client

using Microsoft.SharePoint.Client;

Step 2 – Create the Client Context

[ We will use the Main function to write our piece of code ]

You need to first create a context to the SharePoint site:

ClientContext context =
new ClientContext(http://);
Step 3 – Create Your Query

Here is the next block of code, explanations will follow below:

Web site = context.Web;
context.Load(site, s => s.Title);

As you can see, we are querying for what we require and nothing else will be returned. In our code, we pass the site to the context, but say we want to query only the property Title.

Step 4 – Execute Your Query

Below is the code to execute the query:

context.ExecuteQuery();

The ExecuteQuery() method is a synchronous method call.

Step 5 – The Output

Below is the output:

image

Another Query Example

ListCollection lists = site.Lists;
IEnumerable listsCollection =
context.LoadQuery(lists.Include(
l => l.Title,
l => l.Id));

The above code queries all the Lists in the site, but only returns the Title and the Id properties.

In the next post, we will see how we can query asynchronously.

No comments: