Professional Documents
Culture Documents
1. 3.Tier Architecture
1. 3-Tier Architecture
A 3-tier application is a program which is organized into three major disjunctive tiers.
These tiers are
The Figure 1 shows a typical 3.Tier Architecture scenario. I think, we should look
back the history of computing to understand the advantages of 3.Tier Architecture.
Mainframes ruled the it-landscape until mid 1980s .The main characteristic of a Host
Architecture is that the application and databases reside on the same host computer
and the user interact with the host using an unfriendly and dump terminal. This
monolith architecture does not support distributed computing (the host applications
are not able to connect a database of a strategically allied partner). Some mangers
found that developing a host application take too long and expensive. Consequently
led these disadvantages to Client-Server(C/S) architecture.
Now let us go back to our 3.Tier Architecture and start to explore the tiers.
This Tier is responsible for retrieving, storing and updating from Information
therefore this tier can be ideally represented through a commercial database. We
consider stored procedures as a part of te Data Tier. Usage of stored procedures
increases the performance and code transparency of an application
This 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 screw down performance. I think that we will have more
advantages, if we separate Logical Tier in to Business Tier and Data Access Tier.
Some of these advantages are
This sub tier contents classes to calculate aggregated values such like total revenue,
cash flow and ebit and this tier doesnt know about any GUI controls and how to
access databases. The classes of Data Access Tier will supply the needy information
from the databases to this sub tier.
This tier acts as an interface to Data Tier. This tier knows, how to (from which
database) retrieve and store information.
This Tier is responsible for communication with the users and web service consumers
and it will use objects from Business Layer to response GUI raised events.
After this brief theory, I think we should move now to the practical part. Our aim is
to develop a work diary for employees, in which they can record daily project
activities.
You need a SqlServer, IIS and Microsoft.NET CLR to run the example application.
Please follow the steps to run the ASP.NET application.
1. Create a new Sql Server database with the name TimeManagement and
execute the file TimeManagement.sql (included the Zip file) by using the tool
SQL Query Analyzer to create the needed tables and store procedures for this
application.
<appSettings>
<addkey="SqlConnect"
value="server=F5;database=TimeManagement;uid=sa;pwd=moses;" />
</appSettings>
Fig 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 bijectively
to the values of the attribute PersID. In order to obtain this relationship, application
must keep the values of attribute Email unique. We have implemented this rule in
the stored procedure InsertPerson (see fig 3), which is used to insert a new record.
@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
Fig 3
This table stores information about 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 a new row. The attribute Leader is a foreign key of the table Person.
This table contents information to answer questions such like: how many hours has
spent 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.
Fig 4 ( partial class diagram of the application TimeManagement)
All classes of Data Access Tier are derived from the super class DABasis(See Fig 4),
which is responsible for establishing database connection.
<appSettings>
<addkey="SqlConnect"
value="server=F5;database=TimeManagement;uid=sa;pwd=moses;" />
</appSettings>
/// <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;
}
}
We have stored the global application attributes such like string SqlConnect in the
configuration file Web.config and you can retrieve this value using the sealed class
ConfigurationSettings (See Fig 6: static DABasis()).
We like to show you now exemplary typical data access methods of a DataAccess
class, which are used retrive a Dataset or insert or update some data rows. In our
implementation we distinguish two types Data Access methods and they are:
• Query Data Access Method: which are used typically to retrieve data
structures like DataSet or DataTable from tables.
• Non Query Data Access Method: which are used typically to update a table or
insert a data row in to a table.
/// <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();
}
}
Fig 8 (The method DAPInvolvement.GetDayRecord)
A typical Query Data Access method might be abstractly described like this:
• Establish SqlConnection.
• Create a SqlCommand and necessary SqlParameters to the command.
• Create a DataSet and a SqlDataAdapter.
• Open the connection and fill the DataSet with help of the SqlDataAdapter.
• Close the SqlConnection.
Some of you may ask the question, why we are using a DataSet instead a
SqlDataReader. Indeed , you can retrieve data rows faster using a SqlDataReader
than a Dataset, but if you want use WebService, you ought to use DataSet. Because
it is not possible to transmit a SqlDataReader using SOAP protocol. You can transmit
via SOAP all objects which are belong to the types:
• DataSet (ADO.NET)
• Complex Arrays
• XML nodes
Now, I want to show a typical Non Query Data Access method. The DataAccess
method:
(see Fig 9). The out parameter of this method out int nAlreadyIn serves as a flag to
the classes of Business Logic Tier, whether the record is inserted by this method or
not.
throw oException;}
finally
{
oConnection.Close();
}
}
A typical Non Query Data Access method might be described abstractly like this:
All classes of Business Tier have the super class BLBasis (Fig 11) and it will supply its
derived classes session relevant informations such like 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 in to the current instance of
the HttpContext class.
Now, let us 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, which
deal with the topic project involvement. The method public void
BLPInvolvement.GetDayRecord(DateTime dtEntry,out double dTotal out DataSet
dsDayRecord) (see Fig 12) is responsible to pass a Dataset and a numeric value to
the Presentation Layer.
We have used ASP.NET to implement the Presentation Layer and now we like to show
you exemplarily , how the Presentation Layer communicates with the Data Access
Layer. The 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,
which 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();
The Figure 12 shows a partial source code, which is responsible for inserting a new
project involvement record. The method takes following steps to accomplish the
Task:
2.5 Conclusion
If we look back 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 (Dont jump over a neighbor tier ,because it makes
us easy to follow systematically from the button click to database access).
• Use try, catch and finally control structures in every tier to track bugs.
2.6 Reference