ARTICLE

Building a 3-Tier Application using ASP.NET

Posted by Paul Abraham Articles | ASP.NET Programming December 17, 2001
In the first part we will discuss about 3.Tier Architecture and in the second part we will implement an ASP.NET example to practice the 3.Tier design. You need the Visual Studio.net with c# compiler, IIS and a Microsoft SQL Server to follow this article.
Reader Level:
 

Abstract

This article has two major parts. In the first part we will discuss about 3.Tier Architecture and in the second part we will implement an ASP.NET example to practice the 3.Tier design. You need  the Visual Studio.net with c#  compiler, IIS and a Microsoft SQL Server to follow this article.

Build3tierApp1.jpg

Fig 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 a program which is organized into three major disjunctive tiers. These tiers are

  • Presentation Tier  (Front end)
  • Logical Tier  (Middleware)
  • Data Tier (Backend).

Each layer can be deployed in geographically separated computers in a network. Some architects divide Logic Tier in to two sub tiers  Business  and Data Access Tiers,  in order to  increase scalability and transparency. The tiers can be deployed on physically separated machines. The characteristic of the tier communication is that the tiers will communicate only to 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.

   Build3tierApp4.jpg 

Fig 1  (A typical 3.Tier Architecture)

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.

In fact, Client Server(C/S) architecture is a 2-Tier architecture because the client does not distinguish between Presentation Tier and Logical Tier.  That is why we call this type of client as Fat Client. The increasing demands on GUI controls caused difficulty to manage the mixture of source code from GUI and Business Logic (Spaghetti Code). Further, C\S Architecture does not support enough the Change Management. Let us suppose that the government increases the consume tax rate from 14% to 16 %, then in the C\S case, you have to send an update to each clients 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 compute algorithms faster than a client, so this fact is also an additional pro argument for the 3.Tier Architecture.   

Now let us go back to our 3.Tier Architecture and start to explore the tiers. 

1.1  Data Tier

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 

1.2  Logical Tier

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

  • Increases code transparency
  • Supports changes in Data Layer. You can change or alter database with out touching the Business Layer and this would be a very minimum touch up.  

1.2.1  Business Tier

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.

1.2.2  Data Access Tier:

This tier acts as an interface to Data Tier. This tier knows, how to (from which database) retrieve and store information. 

1.3  Presentation Tier:

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.

2. Creating a  3.Tier  ASP.NET  application.

You need a SqlServer, IIS and Microsoft.NET CLR to run the example application. Please follow the steps to run the ASP.NET application. 

2.1  Installing the web application Timemanagement

You should follow these steps to install the web application TimeManagement on your machine.

  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.

  2. Create an ASP.Net Appliaction  TimeManagement  and replace it with the file TimeManagement which you find in the .zip file

  3. Adjust the  XML Element <appsettings>  in the Web.config file to establish SQL connection.(modify the value from Sqlconnection)

    <appSettings>
    <
    addkey="SqlConnect" value="server=F5;database=TimeManagement;uid=sa;pwd=moses;" />
    </
    appSettings>

  4. 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 Sqlserver database TimeManagement and it has 3 tables. The Fig 2 shows the ERD diagram of  the database TimeManagement. Now, I like describe the tables briefly.

Build3tierApp5.jpg

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. 

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

Fig 3

2.2.2  Table Project

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. 

2.2.3  Table  ProjectInvolvement

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.

  Build3tierApp6.gif

Fig 4 ( partial class diagram of the application TimeManagement)

2.3 Implementing Logical Tier 

2.3.1 Implementing Data Access Tier

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>


Fig 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;
}
}

Fig  6  (class DABasis)

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. 

At first, we going to look a Query Data Access Method.The class DAPInvolvement  wraps a bundle of data access methods which deal with the matter project involvement. The method void Dataset DAPInvolvement.GetDayRecord(int nPersID,DateTime dtEntry) (see Figure 8) will return  a dataset, which contents  all project activities of a person with the ID PersID on a particular day dtEntry This method uses the stored procedure GetDayRecord (see Fig 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

Fig 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();
}
 

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:

public void DAProject.Insert(string strName,string strDescription,int nLeader,out int nAlreadyIn) 
(see Figure  10) is used to insert a new project in to the database  and it uses the stored procedure InsertProject.

(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.  

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 

Fig 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();
}
}  

Fig 10  (Method DAProject.Insert)

A typical Non Query  Data Access method might  be described  abstractly like this:

(see Fig 10)  

  • Establish SqlConnection.
  • Create a SqlCommand and the SqlParameters to the command.
  • Open the connection and execute the query.
  • Retrieve  the values from all output parameters.
  • Close 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;
}
}
}
}  

Fig 11  (class BLBasis)

2.3.2  Implementing Business Tier

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.  

Fig 12 ( class BLPInvolvement)

A typical Business Logic method might abstractly described like this:

  • Instantiate an Data Access object
  • Retrieve the  crude data.
  • Calculate business values from the  crude data.

2.4  Implementing Presentation Tier

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();

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;
}

Fig 12  (Extract from the class  TimeEntry)

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:

  • Draw off the values  from GUI controls.
  • Instantiate an object from the Class BLPInvolvement  and insert it in to the database.
  • Update the other involved GUI controls.
  • Publish the error message , if an error  occurred in the Logic Tier or in Data Tier. 

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 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.

Login to add your contents and source code to this article
comments
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.