Laboratory/Develop

Search Your Web site with MSN Site Search.

theking 2008. 2. 19. 19:56
사용자 삽입 이미지

Introduction

This article is a follow up to my original articleSearch Your Web site with MSN Site Search. I noticed the article was still getting some traction so I decided to put together an updated version.

Changes in this version:

  • Code updated to Visual Studio 2008
  • Code refactoring for better encapsulation and performance
  • Enabled AJAX.NET support. Demo is now Ajax enabled
  • Updated deprecatedxml.xsltransform calls
  • Fixed some pagination bugs
  • Adding a single retry on failure from feed
  • Updated name to Windows Live.
  • Improved general display output

Background

In the example above, I am building the query string on the fly with the search string typed in my Web form. I then parse the RSS feed with an XSL stylesheet and display the results. The pagination is accomplished by passing parameters to the XSL file and handling the pagination within the XSL. To view this example, click the link above.

Using the Code

As you can see, the search works very well and is very fast. You can try searching my site for something like "ASP" or "XML" to generate a sufficient amount of search results.

I am making my code available for download. Please feel free to download it and use it on your site. It will work on any server that will run ASP.NET. There are only two variables that you need to change to personalize the search results in your site. In the ASPX file, you will find two variablessitenameandresultcount.sitenameis the fully qualified domain name of your site andresultcountspecifies the total number of results to return. You may want to adjust this based on the amount of content you have. The less total results you download on each query, the faster it will run.

.NET Code

사용자 삽입 이미지
Collapse
SubDisplaySearchResults()'check if user entered a search term.Ifterm.Text <>""ThenTry'initDimmsnXmlSrcAsString= MSNSearchURL & sitename &"+_                         "& searchterm &"&format=rss&FORM=ZZRE&count=_                         "& resultcount &"&first="& startDimmsnXslFileAsString= Server.MapPath(XslTranformFile)'load output into xml document.DimmsnXmlDocAsXmlDocument =NewXmlDocument()                msnXmlDoc.Load(msnXmlSrc)'set parameters.DimarglistAsXsltArgumentList =NewXsltArgumentList()                arglist.AddParam("top","", top)                arglist.AddParam("page","", pagenum)                arglist.AddParam("searchterm","", searchterm)'Transform xml/xslDimoutAsHtmlGenericControl = _                    TransformXml(msnXmlDoc, msnXslFile, arglist)'add control to placeholderIfResultPLC.Controls.Count >0ThenResultPLC.Controls.RemoveAt(0)                ResultPLC.Controls.Add(out)CatchexAsExceptionTry'retry onceIffailcount >0ThenThrowNewException(ex.Message)                    failcount = failcount +1DisplaySearchResults()Catchex2AsException'message errorDimlitOutAsNewLiteral                    litOut.Text = ex2.Message()                    ResultPLC.Controls.Add(litOut)EndTryEndTryElseDimlitOutAsNewLiteral            litOut.Text ="Please enter a search term."ResultPLC.Controls.Add(litOut)EndIfEndSubPublicFunctionTransformXml(ByValxmldocAsXmlDocument,ByValstylesheetAsString, _ByValparamsAsXsltArgumentList)AsSystem.Web.UI.HtmlControls.HtmlGenericControl'initDimm_TransformXmlAsNewSystem.Web.UI.HtmlControls.HtmlGenericControlDimswAsStringWriter =NewStringWriter()DimxslDocAsNewXslCompiledTransform()Try'perform transformationxslDoc.Load(stylesheet)            xslDoc.Transform(xmldoc, params, sw)CatchexAsException'bubble exceptionThrowNewException(ex.Message())Finally'free memorysw.Dispose()            xslDoc =NothingEndTry'return controlm_TransformXml.InnerHtml = sw.ToString()        sw.Dispose()Returnm_TransformXmlEndFunction

XSLT Transform File

사용자 삽입 이미지
Collapse
<xsl:stylesheetversion="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:outputmethod="html"/><xsl:paramname="top"/><xsl:paramname="page"/><xsl:paramname="searchterm"/><xsl:templatematch="/">You searched for "<xsl:value-ofselect="$searchterm"/>"<br/><hr/><xsl:for-eachselect="rss/channel/item"><xsl:iftest="position() < ($top*($page+1)) + 1 and position() > $page * $top"><ahref= "{link}"><spanclass="style1"><strong><xsl:value-ofselect="title"/></strong></span></a><br/><spanclass="style1"><xsl:value-ofdisable-output-escaping="no"select="translate(substring(description,1,150),'/',' /')"/><xsl:value-ofdisable-output-escaping="no"select="' ...'"/></span><br/><xsl:value-ofselect="link"/><br/><br/></xsl:if><xsl:iftest= "position()=last()"><hr/><div><divclass="paginate"><xsl:iftest= "($page = 0) and ($top<last()-1)"><ahref= "javascript:javascript:__doPostBack                      ('LbHoldClick','{$page+1}');">next >

Points of Interest

Though it may be difficult for Microsoft to track where its feed is being used, the licensing information within the RSS file specifically states that the results are not to be used for commercial purposes. As I understand, Google API is free for all for up to 1,000 searches per day. So if you are building a commercial Web site, I would recommend using the Google search API, but if you are just looking to implement a great quick search on your personal Web site, then MSN site search is a great choice. If you do decide to use this script on your Web site, please post a link so I can take a look.

License

This article, along with any associated source code and files, is licensed underThe Code Project Open License (CPOL)

About the Author

Jason Witty

사용자 삽입 이미지

For more articles please visit my website:
http://www.aprogrammersjournal.com

A Programmers Journal
RSS
Occupation:Software Developer (Senior)
Location:
사용자 삽입 이미지
United States