Primary Web Services Technologies


The preceding discussion has focused on describing a web service process. It is useful now to explain how the client accesses services by employing the core web technologies—namely, Simple Object Access Protocol (SOAP), HTTP, Web Services Description Language (WSDL), and Universal Description, Discovery, and Integration (UDDI)—to locate the service/services the client specifies. Developers can browse numerous web service repositories (registries) and select appropriate services for implementing their own applications. Figure 7-2 demonstrates how a registry serves as host to a collection of web services.

click to expand
Figure 7-2: A web service registry

Simple Object Access Protocol

SOAP provides a standard structure for transmitting XML documents over the wire, which includes SMTP, HTTP, and FTP. SOAP also defines encoding and binding standards for encoding non-XML Remote Procedure Calls. SOAP enhances interoperability between client and server. Clients with .NET can call EJBs through SOAP and vice versa.

Note

Other protocols have been developed, for example, Sun’s RPC, Microsoft’s DCE, Java’s RMI, and CORBA’s ORBC.

Why are so many corporations embracing SOAP? It has industry-wide support and is not bound to one programming language. Interestingly, SOAP does not use a specified set of APIs, but rather leaves the implementation up to the programming language (such as Java) and the platform (such as Microsoft .NET). The SOAP specification does not describe how SOAP messages should be bound to HTTP. SOAP is an XML document. Listing 7-1 is representative of a typical SOAP request and response XML file.

Listing 7-1: SOAP request-response example

start example
POST /MathWebService/Service1.asmx HTTP/1.1
Host: ecom10
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/SelectMaxValue"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<SelectMaxValue xmlns="http://tempuri.org/">
<x>int</x>
<y>int</y>
</SelectMaxValue>
</soap:Body>
</soap:Envelope>

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<SelectMaxValueResponse xmlns="http://tempura.org/">
<SelectMaxValueResult>int</SelectMaxValueResult>
</SelectMaxValueResponse>
</soap:Body>
</soap:Envelope>
end example

Note

In a production environment, change the XML namespace to your own namespace as demonstrated here:

<int xmlns="http://www.dp.org/results/>

SOAP’s Messaging Architecture

Let’s step through Listing 7-1. The header indicates this is an HTTP POST request, followed by the name of the method, MathWebService. The .asmx extension is used for files that implement XML web services. Web services can be accessed directly through .asmx files, or this file can redirect the request to a compiled assembly implementing the web service. The root element of the SelectMaxValue document is the Envelope element. The listing has two subelements, the body and header elements.

The next item of interest is the attribute bearing the name of the host machine. The Content-type specifies the file as text/xml, and the encoding is utf-8. The SOAPAction attribute identifies the URI namespace where the method is located and lists the web service name. The XML declaration indicates the SOAP message is XML-based. Next, all SOAP messages have an envelope, where the message body is embedded. Both client and recipient must strip the content from the envelope for further processing. Notice the default xmlns namespace declarations. These must precede the SOAP body. Finally, the method is processed where the web service determines whether int value x is greater or smaller than y. The response is virtually self-explanatory. Beginning with the traditional SOAP header, the SOAP body result syntax is similar to the request, with the exception that the Method syntax indicates it is a response and returns a result.

Before the discussion focuses on other SOAP attributes, here are the key elements discussed so far:

  • The SOAP envelope This encodes header information about the message and body of the message.

  • SOAP encoding This allows for a standardized method of serializing data into the body of a SOAP message.

  • RPC-style messages This entails the type of protocol a developer can employ to facilitate procedure-oriented communications via a request-response message.

  • HTTP binding This is the industry-wide method of binding SOAP messages to the HTTP messaging protocol.

Other SOAP Attributes

A SOAP message defines a SOAP actor, which is divided in two parts:

  • A default actor is the intended final recipient of a SOAP message.

  • An intermediary actor can act on the content of a SOAP message by modifying the content in some way.

The intermediary actor may manipulate the message content in an unspecified way before forwarding the message to its final destination. Although the message is altered, it is still considered the same message as the one originally sent.

An optional header element will transmit data that might not be appropriate to encode in the envelope body. For example, if a default actor receives an encoded, compressed message, it would need to know what type of algorithm is used to compress the code before it could decode the message. Other types of optional headers include the all-important authentication method, routing information, transactions, and security information. A default actor may require the sender to provide authentication information before the recipient can process the message. A message may require specific routing to more than one destination. In addition, the recipient may require security information to determine whether a message is modified before arriving at its destination. For example, it is important for a stock quote to remain in its original state before a brokerage firm can sell the stock to clients. The header element can be added to the SOAP envelope as a child element. Listing 7-2 demonstrates this.

Listing 7-2: Defining a child node within the SOAP envelope

start example
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<Manifest>BH784Fg23559></Manifest>
</soap:Header>
<soap:Body>
<StockReport>
<StockSymbol>JANS</StockSymbol>
<Price>29.13</Price>
<!--Ouch, a huge financial loss- ->
</StockReport>
</soap:Body>
</soap:Envelope>
end example

The mustUnderstand Attribute

Use the mustUnderstand attribute when information embedded within the header should not be ignored. Therefore, mustUnderstand provides a method for differentiating between noncritical information and mission-critical data that requires attention. By specifying a value of 1 in the header’s root element, the identified data cannot be ignored. Listing 7-3 demonstrates how to use this attribute.

Listing 7-3: Using the mustUnderstand attribute

start example
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<TransactionID soap:mustUnderstand="1">19.92</TransactionID>
</soap:Header>
<soap:Body>
<UpdateStockQuote>
<email>DPeltzer@IFCE.com</email>
<f_Name>Dwight</f_Name>
<l_Name>Peltzer</l_Name>
</UpdateStockQuote>
</soap:Body>
</soap:Envelope>
end example

This example shows how the recipient must update the specified stock quote within scope of the client’s transaction. In the event the transaction is going awry in some way, the application must roll back any changes made to the client’s account. The mechanism used for this is the mustUnderstand attribute, and is achieved by setting the attribute to 1.

The Actor Attribute

The Actor attribute provides a mechanism for annotating SOAP headers. For example, a document can be routed to an intermediary that will create a transaction, specifying the URI for the intermediary for which a portion of the message is intended.

If the header is destined for processing by the next recipient of a SOAP message, set both the mustUnderstand attribute and the Actor attribute. Listing 7-4 demonstrates how to do this.

Listing 7-4: Setting the next recipient

start example
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http:////schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<TransactionID soap:mustUnderstand="1"
actor="urn:TransactionCoordinator>19.90</TransactionID>
</soapHeader>
<soap:Body>
<UpdateStockQuote>
<Source>102420484096</Source>
<Destination>102420484096</Destination>
<Price>12.95></Price>
</AddNewClient>
</soap:Body>
</soap:Envelope>
end example

If the TransactionCoordinator does not know how to interpret this message, it raises an error. The </AddNewClient> directive does not belong in this message. This is evidenced by lack of a corresponding opening tag. Before the message is passed on, all foreign elements must be removed. However, the intermediary can add header elements before forwarding the message to the next intermediary or final recipient.

The Body Element

All SOAP messages must have exactly one <soap:Body> element. The body element contains the payload. There are some constraints on how the body is encoded. The payload can consist of a string of ASCII characters, a byte array, or XML text. However, the contents may not contain any characters that would invalidate the embedded XML document.

XML messages can be placed in two categories: document-oriented messages and procedure-oriented messages. For example, a document that provides a stock quote to a client can be encoded within the body of a SOAP message and specify a particular routing for an intended recipient. The procedure-oriented messages offer two-way communications and are frequently referred to as RPC messages.

The Fault Element

SOAP messages fail for a number of reasons. It is important to use the Fault attribute and generate an error message back to a client. SOAP specifies a format for handling errors. Listing 7-5 demonstrates this.

Listing 7-5: Web services error handling

start example
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http:////schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<soap:FaultCode>Client.Security</soap:faultcode>
<soap:faultstring>Access denied</soap:faultstring>
<soap:faultactor>http://dps.com</soap:faultactor>
<soap:detail>
<myError>
<Originator>File System></Originator>
<Resource>My File.txt></Resource>
</myError>
</soap:detail>
</soap:Fault>
</soap:Body>
</soap:Envelope>
end example

The Faultcode contains a value to determine the kind of error it encounters. Several fault codes are available for use:

  • Version Mismatch This specifies an invalid namespace declared for the SOAP envelope.

  • MustUnderstand A child element residing within the SOAP header contains a mustUnderstand attribute. If the attribute is set to 1, it indicates the attribute was not understood.

  • Client Content located within the message body was found to be faulty.

  • Server The server determines that the error lies with the inability to obtain resources or the inability to process the message.

The SOAP features presented here must be adhered to when processing SOAP messages. The next major web services technology, Web Services Description Language (WSDL), describes what a SOAP payload contains.

Web Services Description Language

WSDL documents contain metadata about a client’s input and output parameters from an invocation externally. This means a user is invoking a method externally. In addition, the WSDL file describes the service’s functionality. In essence, the file facilitates interaction between disparate clients by providing the requisite information on how to achieve interoperability between them.

Let’s create a small web service in ASP.NET and then inspect the WSDL file. The first task required for building a web service in the .NET world is creating a virtual directory in Internet Information Services.

  1. Create a folder on the server, and name it “MySOAPExamples.”

  2. In Windows 2000 or Windows XP, select Start | Control Panel | Administrative Tools | Internet Information Services. Open IIS, right-click the default web site, select New, and then select Virtual Directory. A dialog box will appear on your screen. Select Next, and enter MySOAPExamples in the Alias dialog box. Make sure the subdirectory is already created somewhere on the hard drive. Finally, proceed to Finish to generate the virtual directory.

  3. Create a new project in Visual Studio .NET called “IFCEBrokerage.”

  4. Rename Webservice1.asmx to IFCEBrokerageFirm.asmx. The extension .asmx represents an ASP.NET web service extension.

  5. The namespace should be named “namespace IFCEBrokerage.”

  6. Enter the code shown in Listing 7-6.

Listing 7-6: IFCEBrokerageFirm web service code

start example
using System;
using System.Web;
using System.Web.Services;
namespace IFCEBrokerage
{
public class SecuritiesExchange : System.Web.Services.WebService
{
[WebMethod]
public double StockQuote(string symbol)
{
double quotePrice= 0;
switch(symbol)
{
case "JANS":
quotePrice = 29.95;
break;
case "MSFT":
quotePrice = 49.97;
break;
case "ORCL":
quotePrice = 37.72;
break;
}
return quotePrice;
}
}
}
end example

Several IFCEBrokerageFirm items require clarification. An excellent place to begin learning about them is in web service namespaces. Table 7-1 displays them with comments.

Table 7-1: System.Web.Services Namespace Descriptions

Class

Description

WebMethodAttribute

Adding this attribute to a method when defining a web service created in ASP.NET makes the method callable from remote web clients.

Web Service

This class defines the optional class for XML web services, thereby providing access to common ASP.NET objects, for example, application and session state.

WebServiceAttribute

This class is used to append additional information to an XML web service, such as a string explaining its functionality.

WebServiceBindingAttribute

Declares binding for one or more XML web service methods implemented within the class that is implementing the web service.

These namespaces enable developers to create XML web services using ASP.NET and XML web service clients. XML web services represent applications that enhance the ability to exchange messages in a loosely coupled environment using protocols such as HTTP, XML, XSD, SOAP, and WSDL. They facilitate constructing modular applications in a heterogeneous environment that promotes interoperability between applications, smart client devices, and implementations.

Note

The WebMethodAttribute class must be applied to any method where a developer wants to expose it programmatically.

Because the implementation of a web service is encapsulated within a class, it is important to define an end point for the web service. The .asmx file serves as the end point for the web service. When a client calls the .asmx file, the ASP.NET runtime processes the file.

Usually, each .asmx page has a language directive at the top of the page, as displayed here:

<%@ WebService Language="C#" Class= "IFCEBrokerage.SecuritiesExchange" %>

The first time the web service is called, the ASP.NET runtime uses the Language directive to compile the code first to MSIL and subsequently to the language specified by the directive. In this case, the directive specifies the C# .NET programming language. This means the IFCEBrokerage class code shares the CLR runtime services and data types defined in the CTS with all other .NET programming languages.

Note

The Class attribute bears the fully qualified name of the class that implements the web service. Because the default language in the machine.config file is set to “vb,” the IFCEBrokerageFirm.asmx language should be set to C# .NET. Here is the machine.config file segment:

<compilation debug="false" explicit="true" defaultLanguage="vb"> 

It is also wise to place the web service’s implementation in its own assembly. By convention, the assembly is placed within the web application’s bin directory because this directory is placed within the search path.

The SecuritiesExchange web service client can access this web service only through HTTP for the simple reason that ASP.NET supports only this transmission protocol. However, the web service supports three kinds of protocol bindings:

  • SOAP

  • HTTP Get

  • HTTP POST

All ASP.NET web services support SOAP because the SOAP body content is strongly typed and is XML based through the XSD Schema.

Web Services Documentation

ASP.NET’s runtime includes services such as documentation. This is a major benefit because the CLR uses System.Reflection to generate two kinds of documentation:

  • Documentation utilized by clients so they can interact with web services

  • Documents referenced by people

HTML-based documents are accessible by entering the URL in a browser. Both the WebMethod and its companion attribute WebService expose the Description property. Listing 7-7 demonstrates how to include documentation in the IFCEBrokerage.asmx file.

Listing 7-7: Adding the Description attribute

start example
using System;
using System.Web;
using System.Web.Services;
namespace IFCEBrokerage
{
[WebService(Description ="This demonstrates how to use the Description
attribute")]
public class SecuritiesExchange : System.Web.Services.WebService
{
[WebMethod]
public double StockQuote(string symbol)
{
double quotePrice= 0;

switch(symbol)
{
case "JANS":
quotePrice = 29.95;
break;
case "MSFT":
quotePrice = 49.97;
break;
case "ORCL":
quotePrice = 37.72;
break;
}

return quotePrice;
}
}
}
end example

The documentation automatically generated for the IFCEBrokerageFirm is shown in Listing 7-8:

Listing 7-8: Sample documentation for IFCEBrokerageFirm

start example
SecuritiesExchange
This demonstrates how to use the Description attribute
The following operations are supported.
For a formal definition, please review the Service Description.
StockQuote
This web service is using http://tempuri.org/ as its default namespace.
Recommendation: Change the default namespace
before the XML Web service is made public.
end example

Examining Namespaces

Each XML web service needs a unique namespace in order for client applications to distinguish it from other services on the Web. The http://tempuri.org/ namespace is available for XML web services that are under development, but published XML web services should use a more permanent namespace.

Your XML web service should be identified by a namespace that you control. For example, you can use your company’s Internet domain name as part of the namespace. Although many XML web service namespaces look like URLs, they need not point to actual resources on the Web. (XML web service namespaces are URIs.)

For XML web services created using ASP.NET, the default namespace can be changed using the WebService attribute’s Namespace property. The WebService attribute is an attribute applied to the class that contains the XML web service methods. Listing 7-9 shows an example that sets the namespace to http://microsoft.com/webservices/.

Listing 7-9: HTML-based documentation

start example
C#
[WebService(Namespace="http://microsoft.com/webservices/")]
public class MyWebService {
// implementation
}
Visual Basic.NET
<WebService(Namespace:="http://microsoft.com/
webservices/")> Public Class MyWebService
' implementation
End Class
For more details on XML namespaces,
see the W3C recommendation on Namespaces in XML.
For more details on WSDL, see the WSDL Specification.
For more details on URIs, see RFC 2396.
end example

This web page shows the method exposed by the web service StockQuote. It also provides the following recommendation:

Recommendation: Change the default namespace
before the XML web service is made public.

And it lists some examples for changing the namespace.

Listing 7-10 displays the web service WSDL file that strong-types the web service.

Listing 7-10: IFCEBrokerageFirm WSDL file

start example
<?xml version="1.0" encoding="utf-8" ?>
<definitions xmlns:http="http://
schemas.xmlsoap.org/wsdl/http/" xmlns:soap="http://
schemas.xmlsoap.org/wsdl/soap/" xmlns:s=
"http://www.w3.org/2001/XMLSchema" xmlns:s0="http://tempuri.org/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/"
xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
targetNamespace="http://tempuri.org/" xmlns=
"http://schemas.xmlsoap.org/wsdl/">
<types>
<s:schema elementFormDefault="qualified"
targetNamespace="http://tempuri.org/">
<s:element name="StockQuote">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="symbol" type="s:string" />
</s:sequence>
</s:complexType>
</s:element>
<s:element name="StockQuoteResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="1" maxOccurs="1"
name="StockQuoteResult" type="s:double" />
</s:sequence>
</s:complexType>
</s:element>
</s:schema>
</types>
<message name="StockQuoteSoapIn">
<part name="parameters" element="s0:StockQuote" />
</message>
<message name="StockQuoteSoapOut">
<part name="parameters" element="s0:StockQuoteResponse" />
</message>
<portType name="SecuritiesExchangeSoap">
<operation name="StockQuote">
<input message="s0:StockQuoteSoapIn" />
<output message="s0:StockQuoteSoapOut" />
</operation>
</portType>
<binding name="SecuritiesExchangeSoap" type="s0:SecuritiesExchangeSoap">
<soap:binding transport="http://
schemas.xmlsoap.org/soap/http" style="document" />
<operation name="StockQuote">
<soap:operation soapAction="http://
tempuri.org/StockQuote" style="document" />
<input>
<soap:body use="literal" />
</input>
<output>
<soap:body use="literal" />
</output>
</operation>
</binding>
<service name="SecuritiesExchange">
<documentation>This demonstrates how to use the Description
attribute</documentation>
<port name="SecuritiesExchangeSoap" binding="s0:SecuritiesExchangeSoap">
<soap:address location="http://
localhost/IFCEBrokerage/IFCEBrokerageFirm.asmx" />
</port>
</service>
</definitions>
end example

The WSDL file has several interesting characteristics, described shortly in some detail. But first, Listing 7-11 demonstrates the standard form that every WSDL file takes.

Listing 7-11: IFCEBrokerageFirm.asmx WSDL file

start example
<?xml version="1.0" encoding="utf-8" ?>
<definitions xmlns:http="http://
schemas.xmlsoap.org/wsdl/http//
" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:s="http://www.w3.org/2001/XMLSchema
" xmlns:s0="http://tempuri.org/" xmlns:soapenc=
"http://schemas.xmlsoap.org/
soap/encoding/" xmlns:tm="http://microsoft.com/wsdl/
mime/textMatching/" xmlns:mime="http://
schemas.xmlsoap.org/wsdl/mime/"
targetNamespace="http://tempuri.org/"
xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<s:schema elementFormDefault="qualified"
targetNamespace="http://tempuri.org/">
<s:element name="StockQuote">
<s:element minOccurs="0" maxOccurs="1" name="symbol" type="s:string" />
<s:element name="StockQuoteResponse">
<s:complexType> <s:element minOccurs="1"
maxOccurs="1" name="StockQuoteResult"
type="s:double" />
</s:sequence> </types>
<message name="StockQuoteSoapIn">
<part name="parameters" element="s0:StockQuote" />
</message>
<message name="StockQuoteSoapOut">
<part name="parameters" element="s0:StockQuoteResponse" />
</message>
<portType name="SecuritiesExchangeSoap">
<operation name="StockQuote">
<input message="s0:StockQuoteSoapIn" />
<output message="s0:StockQuoteSoapOut" />
</operation>
</portType>
<binding name="SecuritiesExchangeSoap" type="s0:SecuritiesExchangeSoap">
<soap:binding transport="http://
schemas.xmlsoap.org/soap/http" style="document" />
<operation name="StockQuote">
<soap:operation soapAction="http://
tempuri.org/StockQuote" style="document" />
<input> <soap:body use="literal" />
</input>
<output> <soap:body use="literal" />
<service name="SecuritiesExchange">
<port name="SecuritiesExchangeSoap" binding="s0:SecuritiesExchangeSoap">
<soap:address location="http://localhost/
IFCEBrokerage/IFCEBrokerageFirm.asmx" />
</port> </definitions>
end example

The WSDL file defines its own namespace. WSDL adds a targetNamespace attribute to the <definitions> element. The targetNamespace attribute may not use a relative URI. Conversely, it must use the fully qualified URL. The namespace allows the author to qualify references to entities contained within the WSDL document.

By doing this, the WSDL file assigns the prefix wsdlns to reference the namespace. This prefix fully qualifies all references to entities combined within the document. In addition, it sets prefixes for the <types> element as well as the XSD Schema. The <definitions> element sets boundaries for a specified name. All elements declared within the WSDL file define entities for messages and ports. Assign entities utilizing the Name attribute.

In a production environment, it is imperative to change the target namespace to your own. The temporary namespace displayed in the WSDL document, for example,

targetNamespace="http://tempuri.org/"
xmlns="http://schemas.xmlsoap.org/wsdl/"

specifies the http://tempuri.org namespace. It is better to do the following:

targetNamespace="http://IFCEBrokerageFirm.com/"
xmlns="http://schemas.xmlsoap.org">

Returning to Listing 7-10, the <types> element contains XSD Schema information contained within the WSDL file. For example, examine the following document segment, and observe how the schema element appears as an immediate child of <types>. In addition, <types> functions as a container for XSD Schema complex types.

<s:element name="StockQuote">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="symbol"
type="s:string"/>
</s:sequence>
</s:complexType>
</s:element>

The same is true for StockQuoteResponse. Its type is s:double.

The <message> element contains two parts, the message name and the part name. The message name is StockQuoteSOAPIn. The part name is parameters, and the element is s0:StockQuote. Notice that the message segment contains both a

<message name="StockQuoteSoapIn">

and a

  <part name="parameters" element="s0:StockQuote" />
</message>
<message name="StockQuoteSoapOut">

The <message> element contains descriptions for logical elements of messages. The <part> represents a parameter passed to the method.

The <portType> element defines a list of operations, each individually assigned to a specified <operation> child element. In this case, SecuritiesExchange SOAP is the portType name. The <operation> name is StockQuote. The input and output messages are

s0:StockQuoteIn

and

s0:StockQuoteOut




.NET & J2EE Interoperability
Microsoft .NET and J2EE Interoperability Toolkit (Pro-Developer)
ISBN: 0735619220
EAN: 2147483647
Year: 2004
Pages: 101
Authors: Simon Guest

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net