Developer

Hands-on programming: Using Bing from .NET

Justin James shares his recent Bing experience and provides a code snippet that will put you well on your way to writing a Bing-enabled application.

 

Welcome to a new Programming and Development series called Hands-on programming; this series is meant to be a complement to the Code concepts series that I started a few months ago in this blog. Hands-on programming columns will be tutorials with less emphasis on abstract ideas than the Code concepts pieces. For now, both series will focus on the .NET world. I would love to hear your feedback, positive or negative, about this new series.

My Bing experience

Last week, I sat down to write an application that I had been meaning to write for a number of years. A major part of the application involved interfacing with a search engine. When I began to work on the code, I knew that I had three major provider choices: Google, Yahoo!, and Bing. I decided to go with Bing because, in August, I saw my friend Chris Eargle give a brief demo of calling Bing from .NET, and it looked dead easy. Here's a report about my Bing experience.

First, a brief aside: My experience with consuming Web services is insanely limited. For whatever reason, I managed to dodge this area of work for quite a while. So I understood the principles, I just never put my hands on the nitty-gritty until relatively recently. And when I did (it was a project involving Microsoft Exchange Web Services), I had a very poor experience. Things kept breaking on a regular basis, although it was the fault of the examples in the book I had and the sample code in the SDK at fault, not the Exchange Web Service. However, that bad experience made me feel a bit of queasiness when I started this project.

To start using the Bing API, you will need to apply for an AppID from Microsoft. With the AppID in hand, you can have Visual Studio get the WSDL and auto-generate .NET classes for your use. Follow these steps (which are for Visual Studio 2008):

  1. Right-click your project references and choose Add Service Reference.
  2. Click the Advanced button.
  3. Click Add Web Reference.
  4. Enter http://api.bing.net/search.wsdl?AppID=YourAppId&Version=2.2 for the URL. Make sure to put your correct AppID in there.
  5. Change the reference name if you want; I left it as-is.
  6. Click Go and, when the process completes, click Add Web Reference.

If you prefer, you can use XML or JSON to access Bing, although the SOAP interface makes the most sense for the majority of .NET apps, thanks to Visual Studio's integration with SOAP services.

You're ready to get to work. To start using the newly created references, add the appropriate using (for C# folks) or Imports (for VB.NET) statement to your code that needs to use Bing. The full name is your default namespace for the project, plus the service reference. In this case, my project's namespace is TestProject, so this is my line to bring it in:

using TestProject.net.live.search.api;

I'll show you how to create a basic request for Web results; however, you should know that Bing is capable of providing various kinds of results, including videos, images, and phonebooks, and you can have a search request look for multiple types at the same time. I will leave it as an exercise for you to try the other search types out there.

All search requests share some basic required parameters and offer additional parameters of their own. The required parameters are:

  • AppID (string): The AppID you were issued.
  • Query (string): The query you want to run; this is identical to what you would enter at the Bing site to perform a search.
  • Sources (Sources[]): An array of Sources (an enumeration in the namespace) indicating what type(s) of search to perform.

This is a simple method that takes a query and performs a search:

private void Lookup(string Query)

{

    using (var service = new LiveSearchService())

    {

        try

        {

            var request = new SearchRequest();
            // Common request fields (required)

            request.AppId = "BingAppID";

            request.Query = Query;

            request.Sources = new SourceType[] { SourceType.Web };

            var response = service.Search(request);
            if (response.Web.Results == null)

            {

                return;

            }

        }

        catch (System.Web.Services.Protocols.SoapException ex)

        {

            // Swallow exceptions for the time being

        }

        catch (System.Net.WebException ex)

        {

            // Swallow exceptions for the time being

        }

    }

}
Attribution: This is a greatly stripped down, modified version of the sample code in the Bing documentation. This is all you need to do a search.

From here, you can work with the results of the query. I found LINQ to be a great way to work with the results. In my application, I created a Results class that encapsulated not only the information I needed from Bing but also my post-search processing. So, I populated a List<Result> with a simple LINQ query:

results = (from result in response.Web.Results

select new Result(result.Url, result.DisplayUrl, result.Title, 0, 0, new

 List<string>())).ToList();

Some of the items populating the Result objects in the list come from the Bing results in the response object, and some of the items are just initialization values for my later processing to build on.

With this simple piece of code, you are well on your way to writing a Bing-enabled application.

J.Ja

Disclosure of Justin's industry affiliations: Justin James has a contract with Spiceworks to write product buying guides.

———————————————————————————————————————————-

Get weekly development tips in your inbox Keep your developer skills sharp by signing up for TechRepublic's free Web Developer newsletter, delivered each Tuesday. Automatically subscribe today!

About Justin James

Justin James is the Lead Architect for Conigent.

Editor's Picks

Free Newsletters, In your Inbox