Title: Advanced Web Services Using Microsoft ASP.NET Malini S. Puttaiah
1Advanced Web Services Using Microsoft ASP.NET
Malini S. Puttaiah Ranjit R. Sawant
Developer Support Engineers Microsoft
Corporation
2Topics
- Web services architecture
- Simple Web service
- Managing state in Web service
- SOAP headers
- SOAP extensions
- Formatting SOAP messages
- Security in Web services
- Calling Web services asynchronously
- Exceptions and error handling in Web services
- Transaction support
- XML Web services discovery UDDI, Disco
3Web Services Architecture
- XML Web services protocols and standards
- XML Web services infrastructure
- XML Web services message flow
4XML Web Services Protocols and Standards
- XML
- Simple Object Access Protocol (SOAP)
- Web Services Description Language (WSDL)
- XSD
- application/x-www-form-urlencoded
5XML Web Services Infrastructure
Directory
1) Client attempts to locate a Web service 2)
URL to discovery document is returned
3) Client requests discovery document 4)
Discovery document is returned
Discovery
Description
5) Client requests service description 6)
Description document is returned
Wire Format
7) Client requests the web service 8) Web
service returns result response
6XML Web Services Message Flow
SOAP Request
SOAP MESSAGE
SOAP MESSAGE
Phase II DeSerialize
Phase I Serialize
Network
Web Service
Client Proxy
Phase III Serialize
Phase IV DeSerialize
SOAP MESSAGE
SOAP MESSAGE
SOAP Response
7Simple XML Webservice Declaration
- Class implementing the Web service can optionally
derive from System.Web.Services.WebService to
gain access to common ASP.NET objects like
Application, Session, User, and Context - Simple Webservice declaration
- WebService(Description"MySimpleService does
simple Math operations",Namespace"http//myadvanc
edwebserviceURI/") - public class MySimpleService WebService
-
- WebMethod(Description"Adds 2 numbers")
- public int Add(int num1, int num2)
-
- return num1num2
-
-
- ........
-
8WebMethod Attributes Important Properties
- BufferResponse
- CacheDuration
- Description
- EnableSession
- MessageName
- TransactionOption
9Managing State in XML Web Services
- State data can be saved by using the ASP.NET
Session and Application objects - Data stored in the Session object is available
only when the EnableSession property of the
WebMethod attribute is set to TRUE - Storing state data in Application object
- Applicationstrapplication" This string can
be accessed by any application - Storing state data in Session object
- Sessionstrsession" This string can be
accessed in this session only
10Session State Management
- Session state for each client is identified by
the session ID, which is stored as a cookie on
the client - Session ID cookies are sent to the client when a
call is made to the method that has the
EnableSession property of the WebMethod
attribute set to TRUE - Every subsequent call from the client to the
service has this cookie accompanying it
11Session State Management (2)
- Client should be cookie enabled
- localhost.ManageState objmanagestate new
localhost.ManageState() - System.Net.CookieContainer cc new
System.Net.CookieContainer() - objmanagestate.CookieContainer cc
- objmanagestate.SomemethodCall()
- Example
- //server
- WebMethod(Description"SetSomeProperty",EnableSes
siontrue) - public void SetSomeProperty(string str)
-
- Session"myProperty" str
-
- WebMethod(Description"GetSomeProperty",EnableSe
ssiontrue) - public string GetSomeProperty()
-
- return (string)Session"myProperty"
-
- //client
12SOAP Messages for Session State Enabled Method
- SetSomeProperty REQUEST
- POST /SimpleMathservice/Math.asmx HTTP/1.1
- User-Agent Mozilla/4.0 (compatible MSIE 6.0 MS
Web Services Client Protocol 1.0.3705.0) - Content-Type text/xml charsetutf-8
- SOAPAction "http//myadvancedwebserviceURI/SetSom
eProperty" - Content-Length 338
- Expect 100-continue
- Connection Keep-Alive
- Host localhost
- lt?xml version"1.0" encoding"utf-8"?gt
- ltsoapEnvelope xmlnssoap"http//schemas.xmlsoap.
org/soap/envelope/" - xmlnsxsi"http//www.w3.org/2001/XMLSchema-insta
nce" - xmlnsxsd"http//www.w3.org/2001/XMLSchema"gt
- ltsoapBodygt
- ltSetSomeProperty xmlns"http//myadvancedwebserv
iceURI/"gt - ltstrgtSomePropertyValuesentfromclientlt/strgt
- lt/SetSomePropertygt
- lt/soapBodygt
13SOAP Messages for Session State Enabled Method (2)
- SetSomeProperty RESPONSE
- HTTP/1.1 100 Continue
- Server Microsoft-IIS/5.0
- Date Sat, 09 Mar 2002 173202 GMT
- HTTP/1.1 200 OK
- Server Microsoft-IIS/5.0
- Date Sat, 09 Mar 2002 173202 GMT
- Set-Cookie ASP.NET_SessionIduuvatj55k2bbpsig2fho
icaw path/ - Cache-Control private, max-age0
- Content-Type text/xml charsetutf-8
- Content-Length 313
- lt?xml version"1.0" encoding"utf-8"?gt
- ltsoapEnvelope xmlnssoap"http//schemas.xmlsoap.
org/soap/envelope/" - xmlnsxsi"http//www.w3.org/2001/XMLSchema-instan
ce" - xmlnsxsd"http//www.w3.org/2001/XMLSchema"gt
- ltsoapBodygt
- ltSetSomePropertyResponse xmlns"http//myadvancedw
ebserviceURI/" /gt - lt/soapBodygt
14SOAP Headers
- Represents out-of-bounds data between the
communicating parties - The Header can be can be sent without the
sender/receiver having prior knowledge - The Header element is encoded as the first
immediate child element of the SOAP Envelope XML
element - The SOAP mustUnderstand attribute and SOAP Actor
attribute may be used with the Header element to
indicate how to process the Header entry and by
whom
15Sample SOAP Header
- lt?xml version"1.0" encoding"utf-8"?gt
- ltsoapEnvelope
- xmlnssoap"http//schemas.xmlsoap.org/soap/envelo
pe/ - xmlnsxsi"http//www.w3.org/2001/XMLSchema-instan
ce - xmlnsxsd"http//www.w3.org/2001/XMLSchema"gt
- ltsoapHeadergt
- ltMyauthenticationHeader xmlns"http//tempuri.or
g/"gt ltUsernamegtadminlt/Usernamegt
ltPasswordgtpasswordlt/Passwordgt - lt/MyauthenticationHeadergt
- lt/soapHeadergt
- ltsoapBodygt
- ltMyWebMethod xmlns"http//tempuri.org/"/gt
- lt/soapBodygt
- lt/soapEnvelopegt
16SOAP Header Implementation Server
- //Define a SOAP header by deriving from the
SoapHeader - public class MyauthenticationHeader SoapHeader
-
- public string Username
- public string Password
-
- //Web service
- public class Service1 System.Web.Services.We
bService -
- public MyauthenticationHeader objAuthHeader
- . . . .
- SoapHeader("objAuthHeader")
- WebMethod
- public string MyWebMethod()
- //access the Header values here
- if( objAuthHeader.UserName
admin). . . -
-
17SOAP Header Implementation Client
- void CallWebServiceMethod()
-
- //instantiate the Header object in the client
- localhost.MyauthenticationHeader objauthheader
- new localhost.Myauthenticatio
nHeader() - //Populate the class members
- objauthheader.Username "admin"
- objauthheader.Password "password"
- //instantiate the service object
- localhost.Service1 objservice new
localhost.Service1() - //Equate the proxy class member to the header
object - objservice.MyauthenticationHeaderValue
objauthheader - //Call the method marked with SOAPHeader
attribute on - //the webservice
- objservice.MyWebMethod()
18SoapHeader Attributes Required
- Setting the Required property of the SoapHeader
attribute to FALSE makes the SOAP header optional - //Server
- SoapHeader("objTransactionHeader",Requiredfalse)
- WebMethod
- public string MyWebMethod2()
- if(objTransactionHeader ! null)
- objTransactionHeader.TransactionID 12345678
-
- return "Inside MyWebMethod2"
-
- //Client
- localhost.Service1 objservice new
localhost.Service1() - //you do not have to initialize the Header before
calling - // the webmethod
- objservice.MyWebMethod2()
19SoapHeader Attributes SoapHeaderDirection
- SoapHeaderDirection represents the SOAP Actor
attribute - In, Out, or InOut
- //Server
- WebMethod
- SoapHeader("myOutHeader,DirectionSoapHeaderDire
ction.Out) - public void MyOutHeaderMethod()
-
- // Return the client's authenticated name.
myOutHeader.Username someusername -
- //Client
- localhost.Service1 objservice new
localhost.Service1() - objservice.MyOutHeaderMethod()
- //Displays someusername
- MessageBox.Show( objservice.myOutHeaderValue.UserN
ame)
20Handling Unknown SOAP Headers
- Mustunderstand and Didunderstand properties
- Client calling the method
- localhost.someheader1 objsomeheader
- new localhost.someheader1
() - objservice.Mysomeheader1Value objsomeheader
- objservice.Mysomeheader1Value.MustUnderstand
true - objservice.MyWebMethod3()
- Client define and instantiate header in proxy
class - public class someheader1 SoapHeader
- public string strname
-
- public someheader1 Mysomeheader1Value
- Client modify method attributes in proxy class
- System.Web.Services.Protocols.SoapHeaderAttribute
("Mysomeheader1Value",Requiredfalse) - public string MyWebMethod3().
21Handling Unknown SOAP Headers (2)
- Server defining unknown headers collection
- public SoapUnknownHeader unknownHeaders
- Server method implementation
- SoapHeader("unknownHeaders", Required false)
- WebMethod
- public string MyWebMethod3()
- string str ""
- foreach (SoapUnknownHeader header in
unknownHeaders) - if (header.Element.Name "someheader1")
- header.DidUnderstand true
- str "understood the header"
-
- else
- header.DidUnderstand false
- str "Did not understand the header"
-
22SOAP Extensions
- SOAP extensions allow developers to augment the
functionality of an XML Web service by altering
the SOAP messages sent to and from an XML Web
service or an XML Web service client - A SOAP extension can be injected into the message
infrastructure to inspect or modify the SOAP
messages before and after the serialize and
deserialize phases - Phases defined by SoapMessageStage enumeration
AfterSerialize , BeforeDeserialize
23Implementing SOAP Extensions
- Derive a class from SoapExtension
- Save a reference to the stream representing
future SOAP messages - Initialize SOAP extensionspecific data
- Process the SOAP messages during the pertinent
SoapMessageStage or stages - Configure the SOAP extension to run with specific
XML Web service methods
24SoapExtension Class
- The class deriving from SoapExtension is the
class that performs the functionality of the SOAP
extension - Members
- ChainStream When overridden in a derived class,
allows a SOAP extension access to the memory
buffer containing the SOAP request or response. - GetInitializer Overloaded. When overridden in a
derived class, allows a SOAP extension to
initialize data specific to an XML Web service
method at a one time performance cost.
25SoapExtension Class (2)
- Members (cont)
- Initialize When overridden in a derived class,
allows a SOAP extension to initialize itself
using the data cached in the GetInitializer
method. - ProcessMessage When overridden in a derived
class, allows a SOAP extension to receive a
SoapMessage to process at each SoapMessageStage.
26SoapExtension Implementation
- public class TraceExtension SoapExtension
-
- Stream oldStream Stream newStream string
filename - .
- public override void ProcessMessage(SoapMessage
message) switch (message.Stage) - case SoapMessageStage.BeforeSerialize break
- case SoapMessageStage.AfterSerialize
- WriteOutput( message )
- break
- case SoapMessageStage.BeforeDeserialize
- WriteInput( message )
- break
- case SoapMessageStage.AfterDeserialize
break - default throw new Exception("invalid
stage") -
- public override Stream ChainStream( Stream stream
) oldStream stream newStream new
MemoryStream() return newStream -
-
27Extensions Sequence of Operations for Request
- REQUEST client side
- A client invokes a method on the proxy class.
- A new instance of the SOAP extension is created
on the client. - GetInitializer method is invoked on the SOAP
extension running on the client. - The Initialize method is invoked.
- The ChainStream method is invoked.
28Extensions Sequence of Operations for Request (2)
- REQUEST client side (cont)
- The ProcessMessage method is invoked with the
SoapMessageStage set to BeforeSerialize. - ASP.NET on the client computer serializes the
arguments of the XML Web service method into XML. - The ProcessMessage method is invoked with the
SoapMessageStage set to AfterSerialize. - ASP.NET on the client computer sends the SOAP
message over the network to the Web server
hosting the XML Web service.
29Extensions Sequence of Operations for Request (3)
- REQUEST server side
- ASP.NET on the Web server receives the SOAP
message. - A new instance of the SOAP extension is created
on the Web server. - The GetInitializer method is invoked on the SOAP
extension running on the server. - The Initialize method is invoked.
- The ChainStream method is invoked.
30Extensions Sequence of Operations for Request (4)
- The ProcessMessage method is invoked with the
SoapMessageStage set to BeforeDeserialize. - ASP.NET deserializes the arguments within the
XML. - The ProcessMessage method is invoked with the
SoapMessageStage set to AfterDeserialize. - ASP.NET creates a new instance of the class
implementing the XML Web service and invokes the
XML Web service method, passing in the
deserialized arguments. This object resides on
the same computer as the Web server. - The XML Web service method executes its code,
eventually setting the return value and any out
parameters.
31Extensions Sequence of Operations for Response
- Server side
- The XML Web service method executes its code,
eventually setting the return value and any out
parameters. - The ProcessMessage method is invoked with the
SoapMessageStage set to BeforeSerialize. - ASP.NET on the Web server serializes the return
value and out parameters into XML. - The ProcessMessage method is invoked with the
SoapMessageStage set to AfterSerialize. - ASP.NET sends the SOAP response message over the
network back to the XML Web service client.
32Extensions Sequence of Operations for Response
(2)
- Client side
- ASP.NET on the client computer receives the SOAP
message. - The ProcessMessage method is invoked with the
SoapMessageStage set to BeforeDeserialize. - ASP.NET deserializes the XML into the return
value and any out parameters. - The ProcessMessage method is invoked with the
SoapMessageStage set to AfterDeserialize. - ASP.NET passes the return value and any out
parameters to the instance of the proxy class. - The client receives the return value and any out
parameters.
33Configuring Soap Extensions
- Config file Applies to all methods in the
service - ltwebServicesgt
- ltsoapExtensionTypesgt
- ltadd type"SoapTraceExtension.TraceExtension,
SoapTraceExtension" /gt - lt/soapExtensionTypesgt
- lt/webServicesgt
- Use a custom attribute
- Derive a class from SoapExtensionAttribute
- public class TraceExtensionAttribute
- SoapExtensionAttribute
- Apply the attribute to Web method
- WebMethod
- TraceExtensionAttribute
- public string HelloWorld() . . .
34Formatting SOAP Messages
- SOAP specification does not strictly outline the
formatting of the XML message. - SOAP specification defines message formatting in
two sections - Section 5 How are the parameters within the SOAP
body encoded? - Parameters are either ENCODED or LITERAL
- Section 7 How is the entire SOAP BODY formatted?
- SOAP BODY can be either in RPC or DOCUMENT style
- ASP.NET provides an attribute-based mechanism for
controlling the format of the XML in the SOAP
message. It can be applied to the entire message
or at the individual element in the message.
35Formatting Styles Supported by ASP.NET Web
Services
36Document Literal
- Method definition
- SoapDocumentMethod( UseSoapBindingUse.Literal)
- public Stockinfo GetStockInfoDocumentLiteral(
- string companyname,string
stockExchangename) - Response message
- lt?xml version"1.0" encoding"utf-8"?gt
- ltsoapEnvelope xmlnssoap"http//schemas.xmlsoap.
org/soap/envelope/" - xmlnsxsi"http//www.w3.org/2001/XMLSchema-in
stance" - xmlnsxsd"http//www.w3.org/2001/XMLSchema"gt
- ltsoapBodygt
- ltGetStockInfoDocumentLiteralResponse
- xmlns"http//tempuri.org
/"gt - ltGetStockInfoDocumentLiteralResultgt
- ltstocknamegtABCD123lt/stocknamegt
- ltlasttradedpricegt23.5lt/lasttradedpri
cegt - ltvolumegt3454353lt/volumegt
37Document Encoded
- Method definition
- SoapDocumentMethod( UseSoapBindingUse.Encoded)
- public Stockinfo GetStockInfoDocumentEncoded (
- string companyname,string
stockExchangename) - Response message
- lt?xml version"1.0" encoding"utf-8"?gt
- ltsoap Envelope xmlnssoap"http//schemas.xmlsoap.
org/soap/envelope" xmlnssoapenc"http//sc
hemas.xmlsoap.org/soap/encoding/"
xmlnstns"http//tempuri.org/"
xmlnstypes"http//tempuri.org/encodedTypes"
xmlnsxsi"http//www.w3.org/2001/XMLSc
hema-instance" xmlnsxsd"http//ww
w.w3.org/2001/XMLSchema"gt - ltsoapBody soapencodingStyle"http//schemas.xmls
oap.org/soap/encoding/"gt - lttypesGetStockInfoDocumentEncodedResponsegt
- ltGetStockInfoDocumentEncodedResult
href"id1" /gt - lt/typesGetStockInfoDocumentEncodedResponsegt
- lttypesStockinfo id"id1" xsitype"typesStoc
kinfo"gt - ltstockname xsitype"xsdstring"gtABCD123lt/sto
cknamegt - ltlasttradedprice xsitype"xsddouble"gt23.5lt/
lasttradedpricegt - ltvolume xsitype"xsdint"gt3454353lt/volumegt
- lt/typesStockinfogt
38RPC Encoded
- Method definition
- SoapRpcMethod()
- public Stockinfo GetStockInfoRPCEncoded (
- string companyname,string
stockExchangename) - Response message
- lt?xml version"1.0" encoding"utf-8"?gt
- ltsoapEnvelope xmlnssoap"http//schemas.xmlsoap.
org/soap/envelope" - xmlnssoapenc"http//schemas.xmlsoap.org/soa
p/encoding/" - xmlnstns"http//tempuri.org/"
- xmlnstypes"http//tempuri.org/encodedTypes"
- xmlnsxsi"http//www.w3.org/2001/XMLSchema-i
nstance" - xmlnsxsd"http//www.w3.org/2001/XMLSchema"gt
- ltsoapBody soapencodingStyle"http//schemas.xm
lsoap.org/soap/encoding/"gt - lttnsGetStockInfoRPCEncodedResponsegt
- ltGetStockInfoRPCEncodedResult href"id1" /gt
- lt/tnsGetStockInfoRPCEncodedResponsegt
39Parameter Wrapping/Unwrapping
- Wrapping is the default for document-literal
- UnWrapping
- Method definition
- SoapDocumentMethod(UseSoapBindingUse.Literal,
- ParameterStyleSoapParameterStyle.Bare )
- public Stockinfo GetStockInfoBareParam(
- string companyname,string
stockExchangename). . - SOAP message
- lt?xml version"1.0" encoding"utf-8"?gt
- ltsoapEnvelope
- xmlnssoap"http//schemas.xmlsoap.org/soap/envelo
pe/" - xmlnsxsi "http//www.w3.org/2001/XMLSchema-insta
nce - xmlnsxsd"http//www.w3.org/2001/XMLSchema"gt
- ltsoapBodygt
- ltcompanyname xmlns"http//tempuri.org/"gt
- ABCD123
- lt/companynamegt
- ltstockExchangename xmlns"http//tempuri.org/"gt
40Security in ASP.NET Web Services
- Authentication
- Windows-based
- Basic
- Digest
- Windows integrated-NTLM or Kerberos
- Client certificates
- Custom SOAP headers
- Authorization using ASP.NET configuration
- Impersonation using ASP.NET configuration
- Data encryption
- SSL
- Custom SOAP extension
41Authentication Windows-Based
- Basic authentication
- localhost.Service1 objlocalhost new
localhost.Service1() - // Create a new instance of CredentialCache.
- CredentialCache credentialCache new
CredentialCache() - //Create a new instance of NetworkCredential
using the client - NetworkCredential credentials
new NetworkCredential("Administrator","Password1")
- // Add the NetworkCredential to the
CredentialCache. - credentialCache.Add(new Uri(objlocalhost.Url),"Bas
ic", -
credentials) - // Add the CredentialCache to the proxy class
credentials. - objlocalhost.Credentials credentialCache
- // Call the method on the proxy class.
- objlocalhost.HelloWorld()
42Authentication Windows-Based (2)
- NTLM authentication
- localhost.Service1 objlocalhost new
localhost.Service1() - // Create a new instance of CredentialCache.
- CredentialCache credentialCache new
CredentialCache() - //Create a new instance of NetworkCredential
using the client - NetworkCredential credentials
new NetworkCredential("Administrator","Password1")
- // Add the NetworkCredential to the
CredentialCache. - credentialCache.Add(new Uri(objlocalhost.Url),NTL
M", -
credentials) - // Add the CredentialCache to the proxy class
credentials. - objlocalhost.Credentials credentialCache
- // Call the method on the proxy class.
- objlocalhost.HelloWorld()
43Authentication Client Certificates
- localhost.Service1 objlocalhost new
localhost.Service1() - // Create a new instance of CredentialCache.
- CredentialCache credentialCache new
CredentialCache() - // Create a new instance of NetworkCredential
using the client - NetworkCredential credentials
new NetworkCredential("Administrator","Password1")
- // Add the NetworkCredential to the
CredentialCache. - credentialCache.Add(new Uri(objlocalhost.Url),
"Basic", -
credentials) - // Add the CredentialCache to the proxy class
credentials. - objlocalhost.Credentials credentialCache
- // Load the client certificate from a file.
- X509Certificate x509 X509Certificate.CreateFromC
ertFile("C\\clicert.cer") - // Add the client certificate to the
ClientCertificates property - // of the proxy class.
- objlocalhost.ClientCertificates.Add(x509)
44Authentication Custom SOAP Headers
- Server implementation
- //Define a SOAP header by deriving from the
SoapHeader - public class MyauthenticationHeader SoapHeader
-
- public string Username
- public string Password
-
- //Web service
- public class Service1 System.Web.Services.We
bService -
- public MyauthenticationHeader objAuthHeader
- . . . .
- SoapHeader("objAuthHeader")
- WebMethod
- public string MyWebMethod()
- //access the Header values here
- if( objAuthHeader.UserName
admin). . . -
-
45Authentication Custom SOAP Headers (2)
- Client implementation
- //instantiate the Header object in the client
- localhost.MyauthenticationHeader objauthheader
- new localhost.Myauthenticatio
nHeader() - //Populate the class members
- objauthheader.Username "admin"
- objauthheader.Password "password"
- //instantiate the service object
- localhost.Service1 objservice new
localhost.Service1() - //Equate the proxy class member to the header
object - objservice.MyauthenticationHeaderValue
objauthheader - //Call the method marked with SOAPHeader
attribute on - //the webservice
- objservice.MyWebMethod()
46Authorization
- ASP.NET authorization types
- File authorization NTFS-based on ACL
- URL authorization maps users and roles to
pieces of the URI namespace - Configure authorization in ASP.NET configuration
files - ltauthorizationgt ltallow verb"GET" users"" /gt
- ltallow verb"POST" users"Administrator" /gt
- ltallow verb"POST" users"Kim" /gt
- ltdeny verb"POST" users"" /gt
- lt/authorizationgt
47Impersonation
- Configure Web services impersonation in the
ASP.NET configuration files - ltidentity impersonate"true" userNameuser1
password"pass"/gt
48Encryption
- Secure sockets layer
- Client proxys URL property
- https//localhost/SecureWebservice/Service1.asmx
- Custom encryption
- Use SOAP extension
- Encrypt in AfterSerialize
- Decrypt in BeforeDeSerialize
49Invoking Web Services Asynchronously
- Synchronous versus asynchronous invocations
- Asynchronous design patterns in .NET
- Invoking Web services asynchronously
50Synchronous Calls
- Synchronous calls block a process until operation
is complete
Client
Server
1
Calling Code
Object being called
Client calls object
and call is blocked
Method completes
3
2
Next line of execution
51Asynchronous Calls
- An asynchronous operation will not block the
calling thread - The calling application must then discover
completion of the call by polling, by software
interrupt, or by waiting explicitly for
completion later
Client
Server
1
Calling Code
Object being called
Client calls object
Call returns
2
Next line of execution
3
Sink Object
Method completes
52Asynchronous Programming in .NET
- Client code decides if a call has to be
asynchronous - Called object does not need to do additional
programming to support asynchronous behavior - Called object can also choose to explicitly
support asynchronous behavior if it wants to
implement more efficiently than the general
architecture
53Ways of Calling Asynchronously
- Use callbacks
- Supply the callback delegate when beginning
asynchronous calls - Wait handle
- Wait on IAsyncResult WaitOne, WaitAll, WaitAny
- Poll completed
- Poll the returned IAsyncResult.IsCompleted
property for completion of calls
54Closer Look at Proxy Class
- public int Add(int x, int y, int DelaySeconds)
- object results this.Invoke("Add",
- new object x, y, DelaySeconds)
- return ((int)(results0))
-
- public System.IAsyncResult BeginAdd(int x, int y,
int DelaySeconds, System.AsyncCallback callback,
object asyncState) - return this.BeginInvoke("Add", new
object x, y, - DelaySeconds, callback,
asyncState) -
-
- public int EndAdd(System.IAsyncResult
asyncResult) - object results this.EndInvoke(asyncRes
ult) -
- return ((int)(results0))
-
55Sample Web Service
- WebMethod
- public double Add(int x , int y, int
DelaySeconds) -
- //Create a delay to simulate a long-running
process - if (DelaySeconds gt 0)
-
- System.Threading.Thread.Sleep(DelaySeconds
1000) -
- return x y
56Synchronous Call Client
- localhost.MathServer obj new
localhost.MathServer() - double result obj.Add(firstNumber,
- secNumber, DelaySecs)
-
- Console.WriteLine("Addition result is "
result.ToString() )
57Asynchronous Call Using Callback
- localhost.MathServer obj new
localhost.MathServer() - AsyncCallback cb new AsyncCallback(MyCallBack)
- IAsyncResult ar obj.BeginAdd(firstNumber,
- secNumber, delay, cb, null)
- MessageBox.Show ("Async call invoked
successfully, - "Async call")
-
- public void MyCallBack(System.IAsyncResult ar)
-
- localhost.MathServer obj1 (localhost.MathServe
r)ar.AsyncState - double result obj1.EndAdd(ar)
58Asynchronous Call Using Polling
-
- localhost.MathServer obj new
localhost.MathServer() -
- IAsyncResult ar obj.BeginAdd
(firstNumber, secNumber, delaySecs, null,
null) - Console.WriteLine("I am not blocked")
- if (ar.IsCompleted true)
-
- double result obj.EndAdd(ar)
-
- Console.WriteLine("Addition result is "
result.ToString() )
59Exception Handling
- Exception is repackaged as a SoapException and is
returned to the Web service client via the SOAP
response - Exceptions are sent back to the client in the
form of a SOAP ltFaultgt XML element within a SOAP
message that specifies when an error occurred - The three predefined subelements are ltfaultCodegt,
ltfaultStringgt, and ltdetailgt, and you can define
your own subelements that belong to an
application-specific namespace
60SoapException
- SoapException has eight overloaded constructors,
two of which take in an array of XML nodes. - For example
-
- public SoapException( string message,
- XmlQualifiedName code, string actor,
- XmlNode detail )
61Throw a SoapException with Detailed Error
Information
- try
-
- //do something
-
- catch
-
- XmlDocument doc new XmlDocument()
- System.Xml.XmlNode detail
doc.CreateNode(XmlNodeType.Element,
SoapException.DetailElementName.Name,
SoapException.DetailElementName.Namespace
) - detail.InnerText "This is the detail part
of my sample exception - throw new SoapException("Message string from
your Web service", SoapException.ServerFaultCode,
Context.Request.Url.AbsoluteUri, detail)
62The Serialized SoapException Results in a
ltsoapFaultgt
- lt?xml version"1.0" encoding"utf-8"?gt
- ltsoapEnvelope xmlnssoap"http//schemas.xmlsoap.
org/soap/envelope/"gt - ltsoapBodygt
- ltsoapFaultgt
- ltfaultcodegtsoapServerlt/faultcodegt
- ltfaultstringgtSystem.Web.Services.Protocols.S
oapException Message string from your Web
service - at ThrowExceptionService.Service1.division(
Int32 x, Int32 y) in c\inetpub\wwwroot\throwexcep
tionservice\service1.asmx.csline
111lt/faultstringgt - ltfaultactorgthttp//localhost81/ThrowExcepti
onservice/service1.asmxlt/faultactorgt - ltdetailgtThis is the detail part of my
sample exception lt/detailgt - lt/soapFaultgt
- lt/soapBodygt
- lt/soapEnvelopegt
63Catching SoapExceptions on the Client Side
- try
-
- localhost.Service1 obj new localhost.Service1(
) - double result obj.division(9,0)
-
- catch(System.Web.Services.Protocols.SoapException
se) -
- Console.WriteLine("Server threw a soap
exception, se.Message) -
- catch(System.Exception ee)
-
- Console.WriteLine("It was not a soap
exception", ee.Message ) -
64Transactions in Web Services
- The TransactionOption property of the WebMethod
attribute specifies how an XML Web service method
participates in a transaction - XML Web service methods can only participate in a
transaction as the root of a new transaction - XML Web service methods that call other XML Web
service methods participate in different
transactions because transactions do not flow
across XML Web service methods
65Enabling Transaction Support
- Add reference to the System.EnterpriseServices
namespace - Declare an XML Web service method, setting the
TransactionOption property of the WebMethod
attribute to TransactionOption.RequiresNew -
Possible Values for TransactionOption
66Transactional WebMethod
- WebMethod(TransactionOptionTransactionOption.Req
uiresNew) - public int DeleteAuthor(string lastName)
-
- String deleteCmdSQL "DELETE FROM authors WHERE
au_lname'" lastName "'" - String exceptionCausingCmdSQL "DELETE FROM
NonExistingTable WHERE au_lname'"
lastName "'" - SqlConnection sqlConn new SqlConnection( "user
idsa databasepubs servermyserver") - SqlCommand deleteCmd new SqlCommand(deleteCmdSQ
L,sqlConn) - SqlCommand exceptionCausingCmd new
sqlCommand (exceptionCausingCmdSQL,sqlConn)
- deleteCmd.Connection.Open()
- deleteCmd.ExecuteNonQuery()
- int cmdResult exceptionCausingCmd.ExecuteNonQue
ry() - sqlConn.Close()
- return cmdResult
-
67Web Services Discovery Challenges
- Who provides Web services?
- How are they implemented?
- Where are they exposed?
- What are they for?
- What is their behavior?
- How do I incorporate run time interaction?
- How do I publish my Web service?
68Discovery and UDDI
- Discovery is the process of locating a Web
service and interrogating it - .disco is an XML document that typically points
to a WSDL (or some other description file) that
points to an actual Web service - ltdiscodiscovery xmlnsdisco"http//schemas.xmls
oap.org/disco/" xmlnsscl"http//schemas.xmlsoap.
org/disco/scl/"gt - lt!-- reference to other DISCO document --gt
- ltdiscodiscoveryRef ref"related-services/default
.disco"/gt - lt!-- reference to WSDL and documentation --gt
- ltsclcontractRef ref"math.asmx?wsdl"
docRef"math.asmx"/gt lt/discodiscoverygt
69Dynamic Discovery
- Enables clients to discover all Web services on
your Web server. - Requests for .vsdisco files are handled by
System.Web.Services.Discovery.DiscoveryRequestHand
ler. It searches recursively through all
subdirectories, looking for .asmx and .disco
files. - The .vsdisco file is in the root directory of the
Web application. - lt?xml version"1.0" encoding"utf-8" ?gt
- ltdynamicDiscovery xmlns"urnschemas- dynamicdisc
overydisco.2000-03-17"gt - ltexclude path"_vti_cnf" /gt
- ltexclude path"_vti_pvt" /gt
- ltexclude path"_vti_log" /gt
- ltexclude path"_vti_script" /gt
- ltexclude path"_vti_txt" /gt
- ltexclude path"Web References" /gt
- ltexclude path"MyFolder" /gt
- lt/dynamicDiscoverygt
70Disco Document When Browsed to the .vsdisco File
- lt?xml version"1.0" encoding"utf-8" ?gt
- - ltdiscovery xmlnsxsd"http//www.w3.org/2001/XML
Schema" xmlnsxsi"http//www.w3.org/2001/XMLSchem
a-instance" xmlns"http//schemas.xmlsoap.org/disc
o/"gt - ltdiscoveryRef ref"http//localhost/MyMathServic
e/MyMathService.vsdisco" /gt - ltdiscoveryRef ref"http//localhost/CreditCardCh
eckServiceCS/CreditCardCheckServiceCS.vsdisco" /gt
- ltdiscoveryRef ref"http//localhost/AsyncMathSer
vice/AsyncMathService.vsdisco" /gt - lt/discoverygt
71Disco Document that is Composed Dynamically
- lt?xml version"1.0" encoding"utf-8" ?gt
- ltdiscovery xmlnsxsd"http//www.w3.org/2001/XMLSc
hema" xmlnsxsi"http//www.w3.org/2001/XMLSchema-
instance" xmlns"http//schemas.xmlsoap.org/disco/
"gt - ltcontractRef
- ref http//localhost/AsyncMathService/MathServer
.as mx?wsdl" docRef"http//localhost/AsyncMathSe
rvice/MathServer .asmx" xmlns"http//schemas.x
mlsoap.org/disco/scl/" /gt - lt/discoverygt
72UDDI (Universal Discovery, Description, and
Integration)
- UDDI is an industry specification for description
and discovery of Web services - Enables publish, find, and bind functions of
Web services
Registry operator node
UDDI service cloud
Registry operator node
UDDI Find
UDDI Publish
Client
Service provider
73UDDI Registry
74UDDI Data Structures
- businessEntity
- The white pages of UDDI. Contains basic business
information name, description, contact
information.
ltbusinessEnitity authorizedName0968869
businessKeyA234567-XXXX-XXXX-XXXXXXXX
operatoruddi.microsoft.comgt ltdisco
veryURLsgt ltdiscoveryURLgthttp//uddi.microsoft.com
/services/uddi/uddiget?businessKey
A234567-XXXX-XXXX-XXXXXXXX lt/discoveryURLgt lt/disco
veryURLsgt ltnamegtXYZ Corporationlt/namegt ltdescriptio
ngt...lt/descriptiongt ltcontactsgt ltpersonamegtXYZ
lt/personnamegt ltphonegt..lt/phonegt lt/contactsgt ltbus
inessServicesgt ltbusinessService
businessKeyA234567-XXXX-XXXX-XXXXXXXX
serviceKey7859484-XXXX-XXXX-XXXXXXX
X lt/businessServicessgt lt/businessEntitygt
75UDDI Data Structures (2)
- businessService
- Yellow pages of UDDI. Categorizes Web services
by industry, product, or service and location.
Based on industry standards like NAICS and
UNSPSC. - ltbusinessService businessKeyA234567-XXXX-XXXX-XX
XXXXXX - serviceKey7859484-XXXX-XXXX-XXX
XXXXX - ltnamegt Sample PurchaseService1lt/namegt
- ltdescriptiongt This service enables purchasing
from XYZlt/descriptiongt - ltbindingTemplatesgt ...lt/bindingTemplatesgt
- ltcategoryBaggt
- ltkeyedReference keyNameUNSPSCShopping
software - keyValue 123456
- tModelKeyUUIDABG5678-XXXX-XXXX-XXXX /gt
- lt/categoryBaggt
- lt/businessServicegt
76UDDI Data Structures (3)
- bindingTemplate
- Green pages of UDDI. Contains technical
information the service descriptions and the
binding information to call a Web service. - ltbindingTemplate bindingKey7867..
- serviceKey7859484-XXXX-XXXX-XXXXXXXX
- ltdescriptiongtlt/descriptiongt
- ltaccessPoint URLTypehttpgt
- http//www.xyz.com/ lt/accessPointgt
- lttModelInstanceDetailsgt
- lttModelInstanceInfo tModelKeyUUID76875
-/gt - lt/tModelInstanceDetailsgt
- lt/bindingTemplategt
77UDDI Data Structures (4)
- tModel
- A pointer to a technical specification.
- lttModel authorizedName0968869
- operatoruddi.microsoft.com
- tModelKeyUUID76875-gt
- ltnamegt.lt/namegt
- ltdescriptiongt. lt/descriptiongt
- ltoverviewDocgt
- ltoverviewURLgthttp//www.uddi.org/specific
ation.htmllt/overviewURLgt - lt/overviewDocgt
- lt/tModelgt
78UDDI Programmer's API
- Inquiry API
- Provides operations for retrieving information
from the registry. - Publishing API
- Provides operations for publishing information
to the registry. -
UDDI Inquiry API
Name
Description
79UDDI Publishing API
Name
Description
80Samples Available for Download
- SimpleService simple service
- StateManagementDemo state management
- SoapHeaders SOAP headers
- SoapTraceExtension SOAP extensions
- SoapCustomMessage formatting SOAP messages
- SecureWebService Web service security
- ASysnchronousMathService async call
- ExceptionService SoapException
81References
- MSDN Visual Studio .NET documentation
- http//www.uddi.org
- http//uddi.microsoft.com
82- Thank you for joining us for todays Microsoft
Support - WebCast.
- For information about all upcoming Support
WebCasts - and access to the archived content (streaming
media - files, PowerPoint slides, and transcripts),
please visit - http//support.microsoft.com/webcasts/
- We sincerely appreciate your feedback. Please
send any - comments or suggestions regarding the Support
- WebCasts to feedback_at_microsoft.com and include
- Support WebCasts in the subject line.