Roland Oldengarm - Independent IT Contractor

Living in the coolest little capital Wellington, New Zealand!

WhatsPopularWebPart: render titles instead of URL’s

SharePoint 2010 has a nice new webpart, the WhatsPopularWebPart. I have used it to show me the most frequent viewed pages. However, SharePoint displays the URL of the page instead of the Title! Using Reflector I stepped into the code and in some private method I saw they just render the URL. I’ve got a solution by overriding the webpart

I saw two solutions: override all rendering or regex-replace the current output. Because overriding would mean override a lot of functions, I chose the later. The code was hard to find, but eventually it was pretty simple. The data is loaded using javascript, therefore I created a webpart derived from WhatsPopularWebPart and implemented also ICallbackEventHandler.

Then,

private const string ItemRegEx = @"<span dir=""ltr"">(?<url>[^<]*)</span>";

/// <summary>
/// Replaces the urls with titles.
/// </summary>
/// <param name="html">The HTML.</param>
/// <returns></returns>
private static string ReplaceUrlsWithTitles(string html)
{
if (Regex.IsMatch(html, ItemRegEx))
{
html = Regex.Replace(html, ItemRegEx, delegate(Match match)
{
var url = match.Groups["url"].Value;
// This will only work with items in rootweb. In final code I used a wrapper around the SPSiteDataQuery to quickly retrieve the item. Opening a SPSite + SPWeb is also possible, but will cost some performance.
var item = SPContext.Current.Site.RootWeb.GetListItem(url);
string title = url;
if (item != null)
{
title = item.Title;
}
return "<span>" + title + "</span>";
});
}
else
{
html += "<!-- No match found using ReplaceUrlsWithTitles -->";
}
return html;
}

/// <summary>
/// Gets the callback result. Result is loaded asynchronously using javascript
/// </summary>
/// <returns></returns>
public new string GetCallbackResult()
{
return ReplaceUrlsWithTitles(base.GetCallbackResult());
}

Let me know if you used the code 🙂

3 Comments

  1. Hello,
    we tried to extend the WhatsPopularWebPart and implement the ICallbackEventHandler, but we have the same result as the original web part.
    Could you kindly send us the code?

    Kind regards.

  2. No luck buddy. Its not working.

Leave a Reply

Your email address will not be published.

*