Showing posts with label SOAP. Show all posts
Showing posts with label SOAP. Show all posts

Monday, October 22, 2012

Introducing Serialization in C#.NET

Introducing Serialization in .NET

he serialization is process of convert an object type into stream of bytes.
There are several types

1) Binary serialization
2) SOAP serialization
3) XML serialization
4) Custom serialization


Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

 Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another. 

XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.




Serialization is the process of saving the state of an object in a persistent storage media by converting the object to a linear stream of bytes.  The object can be persisted to a file, a database or even in the memory.  The reverse process of serialization is known as de-serialization and enables us to re-construct the object from the previously serialized instance of the same in the persistent or non-persistent storage media.
Serialization in .NET is provided by the System.Runtime.Serialization namespace.  This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream.  In order to implement serialization in .NET, we basically require a stream and a formatter.  While the stream acts as a container for the serialized object(s), the formatter is used to serialize these objects onto the stream.
The basic advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object if required at a later point of time by de-serializing the object.  Remoting and Web Services depend heavily on Serialization and De-serialization.  Refer to the figure below.
The following are the basic advantages of serialization:
·         Facilitate the transportation of an object through a network
·         Create a clone of an object
The primary disadvantage of serialization can be attributed to the resource overhead (both the CPU and the IO devices) that is involved in serializing and de-serializing the data and the latency issues that are involved for transmitting the data over the network.  Further, serialization is quite slow.  Moreover, XML serialization is insecure, consumes a lot of space on the disk and it works on public members and public classes and not on the private or internal classes.  Therefore, it compels the developer to allow the class to be accessed to the outside world.


The Serializable Attribute


In order for a class to be serializable, it must have the attribute SerializableAttribute set and all its members must also be serializable, except if they are ignored with the attribute NonSerializedAttribute.  However, the private and public members of a class are always serialized by default.  The SerializationAttribute is only used for the binary serialization.  The code snippet below shows the usage of SerializableAttribute.
Listing1:
[Serializable]
public class Employee
{
   public int empCode;
   public string empName;
}
Note the Serializable attribute that is specified at the beginning of the class in the code listing above.  The SerializableAttribute is useful for situations where the object has to be transported to other application domains.  It needs to be applied even irrespective of whether the class implements the ISerializable interface.  If this attribute is not set in that case, then when we try to serialize an object the CLR throws a SerializationException.
Types of Serialization


Serialization can be of the following types:
·         Binary Serialization
·         SOAP Serialization
·         XML Serialization
·         Custom Serialization
All these types of serialization are explained in details in the sections that follow.
Binary Serialization
Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically.  The term binary in its name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media.  A notable difference between Binary serialization and XML serialization is that Binary serialization preserves instance identity while XML serialization does not.  In other words, in Binary serialization the entire object state is saved while in XML serialization only some of the object data is saved.  Binary serialization can handle graphs with multiple references to the same object; XML serialization will turn each reference into a reference to a unique object.  The following code listing shows how we can implement binary serialization.
Listing 2:
public void BinarySerialize(string filename, Employee emp)
{
  FileStream fileStreamObject;
  try
  {
    fileStreamObject = new FileStream(filename, FileMode.Create);
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    binaryFormatter.Serialize(fileStreamObject, emp);
  }
  finally
  {
    fileStreamObject.Close();
  }
}
The following code listing shows how we can implement binary de-serialization.
Listing 3:
public static object BinaryDeserialize(string filename)
{
  FileStream fileStreamObject;
 
  try
  {
    fileStreamObject = new FileStream(filename, FileMode.Open);
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    return (binaryFormatter.Deserialize(fileStreamObject));
  }
  finally
  {
    fileStreamObject.Close();
  }
}
Advantages and Disadvantages of Binary Serialization


One of the major advantages of using Binary Serialization in the managed environment is that the object can be de-serialized from the same data you serialized it to.  Besides, the other advantage of Binary Serialization is enhanced performance as it is faster and even more powerful in the sense that it provides support for complex objects, read only properties and even circular references.  However, the downside to this is that it is not easily portable to another platform.
SOAP Serialization


The SOAP protocol is ideal for communicating between applications that use heterogeneous architectures.  In order to use SOAP serialization in .NET we have to add a reference to System.Runtime.Serialization.Formatters.Soap in the application.  The basic advantage of SOAP serialization is portability.  The SoapFormatter serializes objects into SOAP messages or parses SOAP messages and extracts serialized objects from the message.  The following code listing shows how we can implement serialization using the SOAP protocol.
Listing 4:
public void SOAPSerialize(string filename,Employee employeeObject)
{
  FileStream fileStreamObject = new FileStream(filename, FileMode.Create);
  SoapFormatter soapFormatter = new SoapFormatter();
  soapFormatter.Serialize(fileStreamObject, employeeObject);
  fileStreamObject.Close();
}
The following code listing shows how we can implement de-serialization using the SOAP protocol.
Listing 5:
public static object SOAPDeserialize(string filename)
{
  FileStream fileStreamObject = new FileStream(filename, FileMode.Open);
  SoapFormatter soapFormatter = new SoapFormatter();
  object obj = (object)soapFormatter.Deserialize(fileStreamObject);
  fileStreamObject.Close();
  return obj;
}
XML Serialization


According to MSDN, "XML serialization converts (serializes) the public fields and properties of an object or the parameters and returns values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport. Because XML is an open standard, the XML stream can be processed by any application, as needed, regardless of platform."  Implementing XML Serialization in .Net is quite simple.  The basic class that we need to use is the XmlSerializer for both serialization and de-serialization.  The Web Services use the SOAP protocol for communication and the return types and the parameters are all serialized using the XmlSerializer class.  XML Serialization is however, much slower compared to Binary serialization.  We can set a property as an XML attribute as shown in the code listing below.
Listing 6:
[XmlAttribute("empName")]
public string EmpName
{
  get
  {
    return empName;
  }
  set
  {
    empName = value;
  }
}
The following code listing shows how we can implement XML serialization.
Listing 7:
public void XMLSerialize(Employee emp, String filename)
{
  XmlSerializer serializer = null;
  FileStream stream = null;
  try
  {
    serializer = new XmlSerializer(typeof(Employee));
    stream = new FileStream(filename, FileMode.Create, FileAccess.Write);
    serializer.Serialize(stream, emp);
  }
  finally
  {
    if (stream != null)
      stream.Close();
  }
}
The following code listing shows how we can implement XML de-serialization.
Listing 8:
public static Employee XMLDeserialize(String filename)
{
  XmlSerializer serializer = null;
  FileStream stream = null;
  Employee emp = new Employee();
  try
  {
    serializer = new XmlSerializer(typeof(Employee));
    stream = new FileStream(filename, FileMode.Open);
    emp = (Employee)serializer.Deserialize(stream);
  }
  finally
  {
    if (stream != null)
      stream.Close();
  }
  return emp;
}
Advantages of XML Serialization


The advantages of XML Serialization are as follows:
·         XML based
·         Support for cross platforms
·         Easily readable and editable
Working with Formatters


A formatter is used to determine the serialization format for objects.  In other words, it is used to control the serialization of an object to and from a stream.  They are the objects that are used to encode and serialize data into an appropriate format before they are transmitted over the network.  They expose an interface called the IFormatter interface.  IFormatter's significant methods are Serialize and De-serialize which perform the actual serialization and de-serialization. There are two formatter classes provided within .NET, the BinaryFormatter and the SoapFormatter.  Both these classes extend the IFormatter interface.
The Binary Formatter
The Binary formatter provides support for serialization using binary encoding.  The BinaryFormater class is responsible for binary serialization and is used commonly in .NET's Remoting technology.  This class is not appropriate when the data is supposed to be transmitted through a firewall.
The SOAP Formatter
The SOAP formatter provides formatting that can be used to serialize objects using the SOAP protocol.  It is used to create a Soap envelop and it uses an object graph to generate the result.  It is responsible for serializing objects into SOAP messages or parsing the SOAP messages and extracting these serialized objects from the SOAP messages.  SOAP formatters in .NET are widely used by the Web Services.
Custom Serialization


In some cases, the default serialization techniques provided by .NET may not be sufficient in real life.  This is when we require implementing custom serialization.  It is possible to implement custom serialization in .NET by implementing the ISerializable interface.  This interface allows an object to take control of its own serialization and de-serialization process.  It gives us a great deal of flexibility in the way we can save and restore objects.  The ISerializable interface consists of a single method, GetObjectData, which accepts two parameters.
The SerializationInfo class serves as the container for all the data we want to serialize.  The AddValue method is called to add the objects we want to serialize to this container.  The implementing class needs to have the GetObjectData method and a special constructor which is used by the common language runtime during the process of de-serialization.  The following code listing shows how we can implement Custom Serialization.
Listing 9:
public class Employee: ISerializable
{
  private int empCode;
  private string empName;
  protected Employee(SerializationInfo serializationInfo, StreamingContext
    streamingContext)
  {
    this.empCode = serializationInfo.GetInt32("empCode");
    this.empName = serializationInfo.GetString("empName");
  }
  public void ISerializable.GetObjectData(SerializationInfo serializationInfo,
    StreamingContext streamingContext)
  {
    serializationInfo.AddValue("empCode"this.empCode);
    serializationInfo.AddValue("empName"this.empName);
  }
}
The following listing shows how we can implement Custom Serialization on a Custom Collection class that extends the CollectionBase class of the System.Collections namespace.
Listing 10
[Serializable]
public class EmployeeCollection: System.Collections.CollectionBase,
  ISerializable
{
  private int empCode;
 
  public EmployeeCollection()
  {
    empCode = 1;
  }
 
  protected EmployeeCollection(SerializationInfo info, StreamingContext context)
    : base(info, context)
  {
    empCode = info.GetInt32("empCode");
  }
 
  public virtual void GetObjectData(SerializationInfo info, StreamingContext
    context)
  {
    base.GetObjectData(info, context);
    info.AddValue("empCode", empCode);
  }
}
Points to remember


This section deals with some of the points that we have already covered in this article and some others that we have not, but are still very important and relate to the serialization and de-serialization concepts of .NET.
When you apply the Serializable custom attribute to a type, all instance fields of the class (public, private, protected, etc.) are serialized automatically.
XmlSerializer does not use the ISerializable interface; rather, it uses the IXmlSerializable interface.  The XmlSerializer class can only serialize the public properties of the class, whereas the BinaryFormatter class can serialize private fields using the ISerializable interface.
The Serializable attribute is a must for making a class serializable irrespective of whether we have implemented the ISerializable interface in this class.  When we serialize a class, the objects of the references to other classes that are contained in this class are also serialized if they are marked as serializable.  All members are serialized, including public, private or protected members. Furthermore, even circular references are supported by binary serialization.  Note that read only properties are not serialized except the collection class objects.  However, the read only properties can be serialized using binary serialization.
If we do not require serializing a particular property of a class when using an XmlSerializer, we have to mark the property with the custom attribute XmlIgnoreAttribute.  When using a SoapFormatter we have to use the SoapIgnoreAttribute instead.  The XmlSerializer generates an in-memory assembly optimized for each type since the initial invocation to a Web Service always takes so much time.  To combat this, we can use the sgen.exe tool to pre-generate the serialization assembly.
References

Conclusion


Serialization is the process of storing an object, including all of its members, to a persistent or a non-persistent storage media by converting the object into a linear stream of data.  De-serialization is the process of restoring an object's values from the said stream.  The advantage of serialization is to save the state of an object in order to have the ability to recreate the same object at a later point of time if and when it is required.  The .NET Framework provides a strong support for serialization of objects.  The .NET Framework provides a unified standard for serializing and de-serializing objects for building distributed heterogeneous systems.  This article has explored Serialization and De-serialization and the various types of Serialization concepts with code examples wherever necessary.  It has discussed what Custom Serialization is and how to implement it.  However, I would recommend not using serialization unless it is absolutely necessary due to the drawbacks that I have already explained in this article.  I hope that the readers will find this article quite useful and post their comments and suggestions on this article. Happy reading!

Thursday, October 18, 2012

Using SOAP Headers with ASP.NET 2.0 Web Services


Using SOAP Headers with ASP.NET 2.0 Web Services

by Thiru Thangarathinam
When you communicate with a Web service using SOAP, the SOAP message that is sent to the Web service follows a standard format. The XML document inside the SOAP message is structured into two main parts: the optional headers and the mandatory body. The Body element comprises the data specific to the message. The optional Header element can contain additional information not directly related to the particular message. Each child element of the Header element is called a SOAP header.
SOAP headers are also a good place to put optional information, and a good means to supporting evolving interfaces. For example, imagine your bank allows you to manage multiple accounts with one ATM card. If you use your bank's ATM, you now have to specify if you want the withdrawal to be made from my primary, secondary, or tertiary account. If you use an ATM from another bank that isn't affiliated with you bank, you do not get asked that question. So the account identifier is clearly an optional parameter, with a reasonable default.
ASP.NET provides a mechanism for defining and processing SOAP headers. You can define a new SOAP header by deriving from the SoapHeader class. After you define a SOAP header, you can then associate the header with a particular endpoint within the Web service by using the SoapHeaderattribute. Table 1 lists the properties exposed by the SoapHeader class.
Table 1. Properties of the SoapHeader Class
PropertyDescription
ActorIndicates the intended recipient of the header.
DidUnderstandIndicates whether a header whose mustUnderstand attribute istrue was understood and processed by the recipient.
EncodedMustUnderstandIndicates whether a header whose mustUnderstand attribute istrue and whose value is encoded was understood and processed by the recipient. This property is used when communicating with the SOAP 1.1 version.
EncodedMustUnderstand12Very similar to EncodedMustUnderstand except that it is used in conjunction with SOAP 1.2 version.
MustUnderstandIndicates whether the header must be understood and processed by the recipient.
RelayIndicates if the SOAP header is to be relayed to the next SOAP node if the current node does not understand the header.
RoleIndicates the recipient of the SOAP header.
By default, the name of the class derived from SoapHeader will become the name of the root header element, and any public fields or properties exposed by the class will define elements within the header. SOAP headers are defined by classes derived from the SoapHeader class. Elements within the header are defined by public fields or read/writable properties.

Implementing a SOAP Header Class

Imagine you want to modify the QuotesService used in the previous examples to accept a SOAP header that contains the payment information. Listing 1 illustrates the definition of the Payment header.
Listing 1: SOAP Header Declaration
using System;
using System.Xml;
using System.Xml.Serialization;
using System.Web.Services.Protocols;
public class SoapPaymentHeader : SoapHeader
{
  private string nameOnCard;
  private string creditCardNumber;
  private CardType creditCardType;
  private DateTime expirationDate; 
  public string NameOnCard
  {
    get { return nameOnCard; }
    set { nameOnCard = value; }
  }
  public string CreditCardNumber
  {
    get { return creditCardNumber; }
    set { creditCardNumber = value; }
  }
  public CardType CreditCardType
  {
    get { return creditCardType; }
    set { creditCardType = value; }
  }
  public DateTime ExpirationDate
  {
    get { return expirationDate; }
    set { expirationDate = value; }
  } 
}
The preceding class definition defines a SOAP header named SoapPaymentHeader with four child elements: NameOnCardCreditCardNumberCreditCardType, and ExpirationDate.
This code uses an enum named CardType that is declared as follows:
public enum CardType
{
  VISA,
  MASTERCARD,
  AMX,
  DISCOVER
}
After you define the headers, the next step is to associate them with the actual Web service method.

Processing the SOAP Header from a Web Service

The SoapHeader attribute is used to associate a SOAP header with a Web method. A public member variable is added to the WebService class to hold an instance of the class derived from theSoapHeader class. The name of the member variable is then communicated to the ASP.NET runtime via the SoapHeader attribute. Listing 2 shows the modified QuotesService class definition that is now capable of processing the SoapPaymentHeader.
Listing 2: Web Service Method That Processes the SOAP Header
using System;
using System.Xml;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class QuotesService : System.Web.Services.WebService
{
  public SoapPaymentHeader paymentHeader;
  [WebMethod(Description = 
   "Returns real time quote for a given stock ticker")]
  [SoapHeader("paymentHeader", Direction = SoapHeaderDirection.In)]
  public double GetStockPriceWithPayment(string symbol)
  {
    //Process the SOAP header
    if (paymentHeader != null)
    {
      string nameOnCard = paymentHeader.NameOnCard;
      string creditCardNumber = paymentHeader.CreditCardNumber;
      CardType type = paymentHeader.CreditCardType;
      DateTime ExpirationDate = paymentHeader.ExpirationDate;
      //Process the payment details
      //.........
      ///End Processing
    }
    else 
      throw new SoapHeaderException("Invalid information in SOAP Header", 
        SoapException.ClientFaultCode);
    double price;
    switch (symbol.ToUpper())
    {
      case "INTC":
        price = 70.75;
        break;
      case "MSFT":
        price = 50;
        break;
      case "DELL":
        price = 42.25;
        break;
      default:
        throw new SoapException("Invalid Symbol", 
   SoapException.ClientFaultCode,
          "http://wrox.com/quotes/GetStockPriceWithPayment");
    }
    return price;
  }
}
Listing 2 declares a member variable named paymentHeader to hold the data contained in the payment SOAP header.
public SoapPaymentHeader paymentHeader;
Note that you do not create an instance of the SoapPaymentHeader class because the ASP.NET runtime is responsible for creating this object and populating its properties with the data contained within the payment header received from the client.
Next you add two SoapHeader attributes to declare that the headers should formally be described as part of the Web method. The constructor of the SoapHeader attribute takes a string that contains the name of the public member variable that should be associated with the SOAP header.
[SoapHeader("paymentHeader", Direction = SoapHeaderDirection.In)]
You set the Direction property to SoapHeaderDirection.In. The Direction property indicates whether the client or the server is supposed to send the header. In this case, because the payment header is received from the client, you set the Direction property to SoapHeaderDirection.In. If a SOAP header is received from the client and then also sent back to the client, the value of theDirection property should be set to SoapHeaderDirection.InOut.
Next the code processes the contents of the SOAP payment header. If the payment header information is not passed in, you throw a SoapHeaderException back to the callers.
throw new SoapHeaderException("Invalid information in SOAP Header", 
  SoapException.ClientFaultCode);
The rest of the implementation is similar to the previous example.
Now that you have associated the payment header with the Web method, the next task is to send the payment SOAP header from the client. Listing 3 shows the ASP.NET pages that creates an instance of the SOAP payment header and sends that as part of the SOAP request that is sent to the server.
Listing 3: Passing SOAP Header Information to a Web Service Method
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services.Protocols" %>
<script runat="server">
  void btnGetQuote_Click(object sender, EventArgs e)
  {
    try
    {
      QuotesProxy.SoapPaymentHeader header = new 
        QuotesProxy.SoapPaymentHeader();
      header.CreditCardNumber = "xxxxxxxxxxxxxxxx";
      header.CreditCardType = QuotesProxy.CardType.VISA;
      header.NameOnCard = "XXXXXX";
      header.ExpirationDate = DateTime.Today.AddDays(365);
      QuotesProxy.QuotesService obj = new QuotesProxy.QuotesService();
      obj.SoapPaymentHeaderValue = header;
      output.Text = 
    obj.GetStockPriceWithPayment(txtSymbol.Text).ToString();
    }
    catch (SoapHeaderException soapEx)
    {            
      output.Text = "Actor : " + soapEx.Actor + "<br><br>";
      output.Text += "Code  : " + soapEx.Code + "<br><br>";
      output.Text += "Message: " + soapEx.Message + "<br><br>";
      output.Text += "Detail: 
    " + Server.HtmlEncode(soapEx.Detail.OuterXml);
    }
    catch (Exception ex)
    {
      output.Text = "Exception is : " + ex.Message;
    }
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
  <title>Passing SOAP Headers to a Web Service Method</title>
</head>
<body>
  <form id="form1" runat="server">
    <div>
      Enter Stock Symbol: <asp:TextBox runat="server" ID="txtSymbol" />
      <asp:Button Text="Get Quote" runat="server" ID="btnGetQuote" 
        OnClick="btnGetQuote_Click" />
      <br /><br /><br />
      <asp:Label Font-Bold=true runat="server" ID="output" />
    </div>
  </form>
</body>
</html>
To start with, Listing 3 creates an instance of the SoapPaymentHeader object and sets its properties to appropriate values. It then sets the SoapPaymentHeaderValue property of the proxy object to theSoapHeader object.
obj.SoapPaymentHeaderValue = header;
After you set the SoapPaymentHeaderValue property, the contents of the SOAP header will be automatically transferred as part of the SOAP message. Next you also handle any errors thrown by the Web service using two catch blocks: SoapHeaderException block and a generic Exception block.


Wednesday, October 17, 2012

Introduction Web services 1.0


Introduction Web services 


Web services are open standard ( XML, SOAP, HTTP etc.) based Web applications that interact with other web applications for the purpose of exchanging data
Web Services can convert your existing applications into Web-applications.
In this tutorial you will learn what exactly Web Services are and Why and How to use them.

What are Web Services

Few definitions are given here and all the definitions are correct.
  • A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. For example, a client invokes a web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, web services are not tied to any one operating system or programming language--Java can talk with Perl; Windows applications can talk with Unix applications.
  • Web Services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or Web-based. Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML.
  • Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can include programs, objects, messages, or documents.
  • A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards.
To summarize, a complete web service is, therefore, any service that:
  • Is available over the Internet or private (intranet) networks
  • Uses a standardized XML messaging system
  • Is not tied to any one operating system or programming language
  • Is self-describing via a common XML grammar
  • Is discoverable via a simple find mechanism

Components of Web Services?

The basic Web services platform is XML + HTTP. All the standard Web Services works using following components
  • SOAP (Simple Object Access Protocol)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)
All these components have been discussed in Web Services Architecture section.

How Does it Work?

You can build a Java-based Web Service on Solaris that is accessible from your Visual Basic program that runs on Windows. You can also use C# to build new Web Services on Windows that can be invoked from your Web application that is based on JavaServer Pages (JSP) and runs on Linux.

An Example

Consider a simple account-management and order -processing system. The accounting personnel use a client application built with Visual Basic or JSP to create new accounts and enter new customer orders.
The processing logic for this system is written in Java and resides on a Solaris machine, which also interacts with a database to store the information.
The steps illustrated above are as follows:
  1. The client program bundles the account registration information into a SOAP message.
  2. This SOAP message is sent to the Web Service as the body of an HTTP POST request.
  3. The Web Service unpacks the SOAP request and converts it into a command that the application can understand. The application processes the information as required and responds with a new unique account number for that customer.
  4. Next, the Web Service packages up the response into another SOAP message, which it sends back to the client program in response to its HTTP request.
  5. The client program unpacks the SOAP message to obtain the results of the account registration process. For further details regarding the implementation of Web Services technology, read about the Cape Clear product set and review the product components.

Why Web Services ?

Here are the benefits of using Web Services
  • Exposing the existing function on to network:

    A Web service is a unit of managed code that can be remotely invoked using HTTP, that is, it can be activated using HTTP requests. So, Web Services allows you to expose the functionality of your existing code over the network. Once it is exposed on the network, other application can use the functionality of your program.
  • Connecting Different Applications ie Interoperability:

    Web Services allows different applications to talk to each other and share data and services among themselves. Other applications can also use the services of the web services. For example VB or .NET application can talk to java web services and vice versa. So, Web services is used to make the application platform and technology independent.
  • Standardized Protocol:

    Web Services uses standardized industry standard protocol for the communication. All the four layers (Service Transport, XML Messaging, Service Description and Service Discovery layers) uses the well defined protocol in the Web Services protocol stack. This standardization of protocol stack gives the business many advantages like wide range of choices, reduction in the cost due to competition and increase in the quality.
  • Low Cost of communication:

    Web Services uses SOAP over HTTP protocol for the communication, so you can use your existing low cost internet for implementing Web Services. This solution is much less costly compared to proprietary solutions like EDI/B2B. Beside SOAP over HTTP, Web Services can also be implemented on other reliable transport mechanisms like FTP etc.

    Services Behavioral Characteristics
    Web services have special behavioral characteristics
    • XML-based

      Web Services uses XML at data representation and data transportation layers. Using XML eliminates any networking, operating system, or platform binding. So Web Services based applications are highly interoperable application at their core level.
    • Loosely coupled

      A consumer of a web service is not tied to that web service directly. The web service interface can change over time without compromising the client's ability to interact with the service. A tightly coupled system implies that the client and server logic are closely tied to one another, implying that if one interface changes, the other must also be updated. Adopting a loosely coupled architecture tends to make software systems more manageable and allows simpler integration between different systems.
    • Coarse-grained

      Object-oriented technologies such as Java expose their services through individual methods. An individual method is too fine an operation to provide any useful capability at a corporate level. Building a Java program from scratch requires the creation of several fine-grained methods that are then composed into a coarse-grained service that is consumed by either a client or another service. Businesses and the interfaces that they expose should be coarse-grained. Web services technology provides a natural way of defining coarse-grained services that access the right amount of business logic.
    • Ability to be synchronous or asynchronous

      Synchronicity refers to the binding of the client to the execution of the service. In synchronous invocations, the client blocks and waits for the service to complete its operation before continuing. Asynchronous operations allow a client to invoke a service and then execute other functions. Asynchronous clients retrieve their result at a later point in time, while synchronous clients receive their result when the service has completed. Asynchronous capability is a key factor in enabling loosely coupled systems.
    • Supports Remote Procedure Calls (RPCs)

      Web services allow clients to invoke procedures, functions, and methods on remote objects using an XML-based protocol. Remote procedures expose input and output parameters that a web service must support. Component development through Enterprise JavaBeans (EJBs) and .NET Components has increasingly become a part of architectures and enterprise deployments over the past couple of years. Both technologies are distributed and accessible through a variety of RPC mechanisms. A web service supports RPC by providing services of its own, equivalent to those of a traditional component, or by translating incoming invocations into an invocation of an EJB or a .NET component.
    • Supports document exchange

      One of the key advantages of XML is its generic way of representing not only data, but also complex documents. These documents can be simple, such as when representing a current address, or they can be complex, representing an entire book or RFQ. Web services support the transparent exchange of documents to facilitate business integration.

    Web Services Architecture

    There are two ways to view the web service architecture.
    • The first is to examine the individual roles of each web service actor.
    • The second is to examine the emerging web service protocol stack.

    1. Web Service Roles

    There are three major roles within the web service architecture:
    • Service provider:
      This is the provider of the web service. The service provider implements the service and makes it available on the Internet.
    • Service requestor
      This is any consumer of the web service. The requestor utilizes an existing web service by opening a network connection and sending an XML request.
    • Service registry
      This is a logically centralized directory of services. The registry provides a central place where developers can publish new services or find existing ones. It therefore serves as a centralized clearinghouse for companies and their services.

    2. Web Service Protocol Stack

    A second option for viewing the web service architecture is to examine the emerging web service protocol stack. The stack is still evolving, but currently has four main layers.
    • Service transport
      This layer is responsible for transporting messages between applications. Currently, this layer includes hypertext transfer protocol (HTTP), Simple Mail Transfer Protocol (SMTP), file transfer protocol (FTP), and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP).
    • XML messaging
      This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this layer includes XML-RPC and SOAP.
    • Service description
      This layer is responsible for describing the public interface to a specific web service. Currently, service description is handled via the Web Service Description Language (WSDL).
    • Service discovery
      This layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via Universal Description, Discovery, and Integration (UDDI).
      As web services evolve, additional layers may be added, and additional technologies may be added to each layer.
    Next chapter explains about various components of Web Services.

    Few Words about Service Transport

    The bottom of the web service protocol stack is service transport. This layer is responsible for actually transporting XML messages between two computers.
    • Hyper Text Transfer Protocol (HTTP)
      Currently, HTTP is the most popular option for service transport. HTTP is simple, stable, and widely deployed. Furthermore, most firewalls allow HTTP traffic. This allows XMLRPC or SOAP messages to masquerade as HTTP messages. This is good if you want to easily integrate remote applications, but it does raise a number of security concerns.
    • Blocks Extensible Exchange Protocol (BEPP)
      One promising alternative to HTTP is the Blocks Extensible Exchange Protocol (BEEP).BEEP is a new IETF framework of best practices for building new protocols. BEEP is layered directly on TCP and includes a number of built-in features, including an initial handshake protocol, authentication, security, and error handling. Using BEEP, one can create new protocols for a variety of applications, including instant messaging, file transfer, content syndication, and network management
    SOAP is not tied to any specific transport protocol. In fact, you can use SOAP via HTTP, SMTP, or FTP. One promising idea is therefore to use SOAP over BEEP.

    Web Services Components


    Over the past few years, three primary technologies have emerged as worldwide standards that make up the core of today's web services technology. These technologies are:

    - XML-RPC

    This is the simplest XML based protocol for exchanging information between computers.
    • XML-RPC is a simple protocol that uses XML messages to perform RPCs.
    • Requests are encoded in XML and sent via HTTP POST.
    • XML responses are embedded in the body of the HTTP response.
    • XML-RPC is platform-independent.
    • XML-RPC allows diverse applications to communicate.
    • A Java client can speak XML-RPC to a Perl server.
    • XML-RPC is the easiest way to get started with web services.

    - SOAP

    SOAP is an XML-based protocol for exchanging information between computers.
    • SOAP is a communication protocol
    • SOAP is for communication between applications
    • SOAP is a format for sending messages
    • SOAP is designed to communicate via Internet
    • SOAP is platform independent
    • SOAP is language independent
    • SOAP is simple and extensible
    • SOAP allows you to get around firewalls
    • SOAP will be developed as a W3C standard
    SOAP is a simple and open standard XML-based protocol for exchanging information between computers.
    In this tutorial you will learn what is SOAP and Why and How to use it.
    SOAP is very easy to learn and to use and in demand too.

     WSDL

    WSDL is an XML-based language for describing Web services and how to access them.
    • WSDL stands for Web Services Description Language
    • WSDL is an XML based protocol for information exchange in decentralized and distributed environments.
    • WSDL is the standard format for describing a web service.
    • WSDL definition describes how to access a web service and what operations it will perform.
    • WSDL is a language for describing how to interface with XML-based services.
    • WSDL is an integral part of UDDI, an XML-based worldwide business registry.
    • WSDL is the language that UDDI uses.
    • WSDL was developed jointly by Microsoft and IBM.
    • WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'
      Web Services Description Language is the standard format for describing a web service in XML format.
      In this tutorial you will learn what is WSDL and Why and How to use it.
      WSDL is very easy to learn and very important for Web Services.

      - UDDI

      UDDI is an XML-based standard for describing, publishing, and finding Web services.
      • UDDI stands for Universal Description, Discovery and Integration.
      • UDDI is a specification for a distributed registry of Web services.
      • UDDI is platform independent, open framework.
      • UDDI can communicate via SOAP, CORBA, Java RMI Protocol.
      • UDDI uses WSDL to describe interfaces to web services.
      • UDDI is seen with SOAP and WSDL as one of the three foundation standards of web services.
      • UDDI is an open industry initiative enabling businesses to discover each other and define how they interact over the Internet.

      Web Services - Examples


      Based on the Web Service Architecture we will create following two components as a part of Web Services implementation
      • Service provider or publisher:
        This is the provider of the web service. The service provider implements the service and makes it available on the Internet or intranet.
        We will write and publish a simple web Service using .NET SDK.
      • Service requestor or consumer
        This is any consumer of the web service. The requestor utilizes an existing web service by opening a network connection and sending an XML request.
        We will also write two Web Service requestors: one Web-based consumer (ASP.NET application) and another Windows application-based consumer.
      Following is our First Web Service example which works as a service provider and exposes two methods (add and SayHello) as Web Services to be used by applications. This is a standard template for a Web Service. .NET Web Services use the .asmx extension. Note that a method exposed as a Web Service has the WebMethod attribute. Save this file as FirstService.asmx in the IIS virtual directory (as explained in configuring IIS; for example, c:\MyWebSerces).


      using System;
      using System.Linq;
      using System.Web;
      using System.Web.Services;
      using System.Web.Services.Protocols;
      using System.Xml.Linq;

      [WebService(Namespace = "http://tempuri.org/")]
      [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

      // [System.Web.Script.Services.ScriptService]
      public class Service : System.Web.Services.WebService
      {
          public Service () 
         
      {


           //InitializeComponent(); 





          }

          [WebMethod]
          public string MyClass() 
          {
             return "Our WEB_SERVER_ is Prprly RuNNing in Server Side";
          }
          
      }


      To test a Web Service, it must be published. A Web Service can be published either on an intranet or the Internet. We will publish this Web Service on IIS running on a local machine. Let's start with configuring the IIS.
      • Open Start->Settings->Control Panel->Administrative tools->Internet Services Manager.
      • Expand and right-click on [Default Web Site]; select New ->Virtual Directory.
      • The Virtual Directory Creation Wizard opens. Click Next.
      • The "Virtual Directory Alias" screen opens. Type the virtual directory name—for example, MyWebServices—and click Next.
      • The "Web Site Content Directory" screen opens. Here, enter the directory path name for the virtual directory—for example, c:\MyWebServices—and click Next.
      • The "Access Permission" screen opens. Change the settings as per your requirements. Let's keep the default settings for this exercise. Click the Next button. It completes the IIS configuration. Click Finish to complete the configuration.
      To test that IIS has been configured properly, copy an HTML file (for example, x.html) in the virtual directory (C:\MyWebServices) created above. Now, open Internet Explorer and type http://localhost/MyWebServices/x.html. It should open the x.html file. If it does not work, try replacing localhost with the IP address of your machine. If it still does not work, check whether IIS is running; you may need to reconfigure IIS and Virtual Directory.
      To test our Web Service, copy FirstService.asmx in the IIS virtual directory created above (C:\MyWebServices). Open the Web Service in Internet Explorer (http://localhost/MyWebServices/FirstService.asmx). It should open your Web Service page. The page should have links to two methods exposed as Web Services by our application. Congratulations; you have written your first Web Service!!!

      Testing the Web Service

      As we have just seen, writing Web Services is easy in the .NET Framework. Writing Web Service consumers is also easy in the .NET framework; however, it is a bit more involved. As said earlier, we will write two types of service consumers, one Web- and another Windows application-based consumer. Let's write our first Web Service consumer.

      Web-Based Service Consumer

      Write a Web-based consumer as given below. Call it WebApp.aspx. Note that it is an ASP.NET application. Save this in the virtual directory of the Web Service (c:\MyWebServices\WebApp.axpx).
      This application has two text fields that are used to get numbers from the user to be added. It has one button, Execute, that, when clicked, gets the Add and SayHello Web Services.


      After the consumer is created, we need to create a proxy for the Web Service to be consumed. This work is done automatically by Visual Studio .NET for us when referencing a Web Service that has been added. Here are the steps to be followed:
      • Create a proxy for the Web Service to be consumed. The proxy is created using the wsdl utility supplied with the .NET SDK. This utility extracts information from the Web Service and creates a proxy. Thus, the proxy created is valid only for a particular Web Service. If you need to consume other Web Services, you need to create a proxy for this service as well. VS .NET creates a proxy automatically for you when the reference for the Web Service is added. Create a proxy for the Web Service using the wsdl utility supplied with the .NET SDK. It will create FirstSevice.cs in the current directory. We need to compile it to create FirstService.dll (proxy) for the Web Service.
      c:> WSDL http://localhost/MyWebServices/FirstService.asmx?WSDL
      c:> csc /t:library FirstService.cs
      
      • Put the compiled proxy in the bin directory of the virtual directory of the Web Service (c:\MyWebServices\bin). IIS looks for the proxy in this directory.
      • Create the service consumer, which we have already done. Note that I have instantiated an object of the Web Service proxy in the consumer. This proxy takes care of interacting with the service.
      • Type the URL of the consumer in IE to test it (for example, http://localhost/MyWebServices/WebApp.aspx).

      Windows Application-Based Web Service Consumer

      Writing a Windows application-based Web Service consumer is the same as writing any other Windows application. The only work to be done is to create the proxy (which we have already done) and reference this proxy when compiling the application. Following is our Windows application that uses the Web Service. This application creates a Web Service object (of course, proxy) and calls the SayHello and Add methods on it.


      using System;
      using System.Configuration;
      using System.Data;
      using System.Linq;
      using System.Web;
      using System.Web.Security;
      using System.Web.UI;
      using System.Web.UI.HtmlControls;
      using System.Web.UI.WebControls;
      using System.Web.UI.WebControls.WebParts;
      using System.Xml.Linq;

      public partial class _Default : System.Web.UI.Page
      {
          protected void Page_Load(object sender, EventArgs e)
          {

          }
          protected void Button1_Click(object sender, EventArgs e)
          {
              MYServices.Service ws = new MYServices.Service();
              string s = ws.MyClass();
              Response.Write("<script>alert('" + s.ToString() + "')</script>");
          }
      }



      
      
      Compile it using c:>csc /r:FirstService.dll WinApp.cs. It will create WinApp.exe. Run it to test the application and the Web Service.
      Now, the question arises: How can I be sure that my application is actually calling the Web Service? It is simple to test. Stop your Web server so that the Web Service cannot be contacted. Now, run the WinApp application. It will fire a run-time exception. Now, start the Web server again. It should work.

      Web Services Security

      Security is critical to web services. However, neither the XML-RPC nor SOAP specifications make any explicit security or authentication requirements.
      There are three specific security issues with Web Services:
      • Confidentiality
      • Authentication
      • Network Security

      Confidentiality

      If a client sends an XML request to a server, then question is that can we ensure that the communication remains confidential?
      Answer lies here
      • XML-RPC and SOAP run primariy on top of HTTP.
      • HTTP has support for Secure Socktes Layer (SSL).
      • Communication can be encrypted via the SSL.
      • SSL is a proven technology and widely deployed.
      But a single web service may consist of a chain of applications. For example one large service might tie together the services of three other applications. In this case, SSL is not adequate; the messages need to be encrypted at each node along the service path, and each node represents a potential weak link in the chain. Currently, there is no agreed-upon solution to this issue, but one promising solution is the W3C XML Encryption Standard. This standard provides a framework for encrypting and decrypting entire XML documents or just portions of an XML document. Check it at http://www.w3.org/Encryption

      Authentication

      If a client connects to a web service, how do we identify the user? And is the user authorized to use the service?
      Following options can be considered but there is no clear consensus on a strong authentication scheme.
      • HTTP includes built-in support for Basic and Digest authentication, and services can therefore be protected in much the same manner as HTML documents are currently protected.
      • SOAP Security Extensions: Digital Signature (SOAP-DSIG). DSIG leverages public key cryptography to digitally sign SOAP messages. This enables the client or server to validate the identity of the other party. Check it at http://www.w3.org/TR/SOAP-dsig.
      • The Organization for the Advancement of Structured Information Standards (OASIS) is working on the Security Assertion Markup Language (SAML).

      Network Security

      There is currently no easy answer to this problem, and it has been the subject of much debate. For now, if you are truly intent on filtering out SOAP or XML-RPC messages, one possibility is to filter out all HTTP POST requests that set their content type to text/xml.
      Another alternative is to filter for the SOAPAction HTTP header attribute. Firewall vendors are also currently developing tools explicitly designed to filter web service traffic.