Creating Custom Enterprise Search Web Parts in SharePoint Server 2007

Summary:  Learn how to create a custom Enterprise Search Web Part in Microsoft Office SharePoint Server 2007.

Office Visual How To

Applies to:  2007 Microsoft Office System, Microsoft Office SharePoint Server 2007

Joel Krist, Akona Systems

October 2007

Overview

With Enterprise Search in Microsoft Office SharePoint Server 2007, you can customize the look and functionality of Search Center pages and Web Parts from the browser. To make customizations that are not possible through the browser, you can create a custom Web Part that uses the Query object model to execute queries against the search component. This Office Visual How To article demonstrates creating a custom Enterprise Search Web Part in Office SharePoint Server 2007.

See It Creating Custom Enterprise Search Web Parts

Watch the Video

Length: 08:36 | Size: 12.2 MB | Type: WMV file

Code It | Read It | Explore It

Code It

Download the Code Sample

In the following sections, you use Microsoft Visual Studio 2005 to create a Web Control Library that contains a Web Part that uses the Enterprise Search functionality included with Office SharePoint Server 2007. The sample Web Part accepts a search term via its user interface and then performs a query that searches for results in which the Author property matches the search term. Creating the Web Part requires four major steps. They are:

  1. Creating a Web Control Library project in Visual Studio 2005.

  2. Adding references to the required assemblies to the Visual Studio project.

  3. Adding code that implements the Enterprise Search functionality.

  4. Deploying the Web Part to an Office SharePoint Server 2007 site.

Creating a Web Control Library Project in Visual Studio

First, you create a Web Control Library project in Visual Studio.

To create a Web Control Library project in Visual Studio

  1. Start Visual Studio 2005.

  2. On the File menu, point to New, and then click Project.

  3. In the New Project dialog box, in the Project Types pane, expand Visual C# or Visual Basic, and then select Windows.

  4. In the Templates pane, select Web Control Library.

  5. Type CustomSearchWebParts for the name of the project.

  6. Specify a location for the project, and then click OK.

    Visual Studio generates a Web Control Library project that contains a single source file named WebCustomControl1.cs or WebCustomControl1.vb, depending on the language you selected in Step 3.

  7. In Solution Explorer, right-click the WebCustomControl1.cs or WebCustomControl1.vb source file, and then click Rename. Name the file AuthorSearchWebPart.cs or AuthorSearchWebPart.vb, depending on the language you are using.

Adding References to the Required Assemblies

The sample code in this article uses classes provided with the Microsoft.Office.Server namespace, the Microsoft.Office.Server.Search.Query namespace, and the Microsoft.SharePoint namespace. You must add references to necessary assemblies to the project so that you can use these objects.

To add references to the required assemblies

  • If you are running Visual Studio on a server that has Office SharePoint Server 2007 installed:

    1. In Solution Explorer, right-click the CustomSearchWebParts project, and then click Add Reference.

    2. On the .NET tab of the Add Reference dialog box, press and hold the CTRL key, and select the following components:

      Microsoft Office Server (Microsoft.Office.Server.dll)

      Microsoft Office SharePoint Server Search (Microsoft.Office.Server.Search.dll)

      Windows SharePoint Services (Microsoft.SharePoint.dll)

    3. Click OK to add the references to the project.

    If you are running Visual Studio on a computer that does not have Office SharePoint Server 2007 installed, the necessary assemblies are not available. In this case:

    1. Copy the Microsoft.Office.Server.dll file, the Microsoft.Office.Server.Search.dll file, and the Microsoft.SharePoint.dll file from a server running Office SharePoint Server 2007 to a local project folder on the development computer. The following is the default assembly location on a computer that is running Office SharePoint Server 2007:

      %ProgramFiles%\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI

    2. In Solution Explorer, right-click the CustomSearchWebParts project, and then click Add Reference.

    3. In the Add Reference dialog box, on the Browse tab, navigate to the local folder that contains the copies of the assembly files.

    4. Press and hold the CTRL key, and select Microsoft.Office.Server.dll, Microsoft.Office.Server.Search.dll, and Microsoft.SharePoint.dll.

    5. Click OK to add the references to the project.

The sample code in this article also uses classes defined in the System.Data namespace and the System.XML namespace. You must add the necessary references to the Visual Studio project so that you can use these classes.

To add references to System.Data and System.XML

  1. In Solution Explorer, right-click the CustomSearchWebParts project, and then click Add Reference.

  2. On the .NET tab of the Add Reference dialog box, press and hold the CTRL key, and select the following components:

    System.Data (System.Data.dll)

    System.Xml (System.XML.dll)

  3. Click OK to add the references to the project.

Implementing the Author Search Web Part Functionality

After you add the references to the required assemblies, you add the code that provides the ability for the Web Part to perform a search for items where the Author property matches a search term.

To implement the Author search Web Part functionality

  1. Add the following Imports or using statements to the top of the AuthorSearchWebPart.cs or AuthorSearchWebPart.vb source file. Add the statements after the Imports or using statements that Visual Studio generated when you created the project.

    Imports System.Drawing
    Imports System.Data
    Imports System.Xml.Serialization
    Imports Microsoft.SharePoint.WebPartPages
    Imports Microsoft.Office.Server
    Imports Microsoft.Office.Server.Search.Query
    
    using System.Drawing;
    using System.Data;
    using System.Xml.Serialization;
    using Microsoft.SharePoint.WebPartPages;
    using Microsoft.Office.Server;
    using Microsoft.Office.Server.Search.Query;
    

    The Imports and using statements enable you to use the classes and types defined in the referenced namespaces without needing to use fully qualified namespace paths.

  2. Replace the version of the AuthorSearchWebPart class definition that Visual Studio generated with the following code.

    <XmlRoot(Namespace:="CustomSearchWebParts")> _
    Public Class AuthorSearchWebPart
        Inherits WebPart
    
        Dim cmdSearch As Button
        Dim txtQueryText As TextBox
        Dim lblQueryResult As Label
        Dim grdResults As DataGrid
    
        Protected Overrides Sub CreateChildControls()
            ' Create and add the controls that compose the
            ' user interface of the Web Part. 
            Controls.Clear()
    
            txtQueryText = New TextBox()
            Me.Controls.Add(txtQueryText)
    
            cmdSearch = New Button()
            cmdSearch.Text = "Start Search"
            AddHandler cmdSearch.Click, AddressOf cmdSearch_Click
            Me.Controls.Add(cmdSearch)
    
            lblQueryResult = New Label()
            Me.Controls.Add(lblQueryResult)
        End Sub
    
        Private Sub cmdSearch_Click(ByVal sender As Object, _
            ByVal e As EventArgs)
            If txtQueryText.Text <> String.Empty Then
                keywordQueryExecute(txtQueryText.Text)
            Else
                lblQueryResult.Text = "You must enter a search word."
            End If
        End Sub
    
        Private Sub keywordQueryExecute(ByVal strQueryText As String)
            Dim kRequest As KeywordQuery = _
                New KeywordQuery(ServerContext.Current)
            Dim strQuery As String = "author:" + strQueryText
            kRequest.QueryText = strQuery
    
            ' Configure the query to return relevant results.
            kRequest.ResultTypes = _
                kRequest.ResultTypes Or ResultType.RelevantResults
    
            ' Execute the query.
            Dim resultTbls As ResultTableCollection = kRequest.Execute()
    
            If ResultType.RelevantResults <> 0 Then
                Dim tblResult As ResultTable = _
                    resultTbls(ResultType.RelevantResults)
    
                If tblResult.TotalRows = 0 Then
                    lblQueryResult.Text = "No Search Results Returned."
                Else
                    ReadResultTable(tblResult)
                End If
            End If
        End Sub
    
        Private Sub ReadResultTable(ByVal rt As ResultTable)
            ' Create a DataSet and load the returned ResultTable into it.
            Dim relResultsTbl As DataTable = New DataTable()
            relResultsTbl.TableName = "Relevant Results"
            Dim ds As DataSet = New DataSet("resultsset")
            ds.Tables.Add(relResultsTbl)
            ds.Load(rt, LoadOption.OverwriteChanges, relResultsTbl)
    
            ' Add the results to the DataGrid.
            fillResultsGrid(ds)
        End Sub
    
        Private Sub fillResultsGrid(ByVal grdDs As DataSet)
            ' Create an instance of the DataGrid and set its
            ' DataSource property to the supplied DataSet.
            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
            ' does not automatically bind to all of the columns in the 
            ' search results set. Then create and configure the DataGrid
            ' to display only the desired columns.
    
            grdResults.AutoGenerateColumns = False
            Dim colTitle As HyperLinkColumn = New HyperLinkColumn()
            colTitle.DataTextField = "Title"
            colTitle.HeaderText = "Title"
            colTitle.DatahrefField = "Path"
            grdResults.Columns.Add(colTitle)
            Dim colAuthor As BoundColumn = 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)
        End Sub
    End Class
    
    [XmlRoot(Namespace = "CustomSearchWebParts")]
    public class AuthorSearchWebPart : WebPart
    {
        Button cmdSearch;
        TextBox txtQueryText;
        Label lblQueryResult;
        DataGrid grdResults;
    
        protected override void CreateChildControls()
        {
            // Create and add the controls that compose the
            // user interface of the Web Part. 
            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);
        }
    
        void cmdSearch_Click(object sender, EventArgs e)
        {
            if (txtQueryText.Text != string.Empty)
            {
                keywordQueryExecute(txtQueryText.Text);
            }
            else
            {
                lblQueryResult.Text = "You must enter a search word.";
            }
        }
    
        private void keywordQueryExecute(string strQueryText)
        {
            KeywordQuery kRequest =
                new KeywordQuery(ServerContext.Current);
            string strQuery = "author:" + strQueryText;
            kRequest.QueryText = strQuery;
    
            // Configure the query to return relevant results.
            kRequest.ResultTypes |= ResultType.RelevantResults;
    
            // Execute the query.
            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);
                }
            }
        }
    
        void ReadResultTable(ResultTable rt)
        {
            // Create a DataSet and load the returned ResultTable into it.
            DataTable relResultsTbl = new DataTable();
            relResultsTbl.TableName = "Relevant Results";
            DataSet ds = new DataSet("resultsset");
            ds.Tables.Add(relResultsTbl);
            ds.Load(rt, LoadOption.OverwriteChanges, relResultsTbl);
    
            // Add the results to the DataGrid.
            fillResultsGrid(ds);
        }
    
        private void fillResultsGrid(DataSet grdDs)
        {
            // Create an instance of the DataGrid and set its 
            // DataSource property to the supplied DataSet.
            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
            // does not automatically bind to all of the columns in the 
            // search results set. Then create and configure the DataGrid
            // to display only the desired columns.
    
            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);
        }
    }
    
  3. Build the CustomSearchWebParts project.

Deploying the Web Part to SharePoint Server 2007

Use the following procedure to deploy the sample Web Part to an Office SharePoint Server site.

To deploy the sample Web Part to an Office SharePoint Server site

  1. Determine the path to the _app_bin folder for the Office SharePoint Server site:

    1. In Internet Information Services (IIS), in the IIS Manager console, expand the Web Sites node.

    2. Right-click the application for the site, and then click Properties.

    3. On the Home Directory tab, the Local path displays the path to the application.

  2. Copy the CustomSearchWebParts.dll assembly file to the _app_bin folder of the Office SharePoint Server site.

  3. Register the sample Web Part as a safe control:

    1. Open the web.config file for the site that you are adding the Web Part to.

      The web.config file is in the root folder for the site.

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

      <SafeControl Assembly="CustomSearchWebParts, Version=1.0.0.0,
      Culture=neutral, PublicKeyToken=null" Namespace="CustomSearchWebParts" 
      TypeName="*" Safe="True" />
      
  4. Restart IIS.

  5. Open a Command Prompt window on the server. At the command prompt, type iisreset.

  6. Create a Web Part definition file for the sample Web Part:

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

      <?xml version="1.0"?>
      <WebPart xmlns="https://schemas.microsoft.com/WebPart/v2">
         <Assembly>CustomSearchWebParts, Version=1.0.0.0, Culture=Neutral,
           PublicKeyToken=null</Assembly>
         <TypeName>CustomSearchWebParts.AuthorSearchWebPart</TypeName>
         <Title>Custom Search Web Part</Title>
         <Description>A custom search web part.</Description>
      </WebPart>
      
    2. Name the file CustomSearchWebPart.dwp, and then save it to a folder that you can access from Office SharePoint Server.

  7. Add the Web Part to the Web Part gallery of the Office SharePoint Server site:

    1. On the Site Actions menu, click Site Settings, and then click Modify All Site Settings.

    2. On the Site Settings page, in the Galleries section, click Web Parts.

    3. On the Web Part Gallery page, click Upload.

    4. On the Upload Web Part: Web Part Gallery page, browse to and select the CustomSearchWebPart.dwp file that you created previously. Select Overwrite existing file(s), and then click OK.

      The CustomSearchWebPart.dwp file provisions the Web Part Gallery: CustomSearchWebPart page.

      Figure 1. Adding the Web Part to the Web Part gallery

      Adding the Web Part to the Web Part gallery

    5. In the Group section, in the drop-down list, select Default Web Parts.

    6. If you want to include the Web Part in the Quick Add Groups list, select Default. If you want to leave the custom Web Part out of the Quick Add Groups list, clear the check boxes. Click OK.

After you deploy the Web Part to the Office SharePoint Server site, you should test it.

To test the deployed Web Part

  1. On the Search Center site, click Site Actions, and then click Create Page.

  2. Type Test Page for Custom Search Web Part for the Title.

  3. In the Page Layout list, click (Welcome Page) Search Page.

  4. To create the page, click Create.

  5. With TestPageforCustomSearchWebPart.aspx open in the browser, in the Top Zone, click Add a Web Part.

  6. In the Add Web Parts to Top Zone dialog box, in the Default Web Parts category, select Custom Search Web Part.

    Figure 2. Adding the Web Part to the Top Zone

    Adding the Web Part to the Top Zone

  7. Click Add to add the Web Part to the zone.

    Figure 3. Custom Search Web Part

    Custom Search Web Part

  8. To return those items that were authored by the specified user, in the Custom Search Web Part, type a user name in the text box control, and then click Start.

    Figure 4. Search results

    Search results

For information about creating a custom search tab and a custom search results page, see the Office Visual How To titled Creating a Custom Search Page and Tabs in the Search Center of SharePoint Server.

Read It

This article demonstrates how to create a custom Enterprise Search Web Part in Office SharePoint Server 2007. The steps are:

  1. Creating a Web Control Library project in Visual Studio.

  2. Adding references to the required assemblies to the Visual Studio project.

  3. Adding code that implements the Enterprise Search functionality.

  4. Deploying the Web Part to an Office SharePoint Server site.

Explore It