Wednesday 9 May 2012

SPQuery on a User field

Filtering on a user field in a SPQuery can be a bit tricky.

The following query would look at the displayname in the userfield on the list (not very practical):


<Where>
  <Eq><FieldRef Name="UserId" /><Value Type="User" >contoso\sp</Value></Eq>
</Where>


The userfield is actually a string like this "42#;contoso\sp"
You would then believe, that it was easy to filter on the loginname. However... If the displayname of the user is set, the string value og the userfield would then be "42;#Sune Popp".
The consistent thing is the user id. This id is unique within the site collection.

So... A better way (imho) is to query on the user lookup id. Your caml should then look like this:


<Where>
  <Eq><FieldRef Name="UserId" LookupId="TRUE"/><Value Type="User" >42</Value></Eq>
</Where>


Hint! As the user id is only unique within the site collection, you should use EnsureUser on the loginname, if your solution is spread across more site collections.

Monday 7 May 2012

Enable publishing on a team site

You can make your SharePoint teamsite a publishing site like this.

Active the two features:

On site collection level activate first:
Sharepoint Server Publishing Infrastructure




On site (web) level active:
Sharepoint Publishing


Cannot complete this action. Please try again

I got the error: "Cannot complete this action. Please try again. <nativehr>0x80004005</nativehr><nativestack></nativestack>"
The error itself doesn't say much about where its was thrown, but with some debugging I localized to be centered around an SPQuery on a list in SharePoint.

I checked everything, datatypes, permissions on the list and so forth.

However it turned out to be because I had nested three <Eq></Eq> statements in one <And></And> statement. It turns out that the <And></And> statement can only have to nested elements.
So if you like in my case has to filter on more than two parameters on the list build your caml something like this:


<Where>
  <And>
    <And>
      <Eq><FieldRef Name="UserId" LookupId="TRUE"/><Value Type="User" >{0}</Value></Eq>
      <Eq><FieldRef Name="SiteId" /><Value Type="Text">{1}</Value></Eq>
    </And>
    <Eq><FieldRef Name=\"TSPRelation\" /><Value Type=\"Text\">{2}</Value></Eq>
  </And>
</Where>