zoukankan      html  css  js  c++  java
  • Using Bing Search Service over SOAP Protocol in an ASP.NET Web Application

    Introduction


    This walkthrough shows how to use 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 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 via 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 2010.

    • 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 2010

    2. In the File menu, click New, and then click Project.

    3. The New Project dialog box is displayed.

    4. Under Installed Templates, in the left pane, select Visual Basic or Visual C#.

    5. In the 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:\CS\SOAP\WebApplications

    7. In the Name dialog box enter the name of the project. For example, enter the name UsingBingAPI.

    8. Click OK.

    9. An ASP.NET application is created.

    Adding a Web Reference to Bing Search Service


    This section shows how to add a Web reference to the Bing search service. In order to do that, you use a Web service discovery process by which the client 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, which allows the client code 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 the client application and the Web service itself.


    To add a Web reference to Bing Search Service



    1. In Solution Explorer , right-click the project name, and then click Add Web Reference button.

    2. In the Add Web Reference panel, in the URL box enter the following value: http://api.search.live.net/search.wsdl.

    3. Click GO .

    4. If the process has been added successfully a message is displayed saying that “1 Service Found: Search” and the Web reference is: net.live.search.api.

    5. Click Add Reference button.

    6. A Web References folder is added to the project that contains the reference to the live 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>http://api.search.live.net:80/soap.asmx</value
    >
    </
    setting
    >
    </
    UsingBingService.Properties.Settings
    >
    </
    applicationSettings>

    Performing Search by Using Bing ServiceTypes


    This section shows the code that enables the user to choose the desired Bing ServiceType to perform live search. For simplicity only the following types are used:













    SourceType


    Function


    Web


    Retrieve information from the Internet


    Phonebook


    Find location specific information


    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
    >
    <
    li><a href=”PhonebookSourceType.aspx” target=”_blank”>Using the Phonebook 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=”http://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=”http://msdn.microsoft.com/en-us/library/dd250886.aspx” target=”_blank”>WebRequest</a> type. </li
    >
    <
    li>Display the results obtained from the
    <a href=”http://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=”http://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=”http://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 Web Form.

    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
    // “UsingBingService” and the name of the Bing API web reference is
    // “net.live.search.api”. Modify this using directive as necessary.
    using UsingBingService.net.live.search.api;

    namespace UsingBingService
    {
    public static class UsingWebSourceType
    {
    // Replace the following string with the AppId you received from the
    // Bing Developer Center.
    const string AppId = “Enter your AppId”;

    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;
    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”,
    “http://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 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)


    Working with SourceTypes (Bing, Version 2)

     

    source:http://www.codedstyle.com/using-bing-search-service-over-soap-protocol-in-an-aspnet-web-application/

  • 相关阅读:
    Android:TabHost导航栏
    java:StringUtil工具类
    Android进阶篇MediaPlayer
    Android:图片滚轮
    Android:EditText焦点触发布局隐藏以及显示
    Android:Spinner的使用
    ASP.NET编程模型的理解
    ASP.NET页面事件(页面生命周期)
    根据用户喜欢的爱好选择不同风格CSS(ViewState)
    ASP.NET的页面指令
  • 原文地址:https://www.cnblogs.com/big4panda/p/6417581.html
Copyright © 2011-2022 走看看