Work Management service in SharePoint 2013 (5): Querying Tasks

When you have a session manager object, you can retrieve all the tasks for a user, or filter the tasks to get only those that you need. There are seven possible filters that you can apply when querying the tasks:

  • CustomAttributeFilter
  • FieldFilter
  • KeywordFilter
  • LastModifiedDateRangeFilter
  • LocationFilter
  • PinnedFilter
  • PrivacyFilter

Most of them are self-explanatory. You can filter the tasks by custom attributes (which you can freely assign to each task, although only programmatically), by standard fields, by keywords, by last modified info, location, is task pinned (important) and task privacy. Of course, the filters can be freely combined.

It is often a requirement to get only those tasks for a user, which are stored in one SharePoint site and its subsites. Using the locations collection, and location filter, this becomes very easy to implement:

// Create a new task query
Microsoft.Office.Server.WorkManagement.TaskQuery tq = new TaskQuery();
//Get all locations which are under a specified URL
IEnumerable<Location> myLocations = allLocations.Where(a => a.Url.Contains("http://demo/sites/subsite"));
Location[] locationKeys = myLocations.ToArray();
// Create location filter
LocationFilter locationFilter = new LocationFilter() { IncludeUncategorizedTasks = false, LocationKeys = locationKeys };
tq.LocationFilter = locationFilter;
// Read filtered tasks from the task session
LocationGroupClientCollection tcc = uos.ReadTasks(tq);

This way, we got all the SharePoint tasks for a user, which are stored in all task lists in the http://demo/sites/subsite site, or in one of its subsites.