Creating a Basic Search
With the Live Search Web Service reference in place, you now have access to the
Search method. The following code snippet demonstrates performing a basic search:
MSNSearchService serv = new MSNSearchService();
SearchRequest sRequest = new SearchRequest();
SourceRequest[] sr = new SourceRequest[1];
sr[0] = new LiveSearch.SourceRequest();
sr[0].Source = LiveSearch.SourceType.Web;
sr[0].ResultFields = ResultFieldMask.All;
sRequest.Query = "Live Search Articles";
sRequest.Flags = SearchFlags.None;
sRequest.Requests = sr;
// Replace with your own Application ID
sRequest.AppID = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
sRequest.CultureInfo = "en-US";
SearchResponse resp = serv.Search(sRequest);
Author's Note: To use this code snippet, you'll need to substitute your own Application ID. |
 | |
Figure 5. Basic Search Query Results: Using the Live Search Web Service to search the web for "Live Search Articles" gives these results. |
This basic search searches the entire Internet for results that contain "Live Search Articles" and returns all the result fields. The preceding query returns the results shown in
Figure 5.
The web service returns search results in a SourceResponse
object, which contains an array of results. Depending on the type of search and the fields requested, the results may contain a variety of fields. You should check each field for
null before using to avoid unwanted exceptions:
SearchResponse resp = serv.Search(sRequest);
foreach (Result r in resp.Responses[0].Results)
{
string title, description, url;
title = (!String.IsNullOrEmpty(r.Title))
? r.Title : "";
description =
(!String.IsNullOrEmpty(r.Description))
? r.Description : "";
url = (!String.IsNullOrEmpty(r.Url))
? r.Url : "";
}
 | |
Figure 6. Using the ResultFieldMask: Search query results using ResultFieldMask to display <i>title</i>, <i>description</i>, and <i>displayurl</i> fields. |
The API allows customization of the fields returned using the ResultFieldMask. For example, if you wanted to display only the
title,
description, and
displayurl fields, you would use the following code:
SourceRequest[] sr = new SourceRequest[1];
sr[0].ResultFields =
ResultFieldMask.Description |
ResultFieldMask.DisplayUrl |
ResultFieldMask.Title;
You can see the change in the search results in
Figure 6.
Limiting Search Sites
So far, all the examples search the entire Internet for results; however you can use the API to allow users to limit the search to specified sites. The following code searches for items about "Virtual Earth" on the
http://www.soulsolutions.com.au site only:
SearchRequest sRequest = new SearchRequest();
sRequest.Query =
"Virtual Earth site:www.soulsolutions.com.au";
Figure 7 shows the results.
 | |
Figure 7. Site-Constrained Search: Limiting the search to a specific site provides these results. |