CSC510210. SPQuery scope is not defined.

Description

How'd we know what people want - folder, inside folder, or just items?
SPQuery has an "affected scope". It can be one of the follow:

Member name Description
Default Show only the files and subfolders of a specific folder.
Recursive Show all files of all folders.
RecursiveAll Show all files and all subfolders of all folders.
FilesOnly Show only the files of a specific folder.

All enumeration values are covered all possible developer's intentions. Other words, without specified, SharePoint will use Default value. It is not always correspond developer needs now or later especially in case of new folder added. Notify about missing ViewAttributes we give developer change to specify it's architecture approach.
Let compare results of queries with SharePoint list which contains 561 items stored in folders and subfolders.

string siteUrl = @"http://xxxxxxx:8221";
using (SPSite site = new SPSite(siteUrl))
using (SPWeb web = site.OpenWeb())
{
     SPList list = web.Lists["Project Documents"];
     Console.WriteLine("List: " + list.Title);
     Console.WriteLine("ReallyCount: " + list.ItemCount);
     SPQuery spQry = new SPQuery();
     spQry.RowLimit = 300;
     do
     {
           SPListItemCollection items = list.GetItems(spQry);
           Console.WriteLine("FirstQuery: " + items.Count);
           spQry.ListItemCollectionPosition = items.ListItemCollectionPosition;
     } while (spQry.ListItemCollectionPosition != null);
     spQry = new SPQuery();
     spQry.ViewAttributes = "Scope=\"RecursiveAll\"";
     spQry.RowLimit = 300;
     do
     {
           SPListItemCollection items = list.GetItems(spQry);
           Console.WriteLine("SecondQuery: " + items.Count);
           spQry.ListItemCollectionPosition = items.ListItemCollectionPosition;
      } while (spQry.ListItemCollectionPosition != null);
}

Outcome:
List: Project Documents
ReallyCount: 561
FirstQuery: 8
SecondQuery: 300
SecondQuery: 261

How you can see in first attempting it was only 8 items (root folders only), but in second attempting the result is better so expected 561 items dedicated with two outs according to best practise how to working with large lists.

If you like execute this in PowerShell
$web = Get-SPWeb http://portal.sharepoint.com
$list = $web.Lists["LargeList"]

$spQuery = New-Object Microsoft.SharePoint.SPQuery
$spQuery.ViewAttributes = "Scope='Recursive'";
$spQuery.RowLimit = 2000
$caml = '' 
$spQuery.Query = $caml 

do
{
    $listItems = $list.GetItems($spQuery)
    $spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
    foreach($item in $listItems)
    {
        Write-Host $item.Title
    }
}
while ($spQuery.ListItemCollectionPosition -ne $null)

Links

SPQuery.ViewAttributes property
SPViewScope enumeration

Last edited Jun 26, 2014 at 7:48 AM by dvd73, version 3

Comments

No comments yet.