Partilhar via


Using Simple Bing Search over SOAP Protocol in an ASP.NET Web Application

Introduction

This walkthrough shows how to use a simple Bing search as a Web service in an ASP.NET Web application. The Bing search features are invoked by the ASP.NET Web application using SOAP protocol over HTTP.

You can also use XML and JSON to invoke the service. We'll have related examples at a later time.

This walkthrough shows you how to perform the following tasks:

  • Create a client Web application to interact with BING service.
  • Add the reference to the Bing search service.
  • Perform live search by using Bing SourceTypes.
Bing Service Background

Complex problems such as indexing, relevance logic, and hosting issues such as CPU and storage are solved in transparent way to your application by having the ability to use the BING features as a Web service. This article offers a starting point for adding the service to your application.

Remember that a Web service is a component on a Web server that a client application can call by making HTTP requests across the Web. If you want some good explanation about this subject, see this MSDN article Using ASP.NET Web Services.

By using the Bing search service you can integrate the following features in your application:

  • Retrieve information from the Internet.
  • Add advertisements to your application.
  • Improve and enhance search requests and results.
  • Find location-specific information.
  • Translate terms and blocks of text.

You interact with the Bing Service through the Bing API

Each of the previous feature is associated with one or more Bing API SourceTypes. A SourceType is a source of information accessible using the Bing API.   An overall description of these SourceTypes can be find on MSDN at this location: About the Bing API.

Prerequisites

In order to complete the example in this topic, you need the following:

  • Visual Studio 2008.
  • The ability to send requests using the Simple Object Access Protocol (SOAP) 1.1 and the Hyper Text Transfer Protocol (HTTP 1.1)
  • The ability to parse SOAP and XML

Creating a Web Application

This section shows how to create a Web application that will use the Bing search service.

To create an ASP.NET Web application

  1. Start Visual Studio 2008.
  2. In the File menu, click New, and then click Project.
  3. The New Project dialog box is displayed.
  4. In the left pane, under Project types, expand the Visual C# node then select Web
  5. In the Visual Studio installed templates right pane, select ASP.NET Web Application.
  6. In the Location box enter the name of the folder where you want to keep the Web application. For example, enter the folder name C:\WebApplications\CS\.
  7. In the Name dialog box enter the name of the project. For example, enter the name SoapBasicSearch.
  8. Click OK.
  9. An ASP.NET application is created.

Referencing Bing Search Service

This section shows how to reference the Bing search service. In order to do that, you use a Web service discovery process by which your application locates the service and obtains its description. The process of Web service discovery in Visual Studio involves interrogating a Web site to locate the service description, which is an XML document that uses the Web Services Description Language (WSDL).

When you add a Web reference to a project, Visual Studio generates a proxy class that provides a local representation of the Web service. The proxy enables your application to interface with the Web service. You can access Web service methods by calling the methods in the proxy class. The proxy class handles the communication between your application and the Web service itself.

To reference the Bing Search Service

  1. In Solution Explorer, right-click the project name then click Add Web Reference button.
  2. In the Add Web Reference panel, in the URLbox enter the following value: https://api.search.live.net/search.wsdl.
  3. Click GO (represented by a green arrow).
  4. If the process has been successfully a message is displayed saying that "1 Service Found: Search" and the Web reference is: net.live.search.api.
  5. Click the Add Reference button.
  6. A Web References folder is added to the project that contains the reference to the Bing search service API.
  7. Also, the Web.config file is updated to contains address information about the soap.asmx service. The following is an example of the configuration update.
     <applicationSettings>
       <UsingBingService.Properties.Settings>
           <setting name="UsingBingService_net_live_search_api_LiveSearchService"
               serializeAs="String">
               <value>https://api.search.live.net:80/soap.asmx</value>
           </setting>
       </UsingBingService.Properties.Settings>
   </applicationSettings>

Performing Search by Using Bing Service Types

This section shows the code that enables the user to choose the desired Bing ServiceType to perform live search. For simplicity only the types listed in the table shown next are used. Also, the search are “hard-coded” and code used comes from the Code Samples (Bing, Version 2.0) on MSDN: .  

SourceType

Function

Web

Retrieve information from the Internet

 
Selecting the ServiceType to Use
  1. In Solution Explorer , open the default.aspx page. Then add the following markup.
 <h2>Using BING Service</h2>
  <ul>
    <li><a href="WebSourceType.aspx" target="_blank">Using the Web SourceType over the SOAP Protocol</a></li> 
  </ul>
 
 
Create the Code to Interact with the Web ServiceType
  1. In Solution Explorer , right-click the project name then click Add and select New Item.
  2. In the Installed Templates dialog, select Web Form.
  3. In the Name box enter WebSourceType.aspx.
  4. Click the Add button.
  5. In the newly created WebSourceType.aspx page enter the following markup and save the file.
 <form id="form1" runat="server">
    <div>
        
        <h2>Using the Web SourceType Over the SOAP Protocol</h2>
            
            This example shows how to perform the following tasks:
            
            <ul>
                <li>Set search request basic parameters by using the 
                    <a href="https://msdn.microsoft.com/en-us/library/dd250960.aspx" target="_blank">SearchRequest</a> type.</li>
                <li>Set the Web book request by using the 
                    <a href="https://msdn.microsoft.com/en-us/library/dd250886.aspx" target="_blank">WebRequest</a> type. </li>
                <li>Display the results obtained  from the 
                    <a href="https://msdn.microsoft.com/en-us/library/dd250843.aspx" target="_blank">SearchResponse</a> type. </li>
            </ul>
          
            <h4>See Also </h4>
            <span style="background-color:Yellow">
                <a href="https://msdn.microsoft.com/en-us/library/dd251056.aspx" target="_blank">BING API</a></span>
            <br /> <br />

            <span style="background-color:Yellow">For more information, see 
                <a href="https://blogs.msdn.com/morebits/" target="_blank">Technical Notes</a></span>
            <br /> <br />
            
            <asp:Table ID="WebResultID" BorderWidth="1"    runat="server">  
                <asp:TableHeaderRow BackColor="LightGray">
                    <asp:TableCell ID="hdrID1" BorderStyle="Inset"/>
                </asp:TableHeaderRow>
            </asp:Table>
            
        
    </div>
    </form>
  1. In Solution Explorer , open the code behind file WebSourceType.aspx.cs and add the following code and save the file.
       // Get the search results. Display one result per row.
      private void DisplayResults(SearchResponse response)
      {
          int j = 0; 
          foreach (WebResult result in response.Web.Results)
          {
             
              TableRow tRow = new TableRow();
             
              WebResultID.Rows.Add(tRow);
              TableCell tCell = new TableCell();
              tCell.BorderWidth = Unit.Parse("1");
              if (j % 2 == 0)
                  tCell.BackColor = System.Drawing.Color.Blue;
              else
                  tCell.BackColor = System.Drawing.Color.Tomato;

              tCell.ForeColor = System.Drawing.Color.Yellow;
              tCell.Font.Bold = true;

              System.Text.StringBuilder builder = new System.Text.StringBuilder();
          
              builder.AppendLine(result.Title);
              builder.AppendLine(result.Description);
              builder.AppendLine(result.Url);
              builder.Append("Last Crawled: ");
              builder.AppendLine(result.DateTime);
              j++;

              int i = 0;
              foreach (char c in builder.ToString().ToCharArray())
              {

                  if (c == '\uE000')
                  {
                      // If the current character is the begin highlighting
                      // character (U+E000), change it to a left square bracket.

                      builder[i] = Convert.ToChar("[");


                  }

                  else if (c == '\uE001')
                  {
                      // If the current character is the end highlighting
                      // character (U+E001), change it to a right square bracket.
                      builder[i] = Convert.ToChar("]");
                  }

                  i++;
              }

              tCell.Text = builder.ToString();

              tRow.Cells.Add(tCell);

          }

         
      }

      protected override void OnPreRender(EventArgs e)
      {
          base.OnPreRender(e);
          SearchResponse response = UsingWebSourceType.PerformLiveSearch();
       
          string results = string.Format("Displaying {0} to {1} of {2} results", response.Web.Offset + 1,
                         response.Web.Offset + response.Web.Results.Length, response.Web.Total);

          // Add header information to the table.
          hdrID1.Text = "<div style='color:red; font-weight:bold'>' + "Bing API Version: " + response.Version + "</div>" +
                          "<div style='color:red; font-weight:bold'>' + "Phonebook results for " + response.Query.SearchTerms + "</div>" +
                          "<div style='color:red; font-weight:bold''>' + results + "</div>";
          // Add rows to the table that contain search results.
          DisplayResults(response);

         
      }
  
  1. In Solution Explorer , right-click the project name then click Add and select New Item.
  2. In the Installed Templates dialog, select Code File.
  3. In the Name box enter ApiId.cs.
  4. Click the Add button.
  5. In the newly created file enter the following code and save the file.

The following static class enables you to have a single place where to define the AppID.

Remember you need this ID to use the Bing Search Service. For more information, see Getting Started with Bing API, Version 2.

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

// This using directive assumes that the project's default namespace is
// "SoapBasicSearch" and the name of the Bing API web reference is
// "net.live.search.api". Modify this using directive as necessary.
using SoapBasicSearch.net.live.search.api;

namespace SoapBasicSearch
{
    public static class AppID
    {
        // Replace the following string with the AppId you received from the
        // Bing Developer Center.
        public const string Current = "Enter your AppId";
    }
}

  1. In Solution Explorer , right-click the project name then click Add and select New Item.
  2. In the Installed Templates dialog, select Code File.
  3. In the Name box enter UsingWebSourceType.cs.
  4. Click the Add button.
  5. In the newly created file enter the following code and save the file.
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

// This using directive assumes that the project's default namespace is
// "SoapBasicSearch" and the name of the Bing API web reference is
// "net.live.search.api". Modify this using directive as necessary.
using SoapBasicSearch.net.live.search.api;

namespace SoapBasicSearch
{
    public static class UsingWebSourceType
    {
        
        public static SearchResponse PerformLiveSearch()
        {
            // LiveSearchService implements IDisposable.
            using (LiveSearchService service = new LiveSearchService())
            {
                SearchResponse response = new SearchResponse();

                try
                {
                    SearchRequest request = BuildRequest();

                    // Send the request; display the response.
                    response = service.Search(request);

                }
                catch (System.Web.Services.Protocols.SoapException ex)
                {
                    // A SOAP Exception was thrown. Display error details.
                    DisplayErrors(ex.Detail);
                }
                catch (System.Net.WebException ex)
                {
                    // An exception occurred while accessing the network.
                    HttpContext.Current.Response.Write(ex.Message);
                }

                return response;
            }
        }

        static SearchRequest BuildRequest()
        {
            SearchRequest request = new SearchRequest();

            // Common request fields (required)
            request.AppId = AppID.Current;
            request.Query = "msdn blogs";
            request.Sources = new SourceType[] { SourceType.Web };

            // Common request fields (optional)
            request.Version = "2.0";
            request.Market = "en-us";
            request.Adult = AdultOption.Moderate;
            request.AdultSpecified = true;
            request.Options = new SearchOption[]
        {
            SearchOption.EnableHighlighting
        };

            // Web-specific request fields (optional)
            request.Web = new WebRequest();
            request.Web.Count = 10;
            request.Web.CountSpecified = true;
            request.Web.Offset = 0;
            request.Web.OffsetSpecified = true;
            request.Web.Options = new WebSearchOption[]
        {
            WebSearchOption.DisableHostCollapsing,
            WebSearchOption.DisableQueryAlterations
        };

            return request;
        }


        static void DisplayErrors(XmlNode errorDetails)
        {
            // Add the default namespace to the namespace manager.
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(
                errorDetails.OwnerDocument.NameTable);
            nsmgr.AddNamespace(
                "api",
                "https://schemas.microsoft.com/LiveSearch/2008/03/Search");

            XmlNodeList errors = errorDetails.SelectNodes(
                "./api:Errors/api:Error",
                nsmgr);

            if (errors != null)
            {
                // Iterate over the list of errors and display error details.
                HttpContext.Current.Response.Write("Errors");
                //Console.WriteLine("Errors:");
                //Console.WriteLine();
                foreach (XmlNode error in errors)
                {
                    foreach (XmlNode detail in error.ChildNodes)
                    {
                        HttpContext.Current.Response.Write(detail.Name + ": " + detail.InnerText);
                        // Console.WriteLine(detail.Name + ": " + detail.InnerText);
                    }

                }
            }
        }
    }
}

Testing Bing Search Service in the Web Application

This section shows the steps to perform to test the application.

  1. Build the Web application.
  2. In Solution Explorer right click on default.aspx.
  3. Click the Using the Web SourceType over the SOAP Protocol link
  4. The Web ServiceType search results are displayed.

We are done.

A complete Visual Studio project is attached next. Please download and play with it.

I appreciate your feedback.

See Also

Bing API, Version 2

Working with Protocols (Bing, Version 2)

Code Samples (Bing, Version 2.0)

SimpleBingSearch.zip

Comments

  • Anonymous
    September 27, 2009
    I found this example very useful. It is a good entry point to start experimenting with Bing technology. Thanks

  • Anonymous
    November 09, 2009
    Hi,   What is the namespace used for SearchResponse.

  • Anonymous
    November 10, 2009
    The comment has been removed

  • Anonymous
    November 10, 2009
    The comment has been removed

  • Anonymous
    November 11, 2009
    I was able to add the Web Reference when I set the Authentication Mode to None. But then when I run the code to get the response of the request i.e. response = service.Search(request); I get the error that the remote site name is not resolved. "The remote name could not be resolved: 'api.search.live.net'"

  • Anonymous
    January 04, 2011
    vogue life  http://www.myvogueshow.com   IC Components  http://www.hqew.net

  • Anonymous
    May 23, 2011
    I'm using the MSN API, but I enter the web service URL into my browser get the 404 Not Found message. Any help appreciated. soap.search.live.com/webservices.asmx

  • Anonymous
    November 16, 2011
    Well,thank you so much for the idea..That's very interesting topic.What a nice topic.. Cheers, simple soap www.simplesoapmakingguide.com