.NET Web Services

Abstract

Software Developers have struggled to create software components that can be called remotely over your local networks and the internet. In this process several technologies have come into light but some of them are not quite successful due to many limitations and hurdles such as communication over an unreliable internet, or network of computers running on diverse types of hardware and operating systems.

This is where XML web services are useful. To interact with a web service you simply need to send an XML message over HTTP. Because every internet-enabled device supports HTTP and every programming framework includes a higher-level toolkit that enables communication with a web service (XML is platform-independent). XML web services are not .NET Framework specific, they can also be consumed in other programming frameworks, such as Java, PHP, AJAX, ASP and so on.

Distributed Computing Technologies

Distributed computing is the partitioning of application logic into units that are executed on two or more computers in a network. There are numerous technologies that has been developed to allow the distribution and reuse of application logic.

The following is a comparison of various Distributed Technologies:

Characteristics

Web Services

DCOM

CORBA

Cross Platform

Yes

NO

Partly

Firewall Friendly

LOW

HIGH

HIGH

Protocol Complexity

Yes

NO

NO

Discovery

UDDI

Registry

Naming Service

Interface Description

WSDL

IDL

IDL

RPC Mechanism

HTTP

DCE-RPC

IIOP

Encoding

XML

NDR

CDR

Many reasons exist for distributed application logic such as the following: 

  • High Scalability
  • Improved Security
  • Easy Deployment
  • Load Balancing

Problem with Distributed Components

In a major enterprise, very rarely do you find that the entire organization and its data repository reside on a single vendor platform. Organizations consist of a patchwork of systems, some based on Microsoft, some on UNIX, FREEBSD and others. So there is a big question, how do these disparate systems communicate with each other? Interoperatibilty and load balancing issues are prevalent in CORBA and DCOM because they were developed before the advent of the internet. They are fine for building enterprise applications with software running on the same platform and not appropriate for spanning platforms and the internet.

Advantage of Web Services

  • Web service is simple to build and supported on a wide range of platforms.
  • Web service can extend its interface and add new methods without affecting the client's operations.
  • Web service is firewall friendly because all communication happens using HTTP on port 80.
  • Web service are stateless, there is no permanent connection that scale up the many clients.

Building Simple Web Services

At this point, I will show you, how to create a simple web service executed under .NET. In this example we define some methods in the UtilityWebService class. They are responsible for adding two integer values and displaying a "hello world" text as in the following:

  1. Open a Visual C# .Net website in the Visual Studio 2010 IDE.
  2. Right-click on the project name from the Solution Explorer and click add new item.
  3. Choose web service from the template and name it UtilityWebService.cs.

    Web-Service-Template.jpg

    Figure 1.1: Web Service Template
     
  4. Thereafter, implement additional method functionality in the class "UtilityWebService.cs" as shown below:

    C# web service code
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Web;  
    4. using System.Web.Services;  
    5. ///<summary>  
    6. /// Summary description for UtilityWebService  
    7. ///</summary>  
    8. [WebService(Namespace ="http://tempuri.org/")]  
    9. [WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]  
    10. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
    11. // [System.Web.Script.Services.ScriptService]  
    12. publicclass UtilityWebService : System.Web.Services.WebService {  
    13.   
    14.    public UtilityWebService () {  
    15.   
    16.         //Uncomment the following line if using designed components   
    17.         //InitializeComponent();   
    18.     }  
    19.   
    20.     [WebMethod]  
    21.     public string HelloWorld() {  
    22.         return "Hello World";  
    23.     }  
    24.   
    25.     [WebMethod]  
    26.     public int addition(int a,int b)  
    27.     {  
    28.         return a+b;  
    29.     }  
    30. }  
  5. It is essential to add the [WebMethod] attribute before any new method definition.
  6. Finally build the project and see the output in the browser as in the following. You will see the methods here defined in the web service class.

    Web-Service-Output.jpg

    Figure 1.2: Web Service Output
     
  7. Now click over the addition method, enter some integer values in the text box for adding them and invoke the web service class method as in the following:

    Web-Service-Method-test.jpg

    Figure 1.3: Web Service Method test
     
  8. Finally see the addition result in the form of a XML file that is passed over the wire using HTTP and compatible with nearly every platform:

    method-XML-Output.jpg

    Figure 1.4: method XML Output

Web Services Components

Web Services are piece of business logic that can be accessed over the internet. You can reuse someone else's business logic instead of replicating it yourself. This technique is similar to what programmers currently do with a library of APIs, classes and components. The main difference is that web services can be located remotely on another server and managed by another vendor such as a Google Search engine that is a kind of web service, you submit a search expression and it compiles a list of matching websites and returns the list to your web browser.

There are some key protocol flows that make a complete web services as in the following:

  • SOAP (Simple Object Access Protocol)
  • DISCO (discovery)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)

SOAP

Web Services manipulate objects using a XML message. SOAP enables you to expose and consume complex data structures that includes items such as data sets and tables. The Data Sets you send or consume can flow over the same internet wire (HTTP), thereby passing through firewalls. SOAP defines the message you use to exchange the data but it doesn't describe how you send the message. In other words, to communicate with web services a client opens an HTTP connection and sends a SOAP message. SOAP is XML based; it can be interpreted by a wide range of software on many operating systems.


SOAP Request

Here a typical SOAP message sent from a Web Service client to a server as in the following:

  1. POST /TestWS/UtilityWebService.asmx HTTP/1.1  
  2. Host: localhost  
  3. Content-Type: application/soap+xml; charset=utf-8  
  4. Content-Length: length  
  5. <?xml version="1.0" encoding="utf-8"?>  
  6. <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"  
  7. xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">  
  8.   <soap12:Body>  
  9.     <addition xmlns="http://tempuri.org/">  
  10.       <a>int</a>  
  11.       <b>int</b>  
  12.     </addition>  
  13.   </soap12:Body>  
  14. </soap12:Envelope>  
SOAP Response

Here is a part of the SOAP message back from the server:

  1. HTTP/1.1 200 OK  
  2. Content-Type: application/soap+xml; charset=utf-8  
  3. Content-Length: length  
  4.    
  5. <?xml version="1.0" encoding="utf-8"?>  
  6. <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  7. xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">  
  8.   <soap12:Body>  
  9.     <additionResponse xmlns="http://tempuri.org/">  
  10.       <additionResult>int</additionResult>  
  11.     </additionResponse>  
  12.   </soap12:Body>  
  13. </soap12:Envelope>  
DISCO

Before you can use a Web service, you need to know where to find the Service. The DISCO standard creates a single file that is the repository of all related web services. You can publish a DISCO file on its server that contains links to all the web services it provides. Then the client simply needs to request this file to find all the available web services. When you set a Web Reference inside .NET, the software automatically handles the details of discovery for you. But you can also get into the details of the process yourself by using DISCO.exe as in the following:

disco http://localhost:2186/TestWS/WebService.asmx

This tool disco.exe contacts the web service and creates two additional files with .discomap and .wsdl extension. These files are XML files that will show you the name of other file and the URL.

UDDI

UDDI is a centralized directory where web services are published. This is where potential client can go to search for their specific needs. Each organization may use different UDDI registries. To retrieve information from a UDDI directory, you use a web service interface.

WSDL

Before consuming a web service, it is required to have the knowledge of a SOAP message that it can send and receive. WDSL is a standard by which a web service can tell clients what message it accepts and what results it will return. WSDL defines everything about the public interface of a web service such as data type, the methods it exposes and the URL through which those methods can be accessed.

Consuming Web Service

Before consuming a web service, we need to generate a Proxy class that wraps the call to the web services methods. It takes care of generating the correct SOAP message format and managing the transmission of the message over the wire using HTTP on port 80. When it gets the response message back, it also convert the results back to the corresponding .NET data types.

We can generate a Proxy class in .NET in either of the following two ways:

  1. Visual Studio IDE web reference feature
  2. Command line utility Wsdl.exe

Generating the Proxy class with Visual Studio IDE

  1. Deign the default.aspx with two textboxes, three labels and a single button server control as in the following.
  2. Right-click over the client project in the Solution Explorer and select "Add Service reference", then click on the "Advanced" button in the dialog box and finally click "Add Web Reference" as in the following.
  3. Copy the Web Service URL from the image 1.2, paste into the URL text box and hit Enter. This operation will browse your web service.

    Add-Web-Reference-Dialog-box.jpg

    Figure 1.5: Add Web Reference Dialog box
     
  4. The web service test page will appear in the windows with an entire methods list and the "Add Reference" button will be enabled as:

    Adding-a-Web-Reference.jpg

    Figure 1.6: Adding a Web Reference

  5. In the Web Reference name text box you can change the namespace in which the proxy class will generated.
  6. Now click over the "Add Reference" button.
  7. Now the web reference will appear in the Web References group for the project in the Solution Explorer window as in the following:

    Web-Reference-in-solution-explorer.jpg

    Figure 1.7: Web Reference in Solution Explorer
     
  8. Open the Default.aspx.cs file and add a button click handler and put the following code in it:
    1. publicpartial class_Default : System.Web.UI.Page  
    2. {     
    3.     protected void btnAdd_Click(object sender,EventArgs e)  
    4.     {  
    5.         int x, y, Result;  
    6.         x = Convert.ToInt32(TextBox1.Text);  
    7.         y = Convert.ToInt32(TextBox2.Text);  
    8.         //web service class instantiation  
    9.         localhost.UtilityWebService obj = new localhost.UtilityWebService();  
    10.   
    11.         //Method call  
    12.         Result=obj.addition(x, y);  
    13.   
    14.         //Output  
    15.         Label3.Text = Result.ToString();    
    16.     }  
    17. }  

  9. Finally run the project and enter 2 integer type values in the given text boxes and hit the button for calling the additional web service method as in the following:

    Addition-Web-Reference-Result.jpg

    Figure 1.8: Addition Web Reference Result

Generating the Proxy class WSDL.EXE

This utility takes a WSDL file and generates a corresponding proxy class that you can use to invoke the web service. This tool does not require the web service client to use the .NET IDE.

  1. Open a command prompt from "Start" -> "All Programs" -> "Microsoft Visual Studio 10" -> "Visual Studio Tools".
  2. Then navigate to the folder that contains the WSDL file and fire this command as.

    wsdl /out:UtilityWebServiceProxy.cs http://localhost:2186/TestWS/UtilityWebService.asmx

    By default the generated class is in the C# language, but you can change it by adding the /language:vb parameter.
  3. If you browse to your project directory, notice that the "UtilityWebServiceProxy.cs" file is added there.
  4. Now copy this file to your project's "App_Code" folder by selecting "Add Existing Item" from the Solution Explorer.
  5. And finally instantiate the web service class again.

    Note: if the client is already consuming the web service and you make a change later in this then you don't need to perform the entire process again. Just go the Solution Explorer, right-click over the web reference folder and select update reference. All the new definitions are reflected automatically.

Refining Web Services

There are a couple of other features of web services. For instance, session state, data caching and transactions. The secret of applying these features is the WebMethod attribute. However several other WebMethod properties exist as described in the following table.

Arguments

Description

CacheDuration

This depicts the number of seconds that the method response will be maintained in cache.

Description

This elaborates the method description.

EnableSession

Configure the method to access information in the session collection.

TransactionOption

Get or Set the transaction type such as allowed,NotSupported,Required,Supported and so on..

BufferResponse

It is true by default and determines whether the method response is buffered.

Cache duration

  1. [WebMethod(CacheDuration=50)]  
  2.     public int addition(int a, int b)  
  3.     {   
  4.         ..  
  5.     }  

 

Description

  1. [WebMethod(Description="Retrun the addition of two integer")]  
  2.     public int addition(int a, int b)  
  3.     {  
  4.         ..  
  5.     }  
Session
  1. [WebMethod(EnableSession=true)]  
  2.     public int addition(int a, int b)  
  3.     {  
  4.         ..  
  5.     }  
Transaction Option
  1. [WebMethod(TransactionOption=TransactionOption.RequiresNew)]  
  2.     public int addition(int a, int b)  
  3.     {  
  4.        ..  
  5.     }  
Buffer Response
  1. [WebMethod(BufferResponse=false)]  
  2.     public int addition(int a, int b)  
  3.     {  
  4.        ..  
  5.     }  

 


Similar Articles