Reader Level:
ARTICLE

.NET Web Services

Posted by Vidya Vrat Agarwal Articles | Web Services in C# February 28, 2013
XML web services are not .NET Framework specific, they can also be consumed in other programming frameworks such as Java, PHP, AJAX, ASP etc.
  • 5
  • 0
  • 21288

Learning Modules

  • Introduction
  • Distributing components Technologies
  • Building Simple Web Services
  • Web Services Components
  • Consuming Web Service
  • Refining Web Service

Introduction

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 web a 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 etc...

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.

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. Organization consists 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 each other? Interoperatibilty and Load balancing issues 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 through 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

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Services;

    ///<summary>
    ///
    Summary description for UtilityWebService
    ///</summary>
    [WebService(Namespace ="http://tempuri.org/")]
    [WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    publicclass UtilityWebService : System.Web.Services.WebService {

       public UtilityWebService () {

            //Uncomment the following line if using designed components
            //InitializeComponent();
        }

        [WebMethod]
        public string HelloWorld() {
            return "Hello World";
        }

        [WebMethod]
        public int addition(int a,int b)
        {
            return a+b;
        }
    }

     

  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 notice 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 through HTTP and compatible with almost 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 which 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 through 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:

POST /TestWS/UtilityWebService.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length:
length

<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <addition xmlns="http://tempuri.org/">
      <a>
int</a>
      <b>
int</b>
    </addition>
  </soap12:Body>
</soap12:Envelope>


SOAP Response

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

HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
 
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <additionResponse xmlns="http://tempuri.org/">
      <additionResult>int</additionResult>
    </additionResponse>
  </soap12:Body>
</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 VS 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:

    publicpartial class_Default : System.Web.UI.Page
    {  
        protected void btnAdd_Click(object sender,EventArgs e)
        {
            int x, y, Result;
            x = Convert.ToInt32(TextBox1.Text);
            y = Convert.ToInt32(TextBox2.Text);

            //web service class instantiation
            localhost.UtilityWebService obj = new localhost.UtilityWebService();

            //Method call
            Result=obj.addition(x, y);

            //Output
            Label3.Text = Result.ToString(); 
        }
    }

  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 etc..

BufferResponse

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

Cache duration

[WebMethod(CacheDuration=50)]
    public int addition(int a, int b)
    {
        ..
    }

Description

[WebMethod(Description="Retrun the addition of two integer")]
    public int addition(int a, int b)
    {
        ..
    }

Session

[WebMethod(EnableSession=true)]
    public int addition(int a, int b)
    {
        ..
    }

Transaction Option

[WebMethod(TransactionOption=TransactionOption.RequiresNew)]
    public int addition(int a, int b)
    {
       ..
    }

Buffer Response

[WebMethod(BufferResponse=false)]
    public int addition(int a, int b)
    {
       ..
    }


 

COMMENT USING

Trending up