SharePoint 2010 : Searching Through the API - Creating a Custom Search Application Page

3/27/2013 7:29:14 PM

In this section, we describe how to create a new application page in SharePoint with search functionality. The example provided is designed to be easy to implement and deploy. Using an application page, which is stored as a physical file on the front-end server, makes it easy to extend and experiment with the query API. The example uses data binding to display the query result data in order to reduce the amount of non-search-related changes required when working with the search API. This example is intended to be easy to understand and extend with more complex functionality. Basic knowledge of Visual Studio 2010 and entry-level knowledge of programming in C#.NET are recommended but not required.

Setting Up the Solution

Start by creating a new project in Visual Studio 2010 on a front-end server on the farm where the project is to be deployed (Figure 1). If this is not possible, the Create Package functionality can be used. Choose the Empty SharePoint Project template, and give the project a proper name. In this example, the project is named SearchApplicationPage.


Figure 1. Creating a new SharePoint 2010 project

After creating the project, a prompt appears, asking for the SharePoint server farm URL. Enter the site URL where the solution is to be deployed. The prompt also asks if the solution should be sandboxed or deployed as a farm solution. Choose the option “Deploy as a farm solution” (Figure 2). It is always a good idea to validate the site that the solution is deployed to.


Figure 2. Deployment settings

The next step is to add an application page to the project. In SharePoint 2010, it is best practice to make application pages inherit from the LayoutsPageBase class, which is found in the namespace Microsoft.SharePoint.WebControls. This class is fairly simple but contains common functionality that makes development of application pages easier. When adding the application page, as shown in Figure 3, it automatically inherits from the LayoutsPageBase class.


Figure 3. Creating an application page

Application pages are not available in sandboxed solutions, as they are located in the Layouts folder in the SharePoint root folder structure (Figure 4). When adding a new application page to the project, as just shown, Visual Studio automatically creates the Layouts folder in the project and adds the .aspx and code-behind files to it. When the solution is deployed later on, the application page will automatically be added to the Layouts folder in the SharePoint root folder structure.


Figure 4. Layouts folder added to project containing application page files

Modifying the Application Page Markup

To make the application page useful, some edits to the .aspx page are required. To edit the layout of the application page and to add controls to it, open the SearchApplicationPage.axpx file.

First of all, the titles should be changed to something meaningful. Here the PlaceHolderPageTitle is changed to Search Application Page and the PlaceHolderPageTitleInTitleArea is changed to My Search Application Page.

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Search Application Page

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID=Image
"PlaceHolderPageTitleInTitleArea" runat="server" >
My Search Application Page

For the application page to have any meaningful functionality, some web controls need to be added. In this example, the application page is used for searching and showing simple search results. For this to work, the following five web controls are added in the content placeholder with the ID “PlaceHolderMain”:

  • Text box for entering search terms into
  • Button for executing the query
  • Label instructing user that the text box is for entering search terms
  • Gridview for showing search results (limited to ten results)
  • Label instructing user that the gridview shows search results

When done, the main content placeholder should look like Listing 1.

Listing 1. Rendering simple search results using the SPGridView control.

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<asp:Label>Enter search terms</asp:Label>
<asp:TextBox ID="searchText" runat="server" />
<asp:Button ID="searchButton" Text="Search" runat="server" />
<br /><br />
<asp:Label>Search results:</asp:Label>
<br />
<SharePoint:SPGridView ID="searchGridView" AllowPaging="true" PageSize="10"
AutoGenerateColumns="false" runat="server">
<asp:TemplateField HeaderText="Path">
<HeaderStyle Font-Bold="true"></HeaderStyle>
<ItemStyle Width="100" />
<asp:HyperLink Text='<%# Eval("Title") %>' NavigateUrl='<%# Eval("Path") %>'                               
<asp:BoundField DataField="Write" HeaderText="Edited" ItemStyle-Width="100px">
<HeaderStyle Font-Bold="true"></HeaderStyle>

Build and deploy the solution to SharePoint by right-clicking the project and choosing Deploy. After it is successfully deployed, the solution can be accessed by entering the following URL into the browser:

http://<site url>/_layouts/ SearchApplicationPage/SearchApplicationPage.aspx.

At this time, clicking the Search buttons does not perform any action. However, you will see a layout containing a text field for entering search terms, a button for executing the search, and a data gridview Web Part for displaying search results (Figure 5).


Figure 52. Simple search application page layout

Adding Code-Behind

Code-behind is the .NET code (C# is used in this book) that implements the logic for the markup. It is executed on the server and can alter the properties of the layout prior to rendering. Adding search capabilities to this application page is very easy. First, the assemblies required for the search API must be added as references to the SearchApplicationPage project (Figure 6). This is done by right-clicking the project and then adding references to the following assemblies:

  • Microsoft.Office.Server
  • Microsoft.Office.Server.Search

Both assemblies are usually located in the ISAPI folder in the SharePoint root folder.


Figure 6. Adding references to the search API

With the required references in place, only three changes are required in the code-behind file of the application page:

  • Adding “using” statements for the namespaces
  • An event handler for the button
  • A method to invoke from the event handler that executes the search

Open the file named SearchApplicationPage.axpx.cs, and add the following namespaces to the top of the file:

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server.Search.Query;
using System.Data;

The file contains the SearchApplicationPage class, which has only one default method. This is the Page_Load method. Inside the Page_Load method, add an event handler for the Search button. Each time the Search button gets clicked, the method called searchButton_Click will be invoked.

protected void Page_Load(object sender, EventArgs e)
    this.searchButton.Click += new EventHandler(searchButton_Click);

Last, but not least, the code for performing the search is added. This is encapsulated inside the searchButton_Click method.

A KeywordQuery object is initialized for the current site. Then the result provider is configured as default, which means that it uses SharePoint 2010 Search. The other alternative is to use FAST.

As this solution shows data in only one data gridview, only results of type RelevantResults are returned. The implicit operator for multiple keywords or search terms is set to AllKeywords. This means that there is an implicit AND between keywords if nothing else is specified. Finally the query text is added—the search terms that the user enters into the text field on the search application page. Now the KeywordQuery object is configured, and a search can be executed.

protected void searchButton_Click(object sender, EventArgs e)

    using (SPSite site = new SPSite(SPContext.Current.Web.Site.Url))
        KeywordQuery query = new KeywordQuery(site);
        query.ResultsProvider = Microsoft.Office.Server.Search.Query.SearchProvider.Default;
        query.ResultTypes = ResultType.RelevantResults;
        query.KeywordInclusion = KeywordInclusion.AllKeywords;
        query.QueryText = searchText.Text;

        ResultTableCollection results = query.Execute();

        if (results.Count > 0)
            ResultTable relevant = results[ResultType.RelevantResults];
            DataTable search = new DataTable();
            DataView view = new DataView(search);
            searchGridView.DataSource = search;

If executing the search yields any results, the RelevantResults are extracted from the search and loaded into a data table. This data table is then used as the data source in a data view. Finally a data binding is applied between the data gridview web control and the data view. Since it has already been determined that some results exist, the data gridview web control will now show these results. Keep in mind that the data gridview is configured to show only the first ten results.

Now deploy the solution again. Click the Search button to perform a search for the search terms and display any results in the data gridview web control (Figure 7).


Figure 7. Search application page with search results

Top 10
Review : Sigma 24mm f/1.4 DG HSM Art
Review : Canon EF11-24mm f/4L USM
Review : Creative Sound Blaster Roar 2
Review : Philips Fidelio M2L
Review : Alienware 17 - Dell's Alienware laptops
Review Smartwatch : Wellograph
Review : Xiaomi Redmi 2
Extending LINQ to Objects : Writing a Single Element Operator (part 2) - Building the RandomElement Operator
Extending LINQ to Objects : Writing a Single Element Operator (part 1) - Building Our Own Last Operator
3 Tips for Maintaining Your Cell Phone Battery (part 2) - Discharge Smart, Use Smart
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 1)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 2)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 3)
Popular Tags
Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Exchange Server Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe Photoshop CorelDRAW X5 CorelDraw 10 windows Phone 7 windows Phone 8 Iphone
Visit movie_stars's profile on Pinterest.