Using SharePoint client object model

SharePoint 2010 has powerful client object model that you can use to write external applications that use SharePoint data. In this posting I will show you how to get data from lists using client object model and how to optimize queries to save some bandwidth.

Client object model reminds me a little bit some kind of mix of SharePoint API, Entity Framework and LINQ. I like it because it is more convenient to use than plain SharePoint API.

Some notes about client context

There are couple of important things you should know:

  1. SharePoint client object model uses client context object that is operational bridge head between your code and data in SharePoint.
  2. Context gathers all queries and modifications and completes requested operations when ExecuteQuery() method is called.

In this means we can build up our communication with SharePoint by logical units (we are getting close to transactions). You can see similar pattern in Entity Framework – there is data context that care of querying and persisting of objects. But still data context in Entity Framework and client context in SharePoint client object model are different things.

Adding items to list

It is easy to add new items to SharePoint list using client object model.


private void AddNewListItem()

{

    var clientContext = new ClientContext(“http://sp2010srv:9000/”);

    var list = clientContext.Web.Lists.GetByTitle(“Announcements”);

 

    var param = new ListItemCreationInformation();

 

    var newItem = list.AddItem(param);

    newItem[“Title”] = “This my new announcement”;

    newItem[“Body”] = “This is the body of announcement”;

    newItem.Update();

 

    clientContext.ExecuteQuery();

}


In this code we are saying that we want to use list called Announcement and we want to add new item to this list. After adding new item we assign values to Title and Body fields and then we call ExecuteQuery() to send changes to SharePoint.

Querying lists

Querying of lists is similar to what we are doing using SharePoint API – we are using CAML queries but we will write them fully out. Here is the example:


private static void QueryList()

{

    var clientContext = new ClientContext(“http://sp2010srv:9000/”);

    var list = clientContext.Web.Lists.GetByTitle(“reuters”);

  

    var query = new CamlQuery();

    query.ViewXml = @”

                     <View>

                         <Query>

                             <Where>

                                <Contains>

                                    <FieldRef Name=’Title’ />

                                    <Value Type=’Text’>announcement</Value>

                                </Contains>

                            </Where>

                        </Query>

                     </View>;
 

    var listItems = list.GetItems(query);

 

    clientContext.Load(listItems);

    clientContext.ExecuteQuery();

  

    foreach (var item in listItems)

    {

        Console.WriteLine(item.FieldValues[“Title”]);

    }

}


One thing to notice – query fails with no errors if you don’t specify Query tags. All rows are returned and no exceptions are thrown. Not sure why this kind of design decision was made.

Getting better performance

You can optimize the amount of data that is read from SharePoint by specifying exactly what data you need. By default, all data you ask is retrieved so objects are fully initialized. You hardly need it. Usually you need only a subset of data that client context is able to bring to you.

Let’s see the example where we query announcements list and ask back only small set of fields.


clientContext.Load(listItems,

                        l => l.Include(

                                    m => m[“Title”],

                                    m => m.Id

                        )

                   );

clientContext.ExecuteQuery();


This code asks only Title and Id fields for list items and therefore uses less traffic. Same way you can set loading options for many other objects.

Conclusion

SharePoint client object model is convenient and powerful API that helps us easily and effectively use data in SharePoint. Besides manipulating data it also allows to create, delete and modify other SharePoint objects.


One thought on “Using SharePoint client object model

  • Shardul pasare says:

    Hi, I am using below code to get list item properties in javascript.

    when we select list item in sharepoint list. It will call below function internally to get properties of targetListItem. Some item i am getting uniqueItemID and documentGuid null. If i click second time it display property. Can you please help regarding this

    var Listitem = selectedItems[0].id;
    var targetList = clientContext.get_web().get_lists().getById(listId);
    targetListItem = targetList.getItemById(Listitem);
    clientContext.load(targetListItem);

    function onQuerySucceeded(sender, args) {
    try {
    var listItemInfo = ”;

    uniqueItemID = targetListItem.get_item(‘UniqueId’);
    documentGuid = targetListItem.get_item(‘DocumentGUID’);

    }
    catch (error) {

    }

    }

Leave a Reply

Your email address will not be published. Required fields are marked *