Show All

# Building a Research Web Service

Research Web services must contain the Registration and Query Web methods. In addition, the XML packets that these methods use to communicate with the Research task pane must conform to predefined XML schemas in the Microsoft.Search namespace.

Research service Web methods

The Registration method is used to register research services with the Research task pane. Once it is registered, the service is available as a choice in the Show Results From drop-down list. When the user installs the research service as a Research task pane resource, a request (formatted as defined by the Microsoft.Search.Registration.Request.xsd schema) is sent to the Registration method. The response that is received is used to make appropriate entries in the Microsoft Windows® registry, and must be formatted as defined by the Microsoft.Search.Registration.Response.xsd schema.

Note Services whose Display attribute is set to HIDDEN (such as translation services) or OFF are not available as choices in the Show Results From drop-down list.

The Query method is called when the user requests information from the research service by searching for a term or submitting a form in the Research task pane. The Research task pane sends an XML packet based on the Microsoft.Search.Query.xsd family of schemas. The research service must send a response based on the Microsoft.Search.Response.xsd family of schemas.

## Structure of a Research Web Service

You can build a research Web service as a single service that implements both the Registration and the Query methods, or as a pair of services consisting of a separate service for each method. The latter option is possible because the Research task pane registers a provider's RegistrationPath and QueryPath as distinct settings. The samples included with this SDK demonstrate both approaches.

Web service prototype

Research Web services use the Microsoft.Search namespace and consist of the Registration and Query Web methods. The Web service class must have the WebService attribute applied, and the Registration and Query methods must have the WebMethod attributes applied. You can use the optional properties of the WebService and WebMethod attribute classes to specify descriptions for your Web service and its methods as well as buffering, caching, and other settings.

The following is a prototype for a research Web service. This sample does not include code generated by the Microsoft Visual Studio® .NET Web service designers.

Visual Basic® .Net

    Imports System.Web.Services

    <System.Web.Services.WebService(Namespace:="urn:Microsoft.Search", _
        Description:="A Research Web service.")> _
    Public Class MyResearchService
        Inherits System.Web.Services.WebService

        <WebMethod(Description:="Registers the research service.")> _
        Public Function Registration(ByVal registrationXml As String) _
            As String

        End Function

        <WebMethod(Description:= _
            "Returns query results to the Research task pane.")> _
        Public Function Query(ByVal queryXml As String) As String

        End Function

    End Class

C#

    using System.Web.Services;

    namespace MyResearchServices
    {
        [WebService(Namespace="urn:Microsoft.Search",
            Description="A Research Web service.")]
        public class MyResearchService : System.Web.Services.WebService
        {

            [WebMethod(Description="Registers the research service.")]
            public string Registration(string registrationXml)
            {
            }

            [WebMethod(Description=
                "Returns query results to the Research task pane.")]
            public string Query(string queryXml)
            {
            }

        }
    }

Important considerations when building a research Web service

Keep these points in mind when building a research Web service:

- The WebService attribute must reference the Microsoft.Search namespace.
- The string input parameters for the Registration and Query Web methods must be named `registrationXml` and `queryXml` respectively. (The Discovery Web method also uses `registrationXml`. For more information about discovery, see Configuring Service Discovery.) These names are case-sensitive. If, while testing a research Web service, you find that the incoming argument is empty, check the name and case of the parameter in the function header.

If you want to see the Web Services Description Language (WSDL) definition of an existing Web service and you have the Microsoft .NET Framework installed, you can navigate to:

    	http://<servername>/<servicename>.asmx?wsdl

## Processing Requests and Responses

Note The research Web service samples included with this SDK demonstrate the various approaches discussed in this section.

Reading the request

Since the Research task pane generates the XML registration and query request packets that a research Web service receives to process, you can assume that these packets conform to the Registration.Request schema and to the Query family of schemas. The System.Xml namespace in the .NET Framework offers several different approaches for reading the values that you want to extract out of the incoming request packet. For example, you can:

- Load the packet into an XmlDocument and use the SelectSingleNode method (and similar methods) to extract only the values you want.
- Use an XmlTextReader to read through the packet sequentially until you locate the values that you want to extract.

The registration request packet consists almost entirely of language-related settings from the client computer. If you write your research Web service for use in a single-language setting, and you don't expect registration requests from other locales, you may be able to ignore the incoming registration packet.

Writing the response

Responding to a registration or query request requires that you compose an XML document that conforms to the appropriate schemas. The Registration and Query methods return this XML document to the client computer as a string. The .NET Framework offers several different approaches for assembling this string of XML. For example, you can:

- Use an XmlTextWriter to compose the response one element and one attribute at a time. This offers an advantage because the methods of the XmlTextWriter, including WriteStartDocument, WriteEndDocument, WriteStartElement, WriteEndElement, WriteElementString, and WriteAttributeString, help to ensure a well-formed XML document.
- Use a StringBuilder to assemble the response as strings of literal XML, including both tags and content. This is advantageous because you can clearly see all the XML in your code.
- Load an XML template file into an XmlDocument and fill in the values of the required elements and attributes. In fact, when a service provider's registration information rarely changes, it may be possible to load the complete registration response packet from a file, and return the file contents to the client computer without modification.

You can also validate the response that you have composed against the appropriate schemas by using the XmlValidatingReader class. For more information, see the section titled Validation of XML with XmlValidatingReader in the Microsoft .NET Framework SDK.

## Testing a Research Web Service

Testing tools and approaches

You can take advantage of several testing tools and approaches while developing a research Web service. For example, you can:

- Use the debugging capabilities of Microsoft® Visual Studio® .NET (which is not required for building research services) to set breakpoints and step through your Web service code as it executes. When you run your Web service project with debugging enabled, Visual Studio .NET launches an instance of Microsoft Internet Explorer. Leave this browser window open and switch to the Microsoft Office 2003 application in which you want to test the Research task pane. As you register or query your service, Visual Studio .NET pauses at the breakpoints that you set.
- Use the StreamWriter class to write the contents of the request or response packets to a file for further analysis. You can use a private method similar to the following:

      Private Sub SavePacket(ByVal xmlPacket As String,
          ByVal fileName As String)
          '  NOTE: To allow a Web service to save a file to disk, you may
          '  need to modify a combination of IIS and ASP.NET security
          '  settings and NTFS file permissions.

          Const WORKING_FOLDER As String = _
              "C:\TestOutput\"

          Dim outputFile As String = WORKING_FOLDER & fileName
          Dim xmlPacketFileWriter As StreamWriter = _
              New StreamWriter(outputFile, False)

          xmlPacketFileWriter.Write(xmlPacket)
          xmlPacketFileWriter.Flush()
          xmlPacketFileWriter.Close()
      End Sub

- To view the registration or query packet received by the Web service, use the QueryViewer Sample included with this SDK. When registered through the Research task pane, this sample returns the registration request packet and displays it in the License dialog box. When queried, this sample returns the contents of the query packet it received to the Research task pane.
- To test various query response packets by loading the query response from an XML file on the server, use the Toolkit Sample included with this SDK. This sample can accelerate development and testing that involves the Query Web method, because it is easier to compose a response packet as pure XML than to write the code necessary to generate the same XML packet programmatically.

Web service errors and exceptions

In a research Web service, errors and unhandled exceptions may cause unexpected results. For example, an exception that occurs in the Registration method, or an invalid XML packed returned from the Registration method, causes the following generic error message to be displayed to the user:

An exception that occurs in the Query method, or an invalid XML packed returned from the Query method, may cause the message "This service did not respond" to be displayed in the Research task pane.

When an error or exception occurs in a research Web service during the processing of a registration or query request, the research service should return a valid response that includes the appropriate return code in the Status element.

- When the Registration method fails, return one of the error values from the ResultsCodeType enumeration (defined in the Microsoft.Search.Registration.Response schema) in the Status element of the registration response. For more information, see Microsoft.Search.Registration.Response Schema Documentation and Enumerations Reference.
- When the Query method fails, return one of the error values from the StatusType enumeration (defined in the Microsoft.Search.Response schema) in the Status element of the query response. For more information, see Microsoft.Search.Response Schema Documentation and Enumerations Reference.

This sample code from the Email Sample shows how to return an error message (passed to the sample code in the `sMessageError` string variable) in response to a registration request from a user for whom the service was not intended.

    // The StringBuilder for the response.
    StringBuilder sb = new StringBuilder();

    // If the user is in an inappropriate market,
    // the service is not registered.
    if (fIsSensitiveLocation)
    {
        sb.Append("<ProviderUpdate xmlns=
            'urn:Microsoft.Search.Registration.Response'>");
        sb.Append(	"<Status>ERROR_NOT_COMPATIBLE</Status>");
        sb.Append(	"<Message>" + sMessageError + "</Message>");
        sb.Append(	"<Providers />");
        sb.Append("</ProviderUpdate>");
    }
    // Else it works: Send the standard registration packet.
    else
    {
    ...
    }

©2003-2004 Microsoft Corporation. All rights reserved. Permission to copy, display and distribute this document is available at: http://msdn.microsoft.com/library/en-us/odcXMLRef/html/odcXMLRefLegalNotice.asp