March 15, 2007

Customizing wss 3.0 default search scope

In Moss 2007 , you can define custom search scopes from administration application. However, AFAIK, there is no such support for wss 3.0.

As you may know in wss 3.0 your searches are limited to site and its subsites. That is, ff you are in the context of a subsite, your search can not contain items from its parent.
But, for a project, I wanted to enable site-wide search that is all searches will begin from the root site.To enable this behaviour i have followed the steps in
How to: Customize a Delegate Control. After making sure it has worked as expected, I customized the custom control located in "controltemplates" directory. This process consisted of finding the root web site and setting it as the search scope.
Here is the code:
<% string strScopeWeb = null; string strScopeList = null; string strWebSelected = null; /*-----find the root website -----------*/ SPWeb rootweb= null; foreach (SPWeb spweb in SPContext.Current.Site.AllWebs) { if (spweb.IsRootWeb) { rootweb = spweb; break; } } /*----------------*/ SPWeb web = SPControl.GetContextWeb(Context); string strEncodedUrl = SPHttpUtility.EcmaScriptStringLiteralEncode( SPHttpUtility.UrlPathEncode(web.Url + "/_layouts/searchresults.aspx", false, false) ); strEncodedUrl = "'" + strEncodedUrl + "'"; //following line is commented for the search to include root web site //strScopeWeb = "'" + SPHttpUtility.HtmlEncode( web.Url ) + "'"; strScopeWeb = "'" + SPHttpUtility.HtmlEncode(rootweb.Url) + "'"; SPList list = SPContext.Current.List; if ( list != null && ((list.BaseTemplate != SPListTemplateType.DocumentLibrary && list.BaseTemplate != SPListTemplateType.WebPageLibrary) || (SPContext.Current.ListItem == null) || (SPContext.Current.ListItem.ParentList == null) || (SPContext.Current.ListItem.ParentList != list)) ) { strScopeList = list.ID.ToString(); } else { strWebSelected = "SELECTED"; } %>
That's it. You don't need to install the feature again.
Enjoy.

1 comment:

  1. Can you please provide the code to find the root web site and setting it as the search scope?

    ReplyDelete