Creating ASP - Net Applications With N-Tier Architecture - CodeProject
Creating ASP - Net Applications With N-Tier Architecture - CodeProject
1 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
home
articles
quick answers
discussions
features
community
Search for articles, questions, tips
help
Articles Web Development ASP.NET General
Prev Next
Stats
Revisions (5)
Article
Browse Code
Alternatives
Comments &
Discussions (48)
Introduction
This article describes how to build ASP.NET applications using n-tier architecture. The benefits of
having n-tier architecture is that all the modules having dedicated functionality will be
independent of each other. Changing one tier will not effect other tiers and there is no single
point of failure even if some tier is not working.
Background
About Article
This article describes how
to build ASP.NET
applications using n-tier
architecture.
Type
Article
Licence
CPOL
First Posted
13 Aug 2012
Views
48,115
Downloads
4,845
Bookmarked
79 times
C# ASP.NET Beginner
N-Tier
In a typical n-tier application there will be 4 Layers. The bottom most layer is the Data layer which
contains the tables and stored procedures, scaler function, table values function. This Data layer
is typically the database engine itself. We will be using SqlServer as the data layer in our
example.
On top of Data Layer, we have a Data Access Layer (DAL). This layer is responsible for handling
Database related tasks i.e. only data access. This Data access layer is created as a separate
solution so that the changes in DAL only need the recompilation of DAL and not the complete
website. The benefit of having this layer as a separate solution is that in case the database engine
is changes we only need to change the DAL and the other areas of the website need not be
changed and recompiled. Also the changes in other areas outside this solution will not demand
for DAL recompilation.
On top of DAL, we have our Business Logic Layer(BLL). BLL contains all the calculations
and Business Rule validations that are required in the application. It is also in a separate solution
for the reason that if the Business rules change or the calculations change we only need to
recompile the BLL and the other layers of the application will remain unaffected.
Finally on top of BLL we have our Presentation Layer. The Presentation layer for an ASP.NET web
forms application is all the Forms (apsx pages and their code behinds) and the classes
contained in the App_Code folder. The Presentation layer is responsible for taking the user input,
showing the data to the user and mainly performing input data validation.
Note: Input data filtration and validation is typically done at the Presentation Layer(Both client
side and server side). The business Rule validation will be done at the BLL.
So to visualize the above mentioned architecture:
12-02-2013 09:17
2 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
Top News
How Newegg crushed the
shopping cart patent and
saved online retail
Get the Insider News free each
morning.
Related Articles
N-Tier Architecture and Tips
Walkthrough: Creating an
N-tier Data Application with a
ASP.NET Presentation Tier
A N-Tier Architecture Sample
with ASP.NET MVC3, WCF, and
Entity Framework
Note: The Data Access Layer in this article was written using classic ADO.NET, due to which the
amount of code in DAL is little too much. Nowadays using ORMs like Entity framework to
generate the DAL is recommended. The DAL code will be generated by ORM itself.
12-02-2013 09:17
3 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
Now we will create a set of stored procedures to perform the operations on the Employees Table.
Collapse | Copy Code
12-02-2013 09:17
4 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
Title = @Title,
Address = @Address,
City = @City,
Region = @Region,
PostalCode = @PostalCode,
Country = @Country,
Extension = @Extension
where
EmployeeID = @EmployeeID
RETURN
The Employee class in the above diagram is the Entity that will represent the Employee table.
This class has been created so that the Layers above the DAL will use this class to perform
operations in Employee table and they need not worry about the table schema related details.
Collapse | Copy Code
//
//
//
//
//
//
//
//
//
should
should
should
should
should
should
should
should
should
be
be
be
be
be
be
be
be
be
(20)
(10)
(30)
(60)
(15)
(15)
(10)
(15)
(4)
chars
chars
chars
chars
chars
chars
chars
chars
chars
only
only
only
only
only
only
only
only
only
12-02-2013 09:17
5 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
{
lastName
= value;
}
}
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
public string Title
{
get
{
return title;
}
set
{
title = value;
}
}
public string Address
{
get
{
return address;
}
set
{
address = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public string Region
{
get
{
return region;
}
set
{
region = value;
}
}
public string PostalCode
{
get
{
return postalCode;
}
set
{
postalCode = value;
}
}
public string Country
{
get
{
return country;
}
set
{
country = value;
}
}
public string Extension
{
get
12-02-2013 09:17
6 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
{
return extension;
}
set
{
extension = value;
}
}
}
The EmployeeDBAccess class expose the methods to perform the CRUD operations on the
Employee table.
Collapse | Copy Code
12-02-2013 09:17
7 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
employee.LastName = row["LastName"].ToString();
employee.FirstName = row["FirstName"].ToString();
employee.Title = row["Title"].ToString();
employee.Address = row["Address"].ToString();
employee.City = row["City"].ToString();
employee.Region = row["Region"].ToString();
employee.PostalCode = row["PostalCode"].ToString();
employee.Country = row["Country"].ToString();
employee.Extension = row["Extension"].ToString();
}
}
return employee;
}
public List<employee> GetEmployeeList()
{
List<employee> listEmployees = null;
//Lets get the list of all employees in a datataable
using (DataTable table =
SqlDBHelper.ExecuteSelectCommand("GetEmployeeList", CommandType.StoredProcedure))
{
//check if any record exist or not
if (table.Rows.Count > 0)
{
//Lets go ahead and create the list of employees
listEmployees = new List<employee>();
//Now lets populate the employee details into the list
of employees
foreach (DataRow row in table.Rows)
{
Employee employee = new Employee();
employee.EmployeeID =
Convert.ToInt32(row["EmployeeID"]);
employee.LastName = row["LastName"].ToString();
employee.FirstName =
row["FirstName"].ToString();
employee.Title = row["Title"].ToString();
employee.Address = row["Address"].ToString();
employee.City = row["City"].ToString();
employee.Region = row["Region"].ToString();
employee.PostalCode =
row["PostalCode"].ToString();
employee.Country = row["Country"].ToString();
employee.Extension =
row["Extension"].ToString();
listEmployees.Add(employee);
}
}
}
return listEmployees;
}
}
</employee></employee></employee>
The class SqlDbHelper is a wrapper class for ADO.NET functions providing a more simpler
interface to use by the rest of DAL.
Collapse | Copy Code
class SqlDBHelper
{
const string CONNECTION_STRING = @"Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;User
Instance=True";
// This function will be used to execute R(CRUD) operation of parameterless
commands
internal static DataTable ExecuteSelectCommand(string CommandName, CommandType
cmdType)
{
DataTable table = null;
using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = cmdType;
cmd.CommandText = CommandName;
try
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
using (SqlDataAdapter da = new
SqlDataAdapter(cmd))
12-02-2013 09:17
8 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
{
table = new DataTable();
da.Fill(table);
}
}
catch
{
throw;
}
}
}
return table;
}
// This function will be used to execute R(CRUD) operation of parameterized
commands
internal static DataTable ExecuteParamerizedSelectCommand(string CommandName,
CommandType cmdType, SqlParameter[] param)
{
DataTable table = new DataTable();
using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = cmdType;
cmd.CommandText = CommandName;
cmd.Parameters.AddRange(param);
try
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
using (SqlDataAdapter da = new
SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
catch
{
throw;
}
}
}
return table;
}
// This function will be used to execute CUD(CRUD) operation of parameterized
commands
internal static bool ExecuteNonQuery(string CommandName, CommandType cmdType,
SqlParameter[] pars)
{
int result = 0;
using (SqlConnection con = new SqlConnection(CONNECTION_STRING))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = cmdType;
cmd.CommandText = CommandName;
cmd.Parameters.AddRange(pars);
try
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
result = cmd.ExecuteNonQuery();
}
catch
{
throw;
}
}
}
return (result > 0);
}
}
Note: If we use any ORM(Object Relation Mapper) then DAL need not be written. The ORM will
generate all the DAL code. Entity framework is one of the best ORMs available. This DAL can
simply be replaced with a class library containing the Entity Framework generated Entities
12-02-2013 09:17
9 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
and Contexts.
12-02-2013 09:17
10 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
emp.Region = txtRegion.Text;
emp.PostalCode = txtCode.Text;
emp.Extension = txtExtension.Text;
emp.Title = txtTitle.Text;
EmployeeHandler empHandler = new EmployeeHandler();
if (empHandler.AddNewEmployee(emp) == true)
{
//Successfully added a new employee in the database
Response.Redirect("Default.aspx");
}
Note: All the CRUD operations have been implemented. Please refer tio the sample code for all
the details. When we run the application we can see all the EDIT/UPDATE, DELETE and ADD
operations in action.
Point of Interest
I created this small application to demonstrate application development using n-tier architecture.
The demo application has been created to show the basic idea behind the 3-tier architecture.
There are many things that are still missing from this sample from the completion perspective.
Client side validation and server side validation in presentation layer, Business rule validation and
calculations in BLL are some missing things.
Since the idea here was to talk about how to put n-tier architecture in actual code, I think this
article might have provided some useful information on that. I hope this has been informative.
History
12-02-2013 09:17
11 of 12
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
License
This article, along with any associated source code and files, is licensed under The Code Project
Open License (CPOL)
Rahul
Rajat
Singh
Software
Developer
(Senior)
India
Member
Follow on
Twitter
I Started my Programming career with C++. Later got a chance to develop Windows Form
applications using C#. Now using C# & ASP.NET to write Information Systems, e-commerce/egovernance Portals and Data driven websites.
My interests involves Programming, Website development and Learning/Teaching subjects
related to Computer Science/Information Systems.
Some CodeProject Achievements:
2nd in Best C# article of December 2012
5th in Best overall article of December 2012
5th in Best C# article of October 2012
4th in Best Web Dev article of September 2012
3rd in Best C# article of August 2012
5th in Best Web Dev article of August 2012
5th in Best Web Dev article of July 2012
3rd in Best Overall article of June 2012
2nd in Best Web Dev article of June 2012
5th in Best Web Dev article of May 2012
6th in Best Web Dev article of April 2012
4th in Best C++ article of April 2012
5th in Best C++ article of March 2012
7th in Best Web Dev article of March 2012
5th in Best Web Dev article of February 2012
7th in Best Web Dev article of February 2012
9th in Best Web Dev article of February 2012
5th in Best C++ article of February 2012
Article Top
Like
13
Tweet
11
Excellent
Vote
12-02-2013 09:17
http://www.codeproject.com/Articles/439688/Creating-ASP-NET-appli...
Spacing Relaxed
Noise Medium
Go
Layout Normal
Per page 25
Update
Shantanu Chandra
Excellent
rashidalikhan
xport
Chinni007
YinYang2050
Member 1208478
Master detail
s_safdar
vsanju
My vote of 5
Darkjo
My vote of 5
Savalia Manoj M
Very good.
mark merrens
Excellent
Shashank Shrivastava
Re: Excellent
Re: Excellent
Sanjay K. Gupta
Re: Excellent
My vote of 4
pradiprenushe
My vote of 3
mahdi87_gh
N Tier or layer
Sakshi Smriti
General
News
Sakshi Smriti
Sakshi Smriti
Suggestion
Question
Refresh
Bug
Answer
Joke
1 2
Rant
Next
Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130211.1 | Last Updated 21 Aug 2012
12 of 12
12-02-2013 09:17