Thursday, March 25, 2010

Bing API 2.0: Consume results with SOAP using .NET

Compared to XML, using SOAP in .NET has some advantages.

Advantage

There is less XML processing to do, since the web services infrastructure in .NET handles deserializing the SOAP XML responses from the SOAP interfaces into strongly-typed .NET collections.

Example

The first thing you need to do is add a Web Reference in Visual Studio using the Bing WSDL. The WSDL can be found at http://api.search.live.net/search.wsdl. By adding this web reference, Visual Studio generates some classes based on this WSDL, which we can use to query Bing.

In this example, I create a new LiveSearchPortTypeClient, create a SearchRequest and pass that SearchRequest to the Search method of the LiveSearchPortTypeClient. This returns a SearchResponse. And now it's really easy to display the results. Just look in the SearchResponse properties and pick what you need.

   1:  namespace BingAPIConsumeSOAP
   2:  {
   3:      class Program
   4:      {
   5:          static void Main(string[] args)
   6:          {             
   7:              LiveSearchPortTypeClient client = new LiveSearchPortTypeClient();            
   8:              SearchRequest req = new SearchRequest();            
   9:              req.AppId = "[YourAppId]";
  10:              req.Sources = new SourceType[] { SourceType.Image} ;
  11:              req.Query = "Mini Cooper S";
  12:   
  13:              SearchResponse resp = client.Search(req);
  14:   
  15:              foreach (var res in resp.Image.Results)
  16:              {
  17:                  Console.WriteLine(res.Title);
  18:                  Console.WriteLine(res.MediaUrl);
  19:                  Console.WriteLine(Environment.NewLine);
  20:              }
  21:   
  22:              Console.ReadLine();
  23:          }
  24:      }
  25:  }


This post is part of the Bing API 2.0 series.

3 comments:

  1. Thanks pal for this example ;) Have a happy life.

    ReplyDelete
  2. i got the error at this class variable declaration "LiveSearchPortTypeClient"

    why?

    ReplyDelete
  3. Looks like the WSDL has changed. Try using the BingPortTypeClient.

    ReplyDelete