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:

Microsoft.SharePoint.Client.Silverlight.dll
Microsoft.SharePoint.Client.Silverlight.Runtime.dll

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 = "http://moss.contoso.com/sites/MySpace";

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

     //Executes the current set of data retrieval queries and method invocations
     ctx.ExecuteQuery();

     foreach (List list in site.Lists)
     {
          listBox1.Items.Add(list.Title);
     }
}

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

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

     //Get items for the list

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

     //Display Announcements Title
     foreach (ListItem item in lc)
     {
          listBox2.Items.Add(item["Title"].ToString());
     }
}

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: