Share via


Sample: AdventureWorks Search Web Part Class Sample Code

Following is the complete sample code for the SearchProducts.cs sample, described in Step 2: Add the Code for the Custom Search Web Part of Walkthrough: Creating an ASP.NET Web Part for the AdventureWorks Business Data Application Sample.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.Office.Server.Search.Query;
using System.Xml;
using System.Xml.Xsl;
using System.Collections;
using System.Data;
using System.IO;


namespace customSearchBDC
{

    [ToolboxData("<{0}:SearchProducts runat=server></{0}:SearchProducts>")]
    [XmlRoot(Namespace = "customSearchBDC")]
    public class clsSearchQuery : System.Web.UI.WebControls.WebParts.WebPart
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]

        Table table;
        Label lblID;
        TextBox txtID;
        CompareValidator checkID;
        Label lblName;
        TextBox txtName;
        Button cmdSearch;
        Label lblResults;
        Xml xmlResults;
        Panel xmlPanel;


        protected override void CreateChildControls()
        {
//Create a table control to use for positioning the controls
            table = new Table();
            table.Width = Unit.Percentage(100);
            for(int i =0; i<5; i++)
            {
                TableRow row= new TableRow();
                TableCell cell = new TableCell();
                row.Cells.Add(cell);
                table.Rows.Add(row);
            }
//Create the controls for ProductID input.
            lblID = new Label();
            lblID.Text = "Product ID is:";
            lblID.Width = Unit.Pixel(150);
            txtID = new TextBox();
            txtID.ID = "txtID";
/*
The CompareValidator control is used here to validate
that the value entered for ProductID is an integer.
*/
            checkID = new CompareValidator();
            checkID.ControlToValidate = "txtID";
            checkID.Operator = ValidationCompareOperator.DataTypeCheck;
            checkID.Type = ValidationDataType.Integer;
            checkID.Text = "ProductID must be an integer.";
//Add the controls for the ProductID to the table.
            table.Rows[0].Cells[0].Controls.Add(lblID);
            table.Rows[0].Cells[0].Controls.Add(txtID);
            table.Rows[0].Cells[0].Controls.Add(checkID);
            table.Rows[0].Cells[0].Height = Unit.Pixel(40);
//Create the controls for Product Name input.
            lblName = new Label();
            lblName.Text = "Product Name contains:";
            txtName = new TextBox();
//Add the controls for the Product Name to the table.
            table.Rows[1].Cells[0].Controls.Add(lblName);
            table.Rows[1].Cells[0].Controls.Add(txtName);
            table.Rows[1].Cells[0].Height = Unit.Pixel(40);
//Create the search button and add to table control.
            cmdSearch = new Button();
            cmdSearch.Click += new EventHandler(cmdSearch_Click);
            cmdSearch.Text = "Search Products";
            table.Rows[3].Cells[0].Controls.Add(cmdSearch);
            table.Rows[3].Cells[0].Height = Unit.Pixel(40);
//Create label to display search message.
            lblResults = new Label();
            table.Rows[4].Cells[0].Controls.Add(lblResults);
    t       table.Rows[4].Cells[0].Height = Unit.Pixel(40);
//Add the table to the controls collection
}

        }

        void cmdSearch_Click(object sender, EventArgs e)
        {
            string strName = txtName.Text;
            string strID = txtID.Text;
/*
Validate that user entered something.
If not, prompt the user to enter an ID or search term.
*/
            if (strName == "" & strID == "")
            {
                lblResults.Text = "You must enter a Product ID or a Product name term for the Product Search.";
            }
            else
            {
                returnResults(buildSQL(strName, strID));
            }
        }

        private string buildSQL(string stName, string stID)
        {
        //This is the Scope ID for the AdventureWorks BDC application
            string BDCscopeID = "4";
        //Use the StringBuilder class for the syntax string
            StringBuilder sbSQL = new StringBuilder();
            sbSQL.Append("SELECT ProductName,ProductID,ProductNumber,Path FROM SCOPE() WHERE scope='");
            sbSQL.Append(BDCscopeID);
            sbSQL.Append("'");
            if (stName != "")
            {
                sbSQL.Append(" AND CONTAINS(ProductName,'");
                sbSQL.Append(stName);
                sbSQL.Append("')");
            }
            if (stID != "")
            {
                sbSQL.Append(" AND ProductID=");
                sbSQL.Append(stID);
            }
            return sbSQL.ToString();
        }

        private void returnResults(string strSQL)
        {
            try
            {
        /*
        Create the Xml control to use for displaying the results, and the Panel
        control to use as a container for the Xml control.
        */
                xmlPanel = new Panel();
                xmlResults = new Xml();
                xmlPanel.Controls.Add(xmlResults);
                Controls.Add(xmlPanel);
                HttpContext context = HttpContext.Current;
//Specify the path for the XSL.
                string path = context.Request.MapPath("/_layouts/productXSL.xsl");

//Replace <siteName> with the name of your site.
                string sPath = "http://<siteName>";
                FullTextSqlQuery sqlQuery = new FullTextSqlQuery(new SPSite(sPath));
//Specify result type to return.
                sqlQuery.ResultTypes = ResultType.RelevantResults;
//Specify the full text search query string.
                sqlQuery.QueryText = strSQL;
//Return the search results to a ResultTableCollection.
                ResultTableCollection results = sqlQuery.Execute();
//Create a ResultTable for the relevant results table.
                ResultTable relResults = results[ResultType.RelevantResults];

//Count the number of rows in the table; 0 = no search results.
                int x = relResults.RowCount;
                if (x !=0)
                {
                    lblResults.Text = x.ToString();
                    DataTable dtresults = new DataTable();
                    dtresults.TableName = "Result";
                    dtresults.Load(relResults, LoadOption.OverwriteChanges);
                    StringWriter writer = new StringWriter();
                    DataSet ds = new DataSet("All_Results");
                    ds.Tables.Add(dtresults);
                    ds.WriteXml(writer, XmlWriteMode.IgnoreSchema);
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(writer.ToString());
                    XslTransform trans = new XslTransform();
                    trans.Load(path);
                    xmlResults.Document = doc;
                    xmlResults.Transform = trans;
                }
                else
                {
//Send XML for an empty result set to the Xml control.
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml("<All_Results></All_Results>");
                    XslTransform trans = new XslTransform();
                    trans.Load(path);
                    xmlResults.Document = doc;
                    xmlResults.Transform = trans;
                }
            }
            catch (Exception ex1)
            {
                lblResults.Text = ex1.ToString();
            }
        }

}

See Also

Tasks

Step 2: Add the Code for the Custom Search Web Part
Walkthrough: Creating an ASP.NET Web Part for the AdventureWorks Business Data Application Sample