Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Basics of Bing Search API using .NET

0.00/5 (No votes)
31 Oct 2009 1  
This article will enable you to add custom search rules to your application using Bing Search API with much more

bing-Logo.jpg


Table of Contents

Introduction

Internet is the world where everyone of us rely so heavily in todays world. Internet is one of the most important part of our lives. The heart of Internet lies in the Search Engines. Most of us use Internet just to gather knowledge about the unknown. To grab knowledge we use Search Engine. Search Engines uses Web Crawl feature to gather informations from various Websites and fetch those to us. The First word that comes to all of us when Internet Comes into mind is Google. Google is the most famous search engine that keeps almost all answers that a person can ever think of.

Micorosoft also has search engines but they could never compete with Google's Excellence. Thus for the last few decades Google is the primary search engine for the whole world, until this year when Microsoft First Introduced Bing. Bing is a Smart search engine which gathers everything just like the crawlers do, but it orders the most appropriate items first so that the user needs much lesser time to gather the most valuable info he needs. You will find all the features that Bing introduces recently from the link below:
Important Features of Bing [^]

Bing also introduces a superior service for developers. It encourages developers to use their Search API into their own application. I am going to discuss the Bing Search API here in this article. The Article includes one Sample application, but as I am a newbie in WPF, I have made it most simple.

Features

Bing API gives features to the the developers to build application that enables to:

  • Retrieve Valuable Information from the Search engine when needed.
  • Get instant answers to questions
  • Retrieve telephone numbers for the users.
  • Monetize applications with advertisements.
  • Add Instant News Articles and much more

How to use Bing API on your Application

Bing API gives you the opportunity to use 3 types of protocol for your Request :

  • JSON based Approach
  • XML based Approach
  • SOAP based approach
These protocols could be used to retrieve informations from the servers. But before you do you need to register by creating new ApplicationID to use Bing services. To do this Follow the steps :
  1. Open your browser, point to Bing Developer Center
  2. After you move to the page, follow the link sign in below the page as shown below.
    APIKeyRegister.JPG
  3. Sign in using your live id. (You need to create a new one if you dont have it already)
  4. Now register your application key by filling up the form as in the figure.
    Registration.JPG
  5. Finally you will see the Key registred by you in the list
    APIkeyList.JPG

The key is to be used on every request to the service to work that correctly. Now I am going to discuss each of the protocol one by one, while our primary concern is building application using SOAP. I will give few basic examples on others too to get you bit familiar with them.

Source Types

There are lots of Source Types available with Bing. Let us take a look of each of them:
SourceTypeDescription
WEBThis sourcetype searches the query string and gets you the list of avalable crawn result based on its inbuilt automation ranking algorithm. This represents the basic search algorithm for Bing Services
IMAGEReturns the list of images relevant to the query.
VIDEOReturns List of video result for the searched query
ADReturns Advertisement links relevant to the query
NEWSNews based entries for the current query based on location passed if any.
RELATEDSEARCHA unique feature that enables the Bing service to automatically determine the searches that are relevant to the current searches and display the result.
SPELLSpell Feature enables to automaticaly determine correct spellings of the word passed in the query from its database.
TRANSLATEIt translates three sentences or less passed to the bing service from one language to another based on specified Target Language ID.
INSTANTANSWERThis is another unique feature to enable you to get Instant answers from your current query. It gives authoratitive answers to your questions
PHONEBOOKJust on your imagination, it searches phone numbers. This is another great feature of Bing Services.
MOBILEWEBReturns shrink output for mobile browsers.
Based on these source types you can generate your particular output. The results might start from a normal search option to even Translate between two different languages for your application.

JSON Based Approach

JSON(Javascript Object Notation) based approach is the most simplified approach of all where the request to the server is made only using its appropriate url. We create a string with ApplicationId, Search Criteria, Nos of Offset etc and appropriately connect the server. The server will return a JSON string as Response. This approach is useful when we need AJAX based Calls to the server and when there is no option of server side processing.

To invoke a request using JSON approach we connect the server using the following Url : http://api.search.live.net/json.aspx
It is to be noted each call to the server requires some parameters to be passed :

  • Required Attributes Common to every SourceTypes :
    1. AppId : It is the mandatory field which must be placed on querystring for every request. The value of AppId could be found after Registration of Bing SDK.
    2. Query : This field indicates the Main Search string for which the result will be produced. This is also Mandatory Field.
    3. Sources : It indicates where to search for the string specified in Query string. This is also mandatory criteria to produce the Output. The SourceType are generally of many types, It will be discussed in detail in later section.
  • Optional Parameters Common to every Source Types:
    1. Version : This indicates which version of Bing API should be used to generate the search Output. We need to specify 2.0 here as the current version is 2.0. If you need to use any other Version you need to change your program accordingly. This field is optional.
    2. Market : It is used to specify the Culture which might be used to filter search items. Value should be a valid Culture String (eg. en-Us, fr-Fr, hi-In etc)
    3. Adult : It indicates how much adult content it should display while searching. The default is Moderated.
    4. Options : There are options to indicate if Highlighting search string is required. We use EnableHighlighting to ensure that that search string is highlighted in the result. We may also use DisableLocationDetection to disable location based search for current search criteria.
  • SourceType Specific Parameters, SourceType : WEB
    1. Web.Count : This represents the number of results that is to return when the search is invoked.
    2. Web.Offset : Specifies the number of results that the result have to skip before selecting the Results. For instance, If we want the starting elements, offset will be passed as 0.
    3. Web.Options : There are 2 options that we can specify to customize output. DisableHostCollapsing indicates whether the host that is not available should be listed or not. DisableQueryAlterations indicates whether Query would be altered if data is altered in web.
  • SourceType Specific Parameters, SourceType : IMAGE
    1. Image.Count : Represents Count of Image result that to return
    2. Image.Offset : The number of images to skip
  • SourceType Specific Parameters, SourceType : AD
    1. Ad.MlAdCount : Represents number of mainline advertisement that needed to display on single search
    2. Ad.SbAdCount : Represents sidebar ad count.
    3. Ad.ChannelId :Channel Identifier for the Advertisement, so that appropriate ad is shown to appropriate application.
  • SourceType Specific Parameters, SourceType : PhoneBook
    1. Phonebook.FileType : This is the type of the file that the no is going to search. It has 2 values YP(Commercial) / WP(Residential).
    2. Phonebook.SortBy :Ordering of Numbers.
  • SourceType Specific Parameters, SourceType : News
    1. News.LocationOverride : Represents the location for which news article should be placed
    2. News.Category : Category of News that is to be filtered.
    3. News.SortBy : Sort by element.
  • SourceType Specific Parameters, SourceType : Translate
    1. Translation.SourceLanguage : Language code for the Source Language during Translate operation
    2. Translation.TargetLanguage : Language code for the Target Language during Translate operation
The above are the basic options that we must specify during the process of creating different search types. There are lots more fields other than these you might use. Refer MSDN for the complete list of Options that are available to you.

Therefore our JSON search call would look like :
http://api.bing.net/json.aspx?AppId=YOUR_APPID&Version=2.0&Market=en-US&Query=abhishek+sur&Sources=web+spell&Web.Count=1
If we see the JSON response string, it will look like :

{
    "SearchResponse":{
         "Version":"2.0",
         "Query":{
                "SearchTerms":"abhishek sur"
          },
          "Web":{
          "Total":48800,
          "Offset":0,
          "Results":[
{"Title":"CodeProject: Member Profile: Abhishek Sur. Free source code and ...",
"Description":"Member Profile: Abhishek Sur - Free source code and tutorials for Software developers and Architects.",
"Url":"http:\/\/www.codeproject.com\/script\/Membership\/View.aspx?mid=4293807",
"DisplayUrl":"www.codeproject.com\/script\/Membership
\/View.aspx?mid=4293807",
"DateTime":"2009-10-28T17:49:30Z"
                        }]
          }
     }
}
 
Thus we can see If you replace YOUR_APPID with your appropriate Id and run this url into browser, you will see my Codeproject profile.
Now let us see the complete code :
    var qry = 'abhishek sur';
    var src= 'Web';
    function Search()
    {
        var requestStr = "http://api.search.live.net/json.aspx?"
            + "AppId=" + AppId + "&Query=" + qry + "&Sources=" + src + "&Version=2.0"
            + "&Market=en-us" + "&Adult=Moderate" + "&Web.Count=10" + "&Web.Offset=0"
            + "&Web.Options=DisableHostCollapsing+DisableQueryAlterations"

            // JSON-specific request fields (optional)
            + "&JsonType=callback"
            + "&JsonCallback=SearchCompleted";

        var requestScript = document.createElement("script");
        requestScript.type = "text/javascript";
        requestScript.src = requestStr;
        
        var head = document.getElementsByTagName("head");
        head[0].appendChild(requestScript);
    }

    function SearchCompleted(response)
    {
        var errors = response.SearchResponse.Errors;
        if (errors != null)
        {
            //load error....
        }
        else
        {
            DisplayResults(response);
        }
    }

    function DisplayResults(response)
    {
        var output = document.getElementById("output");
        var results = response.SearchResponse.Web.Results;
        var resultList = document.createElement("ul");
        output.appendChild(resultList);
        // Display the results header.
        resultsHeader.innerHTML = "Web results for " + response.SearchResponse.Query.SearchTerms
            + "
Displaying " + (response.SearchResponse.Web.Offset + 1)+ " to "
            + (response.SearchResponse.Web.Offset + results.length) 
+ " of "+ response.SearchResponse.Web.Total
            + " results
";
               
        var resultsListItem = null;
        var resultStr = "";
        for (var i = 0; i < results.length; ++i)
        {
            resultsListItem = document.createElement("li");
            resultsList.appendChild(resultsListItem);
            resultStr = "%5C%22%22">" + results[i].Title + "
"
                + results[i].Description + "
Last Crawled: " + results[i].DateTime
                + "

";
            resultsListItem.innerHTML = resultStr;
        }
    }
From this code if you execute, it will create the first 10 list of search result items and show it in a list using Ul / Li.

XML Based Approach

We might use XML based approach to use Bing Service for our application. It generates HTTP GET request to get the XML response for the current query statement. If we are using applications that cannot handle complex SOAP request responses, we might take this an option. Just you need to create an object of WebRequest from your application and use the querystring with result criteria and get the response XML from it.

To invoke XML request we connect the server using this url:
http://api.bing.net/xml.aspx

Now as I have already mentioned about the basic querystring properties in JSON based approach section, I am not going to repeat that anymore. Let us quickly look into how the querystring look like:
http://api.bing.net/xml.aspx?AppId=YOUR_APPID&Version=2.2&Market=en-US&Query=abhishek+sur&Sources=web+spell&Web.Count=1

The response we get from this url if we replace YOUR_APPID with appropriate AppId will be :
<?pageview_candidate ?>
<SearchResponse Version="2.2">
  <Query>
     <SearchTerms>abhishek sur</SearchTerms>
   </Query>
    <web:Web>
        <web:Total>48800</web:Total>
        <web:Offset>0</web:Offset>
        <web:Results>
             <web:WebResult>
              <web:Title>
               CodeProject: Member Profile: Abhishek Sur. Free source code and ...
             </web:Title>
             <web:Description>
             Member Profile: Abhishek Sur - Free source code and tutorials for Software developers 
             and Architects.
             </web:Description>
             <web:Url>
              http://www.codeproject.com/script/Membership/View.aspx?mid=4293807
             </web:Url>
             <web:CacheUrl>
              http://cc.bingj.com/cache.aspx?q=abhishek+sur
              &d=4730799138997872&mkt=en-US&w=711d76ec,f208163f
             </web:CacheUrl>
            <web:DisplayUrl>
             www.codeproject.com/script/Membership/View.aspx?mid=4293807
            </web:DisplayUrl>
            <web:DateTime>2009-10-28T17:49:30Z</web:DateTime>
         </web:WebResult>
       </web:Results>
   </web:Web>
</SearchResponse>
Thus we can parse this WebResponse object easily in any language and show in the application. If you are using .NET you can create
string requestString = "http://api.bing.net/xml.aspx?
AppId=YOUR_API&Version=2.2&Market=en-US&Query=abhishek+sur
&Sources=web+spell&Web.Count=1";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestString);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
XmlDocument document = new XmlDocument();
document.Load(response.GetResponseStream());
// Now parse it....
Hope you can do parsing the XmlDocument yourself. You can also use XDocument instead of XmlDocument to make use of LINQ in the response and also to make the job much more easier.

SOAP based Approach

This is the most sophisticated approach which eliminates the limitations of making HTTP GET request of XML Protocol and ensures to create SOAP based Request object sent using Post request and the Response recieved using SOAP protocol. The service that runs in the server is basically a WCF service which implements BasicHttpBinding to work similar to normal web services. This approach could be used with advanced technologies like .NET. I am using .NET to demonstrate how to build application.

Steps to Create Your SOAP based .NET application

  1. Open Visual Studio, and Create a new project. You may choose any project type you want to. In the sample application I used WPF application.
  2. Add Web Reference to your project. The path that you should use is :
    http://api.search.live.net/search.wsdl?AppID=YOUR_APPID
    AddService.JPG
  3. Now create an object of LiveSearchPortTypeClient which is the basic Endpoint class. Let us look at the code below:
    public string SearchOutput(string AppId, string query, int offset, int no_of_res)
    {
        using (LiveSearchService service = new LiveSearchService())
            {
                try
                {
                    SearchRequest request = new SearchRequest();
                    request.AppId = AppId;
            	     request.Query = query;
                    request.Sources = new SourceType[] { SourceType.Web }; //You may specify multiple
                    request.Version = "2.0";
    	           request.Market = "en-us";
    	           request.Adult = AdultOption.Moderate;
    	           request.AdultSpecified = true;
                     request.Web = new WebRequest();
    	           request.Web.Count = no_of_res;
    	           request.Web.CountSpecified = true;
    	           request.Web.Offset = offset;
                    SearchResponse response = service.Search(request);
                    return GetResponsestring(response);
                 }
                catch (Exception ex)
                {
                    return ex.Message;
                }
           }
    } 
    
    Here we invoke the Request to the Bing server and get the response. The response object will hold the resultset of the current search.
  4. We can pass Offset (which indicates the skip element for current search. 0 means it will show from first), and Count(Indicates the no of results to be fetched) to get the desired result. 

SampleApplicationInfo.JPG

Few properties of Result object that might be helpful

There are quite a few properties that might come very handy while producing the desired search results. Here I am going to discuss about few:

  • WebResult.Title : Specifies the Title element of the result string.
  • WebResult.Description : In short description of the link produced.
  • WebResult.Url : Url that points to the Current result.
  • ImageResult.MediaUrl : Returns the url to point the full size of image
  • ImageResult.ContentType : This is the Mime type of the image produced in the result
  • ImageResult.Thumbnail.Url : Represents the Url that corresponds to thumbnail size image of the result
  • InstantAnswerResult.ClickThroughUrl: Represents the Bing url that has the Answer to the the query
  • NewsResult.BreakingNews : Identifies if the News is a breaking news or not. 1 indicates "Breaking News" while 0 not.
  • TranslationResult.TranslatedTerm : Returns the Translation string result from the source specified.
In addition to these there are lot more properties which might come to use. You can refere to MSDN link [^] to get the description of each of those while creating your application.

Reference

http://msdn.microsoft.com/en-us/library/dd251020.aspx [^]

Points of Interest

With this application I have added one sample application. The application is written using WPF. I have just added normal Web search now. I will other SourceType options later on.

Also note that I am a newbie in WPF, so in this version of the sample application, you might not be impressed with Look and feel. I will update that later with more advanced Sample application.

You can find the First version of Sample application from here :
Download SearchAPISample.zip - 200.46 KB

History

Initial Release : 31st November 2009

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here