Using the SharePoint 2010 Client Object Model - Part 3
In the first two parts of this posting I described the pattern you can use to retrieve data with the client object model (“client OM”). I showed how to use the same pattern to retrieve both a set of lists, as well as data contained within a single list. In this post we’ll talk about ways that we can create and use filters when querying for data via the client OM.
I won’t rehash our pattern all over again. Suffice to say, it’s exactly the same, and the only part we are playing with here is step 2 – creating the statement to return the data and selecting which fields to return. Creating the connection and executing the query remain the same:
//create the connection
ClientContext ctx = new ClientContext("https://foo");
//execute the query
ctx.ExecuteQuery();
For this release, the semantics of creating a query, ordering the results, etc. are going to be controlled by CAML. So as we saw in the previous posting, we use an instance of the CamlQuery class to do that. The CAML syntax has not changed between versions, so all the CAML you know and love will still be useful in the client OM.
From an implementation standpoint, the CamlQuery class has a property called ViewXml, and even though it may not be obvious from the property name, that’s where you plug in your criteria for your query as well. The ViewXml property expects to have a parent element called <View>, and then within it you add a <Query> and <Where> element to implement your criteria.
Suppose, for example, you want to retrieve all items from your list where the Title property equals Steve. Your code would look something like this:
CamlQuery cq = new CamlQuery();
cq.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>Steve</Value></Eq></Where></Query></View>";
As you can see it’s just standard CAML that is going in our ViewXml property. To use our CAML in our query, we go back to our List and call its GetItems method, returning an instance of a ListItemCollection. Here’s an example:
ListItemCollection lic = lst.GetItems(cq);
Just as you do with CAML in SharePoint 2007, you can also include sorting in your queries too. Here’s an example where I’m only sorting on one field, and I’m doing so in descending order (the default sort order is ascending):
cq.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>Steve</Value></Eq></Where><OrderBy><FieldRef Name='ID' Ascending='False'/></OrderyBy></Query></View>";
Now remember in the first two postings in this series where I talked about trying to choose the specific fields you wanted when executing a query, and how that impacts the size of the data sent over the wire? And I also showed a way in which you could get non-default properties returned when you asked for a ListItemCollection. Well I’m going to combine those two concepts now as we talk about loading our data. So far I’ve shown you a couple of ways to instruct the client OM to load up property values in a ListItemCollection (where “lic” is ListItemCollection):
METHOD #1:
ctx.Load(lic);
METHOD #2:
ctx.Load(lic, items => items.IncludeWithDefaultProperties(item => item.DisplayName));
Another way to set the list of properties retrieved is with a hybrid approach between these two models. We can use a Lambda expression and define every single property that we want returned for the ListItemCollection. In this example, suppose we only really need to see the ID, Title and DisplayName values. Here is how we would express that:
METHOD #3:
ctx.Load(lic, itms => itms.Include(
itm => itm["ID"],
itm => itm["Title"],
itm => itm.DisplayName));
Not only is it arguably the clearest code in terms of plainly stating what fields we’re going to return, it also delivers the data in the smallest payload by a wide margin. Here’s the size of the resulting data over the wire for each of the three methods above:
Method # | Payload Size |
1 | 13.4K |
2 | 13.6K |
3 | 2.5K |
Again, it may not look like a huge difference when you examine the raw numbers, but over time, with lots of clients, or over a slow or latent network it can really add up. You can also control the number of items that are returned in a query. You can do it in CAML, or you can do it in your Lambda for setting the fields to be returned. Here’s an example of each method to limit the number of rows returned to 3.
CAML:
cq.ViewXml = "<View><RowLimit>3</RowLimit></View>";
Lambda:
ctx.Load(lic, itms => itms.Take(3).Include(
itm => itm["ID"],
itm => itm["Title"],
itm => itm.DisplayName));
What else can we do? The CamlQuery class is also used for paging queries, and lets you set the FolderServerRelativeUrl so you can effectively execute your queries in the subfolder of a list. Paging queries are a little more unique, so here’s a skeleton of how that would be implemented; note this is just for illustrative purposes, not necessarily a real scenario of how one would want to use paging:
//initialize a paging instance
ListItemCollectionPosition pos = null;
while (true)
{
//create the CAML query
CamlQuery cq = new CamlQuery();
//set our paging position and view xml
cq.ListItemCollectionPosition = pos;
cq.ViewXml = "<View><ViewFields><FieldRef Name='ID'/><FieldRef
Name='Title'/><FieldRef Name='Body'/></ViewFields>
<RowLimit>2</RowLimit></View>";
//get items using our CAML class
ListItemCollection lic = lst.GetItems(cq);
//load the items up - note how I have to ask separate for ListItemCollectionPosition
//if I don't, it will say property not initialized when I try and
//work with it below
ctx.Load(lic, itms => itms.ListItemCollectionPosition,
itms => itms.Include(
itm => itm["ID"],
itm => itm["Title"],
itm => itm.DisplayName));
//execute the query
ctx.ExecuteQuery();
//get our new paging position
pos = lic.ListItemCollectionPosition;
//enumerate each item
foreach (ListItem l in lic)
{
ItemsLst.Items.Add(l["Title"]);
}
//see if we've reached the end
if (pos == null)
break;
else
Debug.WriteLine(pos.PagingInfo);
}
Coming Next…
So, what other things can we do? Surprisingly, a lot. You can manage security in your site, you can create new lists, you can change the fields in a list, you can even add custom menu items, all with the client OM. I’ll cover some of these other random things in the future posts in this series.
Comments
Anonymous
January 01, 2003
The comment has been removedAnonymous
March 04, 2011
Hi Steve, method #3 isn't working for me. I get: Cannot convert lambda expression to type 'System.Linq.Expressions.Expression<System.Func<Microsoft.SharePoint.Client.ListItemCollection,object>>[]' because it is not a delegate type in visual studio.Anonymous
March 14, 2011
Steve, Could you please tell us what the point of that provided paging model is? Let's take a real-world example: I need to show the 100th page out of 200, where the total records count is 20000 and the page size is 100. How could I do that using your approach? And how will it be more effective than just taking the whole bunch of data up to 10100th record?Anonymous
November 19, 2011
Hi Steve, I have looked all over for information to get the string value out of a caml question like this you present her to be able to send it on two another function in my application but i can't find any information. Just getting the results in the console is no good for me i need to send the values further on as parameters to a function to do some more work. Do you have any suggestions or hints on this? Best Regards /PatrikAnonymous
April 10, 2014
@Carlos Might be late, but I though it might help someone else. You need to add "using Microsoft.SharePoint.Client;" and "using System.Linq;"Anonymous
October 28, 2014
The comment has been removed