Blog Stats
  • Posts - 24
  • Articles - 0
  • Comments - 16
  • Trackbacks - 0

 

CAML queries for humans

I've recently had to help a couple of splinq-challenged colleagues with some caml queries.

Here are some of my favourite ways to make caml edible.

  • Use '!
    Too many developers seem ignorant of the fact that xml works just as well with single apostrophes as with double. This is, of course, also true for other things, like html.
  • Use @ and multiline
  • Use string.Format
  • Validate the query using a simple webpart or, much better, powershell
  • Don't use third-party clever stuff

I'm not sarcastic when I say "clever," I'm really impressed with what some people, like John Holliday, have done. But I have two major problems. You include a dependency to a dll which is outside your control, which can lead to all kinds of interesting deployment and upgrade problems. But more importantly, these additions seldom cover 100% of the functionality, and you may therefore think that something is impossible just because the addition doesn't support it.

So, examples.

var query = new SPQuery();

query.Query = "<Where><Eq><FieldRef Name=\"Severity\" /><Value Type=\"Choice\">Error</Value></Eq></Where>";

becomes

query.Query = @"

 <Where>

    <Eq>

      <FieldRef Name='Severity' />

      <Value Type='Choice'>Error</Value>

    </Eq>

  </Where>";

Which, IMHO, is more readable.

Another example using string.Format:

            query.Query = string.Format(@"<Where>

                                            <Eq>

                                                <FieldRef Name='Title'/><Value Type='Text'>{0}</Value>

                                            </Eq>

                                        </Where>", filename); // GAH! sorry about tabification (blog editor)

And how do you test it in PowerShell?

$filename = "test"

$query = New-Object Microsoft.SharePoint.SPQuery

$query.Query = @"

<Where>

    <Eq>

            <FieldRef Name='Title'/>

            <Value Type='Text'>$($filename)</Value>

    </Eq>

</Where>

"@

# See? Powershell does multiline strings, too!

# yes, Powershell has string.Format - but in Powershell I prefer using the built-in mechanism

$items = $list.GetItems($query)

foreach ($item in $items)

{

    Write-Host -NoNewline $item.DisplayName

}

 

Beautiful, just beautiful. Well, the PowerShell bit, not the CAML bit. Splinq is, obviously, much prettier.


Feedback

No comments posted yet.


Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 
 

 

 

Copyright © Norgean