Monday 7 July 2014

Accessing SharePoint 2010 Data with the .NET Client Object Model

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.
ClientContext _clientContext = new ClientContext("http://SP");
[...]
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 =
"";
_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;
}
----------------------------------------------------
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);
Ref:http://msdn.microsoft.com/en-us/library/gg277498.aspx