Thursday, July 31, 2008

Unraveling the Content Query Web Part

Well as most of you already know , the Content Query Web Part (CQWP) is a MOSS feature and will be available to you if you have a WSS site hosted on a server with MOSS installed . That’s the catch . There’s more to this webpart than originally thought.

Let us imagine a scenario in which there are 200 MOSS sites and each site has around 300-500 articles in Pages Library and another similar figure in a custom List called ArticleList . That would account to a total of 10000 articles every Site (from both Pages Library and ArticleList) . Our Requirement is to parse through this 200 mulitplied by 10000 articles to display the top 8 or 10 articles whose certain fields satisfy a condition.

What we would normally do is create a custom web part inheritable from
System.Web.UI.WebControls.WebParts and Override the CreateChildControls and Render methods . Inside the CreateChildControls method , we would use an SPSiteDataQuery Object to parse through the entire site collection and return a DataTable of articles matching the filter condition. The problem with this approach is when you load this web part on to your SharePoint page , it causes a tremendous overhead so much so that the Page times out. In contrast when we use a ContentQueryWebPart , the data is loaded on to the page almost instantly .

Taking this into consideration and a bit of R&D I worked on creating a custom ContentQueryWebPart . One that would do our logic and display data with Out of the Box efficiency .

Below I give you a list of steps I followed to make this happen.

1. Inherit the web part from Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart

2. Override the OnInit method and set the properties of the ContentQueryWebPart

private string _customViewFieldsOverride = "Title,Text;Created_x0020_Date,DateTime;MyImage,Text;"

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
//Delegate for sorting data on DESC order of Created_Date
this.ProcessDataDelegate = new ProcessData(ProcessItems);

//This method executes our logic and generates a dynamic query to be passed on to the CQWP.
executeLogicHere();

//The commonViewFields is set here .
this.CommonViewFields = customViewFieldsOverride;

//Data is grouped according to ‘Title’ only to display it in 2 columns because the DisplayColumns property becomes active only if grouping is performed .
this.GroupBy = "{fa564e0f-0c70-4ab9-b863-0177e6ddd247}";

this.GroupByFieldType = "Text";

this.GroupStyle = "Whitespace";

//The ItemXslLink sets the link where the ItemStyle.xsl is located , to apply styles to items returned
this.ItemXslLink = ItemXslLinkOverride;

//the MainXslLink property sets the link where the ContentQueryMain.xsl is located to define new parameters and pass them on to ItemStyle.xsl . In our case this is not required but I am initializing it .
this.MainXslLink = MainXslLinkOverride;

//The total number of items that can be parsed .
this.ItemLimit = SPContext.Current.Web.Site.RootWeb.Lists["Mylist"].Items.Count;

//The ItemStyle that would be applied
this.ItemStyle = "MyStyle";

this.DisplayColumns = 2;

this.ListName = "MyList";

this.ListGuid = SPContext.Current.Web.Site.RootWeb.Lists["MyList"].ID.ToString();
this.WebUrl = "/";

this.Title = string.Empty;

//The category of List to be parsed . For a complete reference of Servertemplates and Lists please visit *
this.ServerTemplate = "100";

//Specifying the contentType to be parsed for in the query
this.ContentTypeBeginsWithId = SPContext.Current.Web.Site.RootWeb.AvailableContentTypes["MyContentType"].Id.ToString();
//To hide the title and border of the webpart
this.ChromeType = PartChromeType.None;
}

* http://egrimmett.wordpress.com/2008/04/01/servertemplate-numbers/

3. Override the GetToolParts method so that the user will not be able to edit the properties of the web part

public override ToolPart[] GetToolParts()
{
return null;
}

4. Inside the method executeLogicHere()

public void executeLogicHere ()
{
//execute our logic here and pass the generated dynamic CAML query to the QueryOverride property of the CQWP.
string query = GenerateDynamicQuery();
this.QueryOverride = query;
}

5. Inside the ProcessItems method . This is an overridable method that can be used to manipulate with the data before style sheets are applied to it . Here I am sorting the data in Descending order of Created_Date.


public DataTable ProcessItems(DataTable data)
{

if (data.Rows.Count > 0)
{
DataView dvData = data.DefaultView;
dvData.Sort = "Created_x0020_Date DESC";
return dvData.ToTable();
}
return null;
}


Here is the top section of ItemStyle.xsl

<xsl:stylesheet
version="1.0"
exclude-result-prefixes="x d xsl msxsl cmswrt asp ddwrt"
xmlns:x="http://www.w3.org/2001/XMLSchema"
xmlns:asp="urn:schemas:calendar"
xmlns:d="http://schemas.microsoft.com/sharepoint/dsp"
xmlns:cmswrt="http://schemas.microsoft.com/WebParts/v3/Publishing/runtime"
xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">


<xsl:template name="MyStyle" match="Row[@Style=' MyStyle']" mode="itemstyle">
<xsl:variable name="SafeLinkUrl">
<xsl:call-template name="OuterTemplate.GetSafeLink">
<xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="DisplayTitle">
<xsl:call-template name="OuterTemplate.GetTitle">
<xsl:with-param name="Title" select="@Title"/>
<xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
</xsl:call-template>
</xsl:variable>
<xsl:variable name="LinkTarget">
<xsl:if test="@OpenInNewWindow = 'True'" >_blank</xsl:if>
</xsl:variable>


<div id="linkitem" class="">
<table width="100%">
<tr>
<td colspan="2">
<xsl:value-of select="ddwrt:FormatDateTime(string(@Created_x005F_x0020_Date) ,1033 ,'dd-MMM-yyyy')"></xsl:value-of>
</td>
</tr>
<tr>
<td colspan="2">
<a href="{@ArticleUrl}" target="{$LinkTarget}" title="{@LinkToolTip}">
<xsl:value-of select="@Title"></xsl:value-of>
</a>
</td>
</tr>
<tr>
<td colspan="2">
<xsl:if test="string-length(@MyImage) != 0">
<img src="{@MyImage}"></img>
</xsl:if>
<xsl:value-of select ="@SafeLinkUrl"/> <img src="{@MyImage}"></img>
</td>

</tr>

</table>
</div>


</xsl:template>

10. Reference Links

a. Below is a detail link on custom Item Style Template creation .
http://www.heathersolomon.com/blog/articles/CustomItemStyle.aspx

b. Working with date http://www.microsoft.com/belux/msdn/nl/community/columns/stevenvandecraen/contentquerywebpart.mspx

c. CQWP and Performance
http://techblog.ranjanbanerji.com/post/2007/07/16/Content-Query-Web-Part-(CQWP)-SharePoint-2007-Performance.aspx

d. CQWP Caching
http://technet.microsoft.com/en-us/library/cc298466.aspx

e. Overridable CQWP
http://www.codeplex.com/sptoolbox/Release/ProjectReleases.aspx?ReleaseId=11150