Friday, December 3, 2010

Dynamic OrderBy CAML statements via Camlex.NET

Today new version of Camlex.NET was released. A new feature was added to it which is called dynamic OrderBy statements. Camlex.NET was created for Sharepoint developers and its purpose to simplify creation of CAML queries. As many other features dynamic OrderBy statements was initiated by discussion in Camlex project page on Codeplex, i.e. it is initiated by developers feedback (thanks to umike user for the feedback). So if you think that some feature will be useful for Camlex, don’t hesitate to contact us in discussions board. This is the end of little preface. Now lets say a few words about new feature.

In many real life scenarious when we need to create CAML query programmatically in compile time we don’t know what actual fields will be used for sorting. E.g. suppose that we have a grid view and it is bind to items’ collection which is retrieved from Sharepoint list using CAML. Users have possibility to sort grid view by several columns in ascending or descending order. So we can’t say what CAML query will be used in each particular case. For such scenarious new Camlex feature was implemented. It allows developers to build dynamic OrderBy statements using parameters provided e.g. from user input. In order to do it a new method was added to IQuery interface which receives list of expressions for OrderBy statement (each expression have the following syntax x => x[“Title”] or x => x[“Title”] as Camlex.Asc – see – Scenario 6. Query with sorting (OrderBy)):

   1: public interface IQuery
   2: {
   3:     ...
   4:     IQuery OrderBy(IEnumerable<Expression<Func<SPListItem, object>>> expressions);
   5: }

So now you can dynamically create list of expressions for OrderBy statement in runtime and pass it directly to Camlex as shown in the following example:

   1: var orderByList = new List<Expression<Func<SPListItem, object>>>();
   2: orderByList.Add(x => x["Title"] as Camlex.Asc);
   3: orderByList.Add(y => y["Date"] as Camlex.Desc);
   5: var caml = Camlex.Query().OrderBy(orderByList).ToString();

It will produce the following CAML:

   1: <OrderBy>
   2:   <FieldRef Name="Title" Ascending="True" />
   3:   <FieldRef Name="Date" Ascending="False" />
   4: </OrderBy>

You can also specify single field for sorting by adding single element to the list. I hope this new feature will be useful in real life development scenarios.

No comments:

Post a Comment