Wednesday, February 10, 2010

CAML Queries, DateRangesOverlap, and Today, oh my!

Well, recently SharePoint views became too limited for my requirements and I've been forced to create my own CAML queries. Yay. Even better, I want to be able to pull recurring events so I'm pretty much forced to use the relatively undocumented "DateRangesOverlap" element. Double yay!

For my first application, pulling all of the events in a week worked. My query looks something like this:
     <Where>
          <DateRangesOverlap>
               <FieldRef Name='EventDate'>
               <FieldRef Name='EndDate'>
               <FieldRef Name='RecurrenceID'>
               <Value Type='DateTime'>
                    <Week/>
               </Value>
          </DateRangesOverlap>
     </Where>

I specify the CalendarDate for my query and life is good. Well, almost good. This query pulls 8 days of data (Sunday through Sunday) so if you iterate through a time range, you've got to do some cleaning.

Next, I needed to pull items for a specific day. I did a little digging and found that instead of "Week" I could also use "Day," "Month," or "Year." Yay! Just plug and chug, right?

WRONG.

"Day" doesn't work. Try "Day" and you'll get back 999 items. Um... that's like, sort of what I wanted, only totally not.

Well, turns out, Day is not a valid element here. "Today" is. You can use all sorts of fancy offset junk to get a specific day, but that just sounds annoying. Turns out, Microsoft doesn't really mean "Today" when they say "Today." They just mean "whatever date is specified for the query."

Sooo... I set up my query like before:

     <Where>
          <DateRangesOverlap>
               <FieldRef Name='EventDate'>
               <FieldRef Name='EndDate'>
               <FieldRef Name='RecurrenceID'>
               <Value Type='DateTime'>
                    <Today/>
               </Value>
          </DateRangesOverlap>
     </Where>

then said:

query.CalendarDate = {target date};

and I get the results I want.

Woo hoo! That's it for this time.

2 comments:

  1. If you use the tag Now instead of Today, You won't have to set calendar's query date. Cheers.

    ReplyDelete
  2. This is great :) Works like a charm.
    Thanks!

    ReplyDelete