Thursday, April 2, 2009

Filter Current User for Document Library in a CAML Query

I had a situation where I needed to create a web part that searched all of the Document Libraries of a SharePoint site, and then gave the option to filter the list by the current user logged onto the site (similar to the "Relavent Documents" OOTB Web Part).

Anyways, the CAML Query is simplistic in nature, but was kind of a pain to reach this conclusion since most of what you will find on the Web is using the "AssignedTo" Field name to match against the current user. The key internal name field for a Document Library to use is "Editor".

Anyways, here is the "Where" clause I used to hit against the Document Libraries:

SPSiteDataQuery q = new SPSiteDataQuery();

q.ViewFields = "<FieldRef Name=\"FileRef\" /><FieldRef Name=\"ID\" /><FieldRef Name=\"Modified\" /><FieldRef Name=\"Modified_x0020_By\" />";
q.Query = "<Where><Eq><FieldRef Name=\"Editor\" /><Value Type=\"User\"><UserID/></Value></Eq></Where><OrderBy><FieldRef Name=\"Modified\" Ascending=\"False\" /></OrderBy>";
q.RowLimit = 10;
q.Webs = "<Webs Scope=\"Recursive\" />";
q.Lists = "<Lists ServerTemplate=\"101\"/>";

SPWeb Collection: List Sites / Webs

I had an opportunity recently to make a web part that is like a site map to the entire site collection no matter where it was dropped on the SharePoint site. I also made an option (not shown in code) that allows the "default starting site/web" to be overridden so that you can start from any site/web node and then show recursive webs from there.

Enough talk, here's the code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;
using System.Data;

namespace JamesCurtis.SharePoint.Examples
{
public class SPWebCollectionExample : Microsoft.SharePoint.WebPartPages.WebPart
{
#region Constants

#endregion

#region Fields

Label lblDisplay = new Label();
Label lblError = new Label();
StringBuilder sb = new StringBuilder();

#endregion

#region Delagates

protected override void CreateChildControls()
{
try
{
base.CreateChildControls();

lblDisplay.Text = GetData(SPContext.Current.Site.Url);
this.Controls.Add(lblDisplay);
}
catch (Exception ex)
{
lblError.Text = ex.Message;
this.Controls.Add(lblError);
}
}

#endregion

#region Private Methods

protected string GetData(string site)
{
using (SPSite s = new SPSite(site))
{
SPWebCollection swc = s.AllWebs;
for (int i = 0; i < swc.Count - 1; i++)
{
sb.Append(SPEncode.HtmlEncode(swc[i].Url));
sb.Append("<br/>");
}
}
return sb.ToString();
}

#endregion

}
}

Happy Programming!