Click here to Skip to main content
15,880,392 members
Articles / Web Development / IIS
Article

SOAP Web Services: Create Once, Consume Everywhere

Rate me:
Please Sign up or sign in to vote.
4.83/5 (72 votes)
15 Jul 2010CPOL8 min read 371.4K   17   165   38
A detailed development of a simple ASP.NET web service, in addition to configuring IIS server to host the service, finally creating an ASP.NET, Java and PHP web clients that consume the service.

Introduction

This tutorial aims to provide a practical introduction to web services given their increased importance in software engineering. In short, web services offer clients the ability to remotely execute certain methods thus eliminating the need for downloading separate API. The communication medium between clients and servers is XML messages that comply with the SOAP protocol. The use of XML allows systems running different operating systems and programming languages to communicate by converting XML requests and responses into their corresponding language equivalents. Fortunately, programming languages like C# (or any .NET language), Java, PHP, etc. support both clients and servers with abstraction layers called proxies that eliminate the need to parse XML SOAP messages. In this tutorial, I'll show you how to create a Web Service in ASP.NET and how to register this service in IIS server 7.0; finally I'll demonstrate the language neutrality of web services by developing three client applications that consume this service in ASP.NET, Java, and PHP.

Creating the ASP.NET Web Service

Launch Visual Studio, and then go to File / New / Web Site...

Choose ASP.NET Web Service as the template and name your project: Server.

Throughout this project, I’ll use C:\Project7 as my default folder.

Image 1

Go to the Service.cs file and create the four needed methods by replacing:

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

with:

C#
[[WebMethod]
    public int Add(int x, int y)
    {
        return x + y;
    }
    [WebMethod]
    public int Subtract(int x, int y)
    {
        return x - y;
    }
    [WebMethod]
    public int Multiply(int x, int y)
    {
        return x * y;
    }
    [WebMethod]
    public int Division(int x, int y)
    {
        return x / y;
    }

Note that [WebMethod] tag allows the methods to be accessible to external clients. Now replace the code:

C#
[WebService(Namespace = "http://tempuri.org/")]

with:

C#
[WebService(Namespace="http://tempuri.org/",
Description="A Simple Web Calculator Service",
Name="CalculatorWebService")]

The Description attribute gives external clients a brief description of the service; the Name attribute lets external clients refer to the service as CalculatorWebService rather than Service.

Installing the Web Service in IIS

This project uses IIS Server 7.0 running on a Windows 7 PC.

Activate IIS server by:

Start Menu / typing IIS in the search bar / Internet Information Services (IIS) Manager

or by: Control Panel / Administrative Tools / Internet Information Services (IIS) Manager

If you couldn’t find IIS, then probably it’s not installed, so consult Appendix A to know how you can activate this program under Windows 7.

Image 2

Expand the tree Sites, then right click on Default Web Site, and choose Add Virtual Directory.

Image 3

Enter WebService in the Alias field, and C:\Project7\Server in the Physical path field.

Image 4

Click on the WebService folder and then switch IIS to Content View in order to see the Service.asmx and the web.config files.

Image 5

Since we’ve manually created the Virtual Directory WebService without the help of Visual Studio testing mode, you should right click the WebService folder and choose Convert to Application followed by clicking OK.

Image 6

Now open your browser and goto http://localhost/WebService/Service.asmx, you should see a screen similar to this:

Image 7

Note: If you didn’t see this screen, then probably IIS server isn’t configured properly, so consult Appendix B to learn how to configure IIS for the first time.

Testing the Web Service on the Server Side

On the CalculatorWebService page, you could see four links to the Add, Division, Multiply, and Subtract methods that we’ve implemented in C#; clicking on any of those links will take you to a new page where you could test your methods.

Image 8

Image 9

Creating the ASP.NET Web Client

Launch Visual Studio, and then go to File / New / Web Site...

Choose ASP.NET Web Site as the template and name your project Client.

Image 10

Create an interface of your ASP.NET page similar to this:

Image 11

Now let’s add our web service as a service reference to our project as follows:

Right Click the Project in the solution explorer / choose Add Service Reference / enter http://localhost/WebService/Service.asmx in the address field /click Go to view the imported functions / choose ServiceReference as your namespace / click OK.

Image 12

Edit your Default.aspx.cs source to add the method GetResult that takes as an input two number strings and an integer function which corresponds to the four basic calculator operations we need.

C#
private string GetResult(string firstNumber, string secondNumber, int function)
    {
        ServiceReference.CalculatorWebServiceSoapClient client = 
            new ServiceReference.CalculatorWebServiceSoapClient();
        int a, b;
        string result = null;

        erra.Text = "";
        errb.Text = "";

        if (!int.TryParse(firstNumber, out a))
        {
            erra.Text = "Must be a valid 32-bit integer!";
            return "";
        }

        if (!int.TryParse(secondNumber, out b))
        {
            errb.Text = "Must be a valid 32-bit integer!";
            return "";
        }

        try
        {
            switch (function)
            {
                case 0:
                    result = firstNumber + " + " + secondNumber + 
			" = " + client.Add(a, b);
                    break;
                case 1:
                    result = firstNumber + " - " + secondNumber + " = "
                    + client.Subtract(a, b);
                    break;
                case 2:
                    result = firstNumber + " * " + secondNumber + " = 
			" + client.Multiply(a, b);
                    break;
                case 3:
                    result = firstNumber + " / " +
                    secondNumber + " = " + client.Division(a, b);
                    break;
            }
        }
        catch (Exception e)
        {
            LabelResult.ForeColor = System.Drawing.Color.Red;
            result = "Cannot Divide by Zero!";
        }
        return result;
    }

Note the statement:

C#
ServiceReference.CalculatorWebServiceSoapClient client = 
            new ServiceReference.CalculatorWebServiceSoapClient();

which allows the client object to access the web service methods. ServiceReference is the namespace of the web service you chose earlier. CalculatorWebServiceSoapClient establishes the SOAP connection with client (i.e. sends requests and receives responses in the form of SOAP XML messages between the proxy server and the proxy client).

Finally, add the Submit Button event handler with the following code to access the GetResult method you created earlier.

C#
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        LabelResult.ForeColor = System.Drawing.Color.Black;
        LabelResult.Text = GetResult(TextBoxFirstNumber.Text,
        TextBoxSecondNumber.Text,
        DropDownList.SelectedIndex);
    }

Installing the Web Client in IIS Server

Now you’re ready to make use of the web service with a small ASP web page that consumes this service.

Create a new Virtual Directory in IIS and choose WebClient as an Alias; and the folder C:\Project7\Client as a Physical Path.

Image 13

And as you did for the WebService Virtual Directory, right click on the WebClient directory and choose Convert to Application followed by an OK.

Finally go to the browser and type in http://localhost/WebClient/, you should see the figure below:

Image 14

Testing the Web Service on the ASP.NET Client Side

Now that we’ve successfully installed the client page that makes use of our calculator web service, we still need to validate the client side results.

Image 15

Installing and Testing the Web Client in a Java 1.6 Class

Regardless of whether we know the programming language that implements the web service or not, we can easily link applications of different platforms. Web services display to their clients standard XML pages called WSDL, which gives them an idea about what functions they implement. For instance, navigating to http://localhost/WebService/Service.asmx?wsdl would generate an XML page with special elements. The ability to read through the WSDL document and to locate elements like: type, message, portType, binding, service is very crucial, as it tells client developers about the functions hosted by the service (not a documentation). For more information about WSDL documents, visit www.w3schools.com/wsdl/wsdl_documents.asp.

Fortunately enough for JAVA 1.6 developers, is the existence of the JAVA jax-ws package that generates the proxy classes necessary for communicating with the web server.

First let’s build the java project in C:\Project7\java_proj\webClient.

So, start by creating a new java class called cl.java. (Make sure your current directory is C:\Project7\java_proj\webClient).

Now let’s run the jax-ws utility by typing the following in the command line:

C:\Project7\java_proj\webClient >wsimport -keep -p webPack.serv 
http://localhost/Service.asmx?wsdl 

The wsimport command will generate the proxy classes we need, -keep keeps the generated source files, and webPack.serv is the package containing the proxy classes. You could see by examining the service section of the WSDL file and by browsing through the webPack\serv folders that you have the two main classes CalculatorWebService and CalculatorWebServiceSoap.

Next, let’s edit our cl.java client as follows:

C#
import webPack.serv.*;

public class cl
{
	public static void main(String[] args)
	{
		CalculatorWebService service = new CalculatorWebService ();
CalculatorWebServiceSoap soap = service.getPort(CalculatorWebServiceSoap.class);
		int x = 5,y = 10;
		System.out.println(soap.Add(x,y));
		
	}
}

The getPort method returns the ‘stub’ of the CalculatorWebService class as defined by the web service and lets you access the four calculator methods defined. For instance, the soap.Add(int,int) method actually calls the server to perform the Add function defined there, and then directs the return value to the client.

Testing this class is easy; just compile as follows:

>javac –classpath . cl.java 

Then run this program as follows:

> java cl 

You’ll get "15" as an output.

Installing and Testing the Web Client in PHP

PHP allows the easy creation and consumption of SOAP based web services through the NuSOAP toolkit. To learn how to download and configure this API toolkit, visit http://sourceforge.net/projects/nusoap/.
First, you need to include the nusoap library so type in your PHP shell:

PHP
require_once('nusoap.php'); 

Then you need to connect to our web service’s WSDL in order to generate the SOAP client, so type in:

PHP
$wsdl="http://localhost/WebService/Service.asmx?wsdl";
$client=new soapclient($wsdl, 'wsdl');

Now that the SOAP $client is ready, we could then simply type in:

PHP
$param=array(
'x'=>10,
'y'=>5
); 
echo $client->call('add', $param);

And we’ll get ‘15’ as expected.

Actually the way to access web services in PHP/NuSOAP is very similar to that in the .NET Framework.

Appendix A: Activating the IIS server and ASP.NET under Windows 7

In most Windows computers, IIS server and ASP.NET are not installed by default as they’re an optional Windows component; however, the installation process runs smoothly as follows.

Goto Control Panel and choose Programs and Features (you may need to click View by: Large Icons in order to see the Programs and Features icon).

On the left margin of the Programs and Features window, choose Turn Windows Features on or off you may need administrative privileges in order to proceed.

Image 16

Next, expand the Internet Information Services tree to ensure the installation of IIS server. Then expand the World Wide Web Services tree and then expand the Application Development Features and make sure that the ASP.NET node icon is checked.

Image 17

Finally click OK to install the IIS and ASP.NET server.

Appendix B: Configuring the IIS Server for First Time Usage

To launch IIS server under Windows 7, go to the start menu and type IIS - you should see Internet Information Services (IIS) Manager.

First, you should start the IIS server, so click Start on the right margin labelled Action.

Image 18

Now that the IIS server has started, you may (optionally) want to enable directory listing in order to permit users to browse the contents of your web server.

To do that, click on the Default Web Site tree in the left margin named Connections and then double click on the Directory Browsing icon located in the middle of the screen. In the Actions, right margin click Enable.

Image 19

You’re now ready to view your site. Just launch your browser and type http://localhost in your browser.

Conclusion

I hope you now understand the importance of web services and their role in facilitating the concept of distributed computing between different systems running different programming languages. If you’re interested in using some freely available web services in your applications, visit www.webservicex.net/WS/wscatlist.aspx for more information.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Google
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Abhishek Pant28-Feb-14 22:27
professionalAbhishek Pant28-Feb-14 22:27 
GeneralMy vote of 3 Pin
chait3015-Feb-14 12:15
chait3015-Feb-14 12:15 
GeneralMy vote of 3 Pin
chait3015-Feb-14 12:14
chait3015-Feb-14 12:14 
QuestionCalculatorWebServiceSoapClient Pin
chait3015-Feb-14 1:33
chait3015-Feb-14 1:33 
AnswerRe: CalculatorWebServiceSoapClient Pin
chait3015-Feb-14 12:00
chait3015-Feb-14 12:00 
GeneralMy vote of 5 Pin
ketan italiya13-Aug-13 0:45
ketan italiya13-Aug-13 0:45 
GeneralMy vote of 5 Pin
ketan italiya13-Aug-13 0:00
ketan italiya13-Aug-13 0:00 
superbb..mann...thankss
Questioncan it be done in VB.net Pin
mohammed Al sayed26-Jul-13 22:04
mohammed Al sayed26-Jul-13 22:04 
Questionmy vote is 5 Pin
baskaran chellasamy11-May-13 8:40
baskaran chellasamy11-May-13 8:40 
GeneralMy vote of 5 Pin
yanhe011627-Mar-13 17:33
yanhe011627-Mar-13 17:33 
QuestionCreating the ASP.NET Web Client Pin
haddan28-Feb-13 5:11
haddan28-Feb-13 5:11 
QuestionVery useful Pin
Developers Code24-Feb-13 18:42
Developers Code24-Feb-13 18:42 
GeneralMy vote of 5 Pin
Vedangi20-Feb-13 21:33
Vedangi20-Feb-13 21:33 
GeneralAppreciation Pin
sampath.pandu00717-Jan-13 0:49
sampath.pandu00717-Jan-13 0:49 
GeneralGets my full vote of 5 Pin
SteveB_Member 940977731-Oct-12 4:09
SteveB_Member 940977731-Oct-12 4:09 
QuestionVery usefull Pin
Musthafa (Member 379898)24-Oct-12 20:22
Musthafa (Member 379898)24-Oct-12 20:22 
GeneralMy vote of 5 Pin
Sandesh M Patil11-Jun-12 5:36
Sandesh M Patil11-Jun-12 5:36 
GeneralMy vote of 5 Pin
jagdish Bhandari28-Sep-11 3:07
jagdish Bhandari28-Sep-11 3:07 
GeneralRe: My vote of 5 Pin
Mohamad K. Ayyash7-Oct-11 15:53
Mohamad K. Ayyash7-Oct-11 15:53 
GeneralMy vote of 5 Pin
Yusuf18-Jan-11 15:17
Yusuf18-Jan-11 15:17 
GeneralRe: My vote of 5 Pin
Mohamad K. Ayyash5-Feb-11 15:48
Mohamad K. Ayyash5-Feb-11 15:48 
Generalmy 5 Pin
Omar Gameel Salem14-Sep-10 3:10
professionalOmar Gameel Salem14-Sep-10 3:10 
GeneralRe: my 5 Pin
Mohamad K. Ayyash14-Sep-10 4:22
Mohamad K. Ayyash14-Sep-10 4:22 
GeneralExcellent Pin
Md. Marufuzzaman10-Aug-10 21:25
professionalMd. Marufuzzaman10-Aug-10 21:25 
GeneralRe: Excellent Pin
Mohamad K. Ayyash11-Aug-10 5:54
Mohamad K. Ayyash11-Aug-10 5:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.