Click here to Skip to main content
15,748,477 members
Articles / Web Development / ASP.NET
Posted 31 Oct 2009


80 bookmarked

Basics of Bing Search API using .NET

Rate me:
Please Sign up or sign in to vote.
4.92/5 (38 votes)
31 Oct 2009CPOL11 min read
This article will enable you to add custom search rules to your application using Bing Search API with much more


Table of Contents


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.


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.
  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.
  5. Finally you will see the Key registred by you in the list

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:
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 :
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 :
If we see the JSON response string, it will look like :

                "SearchTerms":"abhishek sur"
{"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.",
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 = ""
            + "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");

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

    function DisplayResults(response)
        var output = document.getElementById("output");
        var results = response.SearchResponse.Web.Results;
        var resultList = document.createElement("ul");
        // 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");
            resultStr = "<a href="%5C%22%22">" + results[i].Title + "</a>
                + 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:

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:

The response we get from this url if we replace YOUR_APPID with appropriate AppId will be :
<?pageview_candidate ?>
<SearchResponse Version="2.2">
     <SearchTerms>abhishek sur</SearchTerms>
               CodeProject: Member Profile: Abhishek Sur. Free source code and ...
             Member Profile: Abhishek Sur - Free source code and tutorials for Software developers 
             and Architects.
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 = "
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestString);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
XmlDocument document = new XmlDocument();
// 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 :
  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())
                    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. 


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 [^]

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 - 200.46 KB


Initial Release : 31st November 2009


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : to know more about Abhishek.

Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.

Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.

Working as a VP product of APPSeCONNECT, an integration platform of future, he does all sort of innovation around the product.

Have any problem? Write to him in his Forum.

You can also mail him directly to

Want a Coder like him for your project?
Drop him a mail to

Visit His Blog

Dotnet Tricks and Tips

Dont forget to vote or share your comments about his Writing

Comments and Discussions

GeneralMy vote of 5 Pin
kiran dangar4-Oct-11 22:55
kiran dangar4-Oct-11 22:55 
QuestionVB Sample Pin
rspercy6525-Oct-10 17:42
rspercy6525-Oct-10 17:42 
AnswerRe: VB Sample Pin
DaveCS16-Apr-11 5:38
DaveCS16-Apr-11 5:38 
GeneralBing Services for face images. Pin
Janet2214-Oct-10 20:47
Janet2214-Oct-10 20:47 
GeneralURL Info Pin
xxsaxx3-Dec-09 3:25
xxsaxx3-Dec-09 3:25 
GeneralNice Work Again Pin
sashidhar12-Nov-09 1:24
sashidhar12-Nov-09 1:24 
GeneralRe: Nice Work Again Pin
Abhishek Sur12-Nov-09 1:28
professionalAbhishek Sur12-Nov-09 1:28 
GeneralGood Work Again Abhishek Pin
Abhijit Jana7-Nov-09 6:17
professionalAbhijit Jana7-Nov-09 6:17 
GeneralRe: Good Work Again Abhishek Pin
Abhishek Sur7-Nov-09 6:37
professionalAbhishek Sur7-Nov-09 6:37 
GeneralRe: Good Work Again Abhishek Pin
Abhijit Jana7-Nov-09 16:29
professionalAbhijit Jana7-Nov-09 16:29 
GeneralClicking URL does not start browser and retrieve page Pin
BaileyMW4-Nov-09 7:47
BaileyMW4-Nov-09 7:47 
GeneralRe: Clicking URL does not start browser and retrieve page Pin
Abhishek Sur4-Nov-09 11:45
professionalAbhishek Sur4-Nov-09 11:45 
GeneralReally Useful Pin
Amit Developer4-Nov-09 0:26
Amit Developer4-Nov-09 0:26 
GeneralRe: Really Useful Pin
Abhishek Sur4-Nov-09 11:45
professionalAbhishek Sur4-Nov-09 11:45 
GeneralExcellent Pin
karenpayne3-Nov-09 3:19
karenpayne3-Nov-09 3:19 
GeneralRe: Excellent Pin
Abhishek Sur3-Nov-09 4:29
professionalAbhishek Sur3-Nov-09 4:29 
GeneralGood One Pin
Basob Roy1-Nov-09 21:32
Basob Roy1-Nov-09 21:32 
GeneralRe: Good One Pin
Abhishek Sur1-Nov-09 21:38
professionalAbhishek Sur1-Nov-09 21:38 
GeneralBaje article Pin
Ayan Sengupta1-Nov-09 21:32
Ayan Sengupta1-Nov-09 21:32 
GeneralRe: Baje article Pin
Abhishek Sur1-Nov-09 21:37
professionalAbhishek Sur1-Nov-09 21:37 
GeneralOutstanding Pin
Developers Of Bangladesh (DOB)1-Nov-09 3:19
Developers Of Bangladesh (DOB)1-Nov-09 3:19 
GeneralRe: Outstanding Pin
Abhishek Sur1-Nov-09 3:21
professionalAbhishek Sur1-Nov-09 3:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.