|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Want a new Job?
Chapters
Services
Feature Zones
|
IntroductionThis application will bind search results from the Windows Live Search Webservice to a You can customize the search properties via the web.config file. Please have the following requirements met before proceeding.
BackgroundI found bits and pieces of random examples on the net but nothing substantially helpful. I thought this might be helpful for folks who wish to see a working example. You can always take out the AJAX and capture the search query via a querystring, with just a few minor changes. Using the codeThe The main configuration properties are organized as a type called /// <summary>
/// Properties used for setting up web service
/// </summary>
public class LiveSearchProperties
{
private string _searchLic;
public string SearchLic
{
get { return _searchLic; }
set { _searchLic = value; }
}
private int _resultsSize;
public int ResultsSize
{
get { return _resultsSize; }
set { _resultsSize = value; }
}
private string _searchSites;
public string SearchSites
{
get { return _searchSites; }
set { _searchSites = value; }
}
private SafeSearchOptions _searchOptions;
public SafeSearchOptions SearchOptions
{
get { return _searchOptions; }
set { _searchOptions = value; }
}
}
In the constructor, the properties are filled. /// <summary>
/// Creates a WindowsLiveSearch and fills properties with values
/// </summary>
public WindowsLiveSearch()
{
// -------------------------------
// Initialize properties
// -------------------------------
// Error Property
ErrorMsg = "";
// LiveSearchProperties
LiveSearchProperties sp = new LiveSearchProperties();
sp.SearchLic = ConfigurationManager.AppSettings["SearchLic"];
sp.ResultsSize = Int32.Parse(ConfigurationManager.AppSettings["ResultsSize"]);
sp.SearchSites = ConfigurationManager.AppSettings["SearchSites"];
sp.SearchOptions = SafeSearchOptions.Off;
SP = sp; // Save instance to class property
sp = null; // Null out unused object
}
The /// <summary>
/// This is the main function you call after object creation.
/// You can pass the search query in here and get a list of
/// results to work with. You can easily bind these results to an
/// ASP.NET control if desired or foreach the list to get the data.
/// </summary>
/// <param name="searchQuery">The search query</param>
/// <returns>A generic list of search results</returns>
public IList<LiveSearchResults> Search(string searchQuery)
{
// Basic checks
if ((searchQuery == null) ||
(searchQuery.Length == 0) ||
(searchQuery.Trim() == ""))
return null;
IList<LiveSearchResults> resultsCollection =
new List<LiveSearchResults>();
using (MSNSearchService s = new MSNSearchService())
{
SearchRequest searchRequest = new SearchRequest();
searchRequest = SetUpRequest(searchRequest, searchQuery, SP);
SearchResponse searchResponse;
try
{
searchResponse = s.Search(searchRequest);
resultsCollection = CaptureResults(searchResponse);
}
catch (Exception e)
{
ErrorMsg = e.ToString();
}
finally
{
// If there was an error
if (ErrorMsg.Length > 0)
LogMessage("There was an error with searchQuery: " +
searchQuery);
else
LogMessage("A successful search was made with searchQuery: " +
searchQuery);
}
}
return resultsCollection;
}
The The following is the /// <summary>
/// Sets up the MSN SearchRequest Object
/// </summary>
/// <param name="searchRequest">A SearchRequest Object</param>
/// <param name="searchQuery">The search query</param>
/// <param name="sp">LiveSearchProperties Object</param>
/// <returns>The SearchRequest Object</returns>
private SearchRequest SetUpRequest(
SearchRequest searchRequest,
string searchQuery,
LiveSearchProperties sp)
{
SourceRequest[] sr = new SourceRequest[1];
sr[0] = new SourceRequest();
sr[0].Source = SourceType.Web;
sr[0].ResultFields = ResultFieldMask.All;
sr[0].Count = sp.ResultsSize;
sr[0].Offset = 0;
searchRequest.Requests = sr;
searchRequest.Query = searchQuery + " " + sp.SearchSites;
searchRequest.SafeSearch = sp.SearchOptions;
searchRequest.AppID = sp.SearchLic;
searchRequest.Flags = SearchFlags.MarkQueryWords;
searchRequest.CultureInfo = "en-US";
return searchRequest;
}
After you setup the Request, you can use the Webservice to get a The /// <summary>
/// Properties used to store search results
/// </summary>
public class LiveSearchResults
{
private string _url;
public string URL
{
get { return _url; }
set { _url = value; }
}
private string _title;
public string Title
{
get { return _title; }
set { _title = value; }
}
private string _description;
public string Description
{
get { return _description; }
set { _description = value; }
}
private string _displayURL;
public string DisplayURL
{
get { return _displayURL; }
set { _displayURL = value; }
}
private string _cachedURL;
public string CachedURL
{
get { return _cachedURL; }
set { _cachedURL = value; }
}
}
This is the /// <summary>
/// Creates a list of Search Results
/// </summary>
/// <param name="search_Response">The LiveSearch Response</param>
/// <returns>A collection of search results</returns>
private IList<LiveSearchResults> CaptureResults(SearchResponse search_Response)
{
// Create a collection object to build list
IList<LiveSearchResults> resultsCollector = new List<LiveSearchResults>();
//Get data from web service
foreach (SourceResponse response in search_Response.Responses)
{
Result[] response_results = null;
response_results = response.Results;
//Secure and store output
foreach (Result response_result in response_results)
{
LiveSearchResults row = new LiveSearchResults();
row.URL = AntiXss.HtmlEncode(CheckForNull(response_result.Url));
row.Title = AntiXss.HtmlEncode(CheckForNull(response_result.Title))
.Replace("", "<strong>").Replace("", "</strong>");
row.Description = AntiXss.HtmlEncode(CheckForNull(response_result.Description))
.Replace("", "<strong>").Replace("", "</strong>");
row.DisplayURL = AntiXss.HtmlEncode(CheckForNull(response_result.DisplayUrl))
.Replace("", "<strong>").Replace("", "</strong>");
row.CachedURL = AntiXss.HtmlEncode(CheckForNull(response_result.CacheUrl));
resultsCollector.Add(row);
}
}
return resultsCollector;
}
This method uses the AntiXssLibrary.dll from MS. This will prevent unwanted cross-site scripting data from getting stored in the results. This method builds and returns a generic list to the The Presentation layerThe <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="Search"
TypeName="Windows.Live.Search.WindowsLiveSearch" OnSelected="ObjectDataSource1_Selected">
<SelectParameters>
<asp:FormParameter FormField="searchBox" Name="searchQuery" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
As shown, you can see that I included the class in the The The // Get the total number of records
protected void ObjectDataSource1_Selected(object sender,
ObjectDataSourceStatusEventArgs e)
{
Instructionlbl.Text = "";
try
{
IList<LiveSearchResults> resultsCollection =
new List<LiveSearchResults>();
resultsCollection = (IList<LiveSearchResults>)e.ReturnValue;
resultsTotal = resultsCollection.Count;
if (resultsTotal == 0)
Instructionlbl.Text = "Your search provided no results.";
}
catch (System.NullReferenceException)
{
Instructionlbl.Text = "Please enter a search term.";
}
}
If the search query is blank, then there will be a System. AJAX stuffTo get this to work, you must surround the controls you want updated in an AJAX To trigger the update panel, you simply supply the following: <Triggers>
<asp:AsyncPostBackTrigger ControlID="SearchButton" EventName="click" />
</Triggers>
This simply states to trigger the update panel when a Click event occurs. Points of interestEverything you need will be in the project download. You should be able to take what I did and customize it to your needs. You can play around with the Search settings in the web.config file. You can also change the default sites to search. All the settings are the same as if you were doing an advanced search with the Live Search Engine. History
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||