Freigeben über


How to develop a custom SharePoint search webpart

This sample SharePoint webpart is meant to do search using search web service and result the result and show it on SPGridView.

create a new class library in visual studio and paste the below code.

using System;

using System.Data;

using System.Reflection;

using System.Runtime.InteropServices;

using System.Text;

using System.Web;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Serialization;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint.WebPartPages;

using Microsoft.Office.Server.Search;

using Microsoft.Office.Server.Search.WebControls;

using System.IO;

using Microsoft.Office.Server.Search.Query;

using System.Globalization;

namespace SampleGridViewTest

{

public class ErrorTrap

{

public void LogTheMessage(string myMessage)

{

using (StreamWriter sw = new StreamWriter("C:\\error.txt"))

{

sw.Write(myMessage.ToString());

}

}

}

[Guid("7586970D-0EE6-446b-875F-CFE71052C171")]

public class SampleGridViewClass : Microsoft.SharePoint.WebPartPages.WebPart

{

SPGridView GridView1 = new SPGridView();

ObjectDataSource DataSource1 = new ObjectDataSource();

Button Submit = new Button();

TextBox Search = new TextBox();

public static DataTable FillDataTable(string SearchText)

{

try

{

if (SearchText != null)

{

StringBuilder query = new StringBuilder();

query.Append("<QueryPacket xmlns='urn:Microsoft.Search.Query'>");

query.Append("<Query><SupportedFormats><Format revision='1'>urn:Microsoft.Search.Response.Document:Document</Format></SupportedFormats>");

query.Append("<Context><QueryText language='en-US' type=\"MSSQLFT\">");

query.Append("SELECT Size, Rank, HitHighLightedSummary, Path, Title, author, Description, Write FROM scope()");

query.Append("WHERE (\"SCOPE\" = 'TCS') AND FREETEXT(DEFAULTPROPERTIES,'" + SearchText.ToString() + "')");

query.Append("ORDER BY Rank desc</QueryText></Context><Range><StartAt>1</StartAt><Count>5000</Count></Range><TrimDuplicates>false</TrimDuplicates><IgnoreAllNoiseQuery>false</IgnoreAllNoiseQuery><IncludeRelevantResults>true</IncludeRelevantResults><IncludeHighConfidenceResults>false</IncludeHighConfidenceResults><EnableStemming>false</EnableStemming></Query></QueryPacket>");

QueryWebService.QueryService queryService = new QueryWebService.QueryService();

queryService.Url = "https://testserver1:7045/_vti_bin/search.asmx";

queryService.PreAuthenticate = true;

queryService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

System.Data.DataSet queryResults = queryService.QueryEx(query.ToString());

return queryResults.Tables[0];

}

else

{

return null;

}

}

catch (Exception ex)

{

ErrorTrap e = new ErrorTrap();

e.LogTheMessage("FillDataTable" + ex.Message + Environment.NewLine + ex.StackTrace.ToString());

return null;

}

}

public void Submit_Click(object sender, EventArgs e)

{

try

{

Parameter p = new Parameter("SearchText", DbType.String, Search.Text);

DataSource1.SelectParameters["SearchText"] = p;

GridView1.DataBind();

}

catch (Exception ex)

{

ErrorTrap f = new ErrorTrap();

f.LogTheMessage("SubmitClick" + ex.Message + Environment.NewLine + ex.StackTrace.ToString());

}

}

public void CreateGrid()

{

if (Page.IsPostBack == true)

{

GridView1 = new SPGridView();

GridView1.AutoGenerateColumns = false;

GridView1.PageSize = 10;

GridView1.AllowPaging = true;

GridView1.PagerStyle.HorizontalAlign = HorizontalAlign.Center;

GridView1.PageIndexChanging += new GridViewPageEventHandler(GridView1_PageIndexChanging);

CreateGridViewColumns("Size");

CreateGridViewColumns("Rank");

CreateGridViewColumns("HitHighLightedSummary");

CreateGridViewColumns("Path");

CreateGridViewColumns("Title");

CreateGridViewColumns("author");

CreateGridViewColumns("Description");

CreateGridViewColumns("Write");

DataSource1 = new ObjectDataSource();

string strTypeName = "SampleGridViewTest,";

strTypeName += Assembly.GetExecutingAssembly().FullName;

DataSource1.TypeName = String.Format("{0},{1}", this.GetType().FullName, Assembly.GetExecutingAssembly().FullName);

DataSource1.SelectMethod = "FillDataTable";

DataSource1.SelectParameters.Add("SearchText", "");

DataSource1.SelectParameters["SearchText"].Direction = ParameterDirection.Input;

DataSource1.ID = "MyDataSource";

Controls.Add(DataSource1);

GridView1.DataSourceID = DataSource1.ID;

Controls.Add(GridView1);

GridView1.PagerTemplate = null;

}

}

protected override void CreateChildControls()

{

Submit = new Button();

Submit.Text = "Search";

Submit.Click += new EventHandler(Submit_Click);

Controls.Add(Submit);

Search = new TextBox();

Search.Text = "";

Controls.Add(Search);

CreateGrid();

base.CreateChildControls();

}

protected override void RenderWebPart(HtmlTextWriter output)

{

base.RenderWebPart(output);

}

private void CreateGridViewColumns(string strColumn)

{

BoundField oGridColumn = new BoundField();

oGridColumn.DataField = strColumn;

oGridColumn.HeaderText = strColumn;

oGridColumn.Visible = true;

GridView1.Columns.Add(oGridColumn);

}

void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

GridView1.PageIndex = e.NewPageIndex;

}

}

}