Building SharePoint View Queries with CAML
Often times when building applications that will greatly use SharePoint views for data rotation it is helpful to build CAML builders into separate static classes that return a continuous string representation of the arbitrary query. In order to demonstrate this, consider the following examples BuildDefaultViewQuery, BuildPrivateViewQuery, and BuildPublicViewQuery:
- private static string BuildDefaultViewQuery()
- {
- var builder = new StringBuilder();
- builder.Append("<Where>");
- builder.Append("<Eq><FieldRef Name='DefaultView' /><Value Type='Boolean'>");
- builder.Append("1");
- builder.Append("</Value></Eq></Where>");
- return builder.ToString();
- }
- private static string BuildPrivateViewQuery(string user)
- {
- var builder = new StringBuilder();
- builder.Append("<OrderBy><FieldRef Name='ViewName'/> </OrderBy>");
- builder.Append("<Where><Eq><FieldRef Name='ViewCreator' /><Value Type='Text'>");
- builder.Append(user);
- builder.Append("</Value></Eq></Where>");
- return builder.ToString();
- }
- private static string BuildPublicViewQuery(string user)
- {
- var builder = new StringBuilder();
- builder.Append("<OrderBy><FieldRef Name='Audience'/> <FieldRef Name='ViewName'/></OrderBy>");
- builder.Append("<Where><Or><Eq><FieldRef Name='ViewCreator' /><Value Type='Text'>");
- builder.Append(user);
- builder.Append("</Value></Eq>");
- builder.Append("<Eq><FieldRef Name='Audience' /><Value Type='Choice'>");
- builder.Append("1");
- builder.Append("</Value></Eq></Or></Where>");
- return builder.ToString();
- }
It should be noted that there are some constants that could instead be extracted to an enumeration and then Enum.GetName could be used for better component allocation. However, in this example since it is merely to show the overlying constructs, is kept purposefully plain.
In order to use one of static CAML methods, the ReturnCollectionExample method will take some basic parameters, than return the item collection associated with the BuildPrivateViewQuery query.
- private static SPListItemCollection (string url, string viewName, string userId)
- {
- using (var site = new SPSite(url))
- {
- using (SPWeb web = site.OpenWeb())
- {
- var query = new SPQuery { Query = BuildPrivateViewQuery(userId) };
- return web.Lists[viewName].GetItems(query);
- }
- }
- }
Articles & Research
SharePoint Security
SharePoint Development
SharePoint Architecture
Claims Authentication
Forefront For SharePoint
AIS / Dynamics GP
Team Foundation Server
Pex And Moles
ISA/TMG/IAG/UAG
DPM
Cardspace
Research Methodology
Rural ICT Development
Numerical Analysis
Multi-Level Research
Knowledge Management
Personal/Off-Topic