SharePointAds TextOnly

Tuesday, 3 January 2012

SharePoint Client Object Model: CAML query execution using pagination

Below approach is used when user wants to perform pagination based on given parameters. In order to make paging work, you need to get page index and recurring count values from user.
List Items can be retrive in result and user can specify PageIndex and RecCount values which will be used for resulting certain number of values.

If your list is having more than 1 million and user requested only for list items in the rage of 100-200 then it is not good practice to get all list item collection. To avoid to load all list items collection you need to get required list item from CAML and using Paging. The logic is :

  1. Calculate skip value
  2. Assign skip values to ListItemCollectionPosition PagingInfo e.g. Paged=TRUE&p_ID= SKIP_NUMBER”
  3. Pass ListItemCollectionPosition value to CAML query
  4. Apply RowLimit value to CAML query

Suppose if you are trying to get list items from 100 to 200 then assign PageIndex =2 and recCount =100 into the following method.
//Add client
using SP = Microsoft.SharePoint.Client;

public void getItems( int pageIndex, int recCount)
SP. ClientContext ctx = getClientContext(); //authenticate client context
// first , Authentication post for more details

if (ctx != null )
int iSkip = pageIndex * recCount - recCount;
SP. List list = ctx.Web.Lists.GetByTitle( "Your LIst Name" ); // replace with your list name
ListItemCollectionPosition itemPosition = new ListItemCollectionPosition ();
itemPosition.PagingInfo = string .Format( "Paged=TRUE&p_ID={0}" ,iSkip);
CamlQuery camlQuery = new CamlQuery ();
camlQuery.ListItemCollectionPosition = itemPosition;

camlQuery.ViewXml = @"<View><ViewFields>
<FieldRef Name='ID'/>
<FieldRef Name='Title'/>
</ViewFields><RowLimit>" + recCount + @"</RowLimit>
</View>" ;
SP. ListItemCollection listItems = list.GetItems(camlQuery);

foreach (SP. ListItem listItem in listItems)
//Do forward with listItem["ID"].ToString() and  listItem["Name"].ToString()

Please have a look at Authentication post for more details about SharePoint Client object model authentication.