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.
Applies to: 2007 Microsoft Office System, Microsoft Office SharePoint Server 2007
Joel Krist, Akona Systems
October 2007
Code It | Read It | Explore It
Code It
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:
Creating a Web Control Library project in Visual Studio 2005.
Adding references to the required assemblies to the Visual Studio project.
Adding code that implements the Enterprise Search functionality.
Deploying the Web Part to an Office SharePoint Server 2007 site.
First, you create a Web Control Library project in Visual Studio.
Start Visual Studio 2005.
On the File menu, point to New, and then click Project.
In the New Project dialog box, in the Project Types pane, expand Visual C# or Visual Basic, and then select Windows.
In the Templates pane, select Web Control Library.
Type CustomSearchWebParts for the name of the project.
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.
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.
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.
If you are running Visual Studio on a server that has Office SharePoint Server 2007 installed:
In Solution Explorer, right-click the CustomSearchWebParts project, and then click Add Reference.
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)
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:
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
In Solution Explorer, right-click the CustomSearchWebParts project, and then click Add Reference.
In the Add Reference dialog box, on the Browse tab, navigate to the local folder that contains the copies of the assembly files.
Press and hold the CTRL key, and select Microsoft.Office.Server.dll, Microsoft.Office.Server.Search.dll, and Microsoft.SharePoint.dll.
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.
In Solution Explorer, right-click the CustomSearchWebParts project, and then click Add Reference.
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)
Click OK to add the references to the project.
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.
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.
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); } }
Build the CustomSearchWebParts project.
Use the following procedure to deploy the sample Web Part to an Office SharePoint Server site.
Determine the path to the _app_bin folder for the Office SharePoint Server site:
In Internet Information Services (IIS), in the IIS Manager console, expand the Web Sites node.
Right-click the application for the site, and then click Properties.
On the Home Directory tab, the Local path displays the path to the application.
Copy the CustomSearchWebParts.dll assembly file to the _app_bin folder of the Office SharePoint Server site.
Register the sample Web Part as a safe control:
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.
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" />
Restart IIS.
Open a Command Prompt window on the server. At the command prompt, type iisreset.
Create a Web Part definition file for the sample Web Part:
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>
Name the file CustomSearchWebPart.dwp, and then save it to a folder that you can access from Office SharePoint Server.
Add the Web Part to the Web Part gallery of the Office SharePoint Server site:
On the Site Actions menu, click Site Settings, and then click Modify All Site Settings.
On the Site Settings page, in the Galleries section, click Web Parts.
On the Web Part Gallery page, click Upload.
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
In the Group section, in the drop-down list, select Default Web Parts.
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.
On the Search Center site, click Site Actions, and then click Create Page.
Type Test Page for Custom Search Web Part for the Title.
In the Page Layout list, click (Welcome Page) Search Page.
To create the page, click Create.
With TestPageforCustomSearchWebPart.aspx open in the browser, in the Top Zone, click Add a Web Part.
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
Click Add to add the Web Part to the zone.
Figure 3. Custom Search Web Part
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
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:
Creating a Web Control Library project in Visual Studio.
Adding references to the required assemblies to the Visual Studio project.
Adding code that implements the Enterprise Search functionality.
Deploying the Web Part to an Office SharePoint Server site.