Search Scope for SharePoint Web Site

Explains how to create a new Sharepoint search scope and use for searching item from that scope using a custom web part for search.

Introduction

When I was working for my SharePoint project, the requirement for a special feature is requrested. The requirement was to use a only one list for search and provide only that list's information in search results. At the time, I've to find the solution and I came across the Search Scope in the Site Settings of the SharePoint Site. Here in this article I explain how to configure new search scope for a particular list in web site and how to use it in the search and custom web part.

Assumptions

I assume that the reader of this article is familiar to with Visual Studio 2008 and WSPBuilder project templates and SharePoint sites. Also considered the would be familiar how to enabl/disable features. Programming language is C#. Also the SharedService required for this article.

Assembly References

  • Microsoft.Office.Server.Search .NET assembly

Preparation

  1. Create a new WSPBuilder Project using Visual Studio 2008.

  2. Add references to the Microsoft.Office.Server.Search .NET assembly.

  3. Add the Web Part Feature item template to the project.

  4. This will create a 12 hive folder structure and add the feature which is used to add the web part to the site when that feature is activated.

  5. Open the .cs file from WebPartCode folder from Solution Explorer.

  6. Add using statements for Microsoft.SharePoint, Microsoft.Office.Server.Search.WebControls, System.Web.UI.WebControls, Microsoft.SharePoint.Utilities, System.Text namespaces.

  7. Clear the default code provided by the template from the class definition, if you have used the WSP Builder template.

  8. Add the following lines of code at the beginning of the class.

  9. private bool _error = false;
    private string _searchScope = null;
    CoreResultsWebPart m_theResults = null;
    private TextBox m_txtSearch = null;
    private SPWeb m_theWeb;
    private Button m_btnSearch;
    private Table m_theTable;

  • Add the following property code to the class. This property is used as the web part property. The SearchScope property provides the search Scope name to use for search.

  • [Personalizable(PersonalizationScope.Shared)]
    [WebBrowsable(true)]
    [WebDisplayName("Search Scope Name")]
    [WebDescription("Name of the search scope to be used.")]
    public string SearchScope
    {
    get
    {
    if (string.IsNullOrEmpty(_searchScope))
    {
    return string.Empty;
    }
    return _searchScope;
    }
    set { _searchScope = value; }
    }

  • Add the constructor for the class as following. The current context web object is used to get the current web site for the web part.

  • public CustomSearchScopeWebPart()
    {
    this.ExportMode = WebPartExportMode.All;
    m_theWeb = SPContext.Current.Web;
    }

  • Now override the CreateChildControls of the base class and write the code to create and add the content controls. [As like below].

  • protected override void CreateChildControls()
    {
    if (!_error)
    {
    try
    {

    base.CreateChildControls();
    this.createMainTable();
    this.m_theTable.Rows.Add(this.trCreateSearchBoxRow());
    this.m_theTable.Rows.Add(this.trCreateSearchResultsRow());
    }
    catch (Exception ex)
    {
    HandleException(ex);
    }
    }
    }

  • In the above code the method createMainTable() will initializes the main container table object, sets its properties and add that table to the controls collection of the web part. The method trCreateSearchBoxRow() initializes the search box and search button controls and adds them to the table row and returns the table row object. The method trCreateSearchResultsRow() will initializes and add the CoreSearchResult web part object and add it to the table row and returns the table row object.

  • The CoreSearchResultsWebPart object takes the search keyword and other information from the query string of the url and searchs the results and displays on the page. So, we just have to add the search keyword and search scope name to the query string and the redirect to the search page or to the same page to get the search result, which I've done for this example.

  • Code for trCreateSearchBoxRow() method is as follows:

  • private TableRow trCreateSearchBoxRow()
    {
    TableRow row = new TableRow();
    TableCell cellKeywordText = new TableCell();
    cellKeywordText.CssClass = "ms-formlabel";
    cellKeywordText.Controls.Add(new LiteralControl("Search keyword: "));
    row.Cells.Add(cellKeywordText);

    m_txtSearch = new TextBox();
    m_txtSearch.ID = "txtSearch";
    m_txtSearch.CssClass = "ms-long";
    cellKeywordText.Controls.Add(m_txtSearch);
    if (this.Context.Request.QueryString["k"] != null)
    m_txtSearch.Text = this.Context.Request.QueryString["k"];

    m_btnSearch = new Button();
    m_btnSearch.Text = "Search";
    m_btnSearch.ID = "btnSearch";
    m_btnSearch.Click += new EventHandler(m_btnSearch_Click);
    m_btnSearch.Attributes["onclick"] = "return ConfirmSearchValue()";
    cellKeywordText.Controls.Add(new LiteralControl(" "));
    cellKeywordText.Controls.Add(m_btnSearch);

    return row;
    }

  • Code for trCreateSearchResultsRow() method is as follows:

  • private TableRow trCreateSearchResultsRow()
    {
    TableRow row = new TableRow();
    TableCell cell = new TableCell();
    cell.ColumnSpan = 2;
    cell.Style.Add(HtmlTextWriterStyle.PaddingLeft, "5px");
    row.Cells.Add(cell);
    m_theResults = new CoreResultsWebPart();
    cell.Controls.Add(m_theResults);

    return row;
    }

  • Now override the Render method of the base class and add the javascript element for validation of key word as shown below

  • protected override void Render(HtmlTextWriter writer)
    {
    writer.Write(this.createValidationScript());
    base.Render(writer);
    }

    /// <summary>
    /// Adds the search text box validation javascript to the page.
    /// </summary>
    /// <returns></returns>
    private string createValidationScript()
    {
    StringBuilder sb = new StringBuilder();
    sb.Append("<script type=\"text/javascript\" language=\"javascript\">");
    sb.Append("function ConfirmSearchValue(){");
    sb.AppendFormat("if(document.getElementById('{0}').value == '')", m_txtSearch.ClientID);
    sb.Append("{");
    sb.Append("alert('Please enter one or more search words.'); return false;");
    sb.Append("}");
    sb.Append("return true;");
    sb.Append("}");
    sb.Append("</script>");
    return sb.ToString();
    }

  • Now build the solution and resolve any errors.

  • After successful build of the solution, build the WSP file by right clicking the Project Name in Solution Explorer and selecting "Build WSP" context menu item.

  • After successful build of the WSP file, deploy that solution to the SharePoint by right clicking the Project Name in Solution Explorer and selecting "Deploy" context menu item.

  • Now before adding the web part to the page we need to configure the search scope for the site. So, let's do that with following steps.

  • Open you site in IE.

  • Go to Site Settings.

  • Click the "Search Scope" link in the "Site Collection Administration".This will take you to the View Scopes page as displayed in below image.

  • Click on "New Scope" link on top toolbar.

  • On the "Create Scope" page [as displayed in below image], provide the title and description [optional] for the scope. Leave other things as it is and click Ok.

  • Thsi will create new search scope, and takes you to the View Scopes page.

  • Now click on the search scope name link in the Title column. This will take you to the Scope Properties and Rules page. [As displayed in below image]

  • In the Rules section, click on New rule link.

  • This will take you to the "Add Scope Rule" page. [As displayed in below image]

  • Click on "Web Address" radio buttion in the "Scope Rule Type". This will display "Web Address" section. [As displayed in above image at step 40.]

  • By default "Folder" radio button is selected and we will use this for our work out. Enter the url of the list for which you are configuring the search scope. For my example I entered "http://jatinprajapati:20918/Lists/Employees", for Employees list.

  • Leave other settings as it is and click Ok.

  • This way we've added a rule for the search scope.

  • You can add more rules to the single search scope.

  • When you scheduled search crawl runs, after that your new created search scope will be used in search.

  • To manually start the search crawl follow the below steps.

  • Open SharePoint 3.0 Central Administration.

  • Click on the link for SharedServices if any.

  • On Shared Services page click on "Search settings" in "Search" section.

  • On "Configure Search Settings" click on "Content sources and crawl schedules" link.

  • On "Manage Content Sources" right click "Local Office SharePoint Server Sites" in the Name column and click "Start Full Crawl". This will the start the full crawl for the SharePoint and sets the "Status" to "Crawling Full". Frequently Refresh the page and wait for the status to be "Idle".

  • Afther the status gets "Idle", go to your site. Before adding the web part to the web part we need to activate the feature which will add the web part to the web part gallary for the site. [As we have used the Web Part feature item template for this project].

  • To enable the feature go to Site Settings and go to "Site collection features" page by clicking "Site collection features" link in "Site Collection Administration".

  • On Site Collection Features page find your web part feature and Activate it.

  • If you have configured your web part's scope to Web, then you need to go for "Site features".

  • Now, create a new web part page and add that web part on the page.

  • As, we have created the Searc Scope property for the web part. First don't set that web part and try to search for any keyword by entering the word in search box.

  • At this stage you will get the search results from many of the list if your key word matches.

  • Now edit the page and set the web part's Searc Scope property to new name of your created search scope.

  • Now try to find the keyword and you will get the results only from your configured list.

  • Summary

    This type of criteria is useful when you are branding your site as well as only particular list are used for search results. Hope this will help you a lot. You can download the fully working source code from below link.

    Source code

    CustomSearchScope


    By Jatin Prajapati   Popularity  (3203 Views)
    Picture
    Biography - Jatin Prajapati
    I think, most of the people are interested only in answers so no Biography provided... Want know more just write me at jatin.prajapati.er@gmail.com