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.

 Service Oriented

Benefits

  1. It is mainly for scalability and better performance.
  2. An application wants to use some of the services provided by other enterprises.

An interoperable application means one application developed in one language, for example, Java can communicate with another 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 Language (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 data types it uses, and what kind of value it will return.
  • Services should be published in 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 on your personal website.
  • Stock Quote: You can display the latest update of the Share market with a Stock Quote on your website.
  • News Headline: You can display the latest news update using a News Headline Web Service on your website.

Creating an 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 website. 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.

Visual Studio

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

OK Button

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

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
{
    [WebMethod]
    public int Multiplication(int a, int b)
    {
        return (a + b);
    }
}

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

WebMethod

Service.asmx that contains the following code.

<%@ 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 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 a URL that ends with the extension .asmx. It contains the list of web methods that it contains to consume.

URL

Copy the URL of this web service for further use.

Click on the Multiplication link to test the web service.

Web service

Enter the value of a and b.

Value

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

XML File

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

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

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

Web site

Name the website, for example, here I have chosen the name "Test".

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

 Solution Explorer

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

Add reference

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

Service

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

Textboxes

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.

protected void Button1_Click(object sender, EventArgs e)
{
    localhost.Service client = new localhost.Service();     
    // create the object of the web service class  - a proxy class on client side   
    // 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.
    int a = Convert.ToInt32(TextBox1.Text);
    int b = Convert.ToInt32(TextBox2.Text);
    int c = client.Multiplication(a, b);
    TextBox3.Text = c.ToString();
}

Step 10. Now run the website, and you will see.

Firebox

Press the Show button.

Points to remember

  1. Hypertext Transfer Protocol (HTTP) is the protocol widely used by web services to send and receive messages.
  2. The messaging is done using the Simple Object Access Protocol (SOAP). SOAP messages are in XML format.

Interview Questions

  1. What is WSDL and what is its 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 to 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 of 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).

 WCF

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.

.NET communication

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.

 WCF Service

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

Class Files

Here IService.cs is an interface containing Service Contracts and Data Contracts and Services. 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.

[ServiceContract]
public interface IService
{
    [OperationContract]
    string SampleMethod(string Name);
}

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

public class Service : IService
{
    public string SampleMethod(string Name)
    {
        return "First WCF Sample Program " + Name;
    }
}

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 ASP.Net applications and Windows Forms applications.

Calling WCF service using the 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.

Console Application

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.

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

 Wizard

After adding the WCF Service provide the following code in the Program class file's Main method.

static void Main(string[] args)
{
    ServiceReference1.ServiceClient objService = new ServiceClient();
    Console.WriteLine("Please Enter your Name");
    string Message = objService.SampleMethod(Console.ReadLine());
    Console.WriteLine(Message);
    Console.ReadLine();
}

Now everything is ready. Run your application. The output should be like this.

Output

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.
    1. 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
    2. 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.
    3. 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?


Similar Articles