Abstract
This article has two major parts. In the first part we will explain 3-Tier Architecture and in the second part we will implement an ASP.NET example to practice the 3-Tier design. You need Visual Studio, IIS and a Microsoft SQL Server to follow this article.
Figure 0: TimeEntry.aspx
Contents
1. 3-Tier Architecture
1.0 Definition and Motivation.02
1.1 Data Tier,,,04
1.2 Logical Tier ..04
1.2.1 Business Tier.05
1.2.2 Data Access Tier........05
1.3 Presentation Tier....05
2. Creating a 3-Tier ASP.NET application
2.1 Installing the web application TimeManagement..05
2.2 Implementing of Data Tier....07
2.2.1 Table Person...07
2.2.2 Table ProjectI.08
2.2.3 Table ProjectInvolvement.08
2.3 Implementing Logical Tier....10
2.3.1 Implementing Data Access Tier.10
2.3.2 Implementing Business Tier........ 18
2.4 Implementing Presentation Tier.....20
2.5 Conclusion..23
2.6 Reference...23
1. 3-Tier Architecture
1.0 Definition and motivation
A 3-tier application is organized into three major disjunctive (independent) tiers. These tiers are:
- Presentation Tier (Front end)
- Logical Tier (Middleware)
- Data Tier (Back end).
Each layer can be deployed in separate computers in a network. Some architects divide the Logic Tier into two sub-tiers, Business and Data Access Tiers, to increase scalability and transparency. The tiers can be deployed on physically separated machines. The characteristics of the tier communication is that the tiers will communicate only with their adjacent neighbors. For an example, the Presentation Tier will interact directly with the Business Tier and not directly with Data Access or Data Tiers.
Figure 1 (A typical 3-Tier Architecture)
The Figure 1 shows a typical 3-Tier Architecture scenario. I think we should look back at the history of computing to understand the advantages of 3-Tier Architecture.
Mainframes ruled the IT landscape until the mid 1980s. The main characteristic of a Host Architecture is that the application and databases reside on the same host computer and the user interacted with the host using an unfriendly and dumb terminal. This monolith architecture does not support distributed computing (the host applications are not able to connect with a database of a strategically allied partner). Some mangers found that developing a host application took too long and was too expensive. Consequently these disadvantages led to a Client-Server (C/S) architecture.
In fact, a Client Server (C/S) architecture is a 2-Tier architecture because the client does not distinguish between the Presentation Tier and the Logic Tier. That is why we call this type of client a Fat Client. The increasing demands on GUI controls caused difficulty in managing the mixture of source code from GUI and Business Logic (Spaghetti Code). Further, C\S Architecture does not support enough Change Management. Let us suppose that the government increases the consumer tax rate from 14% to 16%, then in the C\S case, you need to send an update to each client and they must update synchronously on a specific time otherwise you may store corrupt information. The C/S Architecture is also a burden to network traffic and resources. Let us assume that about five hundred clients are working on a data server, then we will have five hundred ODBC connections and several ruffian record sets, which must be transported from the server to the clients (because the Business Logic Tier is situated in the client side). The fact that C/S does not have any caching facilities like in ASP.NET, caused additional traffic in the network. In the late 1990s, designers have shifted the Business Logic from the client to server to elude the handicaps from C/S Architecture. Normally, a server has a better hardware than client therefore it is able to compute algorithms faster than a client, so this fact is also an additional pro argument for the 3-Tier Architecture.
Now let us return to our 3-Tier Architecture and start to explore the tiers.
1.1 Data Tier
The Data Tier is responsible for retrieving, storing and updating information, therefore this tier is ideally represented by a commercial database. We consider Stored Procedures as a part of tte Data Tier. Usage of Stored Procedures increases the performance and code transparency of an application.
1.2 Logical Tier
The Logic Tier is the brain of the 3-Tier application. Some architects do not make any distinction between Business Tier and Data Access Tier. Their main argumentation is that additional tiers will degrade down performance. I think that it is more advantageous to separate the Logical Tier into a Business Tier and a Data Access Tier. Some of these advantages are:
- Increases code transparency
- Supports changes in Data Layer. You can change or alter a database without touching the Business Layer and this would be a very minimumal touch up.
1.2.1 Business Tier
This sub-tier consists of classes to calculate aggregated values, such as total revenue, cash flow and ebit and this tier doesn't know about any GUI controls and how to access databases. The classes of a Data Access Tier will supply the needy information from the databases to this sub-tier.
1.2.2 Data Access Tier
The Data Access Tier acts as an interface to the Data Tier. This tier knows how to (from which database) retrieve and store information.
1.3 Presentation Tier
The Presentation Tier Tier is responsible for communication with the users and web service consumers and it will use objects from the Business Layer to respond to GUI raised events.
After this brief theory, I think we should move now to the practical part. Our purpose is to develop a work diary for employees, in which they can record daily project activities.
2. Creating a 3-Tier ASP.NET application
You need SQL Server, IIS and Microsoft .NET CLR to run the example application. Use the following procedure to create the sample ASP.NET application.
2.1 Installing the web application Timemanagement
Use the following procedure to install the web application TimeManagement on your machine.
- Create a new SQL Server database with the name TimeManagement and execute the file TimeManagement.sql (included in the Zip file) using the tool SQL Query Analyzer to create the necessary tables and Stored Procedures for this application.
- Create an ASP.Net Appliaction "TimeManagement" and replace it with the file TimeManagement that you find in the .zip file.
- Adjust the XML Element <appsettings> in the Web.config file to establish a SQL connection. (Modify the value from Sqlconnection.)
<appSettings>
<addkey="SqlConnect" value="server=F5;database=TimeManagement;uid=sa;pwd=moses;" />
</appSettings>
- Set the Page LogIn.aspx as the start page.
I hope now that you can run the web application.
2.2 Implementing of Data Tier
This tier is represented by the SQL Server database TimeManagement and it has 3 tables. Figure 2 shows the ERD diagram of the database TimeManagement. I will now describe the tables briefly.
Figure 2
2.2.1 Table Person
This table stores information about employees. The attribute PersID is the primary key of this table and the database will increment this value automatically during insertion of a new data row. The values of the attribute Email correspond with the values of the attribute PersID. In order to obtain this relationship, the application must keep the values of the attribute Email unique. We have implemented this rule in the Stored Procedure InsertPerson (see Figure 3) that inserts a new record.
CREATE PROCEDURE InsertPerson
(
@Name char(50),
@CName char(50),
@WeekHour int,
@Password
char(50),
@EMail char(50),
@AlreadyIn int out
)
AS
SELECT @AlreadyIn=COUNT(*) FROM Person WHERE EMail=@EMail
IF @AlreadyIn=0
INSERT INTO Person
(Name ,CName ,WeekHour ,Password ,EMail )
VALUES
(@Name ,@CName ,@WeekHour ,@Password ,@EMail )
GO
Figure 3
2.2.2 Table Project
This table stores information about the projects of a firm. The attribute ProjID is the key of this table and it will be automatically incremented by the database during the insertion of a new row. The attribute Leader is a foreign key of the table Person.
2.2.3 Table ProjectInvolvement
This table contains information to answer questions, such as: how many hours have been spent by employee X in the project P on a specific day? The key attributes of this table are EntryDate, ProjID and PersID. The attribute ProjID is a foreign key of the Table Project and the attribute is PersID is a foreign key of the table Person.
Figure 4 ( partial class diagram of the application TimeManagement)
2.3 Implementing Logical Tier
2.3.1 Implementing Data Access Tier
All classes of the Data Access Tier are derived from the super class DABasis (see Figure 4), that is responsible for establishing a database connection.
<appSettings>
<addkey="SqlConnect" value="server=F5;database=TimeManagement;uid=sa;pwd=moses;" />
</appSettings>
Figure 5 (partial source code from Web.config)
/// <summary>
/// This is the super class for Data Access Classes
/// </summary>
class DABasis
{
protected static string strConnect;
public DABasis()
{
}
/// <summary>
/// Please see the web.config file
/// </summary>
static DABasis()
{
strConnect=ConfigurationSettings.AppSettings["SqlConnect"];
}
/// <summary>
/// Gets a SqlConnection to the local sqlserver
/// </summary>
/// <returns>SqlConnection</returns>
protected SqlConnection GetConnection()
{
SqlConnection oConnection = new SqlConnection(strConnect);
return oConnection;
}
}
Figure 6 (class DABasis)
We have stored the global application attributes, such as the string SqlConnect in the configuration file Web.config and you can retrieve this value using the sealed class ConfigurationSettings (see Figure 6: static DABasis()).
Now to show an exemplary typical data access method of a DataAccess class to retrieve a Dataset or insert or update some data rows. In our implementation we distinguish two types of Data Access methods, they are:
- Query Data Access Method: used typically to retrieve data structures like DataSet or DataTable from tables.
- Non Query Data Access Method: used typically to update a table or insert a data row in to a table.
At first, we will look at a Query Data Access Method. The class DAPInvolvement wraps a bundle of data access methods that deal with the matter project involvement. The method void Dataset DAPInvolvement.GetDayRecord(int nPersID,DateTime dtEntry) (see Figure 8) will return a dataset containing all project activities of a person with the ID PersID on a specific day dtEntry This method uses the Stored Procedure GetDayRecord (see Figure 7) to retrieve essential data from the tables ProjectInvolvement and Project.
CREATE PROCEDURE GetDayRecord
(
@PersID int,
@EntryDate datetime
)
AS
SELECT P.Name, P.ProjID, PI.Duration
FROM ProjectInvolvement PI , Project P
WHERE PI.PersID= @PersID and PI.ProjID=P.ProjID and PI.EntryDate=@EntryDate
Figure 7 (Store Procedure GetDayRecord)
/// <sumary>
/// gives the list of activities of the (person)ID for the particular EntryDate
/// </summary>
/// <param name="nPersID">PersID attribute of ProjectInvolvement</param>
/// <param name="dtEntry">EntryDate attribute of ProjectInvolvement</param>
/// <returns>DataSet and the table name is "dtDayRecord" </returns>
public DataSet GetDayRecord(int nPersID,DateTime dtEntry)
{
SqlConnection oConnection = GetConnection();
// build the command
SqlCommand oCommand = new SqlCommand("GetDayRecord",oConnection);
oCommand.CommandType=CommandType.StoredProcedure; // Parametrs
SqlParameter paraPersID= new SqlParameter("@PersID",SqlDbType.Int,4);
paraPersID.Value=nPersID;
oCommand.Parameters.Add(paraPersID);
SqlParameter paraEntryDate=
new SqlParameter("@EntryDate",SqlDbType.DateTime);
paraEntryDate.Value=dtEntry;
oCommand.Parameters.Add(paraEntryDate);
// Adapter and DataSet
SqlDataAdapter oAdapter= new SqlDataAdapter();
oAdapter.SelectCommand=oCommand;
DataSet oDataSet = new DataSet();
try
{
oConnection.Open();
oAdapter.Fill(oDataSet,"dtDayRecord");return oDataSet;
}
catch(Exception oException){
throw oException;
}
finally
{
oConnection.Close();
}
}
Figure 8 (The method DAPInvolvement.GetDayRecord)
A typical Query Data Access method might be abstractly described as:
- Establishes a SqlConnection.
- Creates a SqlCommand and necessary SqlParameters to the command.
- Creates a DataSet and a SqlDataAdapter.
- Opens the connection and fills the DataSet using the SqlDataAdapter.
- Closes the SqlConnection.
Some of you may ask the question, why are we using a DataSet instead of a SqlDataReader. Indeed, you can retrieve data rows faster using a SqlDataReader than a Dataset, but if you want to use a WebService then you ought to use a DataSet because it is not possible to transmit a SqlDataReader using SOAP protocol. You can transmit via SOAP all the objects that belong to the types:
- DataSet (ADO.NET)
- Complex Arrays
- XML nodes
I want to now show a typical Non-Query Data Access method. The DataAccess method:
public void DAProject.Insert(string strName,string strDescription,int nLeader,out int nAlreadyIn)
(see Figure 10) inserts a new project into the database and it uses the Stored Procedure InsertProject.
(see Figure 9). The out parameter of this method out int nAlreadyIn serves as a flag to the classes of the Business Logic Tier, whether the record is inserted by this method or not.
CREATE PROCEDURE InsertProject
(
@Name char(50),
@Description char(150),
@Leader int,
@AlreadyIn int output
)
AS
SELECT @AlreadyIn = Count(*) From Project WHERE Name=@Name
IF @AlreadyIn =0
INSERT INTO Project
(Name,Description,Leader)
VALUES
(@Name,@Description,@Leader)
GO
Figure 9 (store procedure InsertProject)
/// <summary>
/// inserts a new data row into the table "project"
/// </summary>
/// <param name="Name"></param>
/// <param name="Description"></param>/// <param name="Leader">a foreign key
from Person</param>
/// <param name="AlreadyIn">number of records which fulfill the term "Name=strName"
efore the Insertation</param>
public void Insert(string strName,string strDescription,int nLeader,
out int nAlreadyIn)
{
// Establish Connection
SqlConnection oConnection = GetConnection();
// build the command
SqlCommand oCommand = new SqlCommand("InsertProject",oConnection);
oCommand.CommandType=CommandType.StoredProcedure;
// Parameters
SqlParameter paraName= new SqlParameter("@Name",SqlDbType.Char,50);
paraName.Value=strName;
oCommand.Parameters.Add(paraName);
SqlParameter paraDescription= new SqlParameter("@Description",SqlDbType.Char,150);
paraDescription.Value=strDescription; oCommand.Parameters.Add(paraDescription);
SqlParameter paraLeader = new SqlParameter("@Leader",SqlDbType.Int);paraLeader.Value=nLeader;
oCommand.Parameters.Add(paraLeader);
SqlParameter paraAlreadyIn = newSqlParameter("@AlreadyIn",SqlDbType.Int);
paraAlreadyIn.Direction=ParameterDirection.Output;
oCommand.Parameters.Add(paraAlreadyIn);
try
{
oConnection.Open();
oCommand.ExecuteNonQuery();
nAlreadyIn=(int) paraAlreadyIn.Value;
}
catch(Exception oException){
throw oException;}
finally
{
oConnection.Close();
}
}
Figure 10 (Method DAProject.Insert)
A typical Non-Query Data Access method might be described abstractly as:
(see Figure 10)
- Establishes a SqlConnection.
- Creates a SqlCommand and the SqlParameters to the command.
- Opens the connection and executes the query.
- Retrieves the values from all output parameters.
- Closes the SqlConnection.
public class BLBasis
{
// Current HttpContext
protected HttpContext oCurrentContext;
public BLBasis()
{
oCurrentContext= HttpContext.Current;
}
/// <summary>
/// returns true, if the web client authorized or not
/// </summary>
public bool IsAuthenticated
{
get
{
return oCurrentContext.User.Identity.IsAuthenticated;
}
}
/// <summary>
/// returns the UserID,if the user already authorized
/// </summary>
public int UserId
{
get
{
f(IsAuthenticated)
{
string strHelp=oCurrentContext.User.Identity.Name;
return Int32.Parse(strHelp);
}else
{
return -1;
}
}
}
}
Figure 11 (class BLBasis)
2.3.2 Implementing Business Tier
All classes of the Business Tier have the super class BLBasis (Figure 11) and it will supply its derived classes session relevant information, such as UserID. The web application uses the attribute UserID to identify the current user. We use the method public static void FormsAuthentication.Redirect-FromLoginPage(string userName, bool createPersistentCookie) to assign the user identity into the current instance of the HttpContext class.
Let us now analyze a class of this tier in order to understand the pattern. The class BLPInvolvement is a Business Logic class and gathers all interrelated methods, that deal with the topic project involvement. The method public void BLPInvolvement.GetDayRecord(DateTime dtEntry,out double dTotal out DataSet dsDayRecord) (see Figure 12) is responsible for passing a Dataset and a numeric value to the Presentation Layer.
Figure 12 ( class BLPInvolvement)
A typical Business Logic method might be described abstractly like this:
- Instantiates a Data Access object
- Retrieves the crude data
- Calculates business values from the crude data
2.4 Implementing Presentation Tier
We have used ASP.NET to implement the Presentation Layer. Now to show you an exemple, how the Presentation Layer communicates with the Data Access Layer. Figure 0 shows the web side TimeEntry.aspx, where an employee can record his project activities for a certain day. The method private void TimeEntry.btnEnter_Click(object sender, System.EventArgs e) is a callback method that will be activated if the user pushes the Enter button.
/// <summary>
/// this method populates datagrid dgSummary
/// </summary>
void PopulateDataGrid(DateTime dtEntry)
{
try
{
// retrive DataSet and bind to the datagrid
BLPInvolvement oBLPInvolvement = new BLPInvolvement();
DataSet oDataSet;
double dTotalDuration;
oBLPInvolvement.GetDayRecord(dtEntry,out dTotalDuration,out oDataSet);
DataTable dtDayRecord=oDataSet.Tables["dtDayRecord"];
if(dtDayRecord.Rows.Count>0)
{
dgSummary.DataSource=dtDayRecord;
dgSummary.DataBind();
lbDGTitel.Text="Date: "+dtEntry.ToShortDateString()
+" Sum: "+dTotalDuration.ToString();
}
else
{
dgSummary.DataSource=null;dgSummary.DataBind();
lbDGTitel.Text="No Records found";
}
}
catch(Exception oException)
{
this.HelpException(oException);
}
}
/// <summary>/// It is used publish exception text
/// </summary>
/// <param name="oException"></param>
private void HelpException(Exception oException)
{
if(lbMessage.Text!="")
{
lbMessage.Text+=oException.Message;
}
else
lbMessage.Text=oException.Message;
}
Figure 12 (Extract from the class TimeEntry)
Figure 12 shows a partial source code, that is responsible for inserting a new project involvement record. The method takes the following steps to accomplish the task:
- Draw off the values from GUI controls.
- Instantiate an object from the Class BLPInvolvement and inserts it into the database.
- Update the other involved GUI controls.
- Publishes the error message if an error occurred in the Logic Tier or in the Data Tier.
2.5 Conclusion
If we look back at implementation phase, we can say that it is quite simple to build a 3-Tier Architecture using Microsoft.NET. I think the following tips are useful to increase transparency and stability of the system:
- Follow the adjacent rule (Don't jump over a neighbor tier because it makes us easy to follow systematically from the button click to the database access).
- Use the Web.config file to define global values.
- Use try, catch and finally control structures in every tier to track bugs.
2.6 Reference
Heide Balzert :Objektorientierung in 7 Tagen , Spektrum Akademischer Verlag Heidelberg.Berlin 2000
MSDN.