Walkthrough: Creating a Custom Enterprise Search Web Part

With Enterprise Search in Microsoft Office SharePoint Server 2007, you can customize the look and functionality of the Search Center pages and Web Parts from the browser. However, if you want to make customizations that are not possible through the browser, you can create custom Web Parts that use the Query object model to execute queries against the search component.

In this walkthrough, you'll create a custom search Web Part and add it to your site. The Web Part described in this walkthrough provides very basic search functionality.

This walkthrough addresses the following tasks:

  • Creating the project for the Web Part

  • Coding the Web Part

  • Deploying the Web Part

Prerequisites

To perform this walkthrough, you will need the following:

  • Microsoft Visual Studio 2005 installed on your development computer

  • Microsoft Office SharePoint Server 2007 installed on your development computer

  • Permissions to create and modify pages for the Search Center site

Setting Up the Custom Search Web Part Project

To create the project for the Web Part

  1. In Visual Studio 2005, on the File menu, point to New, and then click Project.

  2. In Project types, under C#, select Windows.

  3. Under Templates, select Web Control Library. In the Name field, type CustomSearchWebPart, and then click OK.

Next you must add the required references to your Web Part project.

Note

The supported development environment configuration for Microsoft Office SharePoint Server 2007 is to develop locally on a server with Microsoft Office SharePoint Server 2007 installed.

To add references to CustomSearchWebPart project

  1. On the Project menu, click Add Reference.

  2. On the .NET tab, select each of the following references, and then click OK after each selection:

    • System.Data

    • System.XML

    • Microsoft.SharePoint

    • Microsoft.Office.Server

    • Microsoft.Office.Server.Search

Before you add code for the Web Part, replace the default class file with a new class file.

To create the class file for the Web Part

  1. In Solution Explorer, right-click WebCustomControl1.cs, and then click Delete to remove the default class created with the project.

  2. On the Project menu, click Add New Item.

  3. In the Add New Item dialog box, click Web Custom Control, type clsSearchQuery.cs, and then click Add.

Writing the Custom Search Web Part Code

You will now modify the default code that is included in the new class file.

To modify the default code in clsSearchQuery

  1. Add the following namespace directives near the top of the code in clsSearchQuery.cs:

    using System.Drawing;
    using System.Data;
    using System.Xml;
    using System.Xml.Serialization;
    using Microsoft.SharePoint.WebPartPages;
    using Microsoft.Office.Server;
    using Microsoft.Office.Server.Search.Query;
    
  2. In the following code line, replace WebControl with WebPart:

    public class clsSearchQuery : WebControl
    
  3. Add the following line of code above the class declaration for clsSearchQuery:

    [XmlRoot(Namespace = "CustomSearchWebPart")]
    

Now you're ready to write the code to query the search component, and then render the contents of the Web Part.

To add the Web Part's child controls and render them

  1. Add the following code below the class declaration:

            Button cmdSearch;
            TextBox txtQueryText;
            Label lblQueryResult;
            DataGrid grdResults;
    
  2. Override the CreateChildControls method by using the following code:

    protected override void CreateChildControls()
            {
                Controls.Clear();
                txtQueryText = new TextBox();
                this.Controls.Add(txtQueryText);
                cmdSearch = new Button();
                cmdSearch.Text = "Start Search";
                cmdSearch.Click += new EventHandler(cmdSearch_Click);
                this.Controls.Add(cmdSearch);
                lblQueryResult = new Label();
                this.Controls.Add(lblQueryResult);
            }
    
  3. Add a click event for cmdSearch, using the following code:

            void cmdSearch_Click(object sender, EventArgs e)
            {
                if (txtQueryText.Text != string.Empty)
                {
                  keywordQueryExecute(txtQueryText.Text);
                }
                else
                {
                  lblQueryResult.Text = "You must enter a search word.";
                }
              }
    

Now you're ready to add the code to access the Query object model. This code sample uses the Microsoft.Office.Server.Search.Query.KeywordQuery class to execute the search query, passing the Microsoft.Office.Server.ServerContext object for the parameter value. The search query is a simple keyword query that searches for results where the Author property matches the search term.

To execute the keyword query

  1. Add the following code to clsSearchQuery class:

    private void keywordQueryExecute(string strQueryText)
            {
                KeywordQuery kRequest = new KeywordQuery(ServerContext.Current);
                string strQuery = "author:" + strQueryText;
                kRequest.QueryText = strQuery;
                //to return relevant results
                kRequest.ResultTypes |= ResultType.RelevantResults;
                ResultTableCollection resultTbls = kRequest.Execute();
                if ((int)ResultType.RelevantResults != 0)
                {
                    ResultTable tblResult = resultTbls [ResultType.RelevantResults];
                    if (tblResult.TotalRows == 0)
                    {
                      lblQueryResult.Text = "No Search Results Returned.";
                    }
                    else
                    {
                        ReadResultTable(tblResult);
                    }
    
                }
    }
    
  2. To read the search results data, the keywordQueryExecute method calls the ReadResultTable method. Add the following code for ReadResultTable:

    void ReadResultTable(ResultTable rt)
            {
                DataTable relResultsTbl = new DataTable();
                relResultsTbl.TableName = "Relevant Results";
                DataSet ds = new DataSet("resultsset");
                ds.Tables.Add(relResultsTbl);
                ds.Load(rt,LoadOption.OverwriteChanges,relResultsTbl);
                fillResultsGrid(ds);
            }
    
  3. The ReadResultTable method calls the fillResultsGrid method to bind the search results DataSet to the grdResults DataGrid. Add the code for fillResultsGrid:

    private void fillResultsGrid(DataSet grdDs)
            {
    //Instantiate the DataGrid, and set the DataSource
                grdResults = new DataGrid();
                grdResults.DataSource = grdDs;
    //Set the display properties for the DataGrid.
                grdResults.GridLines = GridLines.None;
                grdResults.CellPadding = 4;
                grdResults.Width = Unit.Percentage(100);
                grdResults.ItemStyle.ForeColor = Color.Black;
                grdResults.ItemStyle.BackColor = Color.AliceBlue;
                grdResults.ItemStyle.Font.Size = FontUnit.Smaller;
                grdResults.ItemStyle.Font.Name = "Tahoma";
                grdResults.HeaderStyle.BackColor = Color.Navy;
                grdResults.HeaderStyle.ForeColor = Color.White;
                grdResults.HeaderStyle.Font.Bold = true;
                grdResults.HeaderStyle.Font.Name = "Tahoma";
                grdResults.HeaderStyle.Font.Size = FontUnit.Medium;
    
    /*Turn off AutoGenerate for the columns, so that the DataGrid
    doesn't automatically bind to all of the columns
    in the search results set.
    Then create and configure only the columns you want to
    include in the DataGrid.
    */
                grdResults.AutoGenerateColumns = false;
                HyperLinkColumn colTitle = new HyperLinkColumn();
                colTitle.DataTextField = "Title";
                colTitle.HeaderText = "Title";
                colTitle.DatahrefField = "Path";
                grdResults.Columns.Add(colTitle);
                BoundColumn colAuthor = new BoundColumn();
                colAuthor.DataField = "Author";
                colAuthor.HeaderText = "Author";
                grdResults.Columns.Add(colAuthor);
    //Bind the data to the DataGrid
                grdResults.DataBind();
    //Add the DataGrid to the controls
                Controls.Add(grdResults);
            }
    

Deploying the Custom Search Web Part

Because the Custom Search Web Part that you create from this sample is not strong-named, you cannot deploy it to the global assembly cache. You must deploy it to the _app_bin directory for your site.

To deploy the Custom Search Web Part to your site

  1. Copy CustomSearchWebPart.dll to your site's _bin directory. The path will resemble the following:

    \Inetpub\wwwroot\wss\VirtualDirectories\Site\_app_bin
    

    Note

    If you do not know the application path for your site, you can verify this in Internet Services Manager.

  2. Open the Internet Services Manager console, expand the Web Sites node, right-click the application for your site, and then click Properties.

  3. Click the Home Directory tab.

    The Local path field contains the path to the application.

To register the Custom Search Web Part as a SafeControl

  1. Open the web.config file for the site you want to add the Custom Search Web Part to. You can find this file in the root folder for the site.

  2. Add the following <SafeControl/> tag to the <SafeControls> </SafeControls> section of the web.config:

    <SafeControl Assembly="CustomSearchWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" Namespace="CustomSearchWebPart" TypeName="*" Safe="True" />
    
  3. Save your changes, and then close the web.config file.

To create the Custom Search Web Part definition file

  1. Open a new file in a text editor such as Notepad, and add the following XML code to the file:

    <?xml version="1.0"?>
    <WebPart xmlns="https://schemas.microsoft.com/WebPart/v2">
       <Assembly>CustomSearchWebPart, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=null</Assembly>
       <TypeName>CustomSearchWebPart.clsSearchQuery</TypeName>
       <Title>Custom Search Web Part</Title>
    </WebPart>
    
  2. Name the file CustomSearchWebPart.dwp, and then save it.

    Note

    If you are not working on the Office SharePoint Server 2007 server, then to complete this step you must copy the file to an Office SharePoint Server 2007 server.

To register the Custom Search Web Part as a SafeControl

  1. Open the web.config for the site you want to add the Custom Search Web Part to.

  2. Add the following <SafeControl/> tag to the <SafeControls> section of the web.config:

    <SafeControl Assembly="CustomSearchWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" Namespace="CustomSearchWebPart" TypeName="*" Safe="True" />
    

To deploy the Custom Search Web Part to your site

  • Copy CustomSearchWebPart.dll to your site's _bin directory. The path will resemble the following:

    \Inetpub\wwwroot\wss\VirtualDirectories\Site
    

Next Steps

You can find the complete code for the clsSearchQuery class sample in Sample: Custom Enterprise Search Web Part Code.

After you deploy the Web Part, you are ready to test it.

To test the Custom Search Web Part

  1. Open the Search Center site in your browser, click the Site Actions menu, and then click Create Page.

  2. In the URL Name field, type customsearchwebparttest.

  3. In the Title field, type Test Page for Custom Search Web Part.

  4. In the Page Layout list, select (Welcome Page) Search Page.

  5. To create the page, click Create.

  6. With the customsearchwebparttest.aspx page open in the browser, click the Add a Web Part link in the Top Zone.

  7. In the Add Web Parts dialog box, click the Advanced Web Part gallery and options link.

  8. Click the Browse link, and then click Import.

  9. Click Browse, navigate to the location where you saved CustomSearchWebPart.dwp, select it, and then click Open.

    You should now see the Custom Search Web Part in the dialog box. You can drag it onto the page to use it.

See Also

Tasks

Walkthrough: Creating an ASP.NET Web Part for the AdventureWorks Business Data Application Sample

Reference

Enterprise Search Keyword Syntax Reference
Microsoft.Office.Server.Search.Query.KeywordQuery

Concepts

Getting Started with Custom Enterprise Search Web Parts
Enterprise Search Query Object Model Overview