Introduction to Service Oriented Architecture

Introduction

A Service Oriented Architecture (SOA) is not a utility or any software. It is an architecture for developing distributed and interoperable applications.

A distributed application has parts of the application running in multiple computer nodes. In other words an application (desktop or web) running in one system in one location and also uses some functionalities or business logic from another system located somewhere in the world.



Benefits

  1. It is mainly for scalability and better performance.

  2. An application wants to use some of the services provided by for other enterprises.

An interoperable application means one application developed in one language, for example Java can communicate with an other application done in another technology such as .Net.

Some important characteristics of Service Oriented Architecture

  • SOA services should be independent of other services.
    Altering a service should not affect the client calling the service.

  • Services should be self-contained.

  • Services should be able to define themselves (in the Web Service Description Languatge (WSDL))
    Services should be able to describe what they do. It should be able to tell the client what all of the operations it does, what are all the data types it uses and what kind of value it will return.

  • Services should be published into a location (directory) where anyone can search for it.

  • SOA applications communicate with each other sending and receiving messages.

  • A client application sends a message to invoke a method of the service.
    Standard messages make them platform-independent.
    (Here the standard doesn't mean standard across Microsoft, it means across all programming languages and technologies.)

  • Services should support reliable messaging.
    That means there should be a guarantee that a request that reaches the correct destination will get the correct response.

ASP.Net Web services and Windows Communication Foundation (WCF) provide Microsoft's implementation of SOA.

Creating a Web Service in ASP.Net

Web services are a standardized way for developing interoperable applications that enable an application to invoke a method of another application. These applications can be on the same computer or different computers. Web services use open standards and protocols like HTTP, XML and SOAP. Since these are open and well-known protocols, applications built on any platform can interoperate with web services. For example, a Java application can interoperate with a web service built using .NET. Similarly a web service built using Java can be consumed by a .NET application.

Web Service Example

A web service can do nearly anything.

  • You can make your own web service and let others use it. For example you can make a free SMS sending service with a footer with your company's advertisement, so whosoever uses this service indirectly advertises your company. You can apply your ideas in N number of ways to take advantage of it.

  • Web Portal: A web portal might obtain top news headlines from an associated press web service.

  • Weather Reporting: You can use a Weather Reporting web service to display weather information in your personal website.

  • Stock Quote: You can display the latest update of the Share market with a Stock Quote on your web site.

  • News Headline: You can display the latest news update using a News Headline Web Service in your website.

Creating a ASP.Net Web Service in Visual Studio

The following is an example of creating a Web Service in .Net. Let's create and consume an ASP.NET Web Service.

Step 1

Create the ASP.NET Web Service Project.

Open Visual Studio 2010 and create a new web site. Select .Net Framework 3.5 then select ASP.NET Web Service template. Then you need to provide the name of your service. In this example I am naming it "mywebservice". Then click the OK button. A screenshot of these activities is provided below.

Step 2

Click on the OK button; you will see the following window.



Here (in the preceding figure), you will note that there is a predefined method "HelloWorld" that returns the string "Hello World". You can use your own method and can various operations. Here I made a simple method that returns the multiplication of two numbers using the code.

Service.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6. [WebService(Namespace = "http://tempuri.org/")]  
  7. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  8. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  9. // [System.Web.Script.Services.ScriptService]   
  10. public class Service : System.Web.Services.WebService  
  11. {  
  12.     [WebMethod]  
  13.     public int Multiplication(int a, int b)  
  14.     {  
  15.         return (a+b);  
  16.     }  
  17. }  
Before debugging the preceding Web Service the following are some important terms.

The service class must inherit from the Websevice class in the System.Web.Services namespace.

The [WebMethod] attribute

The Service class exposes a single method, the public method Multiplication that takes two integer arguments and returns the multiplication of two number as an integer. To expose a method as a part of a web service, you must decorate it with the WebMethod attribute that tells the compiler to treat it as such. Any method marked with the WebMethod attribute must be defined as public. In the Solution Explorer you will see:



Service.asmx that contains the following code:

  1. <%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs" Class="Service" %>  

The page directive WebService is required and the class is the name of the .NET class to expose the Web Service. Each method exposes a Web Service Class Method that must have a declarative attribute statement.

The WebService directive is similar to the Page directive that begins most .aspx pages. For the Multiplication web service to work, you must assign values to two the WebService directive attributes Language and Class.

The required Language attribute lets .NET know which programming language the class has been written in.

Now back to the our web service.

Step 3

Build the Web Service and run the Web Service for testing by pressing the F5 function key.

It will open the browser with an URL that ends with the extension .asmx. It contains the list of web methods that it contains to consume.


Copy the URL of this web service for further use.

Click on the Mutiplication link to test the web service.



Enter the value of a and b.



By pressing the "Invoke" button a XML file is generated.



Now our web service is ready for use. We just need to create a new web site or console application or Windows Forms application or WPF application to consume the web service.

Consuming the preceding web service in the client application (ASP.Net web site)

Step 4: Create a test web site using "File" -> "New" -> "Web Site..." then select "ASP.Net Web Site".



Name the web site, for example here I have choosen the name "Test".

Step 5

Right-click on the project in the Solution Explorer and choose "Add Web Reference".



Step 6

Paste the URL of the web service and click on the "Go" button and then "Add reference".



Step 7

Now your web service is ready for use. In the Solution Explorer you will see:



Step 8

Go to the design of the Default.aspx page. Drag and drop three Textboxes and one button.



Step 9

Go to the Default.cs page and in the button click event use the following code.

Important: when we add a service reference for the web service to our project by copying the service URL, it creates a proxy class of the service class on the client side by reading the Web Service Description Language (WSDL) document.

  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     localhost.Service  client = new localhost.Service();     
  4.     // create the object of the web service class  - a proxy class on client side  
  5.     //we have changed the name of the namespace from servicereference1 to localhost while adding the service         reference, you can use any meaningful name of your choice.   
  6.     int a = Convert.ToInt32(TextBox1.Text);  
  7.     int b = Convert.ToInt32(TextBox2.Text);  
  8.     int c = client.Multiplication(a, b);  
  9.     TextBox3.Text = c.ToString();  
  10. }  
Step 10
 
Now run the website, you will see:


Press the Show button.

Points to remember

Hyper Text Transfer Protocol (HTTP) is the protocol widely used by web services to send and receive messages.

The messaging is done usinig the Simple Object Access Protocol (SOAP). SOAP messages are in XML format.

Interview Questions

  1. What is WSDL and what is it's purpose?

  2. How is a proxy class generated?

  3. What is the use of a proxy class?

  4. What actually happens when a web service reference is added?

Visual Studio generates a proxy class using the Web Service Description Language (WSDL) document of the web service. The WSDL document formally defines a web service. It contains:

  1. All the methods that are exposed by the web service

  2. The parameters and their types

  3. The return types of the methods

This information is then used by Visual Studio to create the proxy class. The client application calls the proxy class method. The proxy class will then serialize the parameters, prepare a SOAP request message and send it to the web service. The web service executes the method and returns a SOAP response message to the proxy. The proxy class will then deserialize the SOAP response message and hand it the client application. We don't need to serialize or deserialize .Net CLR objects to and from SOAP format. The proxy class takes care of serialization and deserialization.

Why WCF instead remoting and web services

Suppose a client application written in Java wants to consume a web method created in an ASP.Net web service, using the HTTP protocol by sending and receiving messages in XML format (see the figure).


Whereas another client application written in .Net wants to consume a method in binary format using the TCP protocol. Then a .Net remoting service is to be developed. Again the same code is required to write what has already been done in ASP.Net web service.

From the preceding two scenarios it is clear that a kind of service is required to develop that can solve the limitations of .Net Remoting Services as well as ASP.Net Web Services.

Windows Communication Foundation (WCF) is the solution to the problem.

WCF

WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication. It was introduced as a part of .Net 3.0.



Difference between WCF and Web service

  • In a web service we need to add the [WebService] attribute to the class.
    In WCF we need to add the [ServiceContract] attribute to the class.

  • Add the [WebMethod] attribute to the method in a web service.
    Add the [OperationContract] attribute to the method in WCF.

  • For serialization in a web service use the System.Xml.serialization namespace.
    WCF uses the System.Runtime.Serialization namespace for serialization.

  • We can host a web service in IIS only.
    We can host WCF in multiple environments, like IIS, Windows Activation Service (WAS), self-hosting, Windows Service, Console hosting or Windows Forms hosting.

Creating a WCF Service in Visual Studio 2010

Creating a simple application using WCF

First open Visual Studio and click "File" -> "New" -> "Web Site..." then under that select WCF Service and provide a name for the WCF Service and click OK.



Once you have created the application you will get the default class files, including Service.cs and IService.cs.



Here IService.cs is an interface containing Service Contracts and Data Contracts and Service.cs is a normal class inherited by IService where you can all the methods and other stuff.

Now open IService.cs and provide the following code:

  1. [ServiceContract]  
  2. public interface IService  
  3. {  
  4.    [OperationContract]  
  5.    string SampleMethod(string Name);  
  6. }  

Then open the Service class file and provide the following code:

  1. public class Service : IService  
  2. {  
  3.    public string SampleMethod(string Name)  
  4.    {  
  5.       return "First WCF Sample Program " + Name;  
  6.    }  
  7. }  
Our WCF service is ready for use with basicHttpBinding. (See the web.config file.)

Now build and run the service. It will open the browser with a URL for the .svc file like we had .asmx in web services.

Copy the WCF service URL for adding the service reference to the client application.

Now we can call this WCF Service method in the client's  console applications and ASP.Net applications  and Windows Forms applications.

Calling WCF Service using Console Application

We have many ways to call a WCF service, like using a console app, Windows app or web app but here we will use a console application.

Create a new console app from Visual Studio by selecting the console application project type then provide the name as you like.



After creating the Console application we need to add a WCF reference to our application. To do that right-click on your Windows application and select Add Service Reference.



Now a wizard will open. In that provide your WCF service URL link the (.svc file link) and click Go. After adding your service click the OK button.



After adding the WCF Service rovide the following code in the Program class file's Main method:

  1. static void Main(string[] args)  
  2. {  
  3.    ServiceReference1.ServiceClient objService = new ServiceClient();  
  4.    Console.WriteLine("Please Enter your Name");  
  5.    string Message = objService.SampleMethod(Console.ReadLine());  
  6.    Console.WriteLine(Message);  
  7.    Console.ReadLine();  
  8. }  
Now everything is ready. Run your application. The output should be like this:


A WCF Service is composed of the following three components:

  1. Service Class: A WCF service class implements some service as a set of methods.

  2. Host Environment: A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS as in the case of a normal asmx web service in .NET.

  3. Endpoints: All communications with the WCF service will happen via the endpoints. The endpoint is composed of 3 parts (collectively called the ABC's of endpoints) as defined below:

    Address: The endpoints specify an address that defines where the endpoint is hosted. It's basically an URL.

    For example: http://localhost/WCFServiceSample/Service.svc

    Important: We can create a WCF service in various ways and host them in multiple ways. If you select the new web site option and then WCF service then you will only get the Service.svc file.

    We can also create a class library project and can add a WCF service to it.

    Binding: The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted. Various components of the WCF are depicted in the figure below.

    • "A" stands for Address: Where is the service?
    • "B" stands for Binding: How can we talk to the service?
    • "C" stands for Contract: What can the service do for us?