Skip to main content
Email Password   helpLost your password?

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:

How to use Bing API on your Application

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

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 :

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:

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

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralNice Work Again Pin
sashidhar
2:24 12 Nov '09  
GeneralRe: Nice Work Again Pin
Abhishek Sur
2:28 12 Nov '09  
GeneralGood Work Again Abhishek Pin
Abhijit Jana
7:17 7 Nov '09  
GeneralRe: Good Work Again Abhishek Pin
Abhishek Sur
7:37 7 Nov '09  
GeneralRe: Good Work Again Abhishek Pin
Abhijit Jana
17:29 7 Nov '09  
GeneralClicking URL does not start browser and retrieve page Pin
BaileyMW
8:47 4 Nov '09  
GeneralRe: Clicking URL does not start browser and retrieve page Pin
Abhishek Sur
12:45 4 Nov '09  
GeneralReally Useful Pin
amity2001
1:26 4 Nov '09  
GeneralRe: Really Useful Pin
Abhishek Sur
12:45 4 Nov '09  
GeneralExcellent Pin
GlimmerMan
4:19 3 Nov '09  
GeneralRe: Excellent Pin
Abhishek Sur
5:29 3 Nov '09  
GeneralGood One Pin
Basob Roy
22:32 1 Nov '09  
GeneralRe: Good One Pin
Abhishek Sur
22:38 1 Nov '09  
GeneralBaje article Pin
Ayan Sengupta
22:32 1 Nov '09  
GeneralRe: Baje article Pin
Abhishek Sur
22:37 1 Nov '09  
GeneralOutstanding Pin
Developers Of Bangladesh (DOB)
4:19 1 Nov '09  
GeneralRe: Outstanding Pin
Abhishek Sur
4:21 1 Nov '09  


Last Updated 31 Oct 2009 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2009