Monday 18 July 2011

Dynamic CAML Query

I had a need to create a CAML query based on a dynamic set of user options. Basically a search routine with parameters such as start date, end date etc. I created this nice recursive method to add n query conditions to the Where part of a CAML query. It's restricted to a single comparison operator at the moment because that's all I needed.

Protected Function ComposeCamlQuery(ByVal conditions As IList(Of String), ByVal op As String, ByVal query As String) As String
Return If(conditions.Count = 1, _
String.Format(query, conditions(0)), _
ComposeCamlQuery(conditions.Skip(1).ToList(), op, String.Format(query, String.Format("<{0}>{1}{{0}}", op, conditions(0)))))

End Function


You can use it like so:
Dim conditions As New List(Of String)

conditions .Add(<Geq>
<FieldRef Name='Created'/>
<Value IncludeTimeValue='FALSE' Type='DateTime'><%= Format(startDate, "yyyy-MM-ddTHH:mm:ssZ") %></Value>
</Geq>.ToString())

Dim whereQuery As String = ComposeCamlQuery(conditions, "And", "<where>{0}</where>")

camlQuery.ViewXml = <view>
<query>
<%= XElement.Parse(whereQuery)) %>
</query>
<rowlimit>2000</rowlimit>
</view>.ToString()