20 July 2012

Customizing a Sharepoint 2010 Search Center

Almost all Sharepoint sites make use of Sharepoint Search Capabilities. Sharepoint also provides OOB site templates for setting up search centers. Today I would like to show how we customized the OOB Basic Search Center site to meet the overall site’s L&F and the customer’s needs. All the customization is done programmatically in a feature event receiver so it can be automatically applied when deploying to the different environments.

We are creating the Search Center as a subsite of the main site. The OOB Basic Search Center has three pages: Default, Advanced Search and SearchResults. The customization steps consists of:

  • Create Search Center subsite
  • Apply custom master page to search center
  • Configure the Web Parts on the Advanced and Search Results Page
  • Create custom Metadata Properties, Search Scopes and Search Rules

Search Center Creation

The search center creation is done programmatically on the feature activated event:

Code Snippet

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
        SPSite site = properties.Feature.Parent as SPSite;

        //create search center subsite
        using (SPWeb web = site.OpenWeb())
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                using (SPWeb existingSearchCenter = site.AllWebs["Search"])
                {
                    if (existingSearchCenter != null && existingSearchCenter.Exists)
                    {
                        existingSearchCenter.Delete();
                    }
                }
                using (SPWeb searchCenter = site.AllWebs.Add("Search", "Search", "Basic Search Center", 1033, "SRCHCENTERLITE#0", false, false))
                {
                    //customize search center
                    cust.CustomizeEnterpriseSearchCenter(searchCenter);
                    searchCenter.Update();
                    //set search center in root web:
                    web.AllProperties["SRCH_ENH_FTR_URL"] = searchCenter.ServerRelativeUrl;
                    //set search drowpdown mode
                    web.AllProperties["SRCH_SITE_DROPDOWN_MODE"] = "HideScopeDD";//Do not show scopes dropdown, and default to target results page
                    web.Update();
                }
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
}

 

In order to redirect search results to the Search Results Page on the Search Center sub site, some settings need to be configured on the main site. Under Site Settings - Site Collection Settings - Search Settings, the Search Center is connected to main site:

 

image

This is what the following lines in the feature receiver do:

//set search center in root web:
web.AllProperties["SRCH_ENH_FTR_URL"] = searchCenter.ServerRelativeUrl;
//set search drowpdown mode
web.AllProperties["SRCH_SITE_DROPDOWN_MODE"] = "HideScopeDD";//Do not show scopes dropdown, and default to target results page

 

Search Master Page

The Search Center has some particularities that prevent them to use the same master page as the main site. So a custom master page needed to be provisioned. In order to provide a master page compatible with the page layouts of the OOB Basic Search Center, we follow the instructions provided in this article: Converting a Custom SharePoint 2010 Master Page into a Search Center Master Page.

Advanced Search Page customization

The requirements for the advanced search web part, were to hide the language picker, display the scopes picker (with custom scopes, like Articles, News, Audio, Video, etc) and add some custom properties to the “Add property restrictions” filter.

image

This customization is performed by the following code:

Code Snippet
private void EditAdvancedSearchBoxWebPart(SPLimitedWebPartManager manager)
        {
            System.Web.UI.WebControls.WebParts.WebPart wp = GetWebPart(manager, "Advanced Search Box");
            if (wp != null)
            {
                AdvancedSearchBox webpart = wp as AdvancedSearchBox;
                if (webpart != null)
                {
                    webpart.ShowLanguageOptions = false;
                    webpart.ShowScopes = true;
                    webpart.Properties = GetFromResources("SearchCenter.WebPartsConfig.AdvancedSearchBoxProperties.xml");
                    manager.SaveChanges(webpart);
                }
            }
        }

 

Even if the code is not complete, you can see what we are doing, editing the page, getting the Advances Search Box web part by name and modifying its properties. We are loading the Properties from an xml file, which includes the custom properties we added for filtering.

Custom Managed Properties and Scopes

In order to add custom properties and scopes to the Advanced Search Web Part , we first need to create them. The matadata properties are mapped to crawled properties. This means that, when Sharepoint crawls the site content and finds data in a particular list and field, if will create a crawled property for that field. For example, in the image below we can see the 0ws_keywords crawled property mapped to the Keywords Managed Property on the Admin site.

image

The creation and mapping of the managed property is done programmatically thru the feature activation event receiver. The crawled property is created by Sharepoint within a crawl, and must exist before activating the feature.

Here is the code for creating a managed property:

Code Snippet
private static void CreateManagedProperty(Schema schema, string managedPropertyName, string crawledPropertyCategory, string crawledPropertyName)
        {
            if (!schema.AllManagedProperties.Contains(managedPropertyName))
            {             
                Category category = schema.AllCategories[crawledPropertyCategory];
                var crawledProps = category.QueryCrawledProperties(crawledPropertyName, 1, Guid.NewGuid(), String.Empty, true).Cast<CrawledProperty>();
                var crawledProp = crawledProps.FirstOrDefault();
                if (crawledProp != null)
                {
                    ManagedDataType managedPropertyType = GetManagedPropertyType(crawledProp);
            
                    ManagedProperty managedProperty = schema.AllManagedProperties.Create(managedPropertyName, managedPropertyType);
                    var mappings = managedProperty.GetMappings();
                    mappings.Add(new Mapping(crawledProp.Propset, crawledProp.Name, crawledProp.VariantType, managedProperty.PID));
                    managedProperty.SetMappings(mappings);
                    managedProperty.Update();
                }
            }
        }

 

For the custom scopes, we are mostly using Property Query rules using the contentclass for the restriction:

image

The example of the figure is the rule of the News scope. In this case the news are stored in a list with a custom list definition. Below is the code of the list definition. Look at the Type number: 10314

Code Snippet
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <ListTemplate
        Name="NewsItemList"
        Type="10314"
        BaseType="0"
        OnQuickLaunch="TRUE"
        SecurityBits="11"
        Sequence="410"
        DisplayName="NewsItemList"
        Description="My List Definition"
        Image="/_layouts/images/itgen.png"/>
</ Elements >

 

That is the same number that we are setting the contentclass property to match: STS_ListItem_10314. This means that only items from that list, the news list, will match that scope. This enables to restrict the search to the News scope on the Advanced Search Web Part. In order for that to happen, we also need to include this scope into the Advanced Search display group.

Conclusion

The code for the complete customization is too much to explain everything here, but the idea was to show how we can make use of the existing Search Center site templates and perform different customizations depending on the project’s requirements. So with little effort we can profit of the OOB advanced search and search results pages that Sharepoint provides.