ASP.NET WebMethods - CiteSeerX
-
Upload
khangminh22 -
Category
Documents
-
view
0 -
download
0
Transcript of ASP.NET WebMethods - CiteSeerX
ASP.NET WebMethodsMapping methods to Web service operations
2
Implementing Web Services
• There are two ways to build Web Services in .NET today– using ASP.NET's built-in plumbing (WebMethods)– using the XML/HTTP APIs directly (custom handlers)
• Typical tradeoff between productivity and flexibility
Productivity
Flex
ibili
ty
WebMethods
custom handlers
3
WebMethods
• WebMethods map CLR methods to SOAP messages– simply annotate methods with the [WebMethod] attribute– found in System.Web.Services namespace– layered over HTTP pipeline and XML stack– offers higher productivity (just write methods)
[WebMethod]public int Add(int n1, int n2){
return n1 + n2;}
4
Web Service Namespace
[WebService(Namespace="urn:examples-org:math")]public class MathService{
[WebMethod]public int Add(int n1, int n2){
return n1 + n2;}
}
• Specify the Web service (XML) namespace on the class– use the [WebService] attribute
5
WebMethod Infrastructure (.asmx handler)
• ASP.NET provides infrastructure for processing WebMethods– WebMethod class must be "bound" to .asmx endpoint– .asmx handler processes incoming SOAP messages
6
using System.Web.Services;public class MathService{
[WebMethod]public int Add(int n1, int n2){
return n1 + n2;}
}
An .asmx Endpoint
<%@ WebService class="MathService"%>math.asmx
math.cs
7
Deploying a WebMethod
• Once an class is implemented, it must be deployed– assembly placed in virtual directory's bin subdirectory or GAC– .asmx file is placed in target virtual directory
\inetpub\wwwroot\math
math.asmx\bin
math.dll
virtual directory
bin subdirectory
8
.asmx and JIT Compilation
• An .asmx file can directly contain WebMethod code– JIT compiled during first invocation
<%@WebService language="C#" class="MathService"%>using System.Web.Services;public class MathService{
[WebMethod]public int Add(int n1, int n2){
return n1 + n2;}
}
9
Functionality Provided by .asmx Handler
WebMethod .asmx handler provides four areas of functionality1. dispatching SOAP messages to CLR methods2. object serialization/deserialization3. automatic WSDL/documentation generation4. extensibility model
10
Method Dispatching
POST /math/math.asmx HTTP/1.1SOAPAction: "urn:math:Mul"<s:Envelope...>
<s:Body><x:Mul>...
</s:Body></s:Envelope>
<%@ WebService language="C#" class="MathService" %>
using System.Web.Services;public class MathService{
[WebMethod]public int Add(int n1, int n2) {return n1 + n2;
}[WebMethod]public int Sub(int n1, int n2) {return n1 - n2;
}[WebMethod]public int Mul(int n1, int n2) {return n1 * n2;
}...
}
.asmx handlerIIS
11
Object Serialization/Deserialization
• WebMethods automatically map between XML and objects– layered over System.Xml.Serialization.XmlSerializer– ensures that objects map to XML and types map to XSD– guarantees interoperability with other platforms– does not handle all complexities of modern object models…
Class
Object
Schema Type
XML Instance
12
WebMethod Deserialization
Deserialize
<s:Envelope...><s:Body><x:Mul...><n1>33.3</n1><n2>66.6</n2>
</x:Mul></s:Body>
</s:Envelope>
n1 n2
System.Int32
<%@ WebService language="C#" class="MathService" %>
using System.Web.Services;public class MathService{
[WebMethod]public int Add(int n1, int n2) {return n1 + n2;
}[WebMethod]public int Sub(int n1, int n2) {return n1 - n2;
}[WebMethod]public int Mul(int n1, int n2) {return n1 * n2;
}...
}
.asmx handler
13
Using Complex Types
• WebMethods can automatically handle most objects– objects may be used as input/output– objects mapped to XSD complex types
public class Point {public double x; public double y;
}public class Geometry {[WebMethod]public double Distance(Point orig, Point dest) {// implementation omitted
}}
14
Complex Type Example
<soap:Envelope xmlns:soap="..."><soap:Body><Distance xmlns="urn:geometry"><orig><x>0</x><y>0</y>
</orig><dest><x>3</x><y>4</y>
</dest></Distance>
</soap:Body></soap:Envelope>
<soap:Envelope xmlns:soap="..."><soap:Body><DistanceResponse xmlns="urn:geometry"><DistanceResult>5</DistanceResult>
</DistanceResponse></soap:Body>
</soap:Envelope>
request
response
15
Complex Type Limitations
• Not all CLR types are safe to use without sacrificing interop– non-hierarchical object graphs– generic data structures (DataSet, Collection, etc.)– polymorphic objects
• If you care about interoperability, keep things simple today!– more on how to get around these issues later…
16
WebMethods and Errors
• SOAP specification defines how to convey errors– SOAP Fault element in message Body– 500 ("Internal Server Error") HTTP status code
• .asmx handler translates CLR exceptions to SOAP Faults– all exceptions caught by infrastructure– can throw SoapException to control exact Fault details
17
Using SoapException
using System.Web.Services;using System.Web.Services.Protocols;public class MathService{[WebMethod]public int Divide(int n1, int n2){if (n2 == 0)throw new SoapException("Cannot divide by 0",SoapException.ClientFaultCode);
return n1 + n2;}
}
18
Generating Documentation and WSDL
• .asmx handler generates human-readable documentation– returned for GET requests with no query string
• .asmx handler generated machine-readable WSDL– use '?wsdl' on query string (e.g., math.asmx?wsdl)– clients can use the WSDL to build proxy classes
19
Human-Readable Documentation
• Generated via DefaultWsdlHelpGenerator.aspx – found in …\Microsoft.NET\Framework\v1.0.3705\CONFIG– Customization possible
20
Machine-Readable WSDL
• Generated by .asmx handler for GET requests with "?wsdl"
21
WSDL and Code Generation
<wsdl:definitions ...>...
</wsdl:definitions>
public abstract class MathService : WebService{...
}
service.dll
wsdl.exe /server
public class MathService : SoapHttpClientProtocol{...
}
wsdl.exe
csc.exe.asmx
?wsdl
22
Additional .asmx Protocols
• In addition to SOAP, handler supports simple HTTP bindings– input modeled as application/x-www-form-urlencoded– request may be issued using GET or POST– output is simple XML element (not SOAP)– may be disabled in configuration file
add.asmx
…/math.asmx/Add?n1=10&n2=20
browser <int xmlns="…">30</int>
23
WebMethods Extensibility Model
• .asmx handler provides extensibility model for WebMethods– allows pre/post processing of SOAP messages– hooks available before/after deserialization/serialization– referred to as "SoapExtension framework"– more on this later...
Machine B
2
1Web Service
SOAPEnvelope
deserialize stage
serialize stage
24
Summary
• ASP.NET provides a complete Web service framework• WebMethod (.asmx) handler provides HTTP/XML plumbing• Dispatches SOAP messages to CLR methods• Parameters marshaled using XmlSerializer• Automatic WSDL/documentation generation• Extensibility model
25
References
• Getting Started with Web Services in VS.NET, MSDN, Caron– http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/dv_vstechart/html/vbtchGettingStartedWithXMLWebServicesInVisualStudioNET.asp
• Building XML Web Services for the Microsoft .NET Platform, MSPress, Short
• Real World XML Web Services, Addison Wesley, Shohoud
SOAPFraming and Extending XML Messages
2
What is SOAP?
• SOAP is an XML-based protocol for message communication– for exchanging information in a distributed environment– uses XML technologies to define a message construct – designed for use over a variety of underlying protocols– two major design goals: simplicity and extensibility
• More advanced distributed system features not included– will be designed as future SOAP extensions (headers)
• Acronym status revoked by W3C– used to mean "Simple Object Access Protocol"
3
XML 1.0 + Namespaces
The Basic Web Services Architecture
XSDSOAP
WSDLUDDI
Portable type system
Serialized form
Framing, protocol binding
Endpoint description
Registry of endpoints
Wire protocols
Description languages
Discovery mechanisms
4
SOAP Standardization
• SOAP 1.1 is de facto standard with broad industry support– several years of implementation experience– today's Web service toolkits support SOAP 1.1– SOAP 1.2 being standardized by W3C XML Protocol Working
Group (currently a Candidate Recommendation)
5
SOAP Specification
• SOAP 1.1/1.2 specifications codify several things– format for message framing and extensibility– a standard representation for errors– binding for sending messages over HTTP– binding for mapping messages to RPC invocations– rules for encoding common data types from programming
languages (e.g., Java, C#, VB, etc.)
6
SOAP Framing and Extensibility
• SOAP Envelope is message's document element– identifies document as SOAP message– indicates protocol version via namespace URI– contains optional Header element for protocol extensions– contains mandatory Body element for message data
• All three elements are from SOAP namespace– SOAP 1.1: http://schemas.xmlsoap.org/soap/envelope/– SOAP 1.2: http://www.w3.org/2002/12/soap-envelope
7
SOAP Envelope
• Header vs. Body distinction designed for extensibility– extensions can be designed via standardized headers– similar to other networking protocols
<soap:Envelopexmlns:soap="..."><soap:Header>
</soap:Header><soap:Body>
</soap:Body></soap:Envelope>
<!-- payload -->
<!-- standardized, pluggable headers -->
8
SOAP 1.1 Envelope Schema
<!-- Envelope complex type and global element decl. --><xs:element name="Envelope" type="tns:Envelope" /> <xs:complexType name="Envelope"><xs:sequence><xs:element ref="tns:Header" minOccurs="0" /> <xs:element ref="tns:Body" minOccurs="1" /> <xs:any namespace="##other" minOccurs="0"
maxOccurs="unbounded" processContents="lax"/> </xs:sequence><xs:anyAttribute namespace="##other"
processContents="lax"/> </xs:complexType>
9
Soap 1.1 Body Schema
<!– Body complex type and global element decl. --><xs:element name="Body" type="tns:Body" /> <xs:complexType name="Body"><xs:sequence><xs:any namespace="##any" minOccurs="0"
maxOccurs="unbounded" processContents="lax" /> </xs:sequence><xs:anyAttribute namespace="##any"
processContents="lax"/></xs:complexType>
10
Soap 1.1 Header Schema<!-- Header complex type and global element decl. --><xs:element name="Header" type="tns:Header" /> <xs:complexType name="Header"><xs:sequence>
<xs:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
</xs:sequence><xs:anyAttribute namespace="##other"
processContents="lax"/> </xs:complexType><!-- Global attribute decls. for marking headers --><xs:attribute name="mustUnderstand" default="0"><xs:simpleType>
<xs:restriction base="xs:boolean"><xs:pattern value="0|1" />
</xs:restriction></xs:simpleType>
</xs:attribute><xs:attribute name="actor" type="xs:anyURI" />
11
SOAP Message Example
<soap:Envelopexmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header>
</soap:Header><soap:Body>
</soap:Body></soap:Envelope>
<s:Order xmlns:s="urn:examples-org:ordersys"><item>Pillow</item><item>Wombat</item><item>Purple crayon</item></s:Order>
<t:Locale xmlns:t="urn:example-org:headers">UK</t:Locale>
12
Headers Enable Application Negotiation
• Well-known headers allow applications to negotiate– HTTP uses headers to negotiate valuable services (e.g.,
security, content, caching, virtual hosts, connections, etc.)• The Web services platform needs additional services
– should be defined as standard SOAP headers– otherwise, every application "rolls their own"– Microsoft is pursuing this with GXA (more later)
• XML-based header negotiation = protocol independence
SOAPclient
SOAPserver
SMTP
13
SOAP Intermediaries
• A SOAP message travels from the sender to the receiver potentially passing through a set of intermediaries – a SOAP intermediary acts as both sender/receiver– intermediaries may use various transport protocols– intermediaries typically process headers
SOAP intermediaries
initialsender
ultimatereceiver
HTTP SMTP
MSMQ
FTP
14
Actor and Role
• Not all headers may be intended for the ultimate receiver– may be intended for one or more intermediaries
• Intermediary nodes assume a role– roles are identified by a URI
• Headers can target a specific role using a global attribute– SOAP 1.1: actor– SOAP 1.2: role– mustUnderstand relative to role
• Upon match, node must process and remove header– contract was only between sender and this node– node may reinsert header to establish new contract
15
SOAP 1.1 Defined Roles
• SOAP 1.1 only defines a single role– http://schemas.xmlsoap.org/soap/actor/next
• Each node (intermediary and receiver) assume this role– hence, targets the next node in the path– omitting actor targets the ultimate receiver
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header>
<wsrp:path soap:mustUnderstand="1"soap:actor="http://schemas.xmlsoap.org/soap/actor/next"xmlns:wsrp="http://schemas.xmlsoap.org/rp">...
16
Processing SOAP Headers with WebMethods
• Web methods can process SOAP headers– headers are mapped to classes derived from SoapHeader– instance of class is used as data member– method adorned with [SoapHeader] attribute specifying data
member to map header to– can also map unknown headers to array of
SoapUnknownHeader type
17
Mapping SOAP Header Types
<xsd:complexType name="MyHeader"><xsd:sequence><xsd:element name="info" type="xsd:string" />
</xsd:sequence></xsd:complexType>
public class MyHeader : SoapHeader{public string info;
}
18
Mapping Headers to Data Members
using System.Web;using System.Web.Services;using System.Web.Services.Protocols;public class MathService{public MyHeader myHeader;[WebMethod][SoapHeader("myHeader")]public int Add(int n1, int n2){... // access myHeader herereturn n1 + n2;
}}
19
SOAP Error Information
• SOAP defines a standard representation for error information– if a SOAP request fails, response message's Body must
contain a Fault element• Fault must include…
– fault code similar to categorical HTTP errors– fault string with brief description
• Fault may include…– fault actor indicating failures at intermediaries– detail containing extra information
20
SOAP Fault Schema
<xs:element name="Fault" type="tns:Fault" /><xs:complexType name="Fault" final="extension" ><xs:sequence><xs:element name="faultcode" type="xs:QName" /><xs:element name="faultstring" type="xs:string" /><xs:element name="faultactor" type="xs:anyURI"
minOccurs="0" /><xs:element name="detail" type="tns:detail"
minOccurs="0" /></xs:sequence></xs:complexType><xs:complexType name="detail"><xs:sequence><xs:any namespace="##any" processContents="lax"
minOccurs="0" maxOccurs="unbounded" /></xs:sequence><xs:anyAttribute namespace="##any" processContents="lax" /> </xs:complexType>
21
SOAP Fault Message
<soap:Envelopexmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:Client</faultcode><faultstring>Failed for some reason</faultstring><detail>The reason might be explained here</detail> </soap:Fault>
</soap:Body></soap:Envelope>
22
WebMethods and SOAP Faults
• WebMethods translate CLR exceptions to SOAP Faults– all exceptions caught by infrastructure– infrastructure fills in SOAP fault details
• Use SoapException to control exact Fault details– specify faultcode, faultstring, actor, and detail
23
Generating Faults with SoapException
// generate detailed SOAP FaultXmlDocument doc = new XmlDocument();XmlElement detail = doc.CreateElement(
SoapException.DetailElementName.Name, SoapException.DetailElementName.Namespace
);doc.AppendChild(detail);XmlElement failed = doc.CreateElement("x", "failedBusinessRules", "http://example.org/rules"
);detail.AppendChild(failed);XmlElement r = doc.CreateElement("rule");r.InnerText = "length must be greater than width";failed.AppendChild(r);r = doc.CreateElement("rule");r.InnerText = "width must be greater than 0";failed.AppendChild(r);throw new SoapException("One or more business rules failed validation", SoapException.ClientFaultCode, "http://example.org/actor", doc);
...24
Resulting SOAP Fault
...<soap:Fault>
<faultcode>soap:Client</faultcode><faultstring>... One or more business rules failed validation...</faultstring><faultactor>http://example.org/actor</faultactor><detail><x:failedBusinessRules xmlns:x="http://example.org/rules"><rule>length must be greater than width</rule><rule>width must be greater than 0</rule>
</x:failedBusinessRules></detail>
</soap:Fault>...
25
SOAP HTTP Binding
• SOAP defines a default binding for messages over HTTP• HTTP request…
– verb is POST– MIME type is text/xml (1.1) or application/soap+xml (1.2)– request URI identifies processor– SOAPAction header expresses intent (optional in SOAP 1.2)
• HTTP response…– MIME type is text/xml (1.1) or application/soap+xml (1.2)– error information conveyed at HTTP and XML levels
26
SOAP Over HTTP Binding
POST /path/foo.ashx HTTP/1.1Content-Type: text/xmlSOAPAction: urn:examples-org:Math#AddContent-Length: nnnn<soap:Envelope… HTTP/1.1 200 OK
Content-Type: text/xmlContent-Length: nnnn<soap:Envelope…HTTP/1.1 500 Internal Server ErrorContent-Type: text/xmlContent-Length: nnnn<soap:Envelope…
request
response
27
SOAP RPC Model
• SOAP is a protocol for message-based communication– SOAP does not mandate particular message flow patterns– SOAP does provide guidelines for most common pattern: RPC
• SOAP models RPC calls as a pair of structures– request structure named for operation– request structure contains elements for in params– response structure contains elements for out params and
return value
28
Mapping RPC Calls
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"xmlns:tns="urn:examples-org:math"targetNamespace="urn:examples-org:math">
<xs:element name="Add" type="tns:Add" /><xs:complexType name="Add" ><xs:sequence><xs:element name="n1" type="xs:int" /><xs:element name="n2" type="xs:int" /></xs:sequence>
</xs:complexType><xs:element name="AddResponse" type="tns:AddResponse" /><xs:complexType name="AddResponse"><xs:sequence><xs:element name="result" type="xs:int"/></xs:sequence>
</xs:complexType></xs:schema>
int Add(int n1, int n2)
29
An RPC Request
<soap:Envelopexmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body>
</soap:Body></soap:Envelope>
<s:Add xmlns:s="urn:examples-org:math"><n1>10</n1><n2>20</n2>
</s:Add>
30
An RPC Response
<soap:Envelopexmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body>
</soap:Body></soap:Envelope>
<s:AddResponsexmlns:s="urn:examples-org:math"><result>30</result>
</s:Add>
31
WebMethod Customization
• WebMethods automatically implement the HTTP binding– SOAPAction based on namespace and method name– message names base on method name (RPC binding)– routes incoming messages to methods using SOAPAction
• Possible to customize using additional attributes– [SoapDocumentService] specifies service-wide details– [SoapDocumentMethod] specifies per-method details– allow you to control routing style, SOAPAction,
request/response message names, etc.
32
Customizing WebMethods
using System.Web;using System.Web.Services;using System.Web.Services.Protocols;using System.Web.Services.Description;[WebService(Namespace="urn:examples-org:math")][SoapDocumentService(RoutingStyle=SoapServiceRoutingStyle.RequestElement)]public class MathService {[WebMethod][SoapDocumentMethod(Action="urn:mymethod:Add"
RequestElementName="AddEm", ResponseElementName="Added")]
public int Add(int n1, int n2) {return n1 + n2;
}}
33
SOAP Encoding Rules
• The original SOAP was written before XSD was completed• It defined a set of encoding rules for inferring a schema
– based on programmatic data types– assumed both sides already had metadata (type library, etc.)– a stopgap measure until XSD was finished– not an effective approach to interoperability
• WS-I's interoperability guidelines disallows SOAP encoding– will be deprecated over time
34
WebMethods and SOAP Encoding
• WebMethods support XSD literal messages by default• Some implementations still use SOAP encoding rules
– May be necessary to handle multi-ref accessors (graphs)– May be necessary to interoperate with certain tools
• Support for SOAP encoding must be explicitly enabled– [SoapRpcService] specifies service-wide encoding– [SoapRpcMethod] specifies per-method encoding– also allow you to control routing style, SOAPAction,
request/response message names, etc.
35
Enabling SOAP encoding rulesusing System.Web;using System.Web.Services;using System.Web.Services.Protocols;using System.Web.Services.Description;[WebService(Name="MathStuff", Namespace="urn:examples-org:math")][SoapRpcService(Routing=SoapServiceRoutingStyle.SoapAction)]public class MathService{[WebMethod][SoapRpcMethod(Action="AddTheseNumbers")]public int Add(int n1, int n2){return n1 + n2;
}}
36
Summary
• SOAP is an XML-based protocol for message communication• SOAP defines a message framing and extensibility format• SOAP defines a message processing model• SOAP defines a standard representation for errors• SOAP defines a binding for sending messages over HTTP• SOAP defines binding for mapping messages to RPC• SOAP defines rules for encoding common data types
37
References
• SOAP 1.1 and 1.2 Specifications– http://www.w3.org/TR/SOAP/– http://www.w3.org/TR/soap12-part1/
• SOAP 1.2 Primer– http://www.w3.org/TR/2002/WD-soap12-part0-20020626/
• The Argument Against SOAP Encoding, MSDN, Ewald– http://msdn.microsoft.com/webservices/understanding/webserv
icebasics/default.aspx?pull=/library/en-us/dnsoap/html/argsoape.asp
• MSDN Web Services Articles– http://msdn.microsoft.com/webservices/understanding/webserv
icebasics/default.aspx
WSDLDescribing Web Services
2
What is WSDL?
• In order to call a SOAP endpoint, you need to know…– target URL– value of SOAPAction header, if required– required input– whether to use literal instances of XSD types or message
formats defined by SOAP encoding rules– SOAP does not specify how you get this information
• WSDL makes it possible to describe such details– WSDL = Web Service Description Language– a machine-consumable format
3
XML 1.0 + Namespaces
The Basic Web Service Architecture
XSDSOAP
WSDLUDDI
Portable type system
Serialized form
Framing, protocol binding
Endpoint description
Registry of endpoints
Wire protocols
Description languages
Discovery mechanisms
4
WSDL Standardization
• WSDL 1.1 is de facto standard with wide industry support– today's Web Service toolkits support WSDL 1.1– lots of issues exist, will shake out over time– W3C Web Service Description Working Group focused on
refining language
5
Structure of a WSDL definition
• WSDL definitions rely on seven major constructs:– a service implements a set of ports– a port is an instance of a binding at a particular URL– a binding adds protocol-specific details to a portType– a portType defines a set of operations– an operation defines an exchange of messages– a message defines a data format in terms of types– a type defines the structure of a portion of a message
6
WSDL Definition Template
• A WSDL definition has a root definitions element – WSDL namespace: http://schemas.xmlsoap.org/wsdl/
<wsdl:definitionsxmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"xmlns:soap-rpc="http://www.w3.org/2001/12/soap-rpc"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsdtns="urn:examples-org:math-types"xmlns:tns="urn:examples-org:math"targetNamespace="urn:examples-org:math">...<!-- definitions go here -->...</wsdl:definitions>
7
Service and Port
<wsdl:service name="MathService"><wsdl:port name="Service1Soap"
binding="tns:MathServiceBinding"><soap:addresslocation="http://localhost/MathService.ashx" />
</wsdl:port></wsdl:service>
• Service element specifies how this service can be accessed– access points defined via port elements– a port maps an address to a particular binding– soap:address specifies a SOAP address
8
Binding: Concrete portType Details
<wsdl:binding name="MathServiceBinding"type="tns:MathServicePortType">
<soap:bindingtransport="http://schemas.xmlsoap.org/soap/http"style="document" />
<wsdl:operation name="Add"><soap:operationsoapAction="http://tempuri.org/Add"style="document" /><wsdl:input><soap:body use="literal" /></wsdl:input><wsdl:output><soap:body use="literal" /></wsdl:output></wsdl:operation>
</wsdl:binding>
9
Style vs. Use
• Style attribute specifies the style of SOAP message– document: no special formatting rules, whatever the
sender/receiver agree upon ahead of time– rpc: message uses SOAP's RPC binding rules
• Use attribute specifies the format of the body – literal: message parts serialized according to literal XML
Schema definitions– encoded: message parts serialized according to some
encoding rules (like those defined in SOAP 1.1)• Document/literal, rpc/encoded most common combinations
– WebMethods support document/literal by default– document/literal is the future
10
portType and Operation
• A portType defines a logical set of operations– roughly equivalent to an interface in COM
• An operation defines a message exchange pattern (MEP)– the order of child input/output elements defines pattern
<wsdl:portType name="MathServicePortType"><wsdl:operation name="Add"><!-- request/response --><wsdl:input message="tns:AddMessage" /><wsdl:output message="tns:AddResponseMessage" />
</wsdl:operation></wsdl:portType>
11
Message Exchange Patterns
• WSDL defines four possible MEPs– request-response– solicit-response– one-way– notification
• WebMethods implement request-response by default– one-way possible using [SoapDocumentMethod(OneWay)]
12
Messages
<wsdl:message name="AddMessage"><wsdl:part name="parameters"
element="xsdtns:Add" /></wsdl:message><wsdl:message name="AddResponseMessage"><wsdl:part name="parameters"
element="xsdtns:AddResponse" /></wsdl:message>
• A message defines a data format in terms of types– supports non-XML formats in message parts– WS-Attachments, MIME, and DIME make this possible
• XML-based message parts defined in terms of XML Schema
13
Types Define Message Part Structure
<wsdl:types><xsd:schematargetNamespace="urn:examples-org:math-types"><xsd:element name="Add" type="xsdtns:Add" /><xsd:complexType name="Add"><xsd:sequence><xsd:element name="n1" type="xsd:int" /><xsd:element name="n2" type="xsd:int" /></xsd:sequence>
</xsd:complexType><xsd:element name="AddResponse" type="xsdtns:AddResponse" /><xsd:complexType name="AddResponse"><xsd:sequence><xsd:element ref="soap-rpc:result" /></xsd:sequence>
</xsd:complexType></xsd:schema></wsdl:types>
14
Deriving SOAP Message Format from WSDL
Namespace of first child of body
Content model defined by
Localname of first child of body
XSD targetNamespace
Defined by schema
XSD global elem. decl.
Document/Literal
Operation name
WSDL targetNamespaceor soap:body
Defined by msg. parts
Rpc/Encoded
• The wire-level message differs greatly depending on style/use– document/literal driven completely by XML Schema definitions– rpc/encoded driven by WSDL definitions (operation name,
message parts, and targetNamespace)
15
WSDL Issues
• WSDL has issues that need to be resolved– language is overly complex– style/use distinction not necessary, possible via schema– no standard way to convey portType/operation information in
SOAP message– needs to differentiate two operations based on same XSD
global element declaration
16
.NET and WSDL
• wsdl.exe tool maps back and forth between WSDL definitions and implementation code– can generate client proxy code using wsdl.exe's default
behavior (VS.NET's "Add Web Reference" command)– can generate server skeleton from using wsdl.exe /server
17
WSDL and Code Generation
<wsdl:definitions ...>...
</wsdl:definitions>
public abstract class MathService : WebService{...
}
service.dll
wsdl.exe /server
public class MathService : SoapHttpClientProtocol{...
}
wsdl.exe
csc.exe.asmx
?wsdl
18
Starting with WSDL on the Server
• You can generate server WebMethod code from WSDL– use wsdl.exe /server
• One approach is to write WSDL first, then generate code– forces you to think about interface (XML contract)– class automatically generated with correct attributes– avoids potential CLR incompatibilities– equivalent to traditional RPC approach (DCOM, Corba)
19
A WSDL-Generated Server
// This source code was auto-generated by wsdl.exeusing System.Web.Services;...[WebService(Name="MathSoap", Namespace="urn:math")]public abstract class Math : WebService {
[WebMethod][SoapDocumentMethod("urn:math/Add",
RequestNamespace="urn:math", ResponseNamespace="urn:math", Use=SoapBindingUse.Literal, ParameterStyle=SoapParameterStyle.Wrapped)]
public abstract Double Add(Double x, Double y);}
20
Summary
• WSDL is a language for describing Web services• WSDL is a machine-readable XML vocabulary• WSDL provides all information required to invoke service• WSDL makes it possible to generate proxy/stubs
21
References
• WSDL 1.1 Specification– http://www.w3.org/TR/wsdl
• WSDL 1.2 Specification– http://www.w3.org/TR/wsdl12/
• WSDL Explained, MSDN, Tapang– http://msdn.microsoft.com/webservices/understanding/default.a
spx?pull=/library/en-us/dnwebsrv/html/wsdlexplained.asp• Understanding Web Services, Addison Wesley, Newcomer• Real World XML Web Services, Addison Wesley, Shohoud
XML SerializationMapping XML to Objects
2
XML serialization in .NET
• The .NET Framework provides support for mapping between XML data and CLR objects– Ideally, isomorphism would be possible, but in reality it's not– One type system always takes precedence
• As a result, .NET provides two approaches…– System.Runtime.Serialization– System.Xml.Serialization
3
Mapping Instances and Types
Class
Object
Schema Type
XML Instance
4
A CLR-centric Mapping
• The System.Runtime.Serialization plumbing favors CLR types over XML types
class class
class class
complexType
complexType
??? complexType
CLR XSD
5
System.Runtime.Serialization Model
• Serializes graphs of serializable CLR objects• Handles complexities of modern object models
– Public and private data– Duplicate pointers– Polymorphism– Collections
6
Which Types Are Serializable?
• By default, types are not serializable• Types annotated with [Serializable]
– Runtime does all the work– Serializes public and private data members
• Objects that implement ISerializable– You do all the work yourself
// a serializable type[Serializable]public class Person {public string name;public string age;
}
7
Using System.Runtime.Serialization
• Objects can be serialized to any System.Stream– Formatter classes define the actual layout in the stream
• IFormatter– Runtime provides standard formatter for SOAP
• SoapFormatter– A binary formatter is also provided and you can build your own
8
Serializing to a Stream
using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Soap;
static void Main(string[] args){Person p = new Person();p.name = "Tim";p.age = 32;FileStream fs = new FileStream(args[0],
FileMode.Create);SoapFormatter sf = new SoapFormatter();sf.Serialize(fs, p);fs.Close();
}
9
Deserializing from a Stream
using System;using System.IO;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Soap;
static void Main(string[] args){FileStream fs = new FileStream(args[0],
FileMode.Open);SoapFormatter sf = new SoapFormatter();Person p = (Person) sf.Deserialize(fs);Console.WriteLine("{0} is {1} years old",
p.name, p.age);fs.Close();
}
10
Serialization Format
<SOAP-ENV:Envelopexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0"SOAP-ENV:encodingStyle=
"http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body>
<a1:Person id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/SerializeViaRuntime/SerializeViaRuntime%2C%20Version%3D1.0.756.28213%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
<name id="ref-3">Tim</name><age>32</age>
</a1:Person></SOAP-ENV:Body>
</SOAP-ENV:Envelope>
11
System.Runtime.Serialization Issues
• System.Runtime.Serialization maps instances but not types to XML– Assumes deserializer is .NET-based and has access to
original (or equivalent) assembly• Why use XML at all in this case?
– A big part of XML's appeal is interoperability across language, platform and vendor platforms
– Enter System.Xml.Serialization
12
???
An XSD-centric Mapping
• The System.Xml.Serialization plumbing favors XSD types over CLR types
class class
class
complexType
complexType
complexType
complexType
CLR XSD
13
System.Xml.Serialization Model
• System.Xml.Serialization serializes trees of CLR objects– Ensures that objects map to XML and types map to XSD– Guarantees interoperability with other platforms– Does not handle all complexities of modern object models…
14
Which Types are Serializable?
• By default, types are serializable• However, there are limitations…
– Public data only– No duplicate pointers– Limited support for polymorphism– Limited support for collections
// a serializable typepublic class Person {public string name;public string age;
}
15
Using System.Xml.Serialization
• XmlSerializer is the focal point of library– XmlSerializer objects bound to specific CLR types– Serialize method writes an object to an XmlWriter– Deserialize method reads an object from an XmlReader– Both use underlying XmlSerializationReader/Writer types– Code generated into temporary assembly for speed
16
<Person><name>Tim</name><age>32</age>
</Person>
How XmlSerializer Works
Xml-Serializer(per-type)
Temp.Assembly
Reader
Xml-Serialization-
Reader
Writer
Xml-Serialization-
Writer
Person
XmlW
riterXmlR
eade
r
Des
eria
lize
Serialize
17
Serializing to a Stream
using System.IO;using System.Xml;using System.Xml.Serialization;
static void Main(string[] args){Person p = new Person();p.name = "Tim";p.age = 32;FileStream fs = new FileStream(args[0],
FileMode.Create);XmlSerializer xs = new XmlSerializer(p.GetType());xs.Serialize(fs, p);fs.Close();
}
18
Deserializing from a Stream
using System.IO;using System.Xml;using System.Xml.Serialization;
static void Main(string[] args){FileStream fs = new FileStream(args[0],
FileMode.Open);XmlSerializer xs = new XmlSerializer(typeof(Person));Person p = (Person) xs.Deserialize(fs);Console.WriteLine("{0} is {1} years old",
p.name, p.age);fs.Close();
}
19
Serialization Format
<?xml version="1.0"?><Personxmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><name>Tim</name><age>32</age>
</Person>
20
XSD Support
• The major advantage System.Xml.Serialization offers over System.Runtime.Serialization is support for XSD– SchemaExporter class translates CLR types to XSD types– CodeExporter class translates XSD types to CLR types– Both classes' functionality wrapped by XSD.EXE
21
Using XSD.EXE
<xs:schema ...><xs:complexType name="Person">...
</xs:complexType>...
</xs:schema>
public class Person{...
}person.dllcsc.exe
xsd.exexsd.exe /c
22
XSD Format
<?xml version="1.0" encoding="utf-8"?><xs:schema elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:element name="Person" nillable="true" type="Person" /><xs:complexType name="Person"><xs:sequence><xs:element name="name" type="xs:string"
minOccurs="0" maxOccurs="1" /><xs:element name="age" type="xs:int"
minOccurs="1" maxOccurs="1" /></xs:sequence>
</xs:complexType></xs:schema>
23
Basic Type Mapping Attributes
• XmlSerializer behavior can be tailored by applying attributes on a per-type basis– Default behavior assumes same-name, no namespace
<xsd:complexType/> per class/struct– [XmlType] controls <xsd:complexType/> declaration– [XmlRoot] controls global <xsd:element/> declaration– [XmlElement] controls local <xsd:element/> declaration
24
Dealing with Invalid Data
• XmlSerializer fires events when it encounters unexpected content– UnknownNode, UnknownAttribute, UnknownElement– XmlSerializer does NOT fire events when it does NOT
encounter expected content– Uses default value instead
• Only solution to latter problem is schema validation– ValidationEventHandler event reports problems, but doesn't
automatically stop processing
25
Handling Arrays
• Fields/properties that are arrays need special treatment– Always serialized as parent/child elements combination– [XmlArray] controls of "container" element– [XmlArrayItem] controls "item" elements
[ XmlRoot(Namespace="urn:examples-org") ]public class Crowd {
[XmlArray(Form=XmlSchemaForm.Unqualified)][XmlArrayItem(Form=XmlSchemaForm.Unqualified)]public Person[] people;
}
26
XSD Array Types
<xs:complexType name="ArrayOfPerson"><xs:sequence>
<xs:element name="Person" type="tns:Person"form="unqualified" nillable="true"minOccurs="0" maxOccurs="unbounded" />
</xs:sequence></xs:complexType><xs:complexType name="Crowd">
<xs:sequence><xs:element name="people" type="tns:ArrayOfPerson"
form="unqualified"minOccurs="0" maxOccurs="1" />
</xs:sequence></xs:complexType>
27
Handling Polymorphic Types
• [XmlInclude] used to mark non-sealed types with list of derived types that might be used in its place– Required for XSD generation– Base type must be updated when new subtypes are added
[XmlRoot(Namespace="urn:examples-org")][XmlInclude(typeof(PetOwner))]public class Person { ... }[XmlRoot(Namespace="urn:examples-org")]public class PetOwner : Person {
public Animal pet;}
28
Polymorphic XSD Types
<xs:complexType name="PetOwner"><xs:complexContent mixed="false">
<xs:extension base="tns:Person"><xs:sequence>
<xs:element name="pet" type="xs:Animal"form="unqualified"minOccurs="0" maxOccurs="1" />
</xs:sequence></xs:extension>
</xs:complexContent></xs:complexType>
29
Further Customizing Data Format
• There are attributes for controlling most aspects of XSD and XML generation– XmlIgnore: unmapped data– XmlElement: how data is mapped to an element– XmlAttribute: how data is mapped to an attribute– XmlEnum: how enum values are mapped– XmlChoiceId: specifies a discriminator for a set of mutually
exclusive elements– XmlAnyElement, XmlAnyAttribute: catches extra stuff
30
XmlSerializer and WebMethods
• WebMethod parameters marshaled using XmlSerializer– Mandates use of XSD-friendly data types– Provides limited support for complex CLR types
• WebMethod plumbing ignores unrecognized content– Doesn't handle XmlSerializer events– Doesn't perform schema validation
• Can customize WebMethod parameter marshaling using XmlSerializer attributes
• [XmlElement], et. al.
31
Customizing WebMethod Parameters
using System.Web;using System.Web.Services;using System.Xml.Serialization;public class MathService{[WebMethod][return: XmlElement("sum")]public int Add([XmlElement("x")] int n1,[XmlElement("y")] int n2
){return n1 + n2;
}}
32
Where are we?
• .NET provides two different object/XML serialization engines• System.Runtime.Serialization is CLR centric• System.Xml.Serialization is XML centric• Both allow some degree of control over generated XML• XML-centric view more to interoperate with other systems• A strongly-typed DOM presents an interesting alternative