XML Web Services and Interview Questions
XML Web Services and Interview Questions
XML Web Services and Interview Questions
In general, Web service methods that call methods that perform I/O operations are good candidates for
asynchronous implementation. Examples of such methods include methods that communicate with other
Web services, access remote databases, perform network I/O, and read and write to large files. All these
methods spend the bulk of their time executing in hardware, which leaves the thread for executing the Web
service method blocked. That thread can be freed up to execute other code if the Web service method is
implemented asynchronously.
Regardless of whether a Web service method is implemented asynchronously, clients can communicate
with it asynchronously. Asynchronous communication is exposed to .NET clients within the proxy class that
is generated by the Web Services Description Language (WSDL.EXE) tool, even if a Web service method is
implemented synchronously. The proxy class contains Begin and End methods for communicating with each
Web service method asynchronously. Therefore, the decision to implement a Web service method
asynchronously or synchronously should be based upon performance.
Example
C#
VB
using System;
using System.Web.Services;
[WebService(Namespace="http://www.contoso.com/")]
public class MyService : WebService
{
public RemoteService remoteService;
public MyService()
{
// Create a new instance of proxy class for
// the Web service to be called.
remoteService = new RemoteService();
}
// Define the Begin method.
[WebMethod]
public IAsyncResult BeginGetAuthorRoyalties(String Author,
AsyncCallback callback, object asyncState)
{
// Begin asynchronous communictation with a different XML Web
// service.
return remoteService.BeginReturnedStronglyTypedDS(Author,
callback,asyncState);
}
// Define the End method.
[WebMethod]
public AuthorRoyalties EndGetAuthorRoyalties(IAsyncResult
asyncResult)
{
// Return the asynchronous result from the other Web service.
return remoteService.EndReturnedStronglyTypedDS(asyncResult);
}
}
How to: Chain Asynchronous
Calls with a Web Service
Method
The following code example demonstrates how to chain asynchronous calls when a Web service method
makes more than one asynchronous call and the calls must execute sequentially.
The BeginGetAuthorRoyaltiesmethod makes an asynchronous call to determine whether the author
passed in is valid and sets up an intermediate callback named AuthorRoyaltiesCallback to receive
the results. That intermediate callback then asynchronously calls to get the royalties for that author, if the
author is valid.
Example
C#
VB
using System.Web.Services;
using System.Data;
using System;
// This imports the proxy class for the Web services
// that the sample communicates with.
using AsyncWS.localhost;
namespace AsyncWS
{
[WebService(Namespace="http://www.contoso.com/")]
public class MyService : System.Web.Services.WebService
{
public RemoteService remoteService;
public MyService()
{
remoteService = new RemoteService();
}
[WebMethod]
public IAsyncResult BeginGetAuthorRoyalties(String Author,
AsyncCallback callback, Object asyncState)
{
// Saves the current state for the call that gets the author's
// royalties.
AsyncStateChain state = new AsyncStateChain();
state.originalState = asyncState;
state.Author = Author;
state.originalCallback = callback;
[WebMethod]
public AuthorRoyalties EndGetAuthorRoyalties(IAsyncResult
asyncResult)
{
// Check whehter the first Web service threw an exception.
if (asyncResult.AsyncState is ArgumentException)
throw (ArgumentException) asyncResult.AsyncState;
else
return remoteService.EndReturnedStronglyTypedDS(asyncResult);
}
}
// Class to wrap the callback and state for the intermediate
// asynchronous operation.
public class AsyncStateChain
{
public AsyncCallback originalCallback;
public Object originalState;
public String Author;
}
}
Wait technique: Use one of the methods of the WaitHandle class to cause a client to wait for
the method to complete.
Callback technique: Pass a callback function into the Begin method, which is then called to
retrieve the results when the method has completed processing.
C#
VB
C#
using System.Web.Services;
VB
Imports System.Web.Services
3. Derive the class that implements the Web service from WebService .
C#
VB
C#
[ WebMethod(EnableSession=true) ]
public int PerSessionServiceUsage()
VB
C#
Session["MyServiceUsage"] = 1;
VB
Session("MyServiceUsage") = 1
6. Access the state variable stored in the Session .
In the following example, the MyServiceUsage state variable is accessed to increment its value.
C#
VB
Session("MyServiceUsage") = CInt(Session("MyServiceUsage")) + 1
C#
VB
C#
using System.Web.Services;
VB
Imports System.Web.Services
3. Derive the class that implements the Web service from WebService .
C#
VB
C#
[ WebMethod ]
public int PerSessionServiceUsage()
VB
< WebMethod > _
Public Function PerSessionServiceUsage() As Integer
5. Store state in the Application, which specifies a name for the state for later retrieval. In the
following example the value 1 is stored in a state variable named appMyServiceUsage.
C#
Application["appMyServiceUsage"] = 1;
VB
Application("appMyServiceUsage") = 1
6. Access the state variable stored in the Application.
In the following example, the appMyServiceUsage state variable is accessed to increment its
value.
C#
Application["appMyServiceUsage"] =
((int) Application["appMyServiceUsage"]) + 1;
VB
Application("appMyServiceUsage") = _
CInt(Application("appMyServiceUsage")) + 1
Example
C#
VB
C#
VB
C#
using System.Web.Services;
using System.EnterpriseServices;
VB
Imports System.Web.Services
Imports System.EnterpriseServices
5. Declare a Web service method, setting the TransactionOption property of
the WebMethodAttribute attribute to System.EnterpriseServices.TransactionOption.RequiresNew .
C#
[ WebMethod(TransactionOption=TransactionOption.RequiresNew)]
public int DeleteAuthor(string lastName)
VB
< WebMethod(TransactionOption:=TransactionOption.RequiresNew)> _
Public Function DeleteAuthor(lastName As String) As Integer
TransactionOption
Enumeration
Specifies the automatic transaction type requested by the component.
Namespace: System.EnterpriseServices
Assembly: System.EnterpriseServices (in System.EnterpriseServices.dll)
Syntax
C#
C++
F#
VB
[SerializableAttribute]
public enum TransactionOption
Members
Member
Description
name
Remarks
When using the .NET Installation Tool (Regsvcs.exe), the transaction option for
a ServicedComponent defaults to Disabled.
Examples
The following code example demonstrates the use of the TransactionOption type.
C#
C++
VB
using System;
using System.EnterpriseServices;
using System.Reflection;
// References:
// System.EnterpriseServices
WebMethodAttribute.Transacti
onOption Property
Indicates the transaction support of an XML Web service method.
Namespace: System.Web.Services
Assembly: System.Web.Services (in System.Web.Services.dll)
Syntax
C#
C++
F#
VB
Remarks
XML Web service methods can only participate as the root object in a transaction, due to the stateless
nature of the HTTP protocol. XML Web service methods can invoke COM objects that participate in the
same transaction as the XML Web service method, if the COM object is marked to run within a transaction
in the Component Services administrative tool. If an XML Web service method with
a TransactionOption property ofRequired or RequiresNew invokes another XML Web service method with
a TransactionOption property of Required or RequiresNew, each XML Web service method participates in
its own transaction, because an XML Web service method can only act as the root object in a transaction.
Item Description
Disabled Indicates that the XML Web service method does not run within the
scope of a transaction. When a request is processed, the XML Web
service method is executed without a transaction.
[WebMethod(TransactionOption= TransactionOption.Disabled)]
NotSupporte Indicates that the XML Web service method does not run within the
d scope of a transaction. When a request is processed, the XML Web
service method is executed without a transaction.
[WebMethod(TransactionOption= TransactionOption.NotSupporte
d)]
Supported Indicates that the XML Web service method does not run within the
scope of transactions. When a request is processed, the XML Web
service is created without a transaction.
[WebMethod(TransactionOption= TransactionOption.Supported)]
Required Indicates that the XML Web service method requires a transaction.
Since XML Web service methods can only participate as the root
object in a transaction, a new transaction will be created for the XML
Web service method.
[WebMethod(TransactionOption= TransactionOption.Required)]
RequiresNe Indicates that the XML Web service method requires a new
w transaction. When a request is processed, the XML Web service is
created within a new transaction.
[WebMethod(TransactionOption= TransactionOption.RequiresNe
w)]
If an exception is thrown from or not caught by an XML Web service method, the transaction is
automatically aborted. If no exceptions occur the transaction is automatically committed unless the method
explicitly callsSetAbort.
Examples
The example below begins a new transaction when the Transfer method is called.
C#
VB
using System;
using System.Web.Services;
using System.EnterpriseServices;
WebMethodAttribute Class
Adding this attribute to a method within an XML Web service created using ASP.NET makes the method
callable from remote Web clients. This class cannot be inherited.
Namespace: System.Web.Services
Assembly: System.Web.Services (in System.Web.Services.dll)
Syntax
C#
C++
F#
VB
[AttributeUsageAttribute(AttributeTargets.Method)]
public sealed class WebMethodAttribute : Attribute
Constructors
Name Description
Top
Properties
Name Description
MessageName The name used for the XML Web service method in the
data passed to and returned from an XML Web service
method.
TransactionOptio Indicates the transaction support of an XML Web service
n method.
Top
Methods
Name Description
Top
Explicit Interface Implementations
Name Description
Top
Remarks
Methods within a class that have this attribute set are called XML Web service methods. The method and
class must be public and running inside an ASP.NET Web application.
Topic
Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer
Examples
In the example below the method GetMachineName can be remotely called across the Web, because it has
a WebMethodAttribute. GetUserName cannot be called remotely, because it does not have
a WebMethodAttribute, even though it is public.
C#
VB
<%@ WebService Language="C#" Class="Util"%>
using System;
using System.Web.Services;
public class Util: WebService {
public string GetUserName() {
return User.Identity.Name;
}
Implementing an Implicit
Transaction using Transaction
Scope
The TransactionScope class provides a simple way to mark a block of code as participating in a transaction,
without requiring you to interact with the transaction itself. A transaction scope can select and manage the
ambient transaction automatically. Due to its ease of use and efficiency, it is recommended that you use
the TransactionScope class when developing a transaction application.
In addition, you do not need to enlist resources explicitly with the transaction.
Any System.Transactions resource manager (such as SQL Server 2005) can detect the existence of an
ambient transaction created by the scope and automatically enlist.
void RootMethod()
{
using(TransactionScope scope = new TransactionScope())
{
/* Perform transactional work here */
SomeMethod();
scope.Complete();
}
}
void SomeMethod()
{
using(TransactionScope scope = new TransactionScope())
{
/* Perform transactional work here */
scope.Complete();
}
}
The top-most transaction scope is referred to as the root scope.
The TransactionScope class provides several overloaded constructors that accept an enumeration of the
type TransactionScopeOption, which defines the transactional behavior of the scope.
A TransactionScope object has three options:
Join the ambient transaction, or create a new one if one does not exist.
Be a new root scope, that is, start a new transaction and have that transaction be the new ambient
transaction inside its own scope.
Not take part in a transaction at all. There is no ambient transaction as a result.
If the scope is instantiated with Required, and an ambient transaction is present, the scope joins that
transaction. If, on the other hand, there is no ambient transaction, then the scope creates a new transaction,
and become the root scope. This is the default value. When Required is used, the code inside the scope
does not need to behave differently whether it is the root or just joining the ambient transaction. It should
operate identically in both cases.
If the scope is instantiated with RequiresNew, it is always the root scope. It starts a new transaction, and its
transaction becomes the new ambient transaction inside the scope.
If the scope is instantiated with Suppress, it never takes part in a transaction, regardless of whether an
ambient transaction is present. A scope instantiated with this value always have null as its ambient
transaction.
The above options are summarized in the following table.
Suppress No No Transaction
Implementing an Explicit
Transaction using
CommittableTransaction
The CommittableTransaction class provides an explicit way for applications to use a transaction, as opposed
to using the TransactionScope class implicitly. It is useful for applications that want to use the same
transaction across multiple function calls or multiple thread calls. Unlike the TransactionScope class, the
application writer needs to specifically call the Commit and Rollback methods in order to commit or abort
the transaction.
Creating a CommittableTransaction
The following sample creates a new CommittableTransaction and commits it.
Creating an instance of CommittableTransaction does not automatically set the ambient transaction
context. Therefore, any operation on a resource manager is not part of that transaction. The
static Current property on the global Transaction object is used to set or retrieve the ambient transaction
and the application must manually set it to ensure that resource managers can participate in the
transaction. It is also a good practice to save the old ambient transaction and restore it when you finish
using the CommittableTransaction object.
To commit the transaction, you need to explicitly call the Commit method. For rolling back a transaction,
you should call the Rollback method. It is important to note that until a CommittableTransaction has
been committed or rolled back, all the resources involved in that transaction are still locked.
A CommittableTransaction object can be used across function calls and threads. However, it is up to the
application developer to handle exceptions and specifically call the Rollback method in case of failures.
Asynchronous Commit
The CommittableTransaction class also provides a mechanism for committing a transaction
asynchronously. A transaction commit can take substantial time, as it might involve multiple database
access and possible network latency. When you want to avoid deadlocks in high throughput applications,
you can use asynchronous commit to finish the transactional work as soon as possible, and run the commit
operation as a background task. TheBeginCommit and EndCommit methods of
the CommittableTransaction class allow you to do so.
You can call BeginCommit to dispatch the commit holdup to a thread from the thread pool. You can also
call EndCommit to determine if the transaction has actually been committed. If the transaction failed to
commit for whatever reason, EndCommit raises a transaction exception. If the transaction is not yet
committed by the time EndCommit is called, the caller is blocked until the transaction is committed or
aborted.
The easiest way to do an asynchronous commit is by providing a callback method, to be called when
committing is finished. However, you must call the EndCommit method on the
original CommittableTransaction object used to invoke the call. To obtain that object, you can downcast
the IAsyncResult parameter of the callback method, since the CommittableTransaction class
implements IAsyncResult class.
The following example shows how an asynchronous commit can be done.
C#
try
{
/* Perform transactional work here */
// No errors - commit transaction asynchronously
committableTransaction.BeginCommit(OnCommitted,null);
}
finally
{
//Restore the ambient transaction
Transaction.Current = oldAmbient;
}
}
void OnCommitted(IAsyncResult asyncResult)
{
CommittableTransaction committableTransaction;
committableTransaction = asyncResult as CommittableTransaction;
Debug.Assert(committableTransaction != null);
try
{
using(committableTransaction)
{
committableTransaction.EndCommit(asyncResult);
}
}
catch(TransactionException e)
{
//Handle the failure to commit
}
}
Transaction Management
Escalation
Windows hosts a set of services and modules that together constitute a transaction manager. Transaction
management escalation describes the process of migrating a transaction from one of the transaction
manager's components to another.
System.Transactions includes a transaction manager component that coordinates a transaction involving at
most, a single durable resource or multiple volatile resources. Because the transaction manager uses only
intra-application domain calls, it yields the best performance. Developers need not interact with the
transaction manager directly. Instead, a common infrastructure that defines interfaces, common behavior,
and helper classes is provided by the System.Transactions namespace.
When you want to provide the transaction to another object in another application domain (including
across process and machine boundaries) on the same computer, the System.Transactions infrastructure
automatically escalates the transaction to be managed by the Microsoft Distributed Transaction
Coordinator (MSDTC). The escalation also occurs if you enlist another durable resource manager. When
escalated, the transaction remains managed in its elevated state until its completion.
Between the System.Transactions transaction and MSDTC transaction, there is an intermediary type of
transaction that is made available through the Promotable Single Phase Enlistment (PSPE). PSPE is another
important mechanism in System.Transactions for performance optimization. It allows a remote durable
resource, located in a different application domain, process or computer, to participate in
a System.Transactions transaction without causing it to be escalated to an MSDTC transaction. For more
information about PSPE, see Enlisting Resources as Participants in a Transaction.
How Escalation is Initiated
Transaction escalation reduces performance because the MSDTC resides in a separate process, and
escalating a transaction to the MSDTC results in messages being sent across process. To improve
performance, you should delay or avoid escalation to MSDTC; thus, you need to know how and when the
escalation is initiated.
As long as the System.Transactions infrastructure handles volatile resources and at most one durable
resource that supports single-phase notifications, the transaction remains in the ownership of
the System.Transactionsinfrastructure. The transaction manager avails itself only to those resources that
live in the same application domain and for which logging (writing the transaction outcome to disk) is not
required. An escalation that results in the System.Transactions infrastructure transferring the ownership of
the transaction to MSDTC happens when:
At least one durable resource that does not support single-phase notifications is enlisted in the
transaction.
At least two durable resources that support single-phase notifications are enlisted in the
transaction. For example, enlisting a single connection with does not cause a transaction to be
promoted. However, whenever you open a second connection to a database causing the database
to enlist, the System.Transactions infrastructure detects that it is the second durable resource in
the transaction, and escalates it to an MSDTC transaction.
A request to "marshal" the transaction to a different application domain or different process is
invoked. For example, the serialization of the transaction object across an application domain
boundary. The transaction object is marshaled-by-value, meaning that any attempt to pass it
across an application domain boundary (even in the same process) results in serialization of the
transaction object. You can pass the transaction objects by making a call on a remote method that
takes a Transaction as a parameter or you can try to access a remote transactional-serviced
component. This serializes the transaction object and results in an escalation, as when a transaction
is serialized across an application domain. It is being distributed and the local transaction manager
is no longer adequate.
The following table lists all the possible exceptions that can be thrown during escalation.
//Client code
using(TransactionScope scope = new TransactionScope())
{
Transaction currentTransaction = Transaction.Current;
DependentTransaction dependentTransaction;
dependentTransaction =
currentTransaction.DependentClone(DependentCloneOption.BlockCommitUntilComp
lete);
WorkerThread workerThread = new WorkerThread();
workerThread.DoWork(dependentTransaction);
/* Do some transactional work here, then: */
scope.Complete();
}
The client code creates a transactional scope that also sets the ambient transaction. You should not pass
the ambient transaction to the worker thread. Instead, you should clone the current (ambient) transaction
by calling theDependentClone method on the current transaction, and pass the dependent to the worker
thread.
The ThreadMethod method executes on the new thread. The client starts a new thread, passing the
dependent transaction as the ThreadMethod parameter.
Because the dependent transaction is created with BlockCommitUntilComplete, you are guaranteed that
the transaction cannot be committed until all of the transactional work done on the second thread is
finished andComplete is called on the dependent transaction. This means that if the client's scope ends
(when it tries to dispose of the transaction object at the end of the using statement) before the new thread
calls Complete on the dependent transaction, the client code blocks until Complete is called on the
dependent. Then the transaction can finish committing or aborting.
Concurrency Issues
There are a few additional concurrency issues that you need to be aware of when using
the DependentTransaction class:
If the worker thread rolls back the transaction but the parent tries to commit it,
a TransactionAbortedException is thrown.
You should create a new dependent clone for each worker thread in the transaction. Do not pass
the same dependent clone to multiple threads, because only one of them can call Complete on it.
If the worker thread spawns a new worker thread, make sure to create a dependent clone from the
dependent clone and pass it to the new thread.
Authenticatio
Description
n option
Windows - Use for non-secure identification of clients, as the user name and
Basic password are sent in base 64-encoded strings in plain text. Passwords
and user names are encoded, but not encrypted, in this type of
authentication. A determined, malicious user equipped with a
network-monitoring tool can intercept user names and passwords.
Windows - Use for secure identification of clients in Internet scenarios. The user
Basic over name and password are sent over the network using Secure Sockets
SSL Layer (SSL) encryption, rather than plain text. This is relatively easy
to configure and works for Internet scenarios. However, using SSL
degrades performance.
SOAP Useful for both secure and non-secure Internet scenarios. User
headers – credentials are passed within the SOAP header of the SOAP
Custom message. The Web server, regardless of the platform hosting the
Web service, provides a custom authentication implementation.
For all options listed above, except the use of SOAP headers, the security settings are specified using a
combination of configuration files and IIS. The custom SOAP headers option is detailed following the
Authorization section, as that solution involves both authentication and authorization.
Windows Authentication
Both IIS and ASP.NET provide support for authenticating Web applications, including Web services, using
security built in to Windows. Windows provides three options for authentication: Basic, Digest, and
Integrated Windows. Additionally, each option can be used with SSL. As all Windows authentication options
except Basic encrypt the data in some form, the additional level of encryption offered by SSL is typically
only used in conjunction with Basic or Client Certificates.
Regardless of which Windows authentication option is used, the procedures for setting up both the Web
service and Web service client are similar. For more information, see How to: Configure an XML Web Service
for Windows Authentication. No code needs to be added to a Web service to use Windows authentication,
as the authentication options are set in a configuration file and IIS. Code to pass the client credentials to the
Web service must be added to a Web service client.
If SSL is chosen as part of the authenticating mechanism used by a Web service, SSL needs to be configured
for the Web application hosting the Web service or for the Web service itself, using IIS. The service
description and, consequently, proxy classes generated from the service description will reflect that the
Web service uses SSL (if the service description and service help page are accessed using SSL). The URL to
the Web service within the service description will be prefixed with https. For more information about
setting up SSL, see the IIS documentation.
Client Certificate Authentication
Client Certificates help provide a secure mechanism for authentication, as clients are required to send an
electronic document, called a client certificate, identifying a client using an SSL connection to the Web
server. The SSL connection encrypts the client credentials contained within the client certificate as they are
sent over the network. Communication between the client and the Web server is encrypted using a
combination of the encryption keys sent by the client and keys provided by the Web server. Once the
communication is established, only the client and server computers can communicate to each other using
that SSL connection.
A client certificate can be obtained from a certificate authority, which can either be the Web server itself or
a trusted intermediary between the client and server. Once a certificate has been obtained, and the Web
server has been configured to accept client certificates, a client can send the client certificate to the Web
server over an SSL connection, when a Web service is called. For more information about client certificates,
see the IIS documentation. For more information about setting up Client Certificate authentication for a
Web service, see How to: Configure an XML Web Service for Windows Authentication.
Authorization Options for XML Web Services
The purpose of authorization is to determine whether an identity should be granted the requested type of
access to a given resource. There are two fundamental ways to authorize access to a given resource: file
authorization and URL authorization. File authorization can be used whenever Windows authentication is
used, as the permissions are set in IIS on a per-file basis. URL authorization can be used with any of the
built-in authentication mechanisms supported by ASP.NET. With URL authorization, configuration is done
through a configuration file, where users can be selectively granted or denied access to any files associated
with ASP.NET, including .asmx files.
For more information about setting up authorization on a per-file basis, see the IIS documentation.
For more information about setting up authorization using a configuration file, see ASP.NET Authorization.
Custom Authentication Using SOAP Headers
The Windows authentication mechanisms, including client certificates, rely on the HTTP transport, whereas
SOAP is transport-independent. Web services built using ASP.NET use SOAP over HTTP, as well as HTTP-
POST and HTTP-GET implementations that return non-SOAP XML documents. So, one reason to create a
custom authentication mechanism is to decouple authentication from the transport. This can be
accomplished by passing the authentication credentials in the SOAP header.
SOAP headers are a great way of passing out-of-band or information not related to the semantics of a Web
service. Unlike the Body element of a SOAP message, which includes the in and out parameters for the
Web service operation that are processed by the Web service method, the Header element is optional and
can thus be processed by the infrastructure. That is, processed by infrastructure developed to provide a
custom authentication mechanism.
For a description of one method of using SOAP headers for authentication, see How to: Perform Custom
Authentication Using SOAP Headers.
To use SOAP headers for authentication, a Web service client would send its credentials to the Web service
by adding the expected SOAP header to the SOAP request and populating it with the client credentials. To
use SOAP header authentication, a Web service must do two things: specify that it expects the SOAP header
containing the authentication credentials and authorize the client access to the Web service.
VB
' Instantiate proxy class to a Bank Web service.
Dim bank As BankSession = new BankSession()
' Call the method on the proxy class, which requires authentication
' using client certificates.
bank.Deposit(500)
C#
Example
When the Credentials property is set to System.Net.CredentialCache.DefaultCredentials then the client
negotiates with the server to do Kerberos and/or NTLM authentication depending on how the server is
configured.
The following code example sets the client credentials passed to a Web service method using Windows
authentication.
C#
VB
using System;
using System.Web.Services.Protocols;
using System.Net;
using MyMath;
The following custom solution is built using ASP.NET to provide an authentication mechanism using SOAP
headers. The solution involves a custom IHttpModule on the Web server that executes the following steps:
1. The HTTP Module parses HTTP messages to check whether they are SOAP messages.
3. If the SOAP message has the SOAP header with authentication credentials, HTTP Module raises a
custom global.asax event.
In the sample provided, the HTTP Module authenticates the user and sets Context properties that a Web
service can use to decide whether the client is authorized access to the Web service.
Note:
In this sample, the text is sent over the network in clearly readable text (it is not encrypted). If
clear text is not secure enough for your application, add an encryption algorithm.
Example
The following code example is an HTTP Module that parses HTTP messages for SOAP requests. If the HTTP
message is a SOAP message, the custom WebServiceAuthenticationEvent is raised.
C#
VB
using System;
using System.Web;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Text;
using System.Web.Services.Protocols;
namespace Microsoft.WebServices.Security {
_eventHandler(this, e);
if (e.User != null)
e.Context.User = e.Principal;
}
try
{
dom.Load(HttpStream);
The following code example is the custom authentication event that is raised by the HTTP Module, if a
SOAP request is received.
C#
VB
namespace Microsoft.WebServices.Security {
using System;
using System.Web;
using System.Security.Principal;
VB
namespace Microsoft.WebServices.Security
{
using System;
VB
using System;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebMethod]
[SoapHeader("authentication")]
public string ValidUser(){
if (User.IsInRole("Customer"))
return "User is in role customer";
if (User.Identity.IsAuthenticated)
return "User is a valid user";
return "not authenticated";
}
}
The following code example is a Web service client that passes the necessary credentials for a custom SOAP
header authentication mechanism within an Authentication SOAP header.
C#
VB
The operation name inside a binding must be globally unique or Wsdl.exe can be run with the
namespace specified to prevent naming collisions caused by other WSDL files imported in the
same application.
1. Add <match> XML elements in the service description within the <text> XML element for each
piece of data you want to return from the parsed HTML page.
2. Apply attributes to the <match> element. The valid attributes are presented in a table under the
topic HTML Parsing by ASP.NET XML Web Services.
Example
The following code example is a simple Web page sample containing <TITLE> and <H1> tags.
<HTML>
<HEAD>
<TITLE>Sample Title</TITLE>
</HEAD>
<BODY>
<H1>Some Heading Text</H1>
</BODY>
</HTML>
The following code example is a service description that parses the contents of the HTML page, extracting
the contents of the text within the <TITLE> and <H1> tags. In the code example,
a TestHeaders method is defined for the GetTitleHttpGet binding. The TestHeaders method
defines two pieces of data that can be returned from the parsed HTML page in <match> XML
elements: Title and H1, which parse the contents of the <TITLE> and <H1> tags, respectively.
<?xml version="1.0"?>
<definitions xmlns:s="http://www.w3.org/2001/XMLSchema"
xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:s0="http://tempuri.org/"
targetNamespace="http://tempuri.org/"
xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<s:schema targetNamespace="http://tempuri.org/"
attributeFormDefault="qualified"
elementFormDefault="qualified">
<s:element name="TestHeaders">
<s:complexType derivedBy="restriction"/>
</s:element>
<s:element name="TestHeadersResult">
<s:complexType derivedBy="restriction">
<s:all>
<s:element name="result" type="s:string" nullable="true"/>
</s:all>
</s:complexType>
</s:element>
<s:element name="string" type="s:string" nullable="true"/>
</s:schema>
</types>
<message name="TestHeadersHttpGetIn"/>
<message name="TestHeadersHttpGetOut">
<part name="Body" element="s0:string"/>
</message>
<portType name="GetTitleHttpGet">
<operation name="TestHeaders">
<input message="s0:TestHeadersHttpGetIn"/>
<output message="s0:TestHeadersHttpGetOut"/>
</operation>
</portType>
<binding name="GetTitleHttpGet" type="s0:GetTitleHttpGet">
<http:binding verb="GET"/>
<operation name="TestHeaders">
<http:operation location="MatchServer.html"/>
<input>
<http:urlEncoded/>
</input>
<output>
<text xmlns="http://microsoft.com/wsdl/mime/textMatching/">
<match name='Title' pattern='TITLE>(.*?)<'/>
<match name='H1' pattern='H1>(.*?)<'/>
</text>
</output>
</operation>
</binding>
<service name="GetTitle">
<port name="GetTitleHttpGet" binding="s0:GetTitleHttpGet">
<http:address location="http://localhost" />
</port>
</service>
</definitions>
The following code example is a portion of the proxy class generated by Wsdl.exe for the previous service
description.
C#
VB
Note:
The operation name inside a binding must be globally unique or Wsdl.exe can be run with the namespace spe
application.
1. Add <match> XML elements in the service description within the <text> XML element for each
piece of data you want to return from the parsed HTML page.
2. Apply attributes to the <match> element. The valid attributes are presented in a table under the
topic HTML Parsing by ASP.NET XML Web Services.
To generate client proxy code for the Web
service
1. Run the Wsdl.exe tool from the Windows® Software Development Kit (SDK). Pass the WSDL file
you created as an input.
Example
The following code example is a simple Web page sample containing <TITLE> and <H1> tags.
<HTML>
<HEAD>
<TITLE>Sample Title</TITLE>
</HEAD>
<BODY>
<H1>Some Heading Text</H1>
</BODY>
</HTML>
The following code example is a service description that parses the contents of the HTML page, extracting
the contents of the text within the <TITLE> and <H1> tags. In the code example,
a TestHeaders method is defined for the GetTitleHttpGet binding. The TestHeaders method
defines two pieces of data that can be returned from the parsed HTML page in <match> XML
elements: Title and H1, which parse the contents of the <TITLE> and <H1> tags, respectively.
<?xml version="1.0"?>
<definitions xmlns:s="http://www.w3.org/2001/XMLSchema"
xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:s0="http://tempuri.org/"
targetNamespace="http://tempuri.org/"
xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<s:schema targetNamespace="http://tempuri.org/"
attributeFormDefault="qualified"
elementFormDefault="qualified">
<s:element name="TestHeaders">
<s:complexType derivedBy="restriction"/>
</s:element>
<s:element name="TestHeadersResult">
<s:complexType derivedBy="restriction">
<s:all>
<s:element name="result" type="s:string" nullable="true"/>
</s:all>
</s:complexType>
</s:element>
<s:element name="string" type="s:string" nullable="true"/>
</s:schema>
</types>
<message name="TestHeadersHttpGetIn"/>
<message name="TestHeadersHttpGetOut">
<part name="Body" element="s0:string"/>
</message>
<portType name="GetTitleHttpGet">
<operation name="TestHeaders">
<input message="s0:TestHeadersHttpGetIn"/>
<output message="s0:TestHeadersHttpGetOut"/>
</operation>
</portType>
<binding name="GetTitleHttpGet" type="s0:GetTitleHttpGet">
<http:binding verb="GET"/>
<operation name="TestHeaders">
<http:operation location="MatchServer.html"/>
<input>
<http:urlEncoded/>
</input>
<output>
<text xmlns="http://microsoft.com/wsdl/mime/textMatching/">
<match name='Title' pattern='TITLE>(.*?)<'/>
<match name='H1' pattern='H1>(.*?)<'/>
</text>
</output>
</operation>
</binding>
<service name="GetTitle">
<port name="GetTitleHttpGet" binding="s0:GetTitleHttpGet">
<http:address location="http://localhost" />
</port>
</service>
</definitions>
The following code example is a portion of the proxy class generated by Wsdl.exe for the previous service
description.
C#
VB
Example
C#
VB
There are two issues that can affect output caching in an ASP.NET 2.0 Web service application.
In ASP.NET 2.0 the HTTP method of the test page has changed from GET to POST. However, POSTs are
not normally cached. If you change the test page in an ASP.NET 2.0 Web service application to use
GET, caching works properly.
In addition, HTTP indicates that a user agent (the browser or calling application) should be able to
override server caching by setting the "Cache-Control" to "no-cache". ASP.NET applications, therefore,
ignore cached results when they find a "no-cache" header.
Example
C#
VB
Interview Questions
Windows services, previously known as NT services, are applications that are installed on the system as
system services. In other words, Windows services are applications that run in the background with the
Windows operating system. The primary use of Windows services is to reduce the consumption of
memory required for performing backend operations. Let's take an example to understand this easily.
Suppose you want to perform a variety of functions, such as monitor the performance of your computer
or application, check the status of an application, and manage various devices, such as printers.
In such a case, you can use Windows services to reduce memory consumption. In addition, Windows
services can run on your system even if you have not logged on to your computer. In addition, these
services do not have any user interface.
The ServiceInstaller class, also known as the project installer class, is used to install a Windows
service.
Yes, it is true.
XML Schema for business descriptions - Includes information about the service publisher
(contact name, address, and so on) and specifications on the Web service
Web registry of Web services - Includes business, service, and binding information for the Web
service
8. Write the file extension for a Web service.
A Web service file extension is .asm file. For example, service1.asmx is a Web service file.
The mustUnderstand attribute indicates that a header entry is either required or optional for the
recipient to process further.
WSDL is a short form for Web Services Description Language, which is used to describe a Web service in
terms of the messages that it creates and accepts. The WSDL document is an XML file that contains the
interface schema for the Web service. It identifies the methods that are used during the exchange
between a Web service consumer and a Web service provider. The following are the elements contained
in the WSDL document:
Types - Describe the variations of data types that are used to exchange messages between the
user and the provider.
Message - Describes the actual message or method call.
portType - Describes the set of operations and each related message.
binding - Describes the protocol details.
service - Used to make groups a set of related ports together.
The UDDI directory has an advantage over a DISCO file, as it provides a single location where a client
can find the Web services offered by different organizations.
13. How can you ensure that only authorized users access your Web service?
You should use the <authorization> element to ensure that only authorized users access your Web
service. This element allows or denies access to your Web service according to their role.
The EventLog class is used to access the Windows event logs from Windows services. Using EventLog,
you can also customize Windows event logs that record information about important software and
hardware events, such as the events of the .NET controls, keyboard, or other hardware devices.
The EventLog class allows you to read or write to event logs, delete logs, and create as well as delete
event sources. You can use the EventLog class to create event logs while creating an event source. An
event source can be used to write to only one event log at a particular time. However, it is possible to
associate one event log to multiple sources.
15. How can you prevent your Web services from unauthorized access?
The following are the ways to prevent your Web service from unauthorized access:
A Web service may be defined as an independent and self-sustained unit of a software application that is
hosted on the Web and implement specific functionalities to execute the business logic. A Web service
provides so many functionalities, such as generating pay slips for employees, computing tax,
broadcasting weather report, and providing updated news. The Web service allows application to share
information or exchange data with other applications across different operating systems and hardware.
Therefore, the work of a Web service is to unite software by exchanging data irrespective of their
operating systems, supported hardware, and programming language used in their development. The
Web services transfer data in the XML format and use Simple Object Access Protocol (SOAP) to
communicate. It is an XML based protocol. The Web services use Web Services Description Language
(WSDL) and Universal Description, Discovery, and Integration (UDDI) to describe itself.
17. What advantages have Web services over Component Object Model (COM) and Distributed
Component Object Model (DCOM)?
The advantages of Web services over COM and DCOM are as follows:
Web services are simple to use and can be implemented on varied platforms.
Web services are loosely coupled; as a result, their interfaces and methods can be extended.
Web services do not carry any state information with them so that multiple requests can be
processed simultaneously.
18. Mention the namespace that you must import in code to build a Web service.
The portType element contains the operations exposed by the Web service, and the messages involved
in the communication between the Web service and its consumers.
DISCO is a technology developed by Microsoft to publish and discover Web services. It discovers URLs of
all XML Web services located on a Web server and creates a list of these Web services in a file called as
a DISCO file.
21. Which two methods are used to discover the URL of Web services?
The two methods to discover the URL of Web services are Web service discovery tool ( Disco.exe)
and UDDI.
22. Which step is necessary to perform before a Web service can be consumed?
It is necessary to build a proxy class by using the wsdl.exe utility before a Web service can be
consumed.
23. Which property of the WebMethod attribute allows you to maintain the state of objects
across sessions in a Web method?
The WebMethod attribute's EnableSession property enables you to enable session state for a Web
method.
Application - Obtains the application object for the current HTTP request
Context - Obtains the HttpContext object for the current request, which encapsulates all
HTTP-specific context used by the HTTP server to process Web requests
Server - Obtains the HttpServerUtility object for the current request
Session - Obtains the HttpSessionState object for the current request
SoapVersion - Obtains the version of the SOAP protocol used to make the SOAP request to a
Web service
User - Obtains the Server User Object. This property can be used to authenticate whether a
user is authorized to execute the request.
The Serialization of the types, such as integers and strings, inside a SOAP message is called encoding.
The SOAP objects use XML elements and attributes to serialized data, for example, encodingStyle is
an attribute of theEnvelop element, which is used to specify the encoding rules for a SOAP object.
A client application uses a .disco file to locate or discover the documents that contain the description
of a Web service. The .disco file contains links to other resources, which describe essential features,
such as capabilities of a Web service. The links contained in a .disco file can refer to other discovery
documents or XSD schemas. The description about the services and capabilities of a Web service is
written in Web services Description Language (WSDL). A .disco file can also contain the information
about other XML Web services that reside on the same or a different Web server.
27. Mention the name of the directory where it is necessary to locate the proxy file to use a
Web service.
The proxy file must be stored in the /bin directory. This directory is situated under the root directory of
the application.
The Web services do not have any technique to maintain state. However, it can access ASP.NET objects,
such as application and session if they extend from the WebService base class.
29. Which namespace must be included in a code that enables a XML Web service to write
events in an event log file?
30. Which tool installs the DLL on your local computer and installs the Windows service in a
transactional manner?
The Installutil.exe tool.
Throw a SoapException exception.
Throw a SoapHeaderException exception.
The following table describes the exceptions a Web service can explicitly throw and how an ASP.NET client
receives each exception:
What a Web service can do, what a
Type of exception thrown
client receives
While The exception is caught by ASP.NET and thrown back to the client.
executing The Web service client created using the .NET Framework receives
the Web a SoapException with the exception details placed in
service the Message property.
method
C#
VB
C#
<soap:Header xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<MyHeader xmlns="http://www.contoso.com">
<Created>dateTime</Expires>
<Expires>long</Expires>
</MyHeader>
</soap:Header>
VB
C#
[WebService(Namespace="http://www.contoso.com")]
public class MyWebService
{
// Add a member variable of the type deriving from SoapHeader.
public MyHeader timeStamp;
VB
<WebService(Namespace:="http://www.contoso.com")> _
Public Class MyWebService
' Add a member variable of the type deriving from SoapHeader.
Public TimeStamp As MyHeader
2. Apply a SoapHeader attribute to each Web service method that intends to process the SOAP
header. Set the MemberName property of the SoapHeader attribute to the name of the member
variable created in the first step.
C#
[WebMethod]
[SoapHeader("timeStamp")]
public void MyWebMethod()
VB
<WebMethod, SoapHeader("TimeStamp")> _
Public Sub MyWebMethod()
3. Within each Web service method that the SoapHeader attribute is applied to, access the member
variable created in the first step to process the data sent in the SOAP header.
C#
[WebMethod]
[SoapHeader("myHeaderMemberVariable")]
public string MyWebMethod()
{
// Verify that the client sent the SOAP Header.
if (timeStamp == null) timeStamp = new MyHeader();
// Set the value of the SoapHeader returned to the client.
timeStamp.Expires = 60000;
timeStamp.Created = DateTime.UtcNow;
return("Hello World!");
}
VB
<WebMethod,SoapHeader("TimeStamp", _
Direction:=SoapHeaderDirection.InOut)> _
Public Function MyWebMethod() As String
' Process the SoapHeader.
If (TimeStamp Is Nothing) Then
TimeStamp = New MyHeader
End If
TimeStamp.Expires = 60000
TimeStamp.Created = DateTime.UtcNow
Example
The following code example demonstrates how to define and process a SOAP header in a Web service
created using ASP.NET. The MyWebService Web service has a member variable
named myHeaderMemberVariable, which is of a type deriving from SoapHeader (MyHeader) and set
to the MemberName property of the SoapHeader attribute. In addition, a SoapHeader attribute is applied
to the MyWebMethod Web service method specifying myHeaderMemberVariable. Within
the MyWebMethod Web service method, myHeaderMemberVariable is accessed to get the value of
the Username XML element of the SOAP header.
C#
VB
[WebService(Namespace="http://www.contoso.com")]
public class MyWebService
{
// Add a member variable of the type deriving from SoapHeader.
public MyHeader myHeaderMemberVariable;
In the previous example, if the SOAP request to the MyWebMethod has a MyHeader SOAP header with
a UserName element set to Admin, additional code is executed. That is, the following SOAP request
causes that code to execute.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<MyHeader xmlns="http://www.contoso.com">
<Created>dateTime</Created>
<Expires>long</Expires>
</MyHeader>
</soap:Header>
<soap:Body>
<MyWebMethod xmlns="http://www.contoso.com" />
</soap:Body>
</soap:Envelope>
VB
C#
VB
mySoapHeader.Username = UserName
mySoapHeader.Password = SecurelyStoredPassword
C#
mySoapHeader.Username = Username;
mySoapHeader.Password = SecurelyStoredPassword
3. Create a new instance of the proxy class.
VB
C#
VB
proxy.MyHeaderValue = mySoapHeader
C#
proxy.MyHeaderValue = mySoapHeader
5. Call the method on the proxy class that communicates with the Web service method.
The SOAP header portion of the SOAP request sent to the Web service will include the contents of
the data stored in the SOAP header object.
VB
C#
Example
The following code example demonstrates how to pass a SOAP header from a client to a Web service.
C#
VB
Using a Web service encompasses the communication of Web service methods over a network using
industry standard protocols. However, before an application can begin communicating with Web service
methods, there are four basic steps it must accomplish:
1. Determine if a Web service exists. You can look in a directory, such as UDDI Services, for the
vendors that provide Web services with specific functionalities. The directory has a URL to the
vendor's Web site.
2. Discover a Web service. Given a URL to a vendor, Web service discovery is invoked to get the
specific details about each Web service that is available at that URL. Information about each Web
service is returned to the client in the form of a service description, which is an XML document that
describes the Web service in the Web Services Description Language (WSDL). The service
description concretely details how to communicate with a Web service. For information about Web
service discovery, see Web Service Discovery.
3. Given a service description, generate a proxy class, which can communicate with Web service
methods based on the precise definition in the service description. For instructions, see Creating an
XML Web Service Proxy.
Because the proxy class communicates with the Web service across the Internet, it is a good idea to
verify that the Url property of the proxy class references a trusted destination.
4. Create a client application, which invokes methods of the proxy class. The methods of the proxy
class can communicate with the Web service methods over the Internet, using industry standard
protocols. For more information, see Creating Clients for XML Web Services.
After discovering that a Web service exists using Web service discovery, you can view information about the
Web service and the Web service methods it implements in a more user-friendly format than the service
description. To do so, access the service help page described in How to: Explore Existing XML Web Services
Created Using ASP.NET.
Web services can be used by a variety of client applications. You can communicate with a Web service from
any Web application, including another Web service. The client of a Web service is not necessarily a client-
based application; in reality, most clients are server-based applications, such as Web Forms and other Web
services.
As shown in the previous graphic, there are two Web service clients: an ASP.NET Web Form and a Web
service. The ASP.NET Web Form, which the user sees, communicates with the GetCurrentPrices Web
service. TheGetCurrentPrices Web service then acts as a Web service client by communicating with
the StockServices Web service to obtain the stock quote. The stock quote is then returned to
the GetCurrentPrices Web service, which subsequently passes it back to the ASP.NET Web Form.
Parameter Value
apppath The name of the Web application that is hosting the Web
service.
webservicename.asm The name of the file where the Web service is defined.
x
3. For example, to access a Web service called StockServices.asmx, residing on a Web server named
StockTicker, enter the following:
4. http://StockTicker/StockServices.asmx
Note:
By default, a Web service created using ASP.NET is able to support multiple protocols, including SOAP over HTTP a
the response.
Apppath The name of your virtual directory and the rest of the Web
application path.
Parameter Value
Apppath The name of your virtual directory and the rest of the Web
application path.
The Web service method name in this syntax is case sensitive, but the server, project, and Web
service names are not.
5. For example, suppose the StockServices Web service from the preceding procedure contains a
Web service method called GetQuote; the Web service method accepts a stock symbol as a
parameter, returning the price as a double-precision floating-point number. Enter the following
HTTP-GET request in the browser's address bar to test this method:
6. http://<servername>/apppath/StockServices.asmx/GetStockQuote?tickerName=MSFT
7. The server sends a response containing an XML document, which is displayed in the browser. For
the GetQuote example, the XML has the current price of the stock you request. The result might
look like the following:
<?xml version="1.0" ?>
<double>74.5</double>
C#
[ WebMethod ]
public int Subtract(int num1, int num2) {
return num1-num2;
}
}
VB
<WebMethod> _
Public Function Add(num1 As Integer, num2 As Integer) As Integer
Return num1 + num2
End Function
<WebMethod> _
Public Function Subtract(num1 As Integer, num2 As Integer) As
Integer
Return num1 - num2
End Function
End Class
2. Create an HTML page with a form that has its method attribute set to POST. Use the following
format:
3. <form method=POST
action='http://www.contoso.com/math.asmx/Subtract'>
4. <input type="text" size="5" name='num1'\"></td> -
5. <input type="text" size="5" name='num2'\"></td> =
6. <input type=submit value="Subtract"> </td>
7. </form>
Parameter Value
Method POST. If you want to test your Web service using HTTP-POST, use
POST.
Action URL to the Web service method. In the previous example, math.asmx
is the Web service and Subtract is the Web service method.
name='num The name of the Web service method parameter. Add as many text
1' input controls on the form as there are parameters in the Web service
method. For instance, if a Web service method has three parameters,
three text input controls are needed that each have
their name attribute set to the name of the parameter.
type=submit Add a submit button so you can post the data back to the Web service
method.
8. Access a Web browser and enter the URL for the HTML document you created in the previous step.
The HTML document created in the previous step is displayed.
9. Enter the appropriate values for the Web service method in the text boxes and click
the submit button.
For example, if you entered 6 and then 3 into the two text boxes for the
example's Subtract Web service method, the following result is returned:
<?xml version="1.0" ?>
<int xmlns="http://tempuri.org/">3</int>
Web Services Discovery
Given the URL to a discovery document residing on a Web server, a developer of a client application can
learn that a Web service exists, what its capabilities are, and how to properly interact with it. This process is
known as Web service discovery.
Through the process of Web service discovery, a set of files is downloaded to the local computer containing
details about the existence of Web services. The files can be service descriptions, XSD schemas, or discovery
documents. Using the Wsdl.exe tool, you can create a proxy class to the Web service described by a service
description or XSD schema. For details about creating a proxy class, see Creating an XML Web Service
Proxy. A downloaded discovery document contains information about the existence of other Web services
that might reside on a different Web server. For details about the contents of a discovery document,
see How to: Enable Discovery for XML Web Services.
You can use the Web Services Discovery tool (Disco.exe) from a command prompt to perform Web service
discovery on a URL.
Disco /out:location /username:user /password:mypwd /domain:mydomain
http://www.contoso.com/my.disco
Note:
The arguments listed are the commonly used arguments for Disco.exe.
For the full syntax of Disco.exe, see Web Services Discovery Tool
(Disco.exe).
Parameter Value
4. If anonymous access has been disabled for the Web application hosting the Web service, set
the Credentials property of the proxy class.
5. Call the method on the proxy class that corresponds to the Web service method with which you
want to communicate.
For most clients, these steps differ only in how the proxy class is referenced and how the Web service client
is deployed.
Note:
If you create a Web service client using the following topics and your proxy fails with the
exception text,
"The request failed with HTTP status 401: Access Denied," there is a good chance that you have
not yet passed your security credentials to the credential cache on the proxy. For details on
passing the correct credential information to the service, see How to: Configure an XML Web
Service for Windows Authentication.
Creating an XML Web Service
Proxy
By definition, Web services can be communicated with over a network using industry standard protocols,
including SOAP. That is, a client and a Web service communicate using SOAP messages, which encapsulate
the in and out parameters as XML. Fortunately, for Web service clients, the proxy class handles the work of
mapping parameters to XML elements and then sending the SOAP message over the network.
As long as a service description exists, a proxy class can be generated if the service description conforms to
the Web Services Description Language (WSDL). A service description defines how to communicate with a
Web service. With a service description, a proxy class can be created with the Wsdl.exe tool. In turn, a Web
service client can then invoke methods of the proxy class, which communicate with a Web service over the
network by processing the SOAP messages sent to and from the Web service. Because the proxy class
communicates with the Web service across the Internet, it is a good idea to verify that the Url property of
the proxy class references a trusted destination.
By default, the proxy class uses SOAP over HTTP to communicate with the Web service. However, Wsdl.exe
can generate proxy classes to communicate with a Web service, using either the HTTP-GET protocol or
HTTP-POST protocol. To specify that the proxy class should use HTTP-GET or HTTP-POST, provide
the /protocol switch to the Wsdl.exe tool, as described in the following table.
Note:
The arguments listed here are the commonly used arguments for Wsdl.exe. For the full syntax of Wsdl.exe, see We
Language Tool (Wsdl.exe).
Parameter Value
VB
Indicates the TargetNamespace for two or more of the supplied service descriptions are identical.
As the TargetNamespace is supposed to be a unique identifier for a particular XML document,
which in this case is a service description, Wsdl.exe assumes that the two service descriptions are
identical. In doing so, Wsdl.exe builds just one proxy class for one of the service descriptions. If this
is not your intended result, you can change this. For service descriptions that represent Web
services created using ASP.NET, you can apply a WebService attribute that specifies a
unique Namespace property to the class that implements the Web service.
That Namespace property is then used as the TargetNamespace in the service description to
uniquely identify the Web service.
Indicates the TargetNamespace for two or more XML schemas within the supplied service
descriptions are identical. Because the TargetNamespace is supposed to be a unique identifier for
a particular XML document, which in this case is the XML schema, Wsdl.exe assumes that the two
XML schemas are identical. In doing so, Wsdl.exe builds a class for just one of the schemas. If this is
not the intended result, theTargetNamespace for each XML schema must be changed to a unique
URI. Exactly how the TargetNamespace is modified depends on the origin of the particular XML
schemas.
Style: For the child element, and possibly the grandchildren, of the Body element in a SOAP
message. This is specified as the style attribute of a binding WSDL element (typically) or
an operation element.
Use: For the Web service method parameters, or a return value, that appear at the next level down.
This is specified as the use attribute of a body element.
For details on the SOAP specification, see the W3C Web site (http://www.w3.org/TR/SOAP). Details on the
WSDL specification can also be found at the W3C Web site ().
RPC: Parameters, or a return value, are automatically placed in a parent element whose own parent
is the SOAP Body element. The parameters or return value appear without namespace
qualification. This scheme is described in Section 7 of the SOAP 1.1 specification.
Specified style="rpc".
For a SOAP request, the element below the SOAP Body is named after a WSDL operation element,
which corresponds to Web service method. Each element within that element represents a
parameter and is named after its respective parameter.
For a SOAP response, the name of the element below the SOAP Body is the operation name
with Response appended. The name of the element underneath, representing the return value, is
the operation name but with the suffix Return.
Document: The contents of the SOAP Body element are fully specified in the WSDL as XML
elements defined in an XML Schema definition. The XML schema is specified in, or imported into,
the WSDL document. The WSDL is oblivious to parameters and return values; it only deals with
XML documents. The developer, or preferably the Web services infrastructure, takes care of how
parameters and return values translate into XML Schema elements and types.
Specified style="document".
The top-level XML elements are specified as message parts -- part elements that are defined in
a message element and point to XSD element declarations. Normally, there is no more than one
part, so that the SOAPBody contents are truly an XML document, although WSDL itself doesn't
prohibit multiple elements.
WSDL allows two values for the use attribute that controls parameter, and return value, formatting:
Encoded: Data is formatted according to a scheme is described in Section 5 of the SOAP 1.1
specification. SOAP encoding uses a subset of the XML Schema for binding between XML
documents and the data they represent. SOAP encoding also employs references for elements that
appear multiple times in a document. Specified use="encoded".
Literal: Data is formatted literally according to XML Schema definitions specified in, or imported
into, the WSDL document. Specified use="literal".
Instead of handcrafting a WSDL document, a developer that creates a Web service for
ASP.NET can specify these SOAP formats by applying attributes to either individual Web
service methods or entire Web service classes. If a developer does not specify these
attributes, the default SOAP formats are used.
If you are developing a Web service based on an existing WSDL document, you can run the
Wsdl.exe tool with the /server option to generate an abstract Web service class that has the
appropriate attribute values automatically set.
Without the /server option, Wsdl.exe produces a client proxy class that sets the relevant
SOAP formatting attributes to the appropriate values to communicate with the Web service
described by the input WSDL document. A client proxy class uses most of the same attributes
that can be specified on the server. Normally, a developer does not need to manually add or
edit these attributes in the client proxy class because normally the client is generated by
Wsdl.exe to ensure that it complies with the service contract specified by the WSDL
document.
The following table outlines the formatting choices supported by Web services and clients
created using ASP.NET and the .NET Framework, along with the attributes that accomplish
each specific combination. The attributes with a Service suffix can be applied to a class that
implements a Web service (not a client proxy class) to set the default formatting style for
Web service methods within the class. The attributes with a Method suffix can be applied
either to a Web service method or to a method in a client proxy class that calls a Web service
method. The details of each combination are covered in the following paragraphs.
Parame
SOAP Body formatting (style)
ter
SOAP Body formatting (style) for for RPC-based SOAP messages
forma
Document-based SOAP messages according to SOAP 1.1 Section
tting
7s
(use)
Note:
The actual attribute names use the Attribute suffix. In the source code, the names can be
abbreviated, as shown in the preceding table.
VB
[SoapDocumentMethod(
"http://www.contoso.com/DocumentBareLiteral",
Use=SoapBindingUse.Literal,
ParameterStyle=SoapParameterStyle.Bare)]
[return: XmlElement(Namespace="http://www.contoso.com",
IsNullable=true)]
public string DocumentBareLiteral(
[XmlElement(Namespace="http://www.contoso.com",
IsNullable=true)]
Address1 MyAddress,
[XmlElement(Namespace="http://www.contoso.com",
IsNullable=false)]
bool useZipPlus4) {
Some commonly used attributes are listed as follows, their names appear without
the Attribute suffix, which can be omitted:
XmlElement: Specifies that a public field or property be serialized as an XML element. This is
the default attribute for serializing non-array public fields and properties. When
the XmlElement attribute is applied to public fields and properties of an array type attribute,
the array is serialized with other members, without a special parent element.
XmlAttribute: Specifies that a public field or property be serialized as an XML attribute of the
element that represents the containing type.
XmlArray: Specifies that a public field of an array type be serialized with a special parent
element. This is the default attribute for serializing public fields and properties of an array
type.
The preceding attributes, except for XmlIgnore, can also be used to specify an element or
attribute name besides the default, which is the member name for non-array members. They
can also be used to specify a namespace for a particular element. Usually, a Web service does
not mix namespaces and a namespace is required to be specified only at the class level, using
an attribute like WebService or WebServiceBinding.
For more information, see , see System.Xml.Serialization.
Note:
For RPC or encoded Web services, using RPC style with SOAP encoding, the use of XML serialization is restricted
Also, SOAP 1.1 Section 5 encoding, combined with document or RPC style, prohibits the binding of data to XML attr
Note:
If an abstract service class or client proxy class is generated from a WSDL document, the correct System.Xml.Ser
that are defined under the WSDL types element, whether they appear inline or are imported.
Note:
Using Nullable types in a Web service results in WSDL that contains the "nillable=true" setting for the type. However, when
not reflected in the resulting WSDL in the following cases: 1) When RPC-based SOAP messages are used, and 2) When Doc
How to implement these methods is explained in the step-by-step topic Walkthrough: Altering the SOAP
Message Using SOAP Extensions.
The ChainStream method is passed a Stream object and returns a Stream object. As the SOAP extension
executes during each SoapMessageStage and modifies the SOAP message, a SOAP extension should read
from theStream passed into ChainStream and write to the Stream returned from ChainStream. Therefore,
it is important within the ChainStream method to assign both Stream references to member variables.
The class deriving from SoapExtension uses the GetInitializer and Initialize methods to initialize internal
data, based on the Web service or Web service method it is applied to. For instance, a SOAP extension that
logs the SOAP message sent to and from a Web service method might initialize the name of a file to save
the logging information (based on the name of the Web service or the Web service method the SOAP
extension is running with).
At what point the Web services infrastructure calls the GetInitializer method and what parameters are
passed to the method depend on how the SOAP extension is configured, as follows:
If the SOAP extension is configured using an attribute, GetInitializer is called by the Web services
infrastructure the first time a Web service method is accessed.
The Web services infrastructure caches the object that the GetInitializer method returns. Then each time
the SOAP extension runs with that Web service or Web service method, the infrastructure passes the
initializer object to the Initialize method.
Actual extended processing beyond the standard SOAP processing is performed by
the ProcessMessage method. Each time the Web services infrastructure calls ProcessMessage, it passes (as
an argument) an instance of a class derived from SoapMessage that contains information about the SOAP
message at that particular stage. If the SOAP extension is running with a Web service, then
a SoapServerMessage object is passed in. If the SOAP extension is running with a Web service client, then
a SoapClientMessage object is passed in.
Soap Extensions and Exceptions
Soap extensions must never throw exceptions themselves. They can, however, add exception information to
the Exception property on the SoapMessage object passed in the ProcessMessage method.
They can also serve as application-wide exception handler using the same facility to catch all exceptions in
the application for which the soap extension is installed and perform some behavior including modifying
the returned SOAP fault.
3. If this is the first time this SOAP extension has executed with this Web service on the client, then
the GetInitializer method is invoked on the SOAP extension running on the client.
4. The Initialize method is invoked.
5. The ChainStream method is invoked.
6. The ProcessMessage method is invoked with SoapMessageStage set to BeforeSerialize.
7. ASP.NET on the client computer serializes the arguments of the Web service method into XML.
9. ASP.NET on the client computer sends the SOAP message over the network to the Web server
hosting the Web service.
3. On the Web server, if this is the first time this SOAP extension has executed with this Web service
on the server side, 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.
9. ASP.NET creates a new instance of the class implementing the Web service and invokes the Web
service method, passing in the deserialized arguments. This object resides on the same computer
as the Web server.
10. The Web service method executes its code, eventually setting the return value and any out
parameters.
12. ASP.NET on the Web server serializes the return value and out parameters into XML.
14. ASP.NET sends the SOAP response message over the network back to the Web service client.
3. ASP.NET deserializes the XML into the return value and any out parameters.
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.
Note:
When implementing a SOAP extension, there is a possibility that a Denial of Service (DOS)
attack could be attempted if your extension uses an XmlTextReader to read the data stream.
One way of preventing such an attack is to ensure that the ProhibitDtd property is set to true.
Highest priority group: SOAP extensions configured using a configuration file with a group setting
of 0.
Lowest priority group: SOAP extensions configured using a configuration file with a group setting
of 1.
The following code example is a configuration file that specifies that
the Logger.LoggerExtension SOAP extension runs within the relative priority group 0 and has a
priority of 1.
<configuration>
<system.web>
<webServices>
<soapExtensionTypes>
<add type="Logger.LoggerExtension,logger"
priority="1"
group="0" />
</soapExtensionTypes>
</webServices>
</system.web>
</configuration>
C#
[SoapDocumentMethod("http://www.contoso.com/DocumentWrappedLiteral",
RequestNamespace="http://www.contoso.com",
ResponseNamespace="http://www.contoso.com",
Use=SoapBindingUse.Literal)]
public string DocumentWrappedLiteral(Address MyAddress,
bool useZipPlus4) {
VB
<SoapDocumentMethod("http://www.contoso.com/DocumentWrappedLiteral",
_
RequestNamespace:="http://www.contoso.com", _
ResponseNamespace:="http://www.contoso.com", _
Use:=SoapBindingUse.Literal)> _
Public Function DocumentWrappedLiteral(ByVal MyAddress As Address,
_
ByVal useZipPlus4 As Boolean)As String
With the Document formatting style, an XSD schema is defined within the service description that
defines both the SOAP request and SOAP response. The following is an excerpt from the service
description for the SOAP request for the DocumentWrappedLiteral Web service method.
Because the first parameter to the DocumentWrappedLiteral Web service method is a class,
and the Literal parameter formatting style was specified, an XSD schema is created for
the address type.
<s:element name="DocumentWrappedLiteral">
<s:complexType>
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="MyAddress"
nillable="true" type="s0:Address" />
<s:element minOccurs="1" maxOccurs="1" name="useZipPlus4"
type="s:boolean" />
</s:sequence>
</s:complexType>
</s:element>
<s:complexType name="Address">
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="Street"
nillable="true" type="s:string" />
<s:element minOccurs="1" maxOccurs="1" name="City"
nillable="true" type="s:string" />
<s:element minOccurs="1" maxOccurs="1" name="Zip"
nillable="true"
type="s:string" />
</s:sequence>
</s:complexType>
With the XSD schema that is defined in the service description, the XML portion of the SOAP
request to the DocumentWrappedLiteral Service method follows. Note that the XML
elements beneath the Bodyelement in the SOAP request match the elements defined in the XSD
schema.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
>
<soap:Body>
<DocumentWrappedLiteral xmlns="http://www.contoso.com">
<MyAddress>
<Street>string</Street>
<City>string</City>
<Zip>string</Zip>
</MyAddress>
<useZipPlus4>boolean</useZipPlus4>
</DocumentWrappedLiteral>
</soap:Body>
</soap:Envelope>
To specify RPC formatting style
1. Apply a SoapRpcMethod attribute to the method in the proxy class calling the applicable Web
service method.
C#
[SoapRpcMethodAttribute("http://www.contoso.com/Rpc",
RequestNamespace="http://www.contoso.com",
ResponseNamespace="http://www.contoso.com")]
public Address Rpc(Address address, bool useZipPlus4) {
VB
<SoapRpcMethodAttribute("http://www.contoso.com/Rpc", _
RequestNamespace:="http://www.contoso.com", _
ResponseNamespace:="http://www.contoso.com")>
_
Public Function Rpc(ByVal address As Address, _
ByVal useZipPlus4 As Boolean) As Address
An XSD schema is not strictly defined in the service description for either the SOAP request or
SOAP response to the Rpc method in the previous example, but rather just the parts that comprise
them. Therefore, look at the SOAP request for the Rpc method, noting that the parameters are
encapsulated inside one element and they are encoded using the Encoded parameter formatting.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/
"
xmlns:tns="http://www.contoso.com"
xmlns:tnsTypes="http://www.contoso.com/encodedTypes"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body
soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<tns:Rpc>
<address href="#1" />
<useZipPlus4>boolean</useZipPlus4>
</tns:Rpc>
<tnsTypes:Address id="1">
<Street id="2">string</Street>
<City id="3">string</City>
<Zip id="4">string</Zip>
</tnsTypes:Address>
</soap:Body>
</soap:Envelope>
Note:
If an XML Web services sample has been developed using Visual Studio, a tilde ('~') can appear in a directive attribu
this usage, see ASP.NET Web Site Paths
In This Section
Term Definition
@ Assembly Directive in XML Links an assembly to an XML Web service during compilation.
Web Services
@ WebService Directive in Defines XML Web service specific (.asmx file) attributes used by
XML Web Services the ASP.NET parser and compiler.
C#
<%@ Assembly Name="assemblyname" %><%@ Assembly Src="pathname" %>
Attributes
Term Definition
Nam The name of the assembly to link to the XML Web service.
e
Note:
The assembly name does not include a file name extension.
Src The path to a source file to dynamically compile and link against.
Note:
You cannot include a Name and a Src attribute in the same @ Assembly directive. If you want to
than one directive on the page.
Remarks
The compiler references the assembly at compile time, allowing early binding. Once compilation of
the XML Web service is complete, the assembly is dyamically loaded into the application domain
when it changes, allowing late binding.
Assemblies that reside in your Web application's \bin directory are automatically linked to XML Web
services in that application. Such assemblies do not require the @ Assembly directive.
Note:
The path to the assembly or source file in an @ Assembly directive must be a relative path to the Web appl
service.
Example
The following code fragment uses two @ Assembly directives, the first to link to MyAssembly, a
user-defined assembly, the second to MySource.vb, a Visual Basic source file located in the src
folder beneath the directory of the Web application hosting the XML Web service.
C#
<%@ WebService attribute="value" [attribute="value"…] %>
Attributes
Term Definition
Class Specifies the class implementing the XML Web service that is automatically compiled
the first time the XML Web service is accessed after changes. This value can be any
valid class name residing in either the same file as the WebService directive or within a
separate file. If the class resides in a separate file, it must be placed in the \Bin directory
underneath the Web application where the XML Web service resides. This attribute is
required for the XML Web service to compile.
CodeBehin Specifies the source file implementing the XML Web service, when the class
d implementing the XML Web service does not reside in the same file and has not been
compiled into an assembly and placed in the \Bin directory.
Debug Indicates whether the XML Web service should be compiled with debug symbols. true if
the XML Web service should be compiled with debug symbols; otherwise, false.
Language Specifies the language used when compiling all inline code within the XML Web
service file (.asmx). The values can represent any .NET-supported language, including
C#, VB, and JS, which refer to C#, Visual Basic .NET, and JScript .NET, respectively.
Introduction
The transaction support for XML Web services created using ASP.NET is based on the same
distributed transaction model found in the COM+ Services. This model is based on declaring
attributes to decide whether an object participates in a transaction, rather than writing specific code to
commit / roll back a transaction.
Once an XML Web service method is marked to participate in a transaction, it will automatically
execute within the scope of a transaction. You can control an object's transactional behavior by setting
a transaction attribute value on XML Web service method. The attribute value, in turn, determines the
transactional behavior of the instantiated object. Thus, based on the declared attribute value, an
object will automatically participate in an existing or ongoing transaction, be the root of a new
transaction, or never participate in a transaction at all.
In an XML Web service created using ASP.NET, you can declare the web method’s transactional
behavior by setting theTransactionOption property of the WebMethod attribute applied to an
XML Web service method. If an exception is thrown while the XML Web service method is executing,
the transaction is automatically aborted; conversely, if no exception occurs, the transaction is
automatically committed.
Lets look at the TransactionOption enumeration:
Disabled: Ignores any transaction in the current context.
NotSupported: Creates the component in a context with no governing transaction.
Required: Shares a transaction if one exists, and creates a new transaction if necessary.
RequiresNew: Creates the component with a new transaction, regardless of the state of the
current context.
Supported: Shares a transaction, if one exists.
To participate in a transaction from an XML Web service method:
1. Declare an XML Web service.
Collapse | Copy Code
using System.Web.Services;
using System.EnterpriseServices;
4. Declare an XML Web service method, setting the TransactionOption property of
the WebMethod attribute toTransactionOption.RequiresNew.
Collapse | Copy Code
[ WebMethod(TransactionOption=TransactionOption.RequiresNew)]
public int DeleteAuthor(string lastName)
The following code example shows an XML Web service that exposes a single XML Web service
method, calledDBOperations. This XML Web service method performs a database operation that is
scoped within a transaction. If the database operation does throw an exception, the transaction is
automatically stopped; otherwise, the transaction is automatically committed.
Collapse | Copy Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.EnterpriseServices;
[ WebMethod(TransactionOption=TransactionOption.RequiresNew)]
public int DeleteAuthor(string lastName)
{
String delCmdSql =
"DELETE FROM authors WHERE au_lname='" + lastName + "'" ;
String exceptionCausingCmdSQL =
"DELETE FROM NonExistingTable WHERE au_lname='" + lastName + "'" ;
SqlConnection myCon =
new SqlConnection("user id=sa;database=pubs;server=myserver");
SqlCommand delCmd = new SqlCommand(delCmdSQL,myCon);
SqlCommand exceptionCausingCmd = new
SqlCommand(exceptionCausingCmdSQL,myCon);
Let us look at an example of how the transaction occurs across XML Web service methods.
Consider we are having two servers Server1 and Server2. Server1 hosts XML Web Services WService1
and WService2. Server2 hosts WService3.
[WebMethod(TransactionOption.RequiresNew)]
public void WMethod1 ()
{
Server1. WService2 Service2 = new Server1. WService2 ();
Server2.WService3 Service3 = new Server2. WService3 ();
Service2.WMethod2();
Service3.WMethod3();
}
The TransactionOption property of WMethod2 and WMethod3 are set
to TransactionOption.Required.
Collapse | Copy Code
[WebMethod(TransactionOption.Required)]
public void WMethod2 ()
{
//Code to update a row in a table
}
[WebMethod(TransactionOption.Required)]
public void WMethod3 ()
{
//Code to update a row in another table
}
Develop a client application named myApp that consumes Wmethod1 of WService1. Run myApp.
While WMethod1 is calling WMethod3, close myApp.
What is the most likely result? What do you expect? A roll back of the updates made
by WMethod2 and WMethod3?
No, the Answer is Wmethod1 continues processing, and whatever updates that are made by
the WMethod2 andWMethod3 persists, because transactions do not flow across XML Web service
methods.
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, as
transactions do not flow across XML Web service methods.