Thursday, 12 April 2012

Web Services: Exposing and Consuming

A Web Service is programmable application logic accessible via standard Web protocols. One of these Web protocols is the Simple Object Access Protocol (SOAP). SOAP uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.

Consumers of a Web Service do not need to know anything about the platform, object model, or programming language used to implement the service; they only need to understand how to send and receive SOAP messages (HTTP and XML).

Example:

We'll use an Add() method that accepts two Integers and returns their sum. Below is this simple Visual Basic logic:

Public Class MyMath
  Public Function Add(a As Integer, b As Integer) As Integer
    Return a + b
  End Function
End Class

We could use this class and its method as follows:

Dim mymath As new MyMath
Dim result As Integer
result = mymath.Add(10, 20)

To expose the above class, MyMath, as an ASP.NET Web Service we need to move the application logic into a *.asmx file. Just as we use the extension *.aspx for ASP.NET Pages, we use *.asmx to tell ASP.NET that the file is an ASP.NET Web Service.

After we created the *.asmx source file and add our application logic, we need to make a few more small changes:


 <%@ WebService Language="VB" Class="MyMath" %>
Public Class MyMath
  Public Function <WebMethod()>Add(a As Integer, b As Integer) As Integer
    Return a + b
  End Function
End Class

Exposing

The changes we've made to the *.asmx file include adding a WebService directive that names both the Language as well as the Class we're exposing as a Web Service. The WebService directive is required, as we must tell ASP.NET the class that contains the application logic. Next, we've added a <WebMethod()> attribute to our Add() function declaration. An attribute is a declarative code element that lets us change the behavior of our application logic without necessarily writing more code. In the case of the <WebMethod()> attribute, this tells ASP.NET that the method with this attribute is to be treated as 'Web callable'. Web callable in the sense that ASP.NET does the necessary work for this method to support SOAP.

Consuming

There are many ways to consume Web Services and have three examples. The first one uses HTTP-POST/HTTP-GET protocol and it has advantage to coexist with today’s application quite well. The second one uses SOAP Proxy Client Object generated by WSDL utility and it provides programmers with their familiar object modal that they call methods provided by the generated Proxy Interface. The final one uses SOAP standard request message and it parses SOAP response message with the help of XMLHTTP COM object that is installed by Microsoft XML Parser 3.0.
.
 

No comments:

Post a Comment