You Searched For User Control in BlogEngine.NET

I received an interesting comment today about my blog.  It was really appreciative of a feature that is included within the blogging engine. Which is the “You Searched For” user control.  This takes the search query that is sent along from the search engine and matches it to a search within the local site when the referrer comes from a search engine.

What especially made me take notice is that the comment came from a member of the DotNetNuke Blog Module team. With a request to understand how this was achieved within my site.  Well I figured I could have just sent back a quick and dumb answer of it is just part of the blogging engine I use.  Which in my case is BlogEngine.NET.  Or I could do what I am doing now and go into to detail about how the blogging engine accomplishes this, which is what was really being looked for.

With that in mind I will walk through how it is accomplished as I think this would be a great control to be a part of the DotNetNuke core Blog Module as well as a module that could be used to allow people to get more search results when they land on a DNN site.  May have to build that.

There are two parts to this to make it work successfully.  The first part is the addition of the user control to skin theme for my blog site.

  1: <blog:SearchOnSearch ID="SearchOnSearch1" 
  2:     runat="server" MaxResults="5" 
  3:     Headline="You searched for"
  4:     Text="Here are some results for the 
  5:     search term on this website" />

The second part is the code that is behind this user control.  First of we have a few properties that can be configured on the control

Properties:

  1. MaxResults: This is the maximum number of results to return to the page if there are any found.
  2. Headline: This is the headline to display for the control when it returns search items found.
  3. Text: This is the text to be displayed below the headline and above the search results.

Class Implementation:

  1: 
  2:  public class SearchOnSearch : Control
  3:  {
  4:      private static Regex _rxSearchTerm = null;
  5:  
  6:      static SearchOnSearch()
  7:      {
  8:  	// Matches the query string parameter "q" and 
  9:         // its value.  Does not match if "q" is blank.
 10:  	_rxSearchTerm = new Regex("[?&]q=([^&#]+)", 
 11:              RegexOptions.Compiled | 
 12:              RegexOptions.IgnoreCase | 
 13:              RegexOptions.CultureInvariant);
 14:      }
 15:  
 16:      public override void RenderControl(
 17:           HtmlTextWriter writer)
 18:      {
 19:   	string html = Html();
 20:   	if (html != null)
 21:   	    writer.Write(html);
 22:      }
 23: 
 24:     /// <summary>
 25:     /// Checks the referrer to see if it qualifies as a search.
 26:     /// </summary>
 27:     private string Html()
 28:     {
 29:         if (Context.Request.UrlReferrer != null 
 30:             && !Context.Request.UrlReferrer.ToString().Contains(
 31:             Utils.AbsoluteWebRoot.ToString()) && IsSearch)
 32:         {
 33: 	    string referrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLowerInvariant();
 34: 	    string searchTerm = GetSearchTerm(referrer);
 35: 	    List<IPublishable> items = Search.Hits(searchTerm, false);
 36:             if (items.Count == 0)
 37:                 return null;
 38:             return WriteHtml(items, searchTerm);
 39: 	}
 40: 
 41: 	return null;
 42:     }
 43: 
 44:     /// <summary>
 45:     /// Writes the search results as HTML.
 46:     /// </summary>
 47:     private string WriteHtml(List<IPublishable> items, 
 48:         string searchTerm)
 49:     {
 50: 	int results = MaxResults < items.Count ? MaxResults : items.Count;
 51: 	StringBuilder sb = new StringBuilder();
 52: 	sb.Append("<div id=\"searchonsearch\">");
 53: 	sb.AppendFormat("<h3>{0} '{1}'</h3>", Headline, HttpUtility.HtmlEncode(HttpUtility.UrlDecode(searchTerm)));
 54: 	sb.AppendFormat("<p>{0}</p>", Text);
 55: 	sb.Append("<ol>");
 56: 
 57: 	for (int i = 0; i < results; i++)
 58: 	{
 59: 		sb.AppendFormat("<li><a href=\"{0}\">{1}</a></li>", items[i].RelativeLink, items[i].Title);
 60: 	}
 61: 
 62: 	sb.Append("</ol>");
 63: 	sb.Append("</div>");
 64: 
 65: 	return sb.ToString();
 66:     }
 67: 
 68:     /// <summary>
 69:     /// Retrieves the search term from the specified referrer string.
 70:     /// </summary>
 71:     private string GetSearchTerm(string referrer)
 72:     {
 73: 	string term = string.Empty;
 74: 	Match match = _rxSearchTerm.Match(referrer);
 75: 	if (match.Success)
 76: 	{
 77: 		term = match.Groups[1].Value;
 78: 	}
 79: 
 80: 	return term.Replace("+", " ");
 81:     }
 82: 
 83:     /// <summary>
 84:     /// Checks the referrer to see if it is from a search engine.
 85:     /// </summary>
 86:     private bool IsSearch
 87:     {
 88: 	get
 89: 	{
 90: 		string referrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLowerInvariant();
 91: 		return _rxSearchTerm.IsMatch(referrer);
 93:     }
 94:  }

As we can see from the class it checks to see if there is a query “q” attached to the referring url to see if this comes from a search engine. If it does then we want to search the site and see if we have any posts that we can display to the user.

This is really neat and helpful for users.

kick it on DotNetKicks.com

Posted on 3/22/2009 1:48:26 AM by omacdon

Permalink | Comments (0) | Post RSSRSS comment feed |

Categories: DotNetNuke | BlogEngine.NET | ASP.NET | Programming

Tags: , , ,

Comments are closed