Monday, August 3, 2009

N-Tier Architecture !!

Dev Palmistry

3-Tier Architecture in ASP.NET with C#

3-Tier architecture is a very well know buzz word in the world of software development whether it web based or desktop based. In this article I am going to show how to design a web application based on 3-tier architecture.

Introduction

3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer (BAL) or Business Logic Layer and Data Access Layer (DAL).

Presentation Layer (UI)
Presentation layer cotains pages like .aspx or windows form where data is presented to the user or input is taken from the user.

Business Access Layer (BAL) or Business Logic Layer
BAL contains business logic, validations or calculations related with the data, if needed. I will call it Business Access Layer in my demo.

Data Access Layer (DAL)

DAL contains methods that helps business layer to connect the data and perform required action, might be returning data or manipulating data (insert, update, delete etc). For this demo application, I have taken a very simple example. I am assuming that I have to play with record of persons (FirstName, LastName, Age) and I will refer only these data through out this article.


Designing 3-Tier Architecture

For the ease of understanding, I have created BAL, DAL into the App_Code folder. In real scenario, you should create separate projects for BAL, DAL (as Class Library) and UI (as Web project) and reference your BAL into UI.



Data Access Layer
Lets proceed with desiging 3-Tier architecture. To do that lets proceed with DAL, BAL and then UI. Add a class named by right clicking App_Code folder. (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for DAL and add reference of this project into your BAL.) and copy-paste folowing code (Your can overwrite your default written code for the class file by pasting this code). Here, I have assumed that you will create the respective stored procedure yourself into the database or you may download attachment from http://www.dotnetfunda.com/articles/article18.aspx article and look for App_Data folder for complete database structure and stored procedure for this article.

Data Access Layer (DAL)


Code for Data Access Layer



In the above code, I have a member variable called connStr that is getting database connection string from my web.config file that is being used through out the class. I have separate method for inserting, deleting, updating records into database and loading records from database. I am not goint into details of how I am connecting database and manipulating the data just to make this tutorials short.


Business Access Layer (BAL)

Now, create a class named PersonBAL3 into App_Code folder by right clicking it and write respective methods for calling Insert, Delete, Update and Load methods of Data Access Layer class file (PersonDAL3) (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for BAL and add reference of this project into your Presentation Layer). As we don't have any business logic here so simply instantiate the PersonDAL3 class of DAL and call methods. Below is the code for BAL (Your can overwrite your default written code for the class file by pasting this code).




Till now we haev our Business Access Layer and Database Access Layer ready. Now we have to write our Presentation Layer that will use our Business Access Layer methods. Lets create a form that will have three textboxes for FirstName, LastName and Age.


Presentation Layer




Create an Insert.aspx page (make is as Startup page) and copy paste following code to bring the insert form something like displaying in the picture.
Code for Insert Record form


















































Add Records


First Name:








Display="dynamic">




Last Name:








Display="dynamic">




Age:








Display="dynamic">



Operator="DataTypeCheck" Type="Integer">


 







Now, lets write method that will fire when Submit button will be clicked on the from.
Code for AddRecords method


protected void AddRecords(object sender, EventArgs e)

{

//Lets validate the page first

if (!Page.IsValid)

return;



int intResult = 0;

// Page is valid, lets go ahead and insert records

// Instantiate BAL object

PersonBAL3 pBAL = new PersonBAL3();

// Instantiate the object we have to deal with

string firstName = txtFirstName.Text;

string lastName = txtLastName.Text;

int age = Int32.Parse(txtAge.Text);



try

{

intResult = pBAL.Insert(firstName, lastName, age);

if (intResult > 0)

lblMessage.Text = "New record inserted successfully.";

else

lblMessage.Text = "FirstName ["+ txtFirstName.Text +"] alredy exists, try another name";



}

catch (Exception ee)

{

lblMessage.Text = ee.Message.ToString();

}

finally

{

pBAL = null;

}

}


In the above code, first I am validating the page by using Page.IsValid method just to check if correct data has been entered. Then I have instantiated PersonBAL3 and calling Insert method of it (pBAL.Insert) by passing firstName, lastName, age as parameter.

Dispalying Records into GridView




Create a .aspx file called List.aspx and create a GridView something like displayed into the picture. To list the record into GridView that will also enable us to Edit, Delete record, copy paste following code.

Code for GridView



DataKeyNames="PersonID" AutoGenerateEditButton="True" AutoGenerateColumns="False"

OnRowEditing="EditRecord" OnRowUpdating="UpdateRecord" OnRowCancelingEdit="CancelRecord"

OnRowDeleting="DeleteRecord" PageSize="5" >























<%# Eval("FirstName") %>





asp:TextBox ID="txtFName" runat="Server" Text='<%# Eval("FirstName") %>'>









<%# Eval("LastName") %>





asp:TextBox ID="txtLName" runat="Server" Text='<%# Eval("LastName") %>'>









<%# Eval("Age") %>





asp:TextBox ID="txtAge" runat="Server" Text='<%# Eval("Age") %>'>

























Code to Load records and Displaying Records into GridView


private DataTable BindGrid()

{

PersonBAL3 p = new PersonBAL3();



try

{

DataTable dTable = p.Load();

GridView1.DataSource = dTable;

GridView1.DataBind();

}

catch (Exception ee)

{

lblMessage.Text = ee.Message.ToString();

}

finally

{

p = null;

}



return dTable;

}


In the above method I am instantiating PersonBAL3 class and calling Load method to get the record into DataTable and binding it into GridView.

Code to Delete Records


protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)

{

int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());





// instantiate BAL

PersonBAL3 pBAL = new PersonBAL3();

try

{

pBAL.Delete(personID);



lblMessage.Text = "Record Deleted Successfully.";

}

catch (Exception ee)

{

lblMessage.Text = ee.Message.ToString();

}

finally

{

pBAL = null;

}



GridView1.EditIndex = -1;

// Refresh the list

BindGrid();

}


Above method will fire when Delete link will be clicked on the GridView. In the above code, I am instantiating PersonBAL3 and calling Delete method by passing personID as parameter so that select reocrds will be deleted from datbase.




Above method will fire when Update link will be clicked for a particular row of the GridView in edit mode. In the above method, I am instantiating PersonBAL3 and calling the Update method by p[assing required parameters.

Now we have all set to go, now just run your project and try inserting records. You can also navigate to another page your created (list.aspx) and try updating, deleting records.

Conclusion

By using 3-Tier architecture in your project you can achive

1. Seperation - the functionality is seperated from the data access and presentation so that it is more maintainable
2. Independence - layers are established so that if one is modified (to some extent) it will not affect other layers.
3. Reusability - As the layers are seperated, it can exist as a module that can be reused by other application by referencing it.

Hope this article helped you understanding 3-Tier architecture and desiging it.

Thanks and Happy Coding !!!

2 comments:

SeeSharpWriter said...

Hello, I have read your article. Basically I agree with the benefits that you have mentioned and your approach is quite intereseting. But I usually prefer to add little more abstraction to the layers, I have written some more code to extend and generalize the functionality the layers provide. I have also standardized the way layers communicate with each other by defining a special set of objects they can exchange. I would like you to read my post about N-tier architecture:
Writing Data Access Layer (DAL) and Business Access Layer (BAL) with CsharpGears Framework and tell me what do you think about my approach.

Anonymous said...

Hello !.
might , perhaps very interested to know how one can collect a huge starting capital .
There is no need to invest much at first. You may commense earning with as small sum of money as 20-100 dollars.

AimTrust is what you haven`t ever dreamt of such a chance to become rich
The company incorporates an offshore structure with advanced asset management technologies in production and delivery of pipes for oil and gas.

Its head office is in Panama with affiliates around the world.
Do you want to become a happy investor?
That`s your choice That`s what you desire!

I`m happy and lucky, I began to take up real money with the help of this company,
and I invite you to do the same. It`s all about how to choose a correct companion utilizes your savings in a right way - that`s the AimTrust!.
I take now up to 2G every day, and my first deposit was 1 grand only!
It`s easy to start , just click this link http://sopigyse.maddsites.com/inatos.html
and lucky you`re! Let`s take this option together to get rid of nastiness of the life