Advanced Web Services Using Microsoft ASPNET by Levone

VIEWS: 138 PAGES: 81

									Topics
   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
                                               1
Web Services Architecture
   XML Web services protocols and standards
   XML Web services infrastructure
   XML Web services message flow




                                               2
XML Web Services Protocols and
Standards
   XML
   Simple Object Access Protocol (SOAP)
   Web Services Description Language (WSDL)
   XSD
   application/x-www-form-urlencoded




                                               3
XML Web Services Infrastructure
                       Directory
              1) Client attempts to locate a Web service

              2) URL to discovery document is returned




                   Discovery
          3) Client requests discovery document


           4) Discovery document is returned

                 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           4
 XML Web Services Message Flow
                            SOAP
                           Request
                  SOAP                 SOAP      Phase II
 Phase I         MESSAGE              MESSAGE   Deserialize
 Serialize

                                                 Web
        Client             Network
                                                Servic
        Proxy                                     e


                                                 Phase III
 Phase IV                                        Serialize
Deserialize       SOAP                 SOAP
                 MESSAGE              MESSAGE
                            SOAP
                           Response

                                                              5
Simple 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://myadvancedwebserviceURI/")]
public class MySimpleService :WebService
{
     [ WebMethod(Description="Adds 2 numbers") ]
     public int Add(int num1, int num2)
     {
          return num1+num2;

     }
........
}                                                            6
WebMethod Attribute's Important
Properties
   BufferResponse
   CacheDuration
   Description
   EnableSession
   MessageName
   TransactionOption


                                  7
Managing 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:
Application["strapplication"]= "This string can be accessed
    by any application";


   Storing state data in Session object:
Session["strsession"] = "This string can be accessed in this
    session only";
                                                               8
Session 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

                                                     9
Session 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",EnableSession=true)]
   public void SetSomeProperty(string str)
   {
     Session["myProperty"] = str;
   }
 [WebMethod(Description="GetSomeProperty",EnableSession=true)]
   public string GetSomeProperty()
   {
     return (string)Session["myProperty"];
   }
//client
. . . . Instantiate cookie container
objproxyMath.SetSomeProperty("Ranjit");
string str = objproxyMath.GetSomeProperty();                          10
SOAP 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; charset=utf-8
SOAPAction: "http://myadvancedwebserviceURI/SetSomeProperty"
Content-Length: 338
Expect: 100-continue
Connection: Keep-Alive
Host: localhost
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
  <SetSomeProperty xmlns="http://myadvancedwebserviceURI/">
       <str>SomePropertyValuesentfromclient</str>
  </SetSomeProperty>
</soap:Body>
</soap:Envelope>

                                                                                 11
SOAP Messages for Session
State Enabled Method (2)
   SetSomeProperty RESPONSE
HTTP/1.1 100 Continue
Server: Microsoft-IIS/5.0
Date: Sat, 09 Mar 2002 17:32:02 GMT
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Sat, 09 Mar 2002 17:32:02 GMT
Set-Cookie: ASP.NET_SessionId=uuvatj55k2bbpsig2fhoicaw; path=/
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Content-Length: 313
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
     xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<SetSomePropertyResponse xmlns="http://myadvancedwebserviceURI/" />
</soap:Body>
</soap:Envelope>
                                                                      12
SOAP 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                 13
Sample SOAP Header
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Header>
  <MyauthenticationHeader xmlns="http://tempuri.org/">
    <Username>admin</Username>
    <Password>password</Password>
  </MyauthenticationHeader>
 </soap:Header>
 <soap:Body>
  <MyWebMethod xmlns="http://tempuri.org/"/>
 </soap:Body>
</soap:Envelope>                                         14
SOAP 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.Protocols
       .WebService
    {
        public MyauthenticationHeader objAuthHeader;
        . . . .
        [SoapHeader("objAuthHeader")]
        [WebMethod]
        public string MyWebMethod() {
          //access the Header values here
           if( objAuthHeader.UserName == "admin"){. . . }
        }
     }
                                                            15
SOAP Header Implementation: Client
void CallWebServiceMethod()
{
//instantiate the Header object in the client
 localhost.MyauthenticationHeader objauthheader =
                     new localhost.MyauthenticationHeader();
//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();
}
                                                               16
SoapHeader Attributes: Required
    Setting the Required property of the SoapHeader
     attribute to FALSE makes the SOAP header optional
//Server
[SoapHeader("objTransactionHeader",Required=false)]
[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();
                                                            17
SoapHeader Attributes:
SoapHeaderDirection
    SoapHeaderDirection: represents the SOAP
     Actor attribute
    In, Out, or InOut

//Server
[WebMethod]
[SoapHeader("myOutHeader",Direction=SoapHeaderDirection.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.UserName);
                                                                      18
Handling 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("Mysomehe
    ader1Value",Required=false)]
public string MyWebMethod3(){….}                               19
Handling 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";
        }
     }
return str;
}                                                           20
SOAP 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
                                                  21
Implementing SOAP Extensions
   Derive a class from SoapExtension
   Save a reference to the stream representing
    future SOAP messages
   Initialize SOAP extension–specific data
   Process the SOAP messages during the
    pertinent SoapMessageStage or stages
   Configure the SOAP extension to run with
    specific XML Web service methods


                                                  22
SoapExtension 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.
                                                           23
SoapExtension Class (2)
   Members: (con't)
       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.




                                                             24
SoapExtension 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;
 }
                                                            25
}
Extensions: Sequence of
Operations for Request
   REQUEST – client side
    1.   A client invokes a method on the proxy class.
    2.   A new instance of the SOAP extension is created
         on the client.
    3.   GetInitializer method is invoked on the SOAP
         extension running on the client.
    4.   The Initialize method is invoked.
    5.   The ChainStream method is invoked.


                                                           26
Extensions: Sequence of
Operations for Request (2)
   REQUEST – client side (con't)
    6.   The ProcessMessage method is invoked with the
         SoapMessageStage set to BeforeSerialize.
    7.   ASP.NET on the client computer serializes the
         arguments of the XML Web service method into
         XML.
    8.   The ProcessMessage method is invoked with the
         SoapMessageStage set to AfterSerialize.
    9.   ASP.NET on the client computer sends the SOAP
         message over the network to the Web server
         hosting the XML Web service.
                                                         27
Extensions: Sequence of
Operations for Request (3)
   REQUEST – server side
    1.   ASP.NET on the Web server receives the SOAP
         message.
    2.   A new instance of the SOAP extension is created
         on the Web server.
    3.   The GetInitializer method is invoked on the SOAP
         extension running on the server.
    4.   The Initialize method is invoked.
    5.   The ChainStream method is invoked.

                                                            28
Extensions: Sequence of
Operations for Request (4)
  6.    The ProcessMessage method is invoked with the
        SoapMessageStage set to BeforeDeserialize.
  7.    ASP.NET deserializes the arguments within the
        XML.
  8.    The ProcessMessage method is invoked with the
        SoapMessageStage set to AfterDeserialize.
  9.    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.
  10.   The XML Web service method executes its code,
        eventually setting the return value and any out
        parameters.
                                                          29
Extensions: Sequence of
Operations for Response
   Server side
    1.   The XML Web service method executes its code,
         eventually setting the return value and any out
         parameters.
    2.   The ProcessMessage method is invoked with the
         SoapMessageStage set to BeforeSerialize.
    3.   ASP.NET on the Web server serializes the return
         value and out parameters into XML.
    4.   The ProcessMessage method is invoked with the
         SoapMessageStage set to AfterSerialize.
    5.   ASP.NET sends the SOAP response message
         over the network back to the XML Web service
         client.                                           30
Extensions: Sequence of
Operations for Response (2)
   Client side
    1.   ASP.NET on the client computer receives the
         SOAP message.
    2.   The ProcessMessage method is invoked with the
         SoapMessageStage set to BeforeDeserialize.
    3.   ASP.NET deserializes the XML into the return
         value and any out parameters.
    4.   The ProcessMessage method is invoked with the
         SoapMessageStage set to AfterDeserialize.
    5.   ASP.NET passes the return value and any out
         parameters to the instance of the proxy class.
    6.   The client receives the return value and any out
         parameters.
                                                            31
Configuring Soap Extensions
   Config file: Applies to all methods in the
    service
<webServices>
<soapExtensionTypes>
<add type="SoapTraceExtension.TraceExtension,
    SoapTraceExtension" />
</soapExtensionTypes>
</webServices>

   Use a custom attribute
     Derive a class from SoapExtensionAttribute
         public class TraceExtensionAttribute:
                               SoapExtensionAttribute

        Apply the attribute to Web method
         [WebMethod]
        [TraceExtensionAttribute]
         public string HelloWorld(){ . . . }            32
Formatting 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.                                    33
Formatting Styles Supported by
ASP.NET Web Services
                       SOAP Body Formatting

                       Document-based SOAP       RPC-based SOAP
                       messages                  messages
                          SoapDocumentMethod or Not supported
                           SoapDocumentService
             Literal      Use=Literal
Parameter                 This is the default
Formatting
                          SoapDocumentMethod or   SoapRpcMethod or
                           SoapDocumentService     SoapRpcService
             Encoded
                          Use=Encoded



                                                                      34
Document Literal
   Method definition
[SoapDocumentMethod( Use=SoapBindingUse.Literal)]
     public Stockinfo GetStockInfoDocumentLiteral(
               string companyname,string stockExchangename)


   Response message
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
     xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Body>
  <GetStockInfoDocumentLiteralResponse
                          xmlns="http://tempuri.org/">
    <GetStockInfoDocumentLiteralResult>
               <stockname>ABCD123</stockname>
               <lasttradedprice>23.5</lasttradedprice>
               <volume>3454353</volume>
    </GetStockInfoDocumentLiteralResult>
  </GetStockInfoDocumentLiteralResponse>
 </soap:Body>
</soap:Envelope>
                                                              35
Document Encoded
   Method definition
[SoapDocumentMethod( Use=SoapBindingUse.Encoded)]
     public Stockinfo GetStockInfoDocumentEncoded (
               string companyname,string stockExchangename)

   Response message
<?xml version="1.0" encoding="utf-8"?>
<soap Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope"
     xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
     xmlns:tns="http://tempuri.org/"
     xmlns:types="http://tempuri.org/encodedTypes"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body
     soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <types:GetStockInfoDocumentEncodedResponse>
      <GetStockInfoDocumentEncodedResult href="#id1" />
    </types:GetStockInfoDocumentEncodedResponse>
    <types:Stockinfo id="id1" xsi:type="types:Stockinfo">
     <stockname xsi:type="xsd:string">ABCD123</stockname>
     <lasttradedprice xsi:type="xsd:double">23.5</lasttradedprice>
     <volume xsi:type="xsd:int">3454353</volume>
    </types:Stockinfo>
</soap:Body>
                                                                     36
</soap:Envelope>
RPC Encoded
    Method definition
[SoapRpcMethod()]
     public Stockinfo GetStockInfoRPCEncoded (
               string companyname,string stockExchangename)


    Response message
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope"
     xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
     xmlns:tns="http://tempuri.org/"
     xmlns:types="http://tempuri.org/encodedTypes"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <tns:GetStockInfoRPCEncodedResponse>
     <GetStockInfoRPCEncodedResult href="#id1" />
  </tns:GetStockInfoRPCEncodedResponse>
  <types:Stockinfo id="id1" xsi:type="types:Stockinfo">
    <stockname xsi:type="xsd:string">ABCD123</stockname>
    <lasttradedprice xsi:type="xsd:double">23.5</lasttradedprice>
    <volume xsi:type="xsd:int">3454353</volume>
   </types:Stockinfo>
 </soap:Body>
</soap:Envelope>                                                              37
Parameter Wrapping/Unwrapping
   Wrapping is the default for document-literal
   UnWrapping
       Method definition
[SoapDocumentMethod(Use=SoapBindingUse.Literal,
  ParameterStyle=SoapParameterStyle.Bare )]
public Stockinfo GetStockInfoBareParam(
           string companyname,string stockExchangename){. .}

       SOAP message
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
 <companyname xmlns="http://tempuri.org/">
    ABCD123
 </companyname>
 <stockExchangename xmlns="http://tempuri.org/">
    STOCKEXGCHG1
 </stockExchangename>
</soap:Body>
</soap:Envelope>                                               38
Security 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                   39
Authentication: 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),"Basic",
                                               credentials);
// Add the CredentialCache to the proxy class credentials.
objlocalhost.Credentials = credentialCache;
// Call the method on the proxy class.
objlocalhost.HelloWorld();
                                                                40
Authentication: 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),"NTLM",
                                               credentials);
// Add the CredentialCache to the proxy class credentials.
objlocalhost.Credentials = credentialCache;
// Call the method on the proxy class.
objlocalhost.HelloWorld();                                     41
Authentication: 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.CreateFromCertFile("C:\\clicert.cer");

// Add the client certificate to the ClientCertificates property
// of the proxy class.
objlocalhost.ClientCertificates.Add(x509);

// Call the method on the proxy class, which requires
// authentication using client certificates.
objlocalhost.Deposit(500);                                             42
Authentication: 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.WebService
    {
       public MyauthenticationHeader objAuthHeader;
       . . . .
       [SoapHeader("objAuthHeader")]
       [WebMethod]
       public string MyWebMethod() {
         //access the Header values here
          if( objAuthHeader.UserName == "admin"){. . . }
       }
                                                             43
     }
Authentication: Custom
SOAP Headers (2)
   Client implementation
//instantiate the Header object in the client
 localhost.MyauthenticationHeader objauthheader =
                     new localhost.MyauthenticationHeader();
//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();
                                                               44
Authorization
   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
<authorization> <allow verb="GET" users="*" />
 <allow verb="POST" users="Administrator" />
 <allow verb="POST" users="Kim" />
 <deny verb="POST" users="*" />
</authorization>
                                                      45
Impersonation
   Configure Web services impersonation in the
    ASP.NET configuration files
<identity impersonate="true" userName="user1"
    password="pass"/>




                                                  46
Encryption
   Secure sockets layer
       Client proxy's URL property:
        https://localhost/SecureWebservice/Service1.asmx
   Custom encryption
       Use SOAP extension
       Encrypt in AfterSerialize
       Decrypt in BeforeDeSerialize




                                                       47
Invoking Web Services
Asynchronously
   Synchronous versus asynchronous
    invocations
   Asynchronous design patterns in .NET
   Invoking Web services asynchronously




                                           48
Synchronous Calls
   Synchronous calls block a process until
    operation is complete

          Client                            Server
                           1
     Calling
                    Client calls object
     Code            and call is blocked   Object being called


                   Method completes
      3
                            2
      Next line
      of
      execution




                                                                 49
Asynchronous 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
                          Client calls object
            Code           Call returns            Object being called

             2

           Next line
           of
           execution

                                       3
            Sink
            Object
                                Method completes
                                                                         50
Asynchronous 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
                                                   51
Ways 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



                                                           52
Closer 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)(results[0]));   }

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(asyncResult);

      return ((int)(results[0]));
  }
                                                               53
Sample Web Service
[WebMethod]
public double Add(int x , int y, int DelaySeconds)
{
    //Create a delay to simulate a long-running process
    if (DelaySeconds > 0)
    {
       System.Threading.Thread.Sleep(DelaySeconds * 1000);
    }
       return x + y;
}




                                                             54
Synchronous Call Client

 localhost.MathServer obj = new localhost.MathServer();
 double result = obj.Add(firstNumber,
                 secNumber, DelaySecs);

 Console.WriteLine("Addition result is = " +
                        result.ToString() );




                                                          55
Asynchronous 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.MathServer)ar.AsyncState;
    double result = obj1.EndAdd(ar);
}                                                            56
Asynchronous 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() );

}

                                                             57
Exception 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 <Fault> XML element within a
    SOAP message that specifies when an error
    occurred
   The three predefined subelements are
    <faultCode>, <faultString>, and <detail>, and
    you can define your own subelements that
    belong to an application-specific namespace
                                                    58
SoapException
   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 );



                                                     59
Throw 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);
}                                                              60
The Serialized SoapException
Results in a <soap:Fault>
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <soap:Fault>
      <faultcode>soap:Server</faultcode>

    <faultstring>System.Web.Services.Protocols.SoapException:
    Message string from your Web service
       at ThrowExceptionService.Service1.division(Int32 x,
    Int32 y) in
    c:\inetpub\wwwroot\throwexceptionservice\service1.asmx.cs
    :line 111</faultstring>

    <faultactor>http://localhost:81/ThrowExceptionservice/ser
    vice1.asmx</faultactor>
      <detail>This is the detail part of my sample exception
    </detail>
    </soap:Fault>
  </soap:Body>
</soap:Envelope>
                                                                61
Catching 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 );
}


                                                           62
Transactions 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                                         63
Enabling 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
    Disabled,        Indicates that the XML Web service method
    NotSupported,    does not run within the scope of a
    Supported        transaction.
                     Default is disabled.
    Required,        Indicates that the XML Web service method
    RequiresNew      requires a transaction. Since Web Service
                     methods can participate only as the root
                     object in a transaction, a new transaction
                     will be created for the Web Service method.   64
Transactional WebMethod
[WebMethod(TransactionOption=TransactionOption.RequiresNew)]
 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 id=sa;
                    database=pubs; server=myserver");
    SqlCommand deleteCmd = new
    SqlCommand(deleteCmdSQL,sqlConn);
    SqlCommand exceptionCausingCmd = new sqlCommand
                           (exceptionCausingCmdSQL,sqlConn);
     deleteCmd.Connection.Open();
     deleteCmd.ExecuteNonQuery();

    int cmdResult = exceptionCausingCmd.ExecuteNonQuery();
    sqlConn.Close();
    return cmdResult;
}                                                              65
Web 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?

                                                 66
Discovery 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
    <disco:discovery
    xmlns:disco="http://schemas.xmlsoap.org/disco/"
    xmlns:scl="http://schemas.xmlsoap.org/disco/scl/">
    <!-- reference to other DISCO document -->
    <disco:discoveryRef ref="related-services/default.disco"/>
     <!-- reference to WSDL and documentation -->
    <scl:contractRef ref="math.asmx?wsdl" docRef="math.asmx"/>
    </disco:discovery>

                                                                 67
Dynamic Discovery
   Enables clients to discover all Web services on your
    Web server.
   Requests for .vsdisco files are handled by
    System.Web.Services.Discovery.DiscoveryRequestH
    andler. It searches recursively through all
    subdirectories, looking for .asmx and .disco files.
   The .vsdisco file is in the root directory of the Web
    application.
    <?xml version="1.0" encoding="utf-8" ?>
    <dynamicDiscovery xmlns="urn:schemas-
       dynamicdiscovery:disco.2000-03-17">
    <exclude path="_vti_cnf" />
    <exclude path="_vti_pvt" />
    <exclude path="_vti_log" />
    <exclude path="_vti_script" />
    <exclude path="_vti_txt" />
    <exclude path="Web References" />
    <exclude path="MyFolder" />
    </dynamicDiscovery>
                                                            68
Disco Document When Browsed
to the .vsdisco File
<?xml version="1.0" encoding="utf-8" ?>
- <discovery xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://schemas.xmlsoap.org/disco/">
  <discoveryRef
    ref="http://localhost/MyMathService/MyMathService.vsdisc
    o" />
  <discoveryRef
    ref="http://localhost/CreditCardCheckServiceCS/CreditCar
    dCheckServiceCS.vsdisco" />
  <discoveryRef
    ref="http://localhost/AsyncMathService/AsyncMathService.
    vsdisco" />
  </discovery>



                                                               69
Disco Document That Is
Composed Dynamically

<?xml version="1.0" encoding="utf-8" ?>
<discovery xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://schemas.xmlsoap.org/disco/">
  <contractRef
    ref= http://localhost/AsyncMathService/MathServer.as
       mx?wsdl"
    docRef="http://localhost/AsyncMathService/MathServer
       .asmx"
       xmlns="http://schemas.xmlsoap.org/disco/scl/" />
 </discovery>




                                                            70
UDDI (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
                                                                     UDDI Find
                       Registry operator node
       UDDI
       Publish
                                                                       Client

    Service provider

                                                                                 71
UDDI Registry
businessEntity: Information about the
party who publishes information about
                                                tModel: Descriptions of
a service.
                                                specifications for services or
                                                taxonomies. Basis for technical
                                                fingerprints.


         businessService: Descriptive
         information about a particular       bindingTemplate data contains
         family of technical services.        references to tModels. These
                                              references designate the
                                              interface specifications for a
                                              service.

               bindingTemplate: Technical
               information about a service
               entry point and construction
               specifications.
                                                                                  72
UDDI Data Structures
     businessEntity:
      The white pages of UDDI. Contains basic business
      information – name, description, contact information.
    <businessEnitity authorizedName="0968869"
                                   businessKey="A234567-XXXX-
    XXXX-XXXXXXXX"
                                   operator="uddi.microsoft.com">
    <discoveryURLs>
             <discoveryURL>http://uddi.microsoft.com/services/udd
    i/uddiget?businessKey= A234567-XXXX-XXXX-XXXXXXXX
    </discoveryURL>
    </discoveryURLs>
    <name>XYZ Corporation</name>
    <description>...</description>
    <contacts>
      <personame>XYZ </personname>
     <phone>…..</phone>
    </contacts>
    <businessServices>
             <businessService businessKey='A234567-XXXX-XXXX-
    XXXXXXXX'
                          serviceKey='7859484-XXXX-XXXX-
    XXXXXXXX'
    </businessServicess>
    </businessEntity>                                               73
UDDI 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.
<businessService businessKey='A234567-XXXX-XXXX-XXXXXXXX'
                 serviceKey='7859484-XXXX-XXXX-XXXXXXXX'
 <name> Sample PurchaseService1</name>
<description> This service enables purchasing from
     XYZ</description>
<bindingTemplates> ...</bindingTemplates>
<categoryBag>
<keyedReference keyName="UNSPSC:Shopping software"
                               keyValue= "123456"
               tModelKey="UUID"ABG5678-XXXX-XXXX-XXXX" />

</categoryBag>
</businessService>
                                                            74
UDDI Data Structures (3)
   bindingTemplate:
    Green pages of UDDI. Contains technical information
    – the service descriptions and the binding
    information to call a Web service.


    <bindingTemplate bindingKey="7867….."
                  serviceKey="7859484-XXXX-XXXX-XXXXXXXX"
       <description>……</description>
       <accessPoint URLType="http">
       http://www.xyz.com/ </accessPoint>
       <tModelInstanceDetails>
              <tModelInstanceInfo tModelKey="UUID:76875-………"/>
       </tModelInstanceDetails>
    </bindingTemplate>
                                                                 75
UDDI Data Structures (4)

   tModel:
    A pointer to a technical specification.

     <tModel authorizedName="0968869"
              operator="uddi.microsoft.com"
          tModelKey="UUID:76875-………">
              <name>….</name>
      <description>…. </description>
      <overviewDoc>

    <overviewURL>http://www.uddi.org/specification.html</overview
    URL>
       </overviewDoc>
     </tModel>



                                                                    76
UDDI 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
     find_business        This locates information about one or more businesses.

     find_service         This locates services within a registered businessEntity.

     find_binding         This locates bindings within a registered businessService.
     find_tModel          This locates one or more tModel information structures.
     get_businessDetail   This gets businessEntity information for one or more
                          businesses.
     get_serviceDetail    This gets full details for a set of registered
                          businessServices.
     get_bindingDetail    This gets bindingTemplate information for making service
                          requests.
     get_tModelDetail     This gets details for a set of registered tModels.           77
UDDI Publishing API
       Name                                 Description
 get_authToken        Requests an authentication token from an operator site.

 get_registeredInfo   Requests information currently managed by the user.

 save_business        Registers/updates a businessEntity.

 save_service         Registers/updates a businessService.

 save_binding         Registers/updates a bindingTemplate.

 save_tModel          Registers/updates a tModel.

 delete_business      Deletes a businessEntity from the registry.

 delete_service       Deletes a businessService from the registry.

 delete_binding       Deletes a bindingTemplate from the registry.

 delete_tModel        Deletes a tModel from the registry.

                                                                                78
Samples 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
                                              79
References
   MSDN Visual Studio® .NET documentation
       Available with Visual Studio .NET, but also in the
        MSDN Library (http://msdn.microsoft.com/library/)
   http://www.uddi.org/
   http://uddi.microsoft.com/




                                                             80
Thank you for joining us for today's 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@microsoft.com and include
"Support WebCasts" in the subject line.
                                                             81

								
To top