Add google search to .Net website

 

If you need to add google search results to an existing asp.Net website there are a few options. This link specifies the differences in the the two products, Google Custom Search (GCS) VS. Google Site Search (GSS) : http://www.google.com/cse/compare

It will cost $100/year to customise this but the standard edition with adverts is free. The Bing equivalent is also Free: http://www.bing.com/developers/

If you use the GSS then the code

if (!String.IsNullOrEmpty(Request.QueryString.Get("q")))
{
 _searchTerm = Request.QueryString.Get("q");

 int currentPage = Convert.ToInt32(SiteUtils.RequestValue("p", "1"));
  int pageStart = (currentPage - 1) * 10;

 string searchUrl = "http://www.google.com/cse?cx=" + ConfigurationManager.AppSettings["GSSearchIndexID"] + "&client=google-csbe&output=xml_no_dtd&q=" + _searchTerm;

  XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.XmlResolver = null;
 xmlDoc.Load(searchUrl);

  XslCompiledTransform xslTran = new XslCompiledTransform();

  xslTran.Load(AppDomain.CurrentDomain.BaseDirectory + "\\Common\\GoogleTransform.xslt");

  StringWriter writerString = new StringWriter();
  XsltArgumentList args = new XsltArgumentList();

 string pagingUrl = HttpContext.Current.Request.Url.LocalPath;

  pagingUrl = String.Concat("?q=", Server.UrlEncode(_searchTerm), "&p=");

 args.AddParam("page", "", currentPage);
 args.AddParam("paging-url", "", pagingUrl);
 args.AddExtensionObject("hh:SiteUtils", new SiteUtils());

 xslTran.Transform(xmlDoc, args, writerString);
 string output = writerString.ToString();
 writerString.Close();
 _resultsHtml = output;
}

Useful links:

http://www.google.com/support/customsearch/bin/topic.py?topic=11503
http://code.google.com/intl/en/apis/customsearch/docs/dev_guide.html
http://www.google.com/cse/docs/resultsxml.html
http://code.google.com/intl/en/apis/customsearch/docs/ui.html
http://code.google.com/p/google-csbe-example/
http://code.google.com/intl/en/apis/customsearch/docs/start.html
http://code.google.com/apis/customsearch/docs/snippets.html
http://www.google.com/support/forum/p/customsearch/thread?tid=4908f4076a2fc8a9&hl=en

GoogleTransform XSLT file attached

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>