Friday, November 06, 2009

SharePoint Client Object Model

SharePoint Client Object Model is the new programming interface to access SharePoint data from a remote client machine.

Client OM unifies the programing model and can be called from JavaScript, .Net Code (Win Forms, Console App) or Silverlight Application.

Let’s program using the Client OM for a Win Forms application.

Add a reference to the following assemblies:


Add a reference to the following namespace:
using Microsoft.SharePoint.Client;

Add 2 list boxes and a button onto your form.

To populate the List and the List Items, add the following code to the button click event:

string siteURL = "";

using (ClientContext ctx = new ClientContext(siteURL))
     //Get List Names
     Web site = ctx.Web;

     //Executes the current set of data retrieval queries and method invocations

     foreach (List list in site.Lists)

//Get List Items from "Announcements" List
using (ClientContext ctx = new ClientContext(siteURL))
     string listTitle = "Announcements"; //listBox1.SelectedItem.ToString()
     Web site = ctx.Web;

     //Load List
                s => s.Lists.Where(l => l.Title == listTitle));
     List list = site.Lists[0];

     //Get items for the list

     CamlQuery query2 = new CamlQuery();
     ListItemCollection lc = list.GetItems(query2);

     //Display Announcements Title
     foreach (ListItem item in lc)

Note that you need to first Load(), and only then call ExecuteQuery().
Accessing the list item without calling Load and ExecuteQuery throws CollectionNotInitializedException.

No comments: