Creating Web Services Using .NET by irriducibili


More Info
									Creating Web Services Using .NET
Summary: This article introduces Web Services, how they are created in .NE T, and how they
can be customized to meet specific needs.

An Introduction to Web Services in .NE T
What Is A Web Service?
Attributes and SOAP
Static Methods with Web Services

What Is A Web Service?
A Web Service is a program that can be invoked in a distribut ed web environment. Web Service
technologies like SOAP, WSDL, and UDDI are standards to describe, publish, discover, and use
Web Services; they define a development model for integrating applications over the web.

Steps to Create a Web Service
    1.   Create (or use an existing) virtual directory for any folder on your computer.
    2.   Create an empty file called “test.asmx” in the folder.
    3.   Edit the file and add the following text:

<%@ WebService Language="C#" Class="MyMath" %>
using System.Web.Services;

public class MyMath
    public int Add(int num1, int num2)
         return num1+num2;

Steps to Test the Web Service
    1.   From the browser, type http://localhost/your_virt_directory/test.asmx
            An HTML page will describe your web service in “human-friendly” terms
    2.   Append “?wsdl” to the URL:
            The WSDL information for your web service will be returned.
    3.   Append “?op=A dd” to your URL (instead of ?wsld).
            Enter some numbers and click invoke
            The SOAP response is returned

                                                Page 1 of 4            
How Does the Web Service Work?
The file suffix “.asmx” means “web service” in the .NE T world. When the .NE T framework is
installed, this file type is automatically associated in IIS to an ISAPI filter called aspnet_isapi.dll.

We know that a web service is defined by a URL to a .WSDL file. In the .NE T world, this is a URL
that points to an .asmx file with a ?wsdl argument. The ISAP I filter supports the SOAP exchange
that follows. The filter invokes the .NE T compiler if the file hasn’t already been called. During
compilation, the compiler looks at the embedded attributes and WebService ASP.NE T directive in
the file and generates “metadata” that describes how the class should behave when invoked as a
web service. The metadata is put into the assembly (the .NE T term for DLL).

Directives give the compiler specific instructions for the code that is being compiled. The @
WebService directive just tells the compiler to create entry points for the ISAPI filter to call. Other
common directives are @ Application for application -specific attributes, @ Import to import a
namespace into an application, and @ Assembly to link an assembly t o the application at parse

Attributes and SOAP
Understanding Attributes
Attributes provide a declarative means to provide additional information to certain entities within
source code such as a class, method, or parameter. An attribute is enclosed within square
brackets. Each attribute definition is implemented as a .NE T class, and custom attributes can
easily be created by writing classes that inherit from the Attribute class. When the compiler
parses an attribute it invokes the underlying class and executes the associated met hod. The code
inside the method can be anything, for example, you could creat e a text file and output
information about your code. The public properties of the instantiated attribute class are
automatically serialized by the compiler and the data is included as metadata in the resulting
assembly (similar to a DLL). In .NE T, metadata is very rich—all kinds of information is captured
and saved when code is compiled. A namespace called Reflection provides mechanisms for
querying this metadata. Most commonly, attributes are used this way —the classes simply expose
properties that are set by the compiler when attribute tags are encountered and the compiler
includes this information in the metadata. Subsequent tools read the metadata to get this extra
information about the code that describes behavior particular to that function. For example,
service component attributes describe COM+ application properties, and SOAP attributes
describe information needed for invoking the methods as SOAP calls.

Customization SOAP with Attributes
Create another file in the same directory called “wow.asmx” and paste the following code into it.
Use the URL calls to check that it works.

<%@ WebService Language="C#" Class="MyService" %>
using System;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;

public class Order

                                                 Page 2 of 4               
     [SoapElement(ElementName = "EncodedOrderID")]
     [XmlElement(ElementName = "LiteralOrderID")]
     public String OrderID;

public class MyService
    public Order MyLiteralMethod()
         Order myOrder = new Order();
         myOrder.OrderID = "L123";
         return myOrder;

public Order MyEncodedMethod()
    Order myOrder = new Order();
    myOrder.OrderID = "E123";
    return myOrder;

This example demonstrates some advanced features:
           The Order class can be serialized without any special code
           There are different styles for making SOAP calls

Classes Know How to Serialize Themselves
Serialization is the process of converting the state of an object into a form that can be persisted or
transported. The .NE T framework features two serializing technologies:
           Binary serialization, which preserves the complete state of an o bject between
            different invocations of an application. For example, you can share an object
            between different applications by serializing it to the clipboard.
           XML serialization, which serializes public properties and fields. This is useful when
            you want to provide or cons ume data without restricting the application that uses the

Because XML is an open standard, XML serialization is an attractive choice for sharing data
across the web. It is not necessary to write any special code to perform XML serial ization and
deserialization—it is built right into the .NE T framework. You can change the default serialization
behavior by using attributes.

Literal and Encoded Styles
The XML generated by an XML web servic e can be formatted in either one of two ways: lit eral or
encoded. This affects how the WSDL describes the arguments and returned result for the web
service met hod call. When literal is used, this is considered “doc ument style”—each argument is
an XML document described by an XML schema (XSD). When encode d is used, this is
considered “RP C style”—each argument is described as a data type.

                                              Page 3 of 4              
For our purposes, document style works well bec ause we often want to pass a complex set of
data that would be burdensome to describe as many arguments. It is much easier t o define it as
an XML schema structure and pass the whole thing as a single SOAP argument.
Within the System.XML.Serialization namespace there are a set of attributes beginning with
SOAP and a set beginning with XML. When customizing the behavior of a web service, use the
SOAP* attributes for RP C style calls and the XML* attributes for doc ument style calls.

Static Methods with Web Services
Static Methods and Instance Methods
In .NE T a static method is complet ely stateless. You call it from the class defini tion—not from an
instance of a class. The more typical method is an instance met hod —it is invoked from an
instance of a class, i.e. an object. Properties are only relevant to instance methods. In fact, the
compiler won’t allow a static method to access any property or variable that is not also static.

In object-oriented programming we typically work wit h instances of classes. Working with static
methods from a class definition is akin to making an AP I call—it doesn’t embody the principles of
encapsulation of data and functionality.

Static Methods and Web Services
Static methods sound like they would make ideal web services. With a web service there isn’t any
state to maintain. You make the call and pass all the data wit h it, you get back the results, and
then you are done. Properties have no use. Somewhat paradoxically, .NET doesn’t allow a static
method to be given the “WebMethod” attribute. You can think about why this may be the case

What we end up with is the creation of instances of classes wit h methods that are not static but
may as well be, bec ause they don’t depend on any data already setup in the class. Rich data can
be passed in arguments and returned though, bec ause objects are allowed as parameters. The
serialization capability does a great job of representing the public interfac e of any class
automatically as XML to support a doc ument-style web service call.

We still want to embody the concept of true OO-classes, so we think about modeling our
requirements around both static-style activities and objects that represent data and functionality
for a logical “entity”. Look at the Directory and DirectoryInfo classes in the System.IO namespace
for an example of this in practice.

In this article, we have introduc ed Web Services in .NE T. We have demonstrated how simple
they are to create and test, and how they can be customized using attributes. Finally, we have
looked at how object-oriented principles in coding can be unified with the Web Services model.

                                               Page 4 of 4             

To top