Thursday, July 12, 2012

Web Analytics with Title

Alot of people are on different forums have put up a requirement to get Titles displayed in Webanalytics instead of URLs, i don't know why webanalytics doesn't allow this in first place :)

But any way, i have a code snippet from Farhan Faiz on subject but have noticed that it has some limitations....


I have tried to get another version of WebAnalytics which which is working for me in sites/sub sites

Try and share your feedback....


Steps to Setup this in your DEV environment

1) Create an empty project in VS 2010
2) Add a new WebPart
3) Build and Deploy this blank webpart
4) Add it to your sharepoint site


5) Add Reference to
C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Server.WebAnalytics.UI\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Server.WebAnalytics.UI.dll

in your project

6) Rename Webpart class to TitleAnalystics and Replace code in webpart.cs file with the one listed below

7) Build and Deploy this updated Webpart




using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text.RegularExpressions;

namespace TitleAnalystics.TitleAnalystics
{
[ToolboxItemAttribute(false)]
public class TitleAnalystics : Microsoft.Office.Server.WebAnalytics.Reporting.WhatsPopularWebPart, ICallbackEventHandler
{

// Make sure that double quotes and single quotes are copied correctly, when you copy html and past it to Visual Studio sometimes it changes the character.


private const string ItemRegEx = @"(?[^<]*)";


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;


string title = url;


using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
{

using (SPWeb spWeb = spSite.OpenWeb(title))
{

try
{


var item = spWeb.GetListItem(title);



if (item != null)
{

title = item.DisplayName;


}

else
{
//var item2 = SPContext.Current.Site.RootWeb.GetListFromUrl(url);
var item2 = spWeb.GetListFromUrl(url);
title = item2.Title;
}


}

catch (Exception e) { }


}


}

return "" + title + "";


}, RegexOptions.IgnoreCase);


}

return html;


}


string ICallbackEventHandler.GetCallbackResult()
{

return ReplaceUrlsWithTitles(base.GetCallbackResult());


}

void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{

base.RaiseCallbackEvent(eventArgument);


}
}
}

1 comment:

Unknown said...

Good article Rehman. It works fine for me, but the web part is showing the site url at the top (Under http://sitename/). Do you have any idea to hide this ?

Thanks,
Dhileep