Web Services
Introduction
Software developers have struggled to create software components that can be called remotely over local networks and the Internet. In this process, several technologies came into light but some of them were not quite successful enough due to many limitations and hurdles such as communicating over an unreliable Internet, or running every type of hardware and operating system in a computer network.
This is where XML web services enter the scene. To interact with a web service, you simply need to send an XML message over HTTP. Because every Internet-enabled device supports HTTP, every programming framework includes a higher level toolkit that makes it possible to communicate with a web service (XML is platform independent). As XML web services are not .NET framework specific, they can also be consumed in other programming frameworks such 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 have been developed to allow the distribution and reuse of application logic.
Comparison of different Distributed Technologies
Web Services
DCOM
CORBA
Distributed application logic has many advantages, 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 entire organization and its data repository residing on a single vendor platform. An organization is usually made up 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? Interoperability
and load balancing issues are prevalent in CORBA and DCOM because they are developed before the advent of the Internet. They are fine for building enterprise applications with software running on the same platform but not for those that span different platforms or the Internet.
Advantage of Web Services
- They are simple to build and are supported on a wide range of platforms.
- They can extend their interface and add new methods without affecting the client's operations.
- They are firewall-friendly because all communication happens through HTTP on port 80.
- They are stateless, since there is no permanent connection which scales up for 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 word" text as follows:
- Open a Visual C#.net website in the Visual Studio 2010 IDE.
- Right click on the project name from the Solution Explorer and click Add New Item.
-
Choose a web service from the template and name it UtilityWebService.cs.
Figure 1.1: Web Service Template
-
Thereafter, implement the addition method functionality in the class UtilityWebService.cs.
C# web service code
- It is essential to add the [WebMethod] attribute before any new method definition.
-
Finally, build the project and see the output in the browser. You will notice the methods here defined in the web service class.
Figure 1.2: Web Service Output
-
Now click the addition method, enter some integer values in the text boxes, and invoke the web service class method as follows:
Figure 1.3: Web Service Method test
-
Finally, see the addition result in the form of an XML file that is passed over the wire through HTTP and is compatible with almost every platform.
Figure 1.4: method XML Output
[c language="#"]using System;
using System.Collections.Generic;
using System.Web;
///
<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]
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;
}
[/c]
Web Services Components
Web services are a 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. Google's search engine is a kind of web service - you submit a search expression, it compiles a list of matching websites, and returns the list to your web browser.
There are some key protocol flows that make web services complete:
-
SOAP( Simple Object Access Protocol)
-
DISCO (Discovery)
-
UDDI (Universal Description, Discovery and Integration)
-
WSDL ( Web Services Description Language)
SOAP
Web services manipulate objects through XML messages. SOAP enables you to expose and consume complex data structures which include 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.
Here is a typical SOAP message sent from a web service client to a server:
SOAP Request
[xml]<!--?xml version="1.0" encoding="utf-8"?-->
<a>int</a>
<strong>int</strong>
[/xml]
Here is a part of the SOAP reply from the server:
SOAP Response
[xml]HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
<!--?xml version="1.0" encoding="utf-8"?-->
int
[/xml]
DISCO
Before you can use a web services, you need to know where to find them. The DISCO standard creates a single file that is the repository of all related web services. You can publish a DISCO file that contains links to all the web services the server provides. The client then 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 follows:
The tool disco.exe contacts the web service and creates two additional files with .discomap and .wsdl extensions. These are XML files that will show you the names of the other files and their URLs.
UDDI
UDDI is a centralized directory where web services are published. This is the place where a potential client can search for their specific needs. Different organizations may use different UDDI registries. To retrieve information from a UDDI directory, you use a web service interface.
WSDL
Before consuming a web service, knowledge of the SOAP message that it can send and receive is required. WSDL is a standard by which a web service can tell clients what messages it accepts and what results it will return. It defines everything about the public interface of a web service such as data types, 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 which wraps the call to the web service's 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 converts the results back to the corresponding .NET data types.
We can generate a Proxy class in .NET in two ways:
- Visual Studio IDE web reference feature
- Command line utility Wsdl.exe
Generating the Proxy class with VS IDE
- Design the default.aspx with two textboxes , three labels and a single button server control.
- Right click over the client project in the Solution Explorer, select Add Service reference, click on the Advance button in the dialog box, and finally click Add Web Reference.
-
Copy the Web Service URL from image 1.2, paste it into the URL text box and hit Enter. This operation will browse your web service.
Figure 1.5: Add Web Reference Dialog box
-
The web service test page will appear in a window with the entire methods list and the Add Reference button enabled:
Figure 1.6: Adding a Web Reference
- In the Web Reference name text box, you can change the namespace in which the proxy class will be generated.
- Click the Add Reference button.
-
Now the web reference will appear in your project's Solution Explorer under the Web References group:
Figure 1.7: Web Reference in Solution Explorer
-
Open the Default.aspx.cs file and add a button click handler and the following code:
-
Finally, run the project and enter two integer type values in the given text boxes. Hit the Addition button to call the web service:
Figure 1.8: Addition Web Reference Result
- Open command prompt from Start-> All Programs-> MS Visual Studio 10-> Visual Studio Tools.
-
Then navigate to the folder that contains the WSDL file and fire this command:
- If you browse your project directory, you will notice that the UtilityWebServiceProxy.cs file is added there.
- Now copy this file to your project App_Code folder by selecting Add Existing Item from Solution Explorer.
- Finally, instantiate the web service class again.
[c language="#"]public partial class _Default : System.Web.UI.Page
{
protected void btnAdd_Click(object sender, EventArgs e)
{
int x, y, Result;
x = Convert.ToInt32(TextBox1.Text);
//web service class instantiation
localhost.UtilityWebService obj = new localhost.UtilityWebService();
//Method call
Result=obj.addition(x, y);
//Output
Label3.Text = Result.ToString();
}
}
[/c]
Generating the Proxy Class WSDL.EXE
This utility takes the 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 .NET IDE.
By default, the generated class is in C#, but you can change it by adding the /language:vb parameter.
Note: If a client is already consuming the web service and you made any changes to it later, you won't need to perform the whole process again. Just go to the Solution Explorer, right click over the Web References folder and select Update reference. All new definitions are reflected automatically.
Refining Web Services
There are other web service features such as session state, data caching and transactions. The secret of applying these features is the WebMethod attribute. However, several other WebMethod properties exist such as those described in this table:
Arguments
Description
Cache duration
[c language="#"][WebMethod(CacheDuration=50)]
public int addition(int a, int b)
{
..
}
Description
[c language="#"][WebMethod(Description="Retrun the addition of two integer")]
public int addition(int a, int b)
{
..
}
Session
[c language="#"][WebMethod(EnableSession=true)]
public int addition(int a, int b)
{
..
}
Transaction Option
[c language="#"][WebMethod(TransactionOption=TransactionOption.RequiresNew)]
public int addition(int a, int b)
{
..
}
Buffer Response
[c language="#"][WebMethod(BufferResponse=false)]
public int addition(int a, int b)
{
..
}