Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Web Services:From a beginner's perspective

0.00/5 (No votes)
1 Mar 2013 1  
This article tries to dig in as to what are WebServices,how to create them and how to call and use them in various scenarios.

Introduction:

WebServices : As the name implies, A WebService is an entity or a piece of code which is hosted on the Web, which serves a specefic purpose. This could be the most simple framed definition.

A more apt version may be: A WebService is a part fo a software application which is hosted on the Web and which does a particular function in order to execute the business logic.

Further, a WebService allows a website to interact with other websites irrespective of the programming language the websites's been written in and also irrespective of the hardware & OS concerns of the machines.

Lets take an example over here: Suppose, you are a developer and you have some 3 different mathematical websites under you, demanded by various clients.A common functionality needs to be implemented in all the 3 websites, lets say displaying a Fibonaaci series in a text area.

The question which arises here is, are you gonna write separate piece of codes to have the same functionality 3 times.Well it would be a redundant extra effort, if you would try to aim at this approach.Here, the need for a WebService comes into picture. Code the functionality of displaying a Fibonaaci series in a WebService just once, and call this webservice in the 3 different websites.There you go, you are done.You need not write the same code thrice or else.

One question that may arise over here is: Why WebServices now?What was the case earlier?Were people able to leverage the functionalities of one application to another application?

The answer is yes, people were able to do so.There were technologies such as COM (Component Object Model), DCOM (Distributed Component Object Model) which were helpful in achieving this leverage, but they had their limitations as well. Infact they had to be explicitly registered on each user's machine, thus giving chances for registery glitches and stuffs.

A WebService overcomes all those limitations.

The aim of this artcle is to make a person understand what's a webservice (which I have tried to do in the Introduction section) and "How to create a WebService and call & use them via different methods?".The later will be discussed in the below coming sections. Stay tuned..



Background 

Well I belong to the .NET domain and the code files in this article aim at .NET 3.5, so the only pre-requisite would be the presence of Visual Studio 2008 client.


Using the code

Lets start with the creation of the WebService.

1) Open Visual Studio 2008 Client.Click on New>WebSite>ASP.NET Web Service.Give the path where you want to place the code. Refer to the below screenshots.

2) Visual Studio will open a default Service.cs file in which you can write your methods.Write the below lines of code. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
 
[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]
 public class Service : System.Web.Services.WebService
{
public Service ()
{
 
//Uncomment the following line if using designed components 
//InitializeComponent();
}
 
    [WebMethod]
	public int Area(int l, int b)
    	{
	return l * b;
    	}
 
    [WebMethod]
	public int Perimeter(int l, int b)
	{
	return 2 * (l +b);
	}
}  

3) Build the solution and view the Service.asmx file in the browser. It will be something like below: 

 

4) The Web Methods created will be evident and will be invoked via HTTP POST method if the links Area and Perimeter are clicked.

 

So here it is, a very basic WebService has been coded and created, which will help us to calculate the area and perimeter of a rectangle.

You might wana copy the Web Service URL because they are used later in the article. 

Next, we will see how to call and use the Web Service in times of need.

Well, there may be 3 methods by which a Web Service is called, depending upon the scenarios. 

1)       By HTTP POST method.

2)       By creating a Proxy Class 

3)       By using XMLHTTP Request object over SOAP 

Let's discuss each of them in brief:    

HTTP POST method: This method can be used directly by calling the .asmx file from the client.

The most favorable method to execute an HTTP POST method is to have the codes inside an HTML file. Let’s get started to implement it.

Open your notepad and write the below lines of code in it:

  

<html>
<head>
<title>WebService Call using HTTP POST</title>
	<body>
	<form action="http://localhost:43529/WebService/Service.asmx/Area" method="POST">
	<input name="l">
	<input name="b">
	<input type="submit" value="Click for Area">
	</form>
	<form action="http://localhost:43529/WebService/Service.asmx/Perimeter" method="POST">
	<input name="l">
	<input name="b">
	<input type="submit" value="Click for Perimeter">
	</form>
	</body>
</head>
</html> 

Just a friendly reminder, you would wana change the Web Service URL in the above code, by your own URL, which you would have copied sometime earlier..Smile | :)  

The bold lines of code exhibit as to how we can call the methods of the WebService separately via HTTP POST. Upon saving the above lines of code as .html and executing it will result in a browser action. 

  

W  

 

 When the button “Click for Area” or “Click for Perimeter” is clicked, we would see that the specific methods of the WebService are called and the result is in the form of an XML.

  

One of the limitations of HTTP POST method can be thought as of: We are unable to build Web Methods which take complex types as parameter or return values.

 2)      Creation of a Proxy Class: This method is widely used by developers. This method actually makes use of the full potential of a Web Service. Let’s implement this and see its wonders.

We need to create one ASP.NET website to see and implement this method.

Open Visual Studio once again and click on New>Website>ASP.NET Website. Give the path where you want to place the code. 

 

This web site creation will open a Default.aspx page, its aspx.cs page, an App_Code folder and few more stuffs.

Open the Default.aspx page and design it as per below screenshot:

It’s basically 4 ASP label controls, 4 ASP text box controls and 1 ASP button bound under 1 div.

 

Now the most important aspect of this very method comes into play. Addition of the previously created Web Service.

Right-click the project and click on “Add Web Reference”. The click will open a dialog box similar to the below screenshot.

 

Now, we need to catch the Web Service here either by adding the URL or by browsing through the various options given. Successful addition of the Web Service will yield “Web services found at this URL”. You would see the methods that you have actually created. You might want to change the name of the web reference from “localhost” to something else to avoid confusion and stuffs. Click on Add Reference and there you go. You have successfully added a Web Reference to your ASP.NET website.

 

The solution explorer will be something like below:

 


Now, once the Web Reference is added, let’s write some code in Code-Behind to make use of the web service.

Open Default.aspx.cs file and on Button Click event, add the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partialclass_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 protected void btnClick_Click(object sender, EventArgs e)
    {
	if (!string.IsNullOrEmpty(txtLength.Text) && !string.IsNullOrEmpty(txtBreadth.Text))
        {
	Maths.Service obj = new Maths.Service();
 
	int l = Convert.ToInt32(txtLength.Text);
	int b = Convert.ToInt32(txtBreadth.Text);
  	txtArea.Text = Convert.ToString(obj.Area(l, b));
  	txtPerimeter.Text = Convert.ToString(obj.Perimeter(l, b));
        }
    }
} 

Now, let me explain the above code further. The bold line of code is what this method is all about, Creation of proxy class.

We are making an object of the Web Service added and then are using that object to call the individual methods of the WebService. Rest of the code is self-explanatory, which will calculate the area and perimeter of the rectangle.

Build the solution and view the Default.aspx file in the browser.

Enter some values for length and breadth and click on the button.

You will see the area and perimeter displayed in the placed textboxes.

Similar screenshots are below. 





We see in this method that we can call a Web Service by just adding a Web Reference and creating a proxy class and without even coding the required functionality (done by the Web Service) in the current project.

1)    By using XMLHTTP Request object over SOAP:

First let’s see what SOAP is.

SOAP (Simple Object Access Protocol) is a protocol used for messaging and is completely XML based.

SOAP provides a complete set of rules for messages and also, rules for entities like message encoding, message handling etc. 

Syntax of a SOAP message will be as follows:

<?xml version="1.0" encoding="utf-8"?>

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">

<soap:Body> 

</soap:Body>

</soap:Envelope>

A SOAP message is called an Envelope, which further has Header and Body tags.

Header tag is optional whereas Body tag is mandatory to use in order to submit a message.

Now, let’s see what exactly XMLHttpRequest is.

The XMLHttpRequest specification defines an API that provides scripted client functionality for transferring data between a client and a server.

It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script.

In this implementation we will use an HTML form and a JavaScript function to demonstrate the full potential of this method.

a) First of all we will create an object of XMLHttpRequest. Refer the below lines of code. 

var sample;
if (window.XMLHttpRequest) 
{
sample= new window.XMLHttpRequest;//For browsers other than IE
}
else 
{
try 
{
sample=new ActiveXObject("MSXML2.XMLHTTP.3.0"); //for IE   
}
catch(ex) 
{

}
}

b) Now, we will set the Web Service URL using the Open method of XMLHttpRequest.

sample.open ("POST",”http://localhost:43529/WebService/Service.asmx",true);  

Basically Open method of XMLHttpRequest has 5 parameters:

 Type of HTTPMethod, Url, Boolean value (true most of the times), Username and password (optional).

c) Now, we will create the Request Headers and SOAP request (Shown in the below code).

d) The demonstration will be basically done by an HTML code. Hence open your notepad and type in the below code:  

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" >

var sample;
if (window.XMLHttpRequest) 
{
	sample = new window.XMLHttpRequest;
}

else 
{
try 
{
	sample = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch (ex) 
{

}
} 
	sample.open("POST", "http://localhost:43529/WebService/Service.asmx",true);
	sample.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
	sample.setRequestHeader("SOAPAction", "http://tempuri.org/Area");

	strRequest = "<?xml version='1.0' encoding='utf-8'?>";
	strRequest = strRequest + "<soap:Envelope " +"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +"xmlns:xsd='http://www.w3.org/2001/XMLSchema' " +"xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
	strRequest = strRequest + " <soap:Body>";
	strRequest = strRequest + "<Area xmlns='http://tempuri.org/'><l>4</l><b>5</b></Area>";
	strRequest = strRequest + "</soap:Body>";
	strRequest = strRequest + "</soap:Envelope>";


	sample.onreadystatechange = function () {
	if (sample.readyState == 4 &&xmlHTTP.status == 200) 
{
	alert(xmlHTTP.responseXML.xml);
}
}
sample.send(strRequest);

</script>
</head>
<body>

</body>
</html>  

e) Save the notepad as .html extension and execute it to have a browser action. 

The browser will give the output as a JavaScript alert box, similar to below.

 

 SetRequestHeader creates the Header tag of the SOAP message, while OnReadyStateChange property of XMLHTTPRequest object assists us to execute the code after the response from the Web Service is processed. 

Points of Interest 

Initially i used to think web services,wcf's and stuffs are aliens, and had no interests in them at all.

Interests in Web Services grew when I got a .NET project dealing with web services, wcf services and else, had to learn them you know. Now I know that they are damn helpful..Smile | :)  

Well, wasn't really successful in finding a great resource for a beginner(including me) under this topic, hence decided to pen down something.

First article at CP...Smile | :) Comments and criticisms are pretty welcome. And please don't mind much on the formatting, had a hart time doing it....:P

History

28th Feb 2013 Version 1.0

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here