Integrate Bing Search in your .NET Framework Application

Introduction

In this article you will learn how to integrate the Bing search in your ASP.NET application. The Bing Developer Center exposes a few APIs for Bing search which can be used to integrate it in your .NET framework application. Our applications can make requests with the required parameters to the Bing search APIs and get the search results back.

The Bing API's are exposed through HTTP and can support the message formats below.



  1. SOAP
  2. JSON
  3. XML

What is the use?

For most of the readers the first thought to cross their minds is, what would be the use of integrating Bing Search into our application. The obvious answer would be, so the user doesn't have to leave your web site in case he needs to search the web.

Token to access the Bing Search API - AppId

In order to use the Bing APIs you need to have a valid AppId. You can get the AppId by going to the Microsoft Developer Center and follow the steps below.

  1. Sign in using your Windows Live Id. If you don't have one then please go ahead and create it.
  2. Click on the link "Create new AppId", which will take you to a form. Fill in the form and click on Agree. Fig 1.0 shows the screen shot of the AppId form.

    Fig 1.0
  3. The AppId will be displayed on the page. Copy it and have it for the usage in our application.

Implementing Bing Search in an ASP.NET application

Let us create an ASP.NET application and then implement the Bing search in it. I will be using the Bing search API for SOAP in our demo application.

Using Microsoft Visual Studio 2010 create an ASP.NET Web Application and name it as BingSearchAPIDemo. Now open the web.config file and add an appSettings value for the AppId as shown below.

<appSettings>
    <add key="BingAppId" value="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"/>
</appSettings>

Add a webform named SearchPage.aspx. Fig 2.0 is the .aspx designer code.


Fig 2.0



Integrate Bing Search in your .NET Framework Application

Consuming the Bing API

You can simply add the Web reference to the BingAPI appended with the AppId. Below are the API Urls available:

  1. http://api.search.live.net/json.aspx?Appid=<AppId>
  2. http://api.search.live.net/xml.aspx?Appid=<AppId>
  3. http://api.search.live.net/soap.aspx?Appid=<AppId>

Add the web reference to the soap.aspx since our demo will be using the SOAP requests. Refer fig 3.0.

[bing3.jpg] Fig 3.0

Go to the code behind file and implement the SearchButton click event handler to perform the search and to display the results onto the ResultsTable. Below is the code behind of SearchPage.aspx.cs:

using System;

using BingSearchAPIDemo.LiveSearchApi;
using System.Configuration;
using System.Web.UI.HtmlControls;

namespace BingSearchAPIDemo
{
    public partial class SearchPage : System.Web.UI.Page
    {
        private const string APP_ID_KEY = "BingAppId";
        private const string ALT_ROW_STYLE_KEY = "AlternateRowStyle";

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void SearchButton_Click(object sender, EventArgs e)
        {
            LiveSearchService liveSearchService = new LiveSearchService();
            SearchRequest searchRequest = new SearchRequest();
            //Set the AppId
            searchRequest.AppId = ConfigurationManager.AppSettings[APP_ID_KEY];
            //Set the source type
            searchRequest.Sources = new SourceType[] { SourceType.Web };
            //Set the query with the value entered in the TextBox
            searchRequest.Query = SearchTextBox.Text;
            //Do the search by passing the SearchRequest object created
            SearchResponse searchResponse = liveSearchService.Search(searchRequest);

            int index = 1;
            //Do a for each
            foreach (var webResult in searchResponse.Web.Results)
            {
                //Bind the result row
                BuildResultRow(webResult, index);
                index++;
            }
        }

        private void BuildResultRow(WebResult webResult, int index)
        {
            HtmlTableRow row = new HtmlTableRow();
            HtmlTableCell cell = new HtmlTableCell();
            HtmlAnchor anchor = new HtmlAnchor();
            anchor.InnerText = webResult.Title;
            anchor.HRef = webResult.Url;
            cell.Controls.Add(anchor);
            row.Controls.Add(cell);
            if (index % 2 > 0)
                row.Attributes.Add("class", ALT_ROW_STYLE_KEY);
            ResultsTable.Controls.Add(row);
            row = new HtmlTableRow();
            cell = new HtmlTableCell();
            cell.InnerText = webResult.Description;
            row.Controls.Add(cell);
            if (index % 2 > 0)
                row.Attributes.Add("class", ALT_ROW_STYLE_KEY);
            ResultsTable.Controls.Add(row);
        }
    }
}

There are many source types available, in the above example we have used Web. Some of the other SourceTypes are Image, Video, Weather, etc.

Run the application, enter the SearchText as Kodaikanal and see the result getting bound to the Results table. Below is the output screen shot Fig 3.1.

[bing4.jpg]
Fig 3.1

Performing Asynchronous Search

The API also allows performing searches in an asynchronous manner. In order to do that you have to use the SearchAsync method and use the SearchCompleted event to perform any post search operations like binding the results to the HTML Table.

private void DoSearch()
{
     LiveSearchService liveSearchService = new LiveSearchService();
     SearchRequest searchRequest = new SearchRequest();
     //Set the AppId
     searchRequest.AppId = ConfigurationManager.AppSettings[APP_ID_KEY];
     //Set the source type
     searchRequest.Sources = new SourceType[] { SourceType.Web };
     //Set the query with the value entered in the TextBox
     searchRequest.Query = SearchTextBox.Text;
     //Hook up the SearchCompleted event with an event handler
     liveSearchService.SearchCompleted += new SearchCompletedEventHandler(liveSearchService_SearchCompleted);
     //Do the search by passing the SearchRequest object created
     liveSearchService.SearchAsync(searchRequest);
}

void liveSearchService_SearchCompleted(object sender, SearchCompletedEventArgs e)
{
     //Get the result using e.Result.Web
}

Conclusion

Thus in this article I have described with an example how to implement Bing search in your application using the Bing APIs available. The sample application is attached below.

Happy reading! See you in my next article.

Related Articles





About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds