CAML Query comparing current user with a list field
I used the next query to check or the current user (logged in) is the same as the user stored in a specific listfield.
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name=\"Sender\" /><Value Type='User'>" + SPContext.Current.Web.CurrentUser.LoginName.ToString() + "</Value></Eq></Where><OrderBy><FieldRef Ascending='DESC' Name='Created' /></OrderBy>";
SPListItemCollection collListItems = myList.GetItems(query); //myList is a listobject of type SPList
You can get the SPUser object in the following way:
private SPUser GetUserFromList(SPListItem item)
{
string strUserValue = item["Sender"].ToString();
int intIndex = strUserValue.IndexOf(';');
int intID = Int32.Parse(strUserValue.Substring(0, intIndex));
SPUser oUser = this.site.SiteUsers.GetByID(intID);
return oUser;
}
CAML Query with dynamic date evaluation
You can use this caml for example in a calendar list.
<Where>
<Geq>
<FieldRef Name="EventDate" />
<Value Type="DateTime" IncludeTimeValue="TRUE">[My Date]</Value>
</Geq>
</Where>
// For [MyDate] you have to use: SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Today)
// You have to convert the date from a DateTime value into a CAML Date format, which is the ISO8601 format.
// This works only for date, not time (even using the IncludeTimeValue attribute). [/code]
You can also use the next code to get item(s) that have an ImageCreateDate in the last seven days
<Query>
<Where>
<Geq>
<FieldRef Name="ImageCreateDate" />
<Value Type="DateTime">
<Today OffsetDays="-7" />
</Value>
</Geq>
</Where>
</Query>
[/code]
Exception - One or more field types are not installed properly
After debugging my code it seemed to be an error in my CAML query. An interesting field in my CAML was the "Start Time" of the Event List (e.g. used in combination with calender view). I used it as:
<OrderBy><FieldRef Name='Start Time' /></OrderBy><Where>
I remembered the trick with replacing the spaces in CAML so I changed my query in:
<OrderBy><FieldRef Name='Start_x0020_Time' /></OrderBy><Where>
Still the same error
. I decided to open the U2U Caml Query Builder (http://www.u2u.info/SharePoint/U2U%20Community%20Tools/Forms/AllItems.aspx) to check my query. Then there was the "aha" moment. The internal field name of the field Start Date is: "EventDate". After changing the caml code again it worked!
<OrderBy><FieldRef Name='EventDate' /></OrderBy><Where>
Lesson learned: U2U Caml Query builder is a must have and the internal name may be totaly different from the display name. If you have the same "aha" moment, feel free to leave a comment.