Accessing SharePoint 2010 Data with the .NET Client Object Model

SharePoint Visual How To

Summary:  Learn how to use the Microsoft SharePoint 2010 managed client object model to read and write data in SharePoint sites from Microsoft .NET Framework–based applications.

Applies to: SharePoint Foundation 2010 | SharePoint Server 2010 | Visual Studio | Visual Studio 2008 | Visual Studio 2010

Provided by:  Andrew Connell, MVP, Critical Path Training

Overview

With each release of Microsoft SharePoint, developers ask for additional web services to simplify reading and writing SharePoint site data from custom code not on the server that is running SharePoint. Instead of building more and more web services, Microsoft introduced in SharePoint 2010 the client object model, which contains a familiar subset of frequently used objects. The client object model is very similar to the SharePoint server object model. This SharePoint Visual How To demonstrates how to use the SharePoint 2010 .NET client object model.

Code It

In your project, add references to the two required assemblies that compose the .NET client object model. These two assembles (Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll) are located in the ISAPI folder of %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\.

Connect to SharePoint and get some data. The example in the video demonstrates getting a list of product categories from a SharePoint list. All communication centers around the ClientContext object. This object is responsible for connecting to the server and sending all queued commands for processing.

After you use either the ClientContext.Load method or the ClientContext.LoadQuery method to queue instructions, a call to the ClientContext.ExecuteQuery method triggers the communication back to the server. The sample application in this Visual How To is a Windows Presentation Foundation (WPF) application. Unlike the Microsoft Silverlight client object model, the .NET client object model does not include an asynchronous version of the ExecuteQuery method. Therefore, to create a user-friendly application, use the ThreadPool.QueueUserWorkItem method to communicate with SharePoint on a background thread. When the thread finishes, it uses the Dispatcher to send a delegate back to the initiating thread to update the user interface (UI). This technique keeps the UI from locking up while waiting for the ExecuteQuery method to complete.

ClientContext  _clientContext = new ClientContext("http://intranet.wingtip.com");
[...]
private void MainWindow_ConnectedStatusChanged(object sender, EventArgs e)
{
    if (this.IsConnected)
    {
        // Start async call on background thread
        // to avoid blocking UI thread.
        ThreadPool.QueueUserWorkItem(LoadProductCategories);
    }
}
private void LoadProductCategories(object state)
{
    SP.List categoryList = _clientContext.Web.Lists.GetByTitle("Product Categories");

    SP.CamlQuery query = new SP.CamlQuery();
    query.ViewXml = 
      "<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy></Query></View>";
    _productCategories = categoryList.GetItems(query);

    _clientContext.Load(_productCategories);
    _clientContext.ExecuteQuery();

    // Start the UI work on another thread.
    this.Dispatcher.BeginInvoke(new Action(LoadProductCategoriesUIUpdater), 
                                DispatcherPriority.Normal);
}
private void LoadProductCategoriesUIUpdater()
{
    if (_productCategories != null)
        ProductCategoriesListBox.ItemsSource = _productCategories;
}

Adding List Items

Another useful technique is to add items to SharePoint lists. This is done by using creation information objects—for list items, the ListItemCreationInformation object. By using this object, you can create a list item, update the fields of the new list item, and save the changes.

List products = _clientContext.Web.Lists.GetByTitle("Products");
ListItemCreationInformation newProductInfo = new ListItemCreationInformation();

ListItem newProduct = products.AddItem(newProductInfo);

// Dialog is a child dialog window that displays a form with a few controls.
newProduct["Title"] = dialog.ProductNameTextBox.Text;
newProduct["Product_x0020_Number"] = 
  dialog.ProductNumberTextBox.Text;
newProduct["Price"] = dialog.ProductPriceTextBox.Text;
FieldLookupValue fieldValue = new FieldLookupValue();
foreach (ListItem item in Global.ProductCategories)
    if (item["Title"].ToString() == 
      dialog.ProductCategortyComboBox.SelectedItem.ToString())
    {
        fieldValue.LookupId = item.Id;
    }
newProduct["Category"] = fieldValue;

newProduct.Update();

// Update the user interface by calling back to the original thread.
this.Dispatcher.BeginInvoke(new Action(OnProducteditorAddUIUpdater), 
  DispatcherPriority.Normal); 
Read It

The client object model in SharePoint 2010 simplifies interacting programatically with SharePoint sites from custom code that is not running on the same server as SharePoint 2010. This Visual How To demonstrates how to use the .NET client object model to create a WPF application that communicates directly with SharePoint. Instead of using the traditional web services approach, the client object model provides a rich, SharePoint-specific object model that closely matches the SharePoint 2010 server object model.

See It

Watch the video

Length: 00:21:36

Click to grab code

Grab the Code

Explore It

About the Author

MVP ContributorMVP Andrew Connell is an author, instructor, and co-founder of Critical Path Training, a SharePoint education-focused company. Andrew is a six-time recipient of Microsoft’s Most Valuable Professional (MVP) award (2005-2010) for Microsoft Content Management Server (MCMS) and Microsoft SharePoint Server. He authored and contributed to numerous MCMS and SharePoint books over the years including his book Professional SharePoint 2007 Web Content Management Development by WROX. Andrew speaks about SharePoint development and WCM at conferences such as Tech-Ed, SharePoint Connections, VSLive, SharePoint Best Practice Conference, SharePoint Evolutions Conference, Office Developer Conference, and Microsoft SharePoint Conference in the United States, Australia, England, and Spain. Andrew blogs at Andrew Connell Blog and on Twitter @andrewconnell.