|
How can you use the CAML Query Builder dlls to query lists over the SharePoint Lists
web service?
Lets say I have an Employees list and I want to retrieve the first name, last name and email address of all
employees who's last name starts with the letter. I want them all sorted by last name.
First you have to instantiate the U2U.SharePoint.CAML.Builder class by passing the type of query you want to perform
U2U.SharePoint.CAML.Builder camlBuilder = new U2U.SharePoint.CAML.Builder(U2U.SharePoint.CAML.Enumerations.CamlTypes.GetListItems);
Next define the fields you want to see returned in the result. This is the ViewFields part.
camlBuilder.AddViewField("FirstName");
camlBuilder.AddViewField("LastName");
camlBuilder.AddViewField("EmailAddress");
As I want to select all employees who's last name starts with the letter D, I have to define a Where clause for the query.
bool addCombinerNode;
camlBuilder.AddWhereField("LastName", "D", "Text", "BeginsWith", out addCombinerNode);
Next step is the get the resulting list items ordered by last name:
camlBuilder.AddOrderByField("LastName");
When executing the GetListItems method of the Lists web service, you can also specify a certain number of
QueryOptions. In this case you don't want to have the mandatory fields returned together with the fields
you specified in the ViewFields part.
camlBuilder.AddQueryOptionField("IncludeMandatoryColumns", false);
Now its time to execute the query. In this example you want to execute the GetListItems method of the Lists
web service so you have to instantiate the client helper.
U2U.SharePoint.CAML.Client.Helper helper = new U2U.SharePoint.CAML.Client.Helper(
"http://wss.u2ucourse.com", "Employees", camlBuilder.CamlDocument);
Then call the GetListItems method of the client dll. The method name is called the same for your ease of use.
XmlNode result = helper.GetListItems();
In case you want to display the resulting records in a data grid, you can assign the resulting xml to a StringReader,
which you can then assign to a DataSet.
System.IO.StringReader sr = new System.IO.StringReader(result.OuterXml);
XmlTextReader tr = new XmlTextReader(sr);
DataSet ds = new DataSet("resultDataSet");
ds.ReadXml(tr);
If no errors occurred and the resulting xml contains the selected list items, set the DataSource property of
the data grid to the second table of the dataset. (The first table will contain metadata and the second table will
contain the list items). To be sure you can always test on the error code in the first table before assigning the result
to the data grid.
if (ds != null && ds.Tables.Count >= 2)
this.resultDataGrid.DataSource = ds.Tables[1];
|