Search
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Fri, 24-Oct-2014 Authors
All Time Authors
Sourav.Kayal
39750
Sheonarayan
38050
Niladri.Biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

Service Oriented Architecture, a real world example in ASP.NET with C#

SheoNarayan
Posted by under .NET Framework category on for Intermediate level | Views : 57004 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 5 out of 5
3 vote(s)
Service Oriented Architecture (SOA) a buzzing word in the world of software development these days. In this article, we will try to understand what the SOA is and how to create and consume it in ASP.NET with C#.

 Download source code for Service Oriented Architecture, a real world example in ASP.NET with C#



Introduction

According to Wikipedia, Service-Oriented Architecture (SOA) is a software architecture where functionality is grouped around business processes and packaged as interoperable services. The actual definition goes here "A service-oriented architecture can be defined as a group of services, which communicate with each other. The process of communication involves either simple data passing or it could involve two or more services coordinating some activity. Some means of connecting services to each other is needed."

SOA is mostly implemented using Web Services because it is a standard Internet protocols that are independent from platforms and programming languages. There are a bunch of benefits of Web Services and describing that itself will take a separate article. At the end of this article, I have provided few references that may be useful to fully understand SOA and Webservices.

In order to show how to create and consume SOA Application, I have taken a simple example to pre-populate Insert Employee Details form as shown below and Insert records into database (To understand this article completely reader must have knowledge about Tierd Architecture. If not, please refer to http://www.dotnetfunda.com/articles/article18.aspx).

Picture - 1

 

Creating Service Oriented Architecture (SOA) Application

SOA is created based on purely OOPS concept so you must have a complete architecture designed for the services you are going to provide to others based OOPS concept. The same architecture will be the base of our SOA application. In Service Oriented Architecture design, Web Service is created to focus on providing a kind of related services to the calling client and its methods are created to provide a complete service to achive a particular task, irrespective of how many objects it has to instantiate and how many method it has to call internally. For this tutorials, I have created a web service that has three methods as shown below to achive respective tasks.

Picture - 2

In the above form (Picture - 1), as soon as the form loads, I have to populate Department, Country and State dropdown boxes so that user can select these details while inserting employee data. To do this, I have a method called GetEmployeeInsertDetails() that will return a DataSet that will have 3 different DataTables containing records for Department, Country and State DropDownLists respectively.

/// <summary>

/// Returns all data required to populate insert employee form

/// </summary>

/// <returns></returns>

[WebMethod]

public DataSet GetEmployeeInsertDetails()

{

DataSet dSet = new DataSet();

// Instantiate all objects that need get required data

 

 

 

DepartmentBAL deptt = new DepartmentBAL();

StateBAL state = new StateBAL();

CountryBAL country = new CountryBAL();

try

{

dSet.Tables.Add(deptt.LoadAll());

dSet.Tables.Add(state.LoadAll());

dSet.Tables.Add(country.LoadAll());

}

catch

{

throw;

}

finally

{

deptt = null;

state = null;

country = null;

}

return dSet;

}



You can see in the above code snippet that I have decalred a DataSet and instantiated three separate Business Layer objects to get Department, State and Country data and added them into my DataSet (I am getting DataTable from all LoadAll methods of these three objects). This is where the concept of SOA goes. This method is responsible to get all required data that is needed to the client to pre-populate Insert Employee forms. The client doens't know from where these data will come or which object to instantiate or which method to invoke. Clients only knows that it has to call GetEmployeeInsertDetails() method of the web service and get all required data that is needed to pre-populate the form.

Lets create another method called InsertRecords() to insert employee records into database. This method will accept Person object (it will contain all employee data as its properties). My Insert method is very simple as I don't have to do anything except to pass the Person object again to my Business Access Layer method.

[WebMethod]

/// <summary>

/// Insert employee records into database

/// </summary>

/// <param name="person">Person Object along with all properties set</param>

/// <returns></returns>

public int InsertRecords(Person person)

{

return new PersonBAL().Insert(person);

}

I have one another method to Load employee details called LoadAll(). This method simply call the Load method of Business Access Layer and return the same DataTable to the client.

[WebMethod]

/// <summary>

/// Load all employee records from database

/// </summary>

/// <returns></returns>

public DataTable LoadAll()

{

return new PersonBAL().Load();

}

Now, we have your service ready, this must be hosted somewhere so that out client can call it. For this demo, I have simply run my SOA application and in my case  its looks like http://localhost:49371/Architecture/4-Tier/Service/EmployeeService.asmx. I will not close this application till I am done with testing my client application otherwise my client will not be able to access the service and complain "Unable to connect to the remote server".

Till this point, I have everything for my Insert Employee Details form. Now lets create a client application that will call my Service Oriented Architecture application web service.

Consuming Service Oriented Architecture (SOA) Application

To consume the SOA application, create a separate project or website and try adding web reference to the Web Service we just created. To do that try to follow steps shown in below picutre.

Picture - 3

As soon as you will click Add Web Reference..., you should get a dialogue box asking for URL of the webservice, similar to Picture - 2 above. Provide the url of the webservice (As I said for this demo, I have this service at my pc only and I had run that application, so my url looks like http://localhost:49371/Architecture/4-Tier/Service/EmployeeService.asmx). and click Go. You should see similar screen as in Picture - 2, now provide your desired Web Reference name in the box (This is the namespace that you need to use to consume this service in your client application). Finally click Add Reference button and you should see your Solution Explorer something like this.

Picture - 4

Now we have our service in the client application, now write code to pre-populate the Insert Employee Details form (Picture - 1). I have written a method called PopulateRequiredData() and called the service like this. Here SOA.EmployeeService is the service that we just added.

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

PopulateRequiredData();

}

}

 

/// <summary>

/// Populate required data for insert employee detials form

/// </summary>

private void PopulateRequiredData()

{

SOA.EmployeeService es = new EmployeeService();

DataSet dSet = new DataSet();

try

{

dSet = es.GetEmployeeInsertDetails();

dropDept.DataSource = dSet.Tables[0];

dropDept.DataBind();

dropState.DataSource = dSet.Tables[1];

dropState.DataBind();

dropCountry.DataSource = dSet.Tables[2];

dropCountry.DataBind();

}

catch (System.Web.Services.Protocols.SoapException ee)

{

lblMessage.Text = ee.Message;

}

catch (Exception ee)

{

lblMessage.Text = ee.Message;

}

finally

{

dSet.Dispose();

es.Dispose();

}

}

As I know that my service is returning DataSet that has three DataTables so I am binding them to their respective form elements and my form is ready to insert employee records. Now, lets create a InsertRecords method that will fire when user clicks Submit button.

/// <summary>

/// Add records into database

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

protected void AddRecords(object sender, EventArgs e)

{

//Lets validate the page first

if (!Page.IsValid)

return;

 

SOA.Person person = new Person();

person.Address = txtAddress.Text;

person.Age = int.Parse(txtAge.Text);

person.CountryID = int.Parse(dropCountry.SelectedValue);

person.DeptID = int.Parse(dropDept.SelectedValue);

person.District = txtDistrict.Text;

person.FirstName = txtFirstName.Text;

person.LastName = txtLastName.Text;

person.StateID = int.Parse(dropState.SelectedValue);

 

SOA.EmployeeService es = new EmployeeService();

try

{

int result = es.InsertRecords(person);

if (result > 0)

lblMessage.Text = "Records inserted successfully";

}

catch (System.Web.Services.Protocols.SoapException ee)

{

lblMessage.Text = ee.Message;

}

catch (System.Exception ee)

{

lblMessage.Text = ee.Message;

}

finally

{

es.Dispose();

person = null;

}

}

In this method, I have instantiated my Business Object (Person) and set its properties then instantiated my service and passed this object to its InsertRecords method.

Exception Handling

As you can see that I have used two catch blocks to catch two different types of error that might occur. Any error that may occur at service side (such as error in Data Access Layer, Business Access Layer or even in calling different methods inside WebMethod) will fall under first catch (System.Web.Services.Protocols.SoapException) block while any error that may occur at client side like Network problem while calling web service or our service is down for any reason will fall under second catch (System.Exception).

Now try running your client application and insert records, Hopefully you should be able to see "Records Inserted Successfully" message after clicking Submit button. You can download the source code of this demo that contains SOA application with database (containing Tables and Stored Procedure too) and Client Application.

Design Considerations while designing Service Oriented Architecture

The design goal of designing SOA should be to minimize round-trips in getting required data to achieve a particular task. Here web service is not a data dump but a complete service to peform a particular task. The WebMethods should be designed to peform a complete service for the entire page (or task). So in brief our design goals should be following:

  1. Provide a complete web method that can return data or do the work for entire task.
  2. Let the WebMethod invoke whatever objects/services it needs to perform the task.
  3. Return the client the whole service result instead of returning part by part in differnt calls. The way I am returning having three different tables in a single DataSet.

Note that In my case I have returned DataSet object from my Web Service (To keep this demo application simple) despite the fact that it is not completely Platform independent (Java application may find difficulty to understand it), If you want to write SOA application to be platform independent, you may return several blocks of XML for different types of data.

Hope this articles will be help to learn creating and consuming small Service Oriented Architecture application. If you have any feedback, suggestions or comments, please feel free.

Thanks and Happy Coding !!!

Reference:
http://msdn.microsoft.com/en-us/library/aa480021.aspx
http://www.15seconds.com/issue/031215.htm
http://en.wikipedia.org/wiki/Service-oriented_architecture

Page copy protected against web site content infringement by Copyscape
About the Author

SheoNarayan

Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Microsoft_MVP,Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com

Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan
Login to vote for this post.
Found interesting? Add this to:


Comments or Responses

Posted by: Mrshanth on: 7/1/2009

hi...here you are able to access the Person class from the web service in the websites code behind csharp file(Default.aspx.cs) ...could you tell how you made that possible..?
how to create an instance for classes other than webservice class in the website's code behind csharp file..

Posted by: SheoNarayan on: 7/1/2009

When you add Web Reference of the web service, you will have the Person class reference as well.

Try that with the namespace of the Web Service and you should be able to create the instance. In my case the namespace is SOA (Refer Picture - 4).

Thanks

Posted by: Bijay87 on: 2/19/2012 | Points: 25

Again a great article. Can we do unit testing in Service Oriented Architecture ? can we follow test driven development while creating this application? and do you written any article in test driven development?

Login to post response

Comment using Facebook(Author doesn't get notification)