Thursday 21 June 2007

Sharepoint Development Tips 2-CAML Power!

CAML(Collaborative Application Markup Language) is the tool you want to use before you mess around with querying your sharepoint list and views with foreach(s). Experience prooved that foreach the whole list or in case you have to use embedded foreach statement, the performance is quite disappointing. The alternative is to use CAML which is used by sharepoint by default when creating views for lists.

The usage is easy. It's like the NHibernate's HQL if you use it before.
In here, I have a list called "Team List". Now I want to obtain the item that has the Job No.(job number)of 12 and Customer Name(customer's name )is equal to "Your Name", the CAML statement will be like following


the syntax is relatively easy apart from one wicked requirement, the ASCII characters are needed to be encoded to hexidecimal value and with both prefix and suffix of '_', in our case the space character is encoded as x0020, and the '.' as x002e.

So the usage of above CAML will be by putting the CAML statement into a string e.g. teamQueryString:



SPQuery query = new SPQuery();
SPListItem resultItem =null;
query.Query= teamQueryString;

//in our case the result is unique
resultItem = teamList.GetItems(query);

By this way , you get the team with job number is 12 and customer name is "Your Name"

If you wonder how you could figure out what hex value to encode all the characters out there or you are too lazy to write the CAML at all, I recommend using U2U's CAMLBuilder, they are pretty handy and most importantly, it's free! (You can tell that I am that lazy by sensing the tone :P )

No comments: