0% found this document useful (0 votes)
775 views

3-Tier Architecture in C# - CodeProject

Development guide
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
775 views

3-Tier Architecture in C# - CodeProject

Development guide
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

4/10/2014 3-tier architecture in C# - CodeProject

http://www.codeproject.com/Articles/11128/tier-architecture-in-C 1/8
10,531,044 members (67,803 online) 391 Sign out


CobolNerd
home quick answers discussions features community
help
Search f or articles, questions, tips
Articles Development Lifecycle Design and Architecture General

Article
Browse Code
Bugs / Suggestions
Stats
Revisions
Alternatives
Comments (82)
View this article's
Workspace
Fork this Workspace
Connect using Git
Share
About Article
An article on the
background, advantages
and usage of 3-tier
architectures in C#.
Type Article
Licence
First Posted 27 Jul 2005
Views 526,327
Bookmarked 169 times
VC7 .NET1.1 WinXP
VS.NET2003 C# Dev , +

Top News
C# 6: First reactions
Get the Insider News free each
morning.
Related Videos
Related Articles
Difference in layer and tier
architecture
Making WCF RIA Services work
in a DMZ/Multitier architecture
using Application Request
Routing
N-Tier Architecture and Tips
A Tool to create N-Layer
Architecture Classes
Next
Rate:
3-tier architecture in C#
By Rahman Mahmoodi, 27 Jul 2005
Download source files - 17.4 Kb
Introduction
This article discusses and implements 3-tier architecture using C# and a dummy customer using
MS Access database. In this article I am trying to implement a small reusable component that
maintains customers in 3-tier architecture. It shows how to add, update and find customer details.
Background
To begin with I would like to discuss a little about the theoretical aspects of 3-tier architecture. I'll
briefly go through what 3-tier architecture is and what are its advantages.
What is a 3-tier architecture?
Three-tier (layer) is a client-server architecture in which the user interface, business process
(business rules) and data storage and data access are developed and maintained as independent
modules or most often on separate platforms. Basically, there are 3 layers, tier 1 (presentation tier,
GUI tier), tier 2 (business objects, business logic tier) and tier 3 (data access tier). These tiers can
be developed and tested separately.
What is the need for dividing the code in 3-tiers? Separation of the user interface from business
logic and database access has many advantages. Some of the advantages are as follows:
Reusability of the business logic component results in quick development. Let's say we have
a module that handles adding, updating, deleting and finding customers in the system. As
this component is developed and tested, we can use it in any other project that might
involve maintaining customers.
Transformation of the system is easy. Since the business logic is separate from the data
access layer, changing the data access layer wont affect the business logic module much.
Let's say if we are moving from SQL Server data storage to Oracle there shouldnt be any
changes required in the business layer component and in the GUI component.
Change management of the system is easy. Let's say if there is a minor change in the
business logic, we dont have to install the entire system in individual users PCs. E.g. if GST
(TAX) is changed from 10% to 15% we only need to update the business logic component
without affecting the users and without any downtime.
Having separate functionality servers allows for parallel development of individual tiers by
application specialists.
Provides more flexible resource allocation. Can reduce the network traffic by having the
functionality servers strip data to the precise structure needed before sending it to the
clients.
Using the code
3.47 (91 votes)
articles
4/10/2014 3-tier architecture in C# - CodeProject
http://www.codeproject.com/Articles/11128/tier-architecture-in-C 2/8
Three Tier Code Generator For
ASP.NET
Notification of Silverlight
Applications about Database
State Changes
Three Layer Architecture in C#
.NET
Introduction to Object-Oriented
Tiered Application Design
SALT and PEPPER 3 TIER and
LINQ
ADO.NET Sync Services in N
Tier Architecture
A N-Tier Architecture Sample
with ASP.NET MVC3, WCF, and
Entity Framework
Making HTTP Communication
from MFC/Windows
Application
Walkthrough: Creating an N-tier
Data Application with a
ASP.NET Presentation Tier
Introduction to Object Oriented
Programming Concepts (OOP)
and More
Designing and implementing a
versatile data access tier for an
ASP.NET application
Tiered Architecture
Application Architecture -
Driving Forces, Approaches, and
Implementation Considerations
Coding in Tiers - Part I
Distributed Programming
Framework - Part 1 (Abstract)
Design a Dictionary with
Spellchecker (En-Fa)(De-En)
Related Research
Fine-Tuning the Engines of SMB
Growth: 4 strategies for growing
your business
Protecting Your Business Data:
Five Dos and Donts
This component has 3 tiers. Tier 1 or GUI tier with a form will be called FrmGUI, tier 2 or business
logic will be called BOCustomer short for Bussniess Object Customer and finally the tier 3 or the
data tier will be called DACustomer short for Data Access Customer. I have compiled all the 3 tiers
in the same project for ease of work. I am including all the source code along with the MS Access
database that is used to test this project in the included zip file.
User Interface tier
This is a chunk of code from the user interface. I am only including the functions that are used to
call the middle tier or the business logic layer.
I am keeping a reference to business logic layer as BOCustomer.
Collapse | Copy Code
//This function get the details from the user via GUI
//tier and calls the Add method of business logic layer.
private void cmdAdd_Click(object sender, System.EventArgs e)
{
try
{
cus = new BOCustomer();
cus.cusID=txtID.Text.ToString();
cus.LName = txtLName.Text.ToString();
cus.FName = txtFName.Text.ToString();
cus.Tel= txtTel.Text.ToString();
cus.Address = txtAddress.Text.ToString();
cus.Add();
}
catch(Exception err)
{
MessageBox.Show(err.Message.ToString());
}
}
//This function gets the ID from the user and finds the
//customer details and return the details in the form of
//a dataset via busniss object layer. Then it loops through
//the content of the dataset and fills the controls.

private void cmdFind_Click(object sender, System.EventArgs e)
{
try
{
String cusID = txtID.Text.ToString();

BOCustomer thisCus = new BOCustomer();

DataSet ds = thisCus.Find(cusID);

DataRow row;
row = ds.Tables[0].Rows[0];

//via looping
foreach(DataRow rows in ds.Tables[0].Rows )
{
txtFName.Text = rows["CUS_F_NAME"].ToString();
txtLName.Text = rows["CUS_L_NAME"].ToString();
txtAddress.Text = rows["CUS_ADDRESS"].ToString();
txtTel.Text = rows["CUS_TEL"].ToString();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}

}
//this function used to update the customer details.
private void cmdUpdate_Click(object sender,
System.EventArgs e)
{
try
{
cus = new BOCustomer();
cus.cusID=txtID.Text.ToString();
cus.LName = txtLName.Text.ToString();
cus.FName = txtFName.Text.ToString();
cus.Tel= txtTel.Text.ToString();
cus.Address = txtAddress.Text.ToString();

cus.Update();
}
catch(Exception err)
{
MessageBox.Show(err.Message.ToString());
}
}
4/10/2014 3-tier architecture in C# - CodeProject
http://www.codeproject.com/Articles/11128/tier-architecture-in-C 3/8
Business Logic layer
Here, I am including all the code for this tier. Basically it has properties that are needed to define
the customer object. But as I mentioned it is just a dummy customer and many other properties
can be added if required. It also has all the methods including Add, update, find that are required
to maintain customer details.
This is the middle tier and acts between the GUI and the Data access layer. It keeps a reference to
the data access tier as cusData = new DACustomer(). It also has a reference to System.Data
namespace as sometimes it returns details in the form of DataSet to the GUI tier.
Collapse | Copy Code
using System;
using System.Data;
namespace _3tierarchitecture
{
/// <span class="code-SummaryComment"><SUMMARY>
</span>
/// Summary description for BOCustomer.
/// <span class="code-SummaryComment"></SUMMARY>
</span>

public class BOCustomer
{
//Customer properties
private String fName;
private String lName;
private String cusId;
private String address;
private String tel;

private DACustomer cusData;

public BOCustomer()
{
//An instance of the Data access layer!
cusData = new DACustomer();
}



/// <span class="code-SummaryComment"><SUMMARY>
</span>
/// Property FirstName (String)
/// <span class="code-SummaryComment"></SUMMARY>
</span>
public String FName
{

get
{
return this.fName;
}
set
{
try
{
this.fName = value;

if (this.fName == "")
{
throw new Exception(
"Please provide first name ...");
}
}
catch(Exception e)
{
throw new Exception(e.Message.ToString());
}
}
}

/// <span class="code-SummaryComment"><SUMMARY>
</span>
/// Property LastName (String)
/// <span class="code-SummaryComment"></SUMMARY>
</span>
public String LName
{
get
{
return this.lName;
}
set
{
//could be more checkings here eg revmove ' chars
//change to proper case
//blah blah
this.lName = value;
if (this.LName == "")
4/10/2014 3-tier architecture in C# - CodeProject
http://www.codeproject.com/Articles/11128/tier-architecture-in-C 4/8
{
throw new Exception("Please provide name ...");
}

}
}

/// <span class="code-SummaryComment"><SUMMARY>
</span>
/// Property Customer ID (String)
/// <span class="code-SummaryComment"></SUMMARY>
</span>
public String cusID
{
get
{
return this.cusId;
}
set
{
this.cusId = value;
if (this.cusID == "")
{
throw new Exception("Please provide ID ...");
}

}
}

/// <span class="code-SummaryComment"><SUMMARY>
</span>
/// Property Address (String)
/// <span class="code-SummaryComment"></SUMMARY>
</span>
public String Address
{
get
{
return this.address;
}
set
{
this.address = value;

if (this.Address == "")
{
throw new Exception("Please provide address ...");
}
}
}

/// <span class="code-SummaryComment"><SUMMARY>
</span>
/// Property Telephone (String)
/// <span class="code-SummaryComment"></SUMMARY>
</span>
public String Tel
{
get
{
return this.tel;
}
set
{
this.tel = value;
if (this.Tel == "")
{
throw new Exception("Please provide Tel ...");
}

}
}

/// <span class="code-SummaryComment"><SUMMARY>
</span>
/// Function Add new customer. Calls
/// the function in Data layer.
/// <span class="code-SummaryComment"></SUMMARY>
</span>
public void Add()
{
cusData.Add(this);
}


/// <span class="code-SummaryComment"><SUMMARY>
</span>
/// Function Update customer details.
/// Calls the function in Data layer.
/// <span class="code-SummaryComment"></SUMMARY>
</span>
public void Update()
{
cusData.Update(this);
}
4/10/2014 3-tier architecture in C# - CodeProject
http://www.codeproject.com/Articles/11128/tier-architecture-in-C 5/8

/// <span class="code-SummaryComment"><SUMMARY>
</span>
/// Function Find customer. Calls the
/// function in Data layer.
/// It returns the details of the customer using
/// customer ID via a Dataset to GUI tier.
/// <span class="code-SummaryComment"></SUMMARY>
</span>
public DataSet Find(String str)
{
if (str == "")
throw new Exception("Please provide ID to search");

DataSet data = null;

data = cusData.Find(str);

return data;
}
}
}
Data Access Layer
The data tier has details to manipulate an MS Access database. However, all these details are
transparent and do not affect the business logic layer. This module has a reference to the business
logic layer as BOCustomer cus. To make the usage easier and be supported by any other
database I have created some constants including the database name and field name that need to
be changed as per the customer table details. This is an usable module for any database after
making these changes.
Collapse | Copy Code
using System;
using System.Data.OleDb;
using System.Data;
namespace _3tierarchitecture
{
/// <span class="code-SummaryComment"><SUMMARY>
</span>
/// Summary description for DACustomer.
/// <span class="code-SummaryComment"></SUMMARY>
</span>
public class DACustomer
{
private OleDbConnection cnn;
//change connection string as per the
//folder you unzip the files
private const string CnnStr =
"Provider=Microsoft.Jet.OLEDB.4.0;Data " +
"Source= D:\\Rahman_Backup\\Programming\\" +
"Csharp\\3tierarchitecture\\customer.mdb;";
//local variables
private String strTable="";
private String strFields="";
private String strValues="";
private String insertStr="";

//this needs to be changed based on customer
//table fields' Name of the database!
private const String thisTable = "tblCustomer";
private const String cus_ID = "CUS_ID";
private const String cus_LName = "CUS_L_NAME";
private const String cus_FName = "CUS_F_NAME";
private const String cus_Tel = "CUS_TEL";
private const String cus_Address = "CUS_ADDRESS";

public DACustomer()
{
}

public DACustomer(BOCustomer cus)
{
// A reference of the business object class
}

//standard dataset function that adds a new customer
public void Add(BOCustomer cus)
{
String str = BuildAddString(cus);

OpenCnn();
4/10/2014 3-tier architecture in C# - CodeProject
http://www.codeproject.com/Articles/11128/tier-architecture-in-C 6/8
//Open command option - cnn parameter is imporant
OleDbCommand cmd = new OleDbCommand(str,cnn);
//execute connection
cmd.ExecuteNonQuery();

// close connection
CloseCnn();

}

//standard dataset function that updates
//details of a customer based on ID
public void Update(BOCustomer cus)
{
OpenCnn();

String selectStr = "UPDATE " + thisTable +
" set " + cus_LName + " = '" + cus.LName + "'" +
", " + cus_FName + " = '" + cus.FName + "'" +
", " + cus_Address + " = '" + cus.Address + "'" +
", " + cus_Tel + " = '" + cus.Tel + "'" +
" where cus_ID = '" + cus.cusID + "'";
OleDbCommand cmd = new OleDbCommand(selectStr,cnn);
cmd.ExecuteNonQuery();

CloseCnn();
}

//standard dataset function that finds and
//return the detail of a customer in a dataset
public DataSet Find(String argStr)
{
DataSet ds=null;
try
{
OpenCnn();

String selectStr = "select * from " + thisTable +
" where cus_ID = '" + argStr + "'";
OleDbDataAdapter da =
new OleDbDataAdapter(selectStr,cnn);
ds = new DataSet();
da.Fill(ds,thisTable);

CloseCnn();

}
catch(Exception e)
{
String Str = e.Message;
}
return ds;
}
private void OpenCnn()
{
// initialise connection
String cnnStr = CnnStr;
cnn = new OleDbConnection(cnnStr);
// open connection
cnn.Open();
}
private void CloseCnn()
{
// 5- step five
cnn.Close();
}

// just a supporting function that builds
// and return the insert string for dataset.
private String BuildAddString(BOCustomer cus)
{
// these are the constants as
// set in the top of this module.
strTable="Insert into " + thisTable;
strFields=" (" + cus_ID +
"," + cus_LName +
"," + cus_FName +
"," + cus_Address +
"," + cus_Tel + ")";

//these are the attributes of the
//customer business object.
strValues= " Values ( '" + cus.cusID +
"' , '" + cus.LName +
"' , '" + cus.FName +
"' , '" + cus.Address +
4/10/2014 3-tier architecture in C# - CodeProject
http://www.codeproject.com/Articles/11128/tier-architecture-in-C 7/8
Rahman Mahmoodi
Software Developer
Australia
Rahman has worked in different areas of Software System Development Life Cycle. He started
working as Tester and then moved to application programming and web application
programming.

At the moment his area of interest are .Net including ASP.Net/2, VB.net, C# and object oriented
design using UML.

He has Bachelor of Computing with Distinction Grade.
Add a Comment or Question

Search this forum Go

"' , '" + cus.Tel + "' )";
insertStr = strTable + strFields + strValues;

return insertStr;

}
}
}
Possible enhancements
This code is very simple and shows the basic usage of 3-tier architecture. A lot of enhancements
including complete details of a client, error handling and many more are possible.
History
I wrote this paper just before my recent visit to South East Asia on 10/06/05 but didn't find the
time to post it.
License
This article has no explicit license attached to it but may contain usage terms in the article text or
the download files themselves. If in doubt please contact the author via the discussion board
below.
A list of licenses authors might use can be found here
About the Author
Article Top
Comments and Discussions
Profile popups Spacing Relaxed Noise Medium Layout Normal Per page 25
4/10/2014 3-tier architecture in C# - CodeProject
http://www.codeproject.com/Articles/11128/tier-architecture-in-C 8/8
Permalink | Advertise | Privacy | Mobile
Web03 | 2.8.140408.1 | Last Updated 27 Jul 2005
Article Copyright 2005 by Rahman Mahmoodi
Everything else Copyright CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid
Update
First Prev Next
Member 10355277 23-Oct-13 12:58
jaganichirag 15-Sep-13 4:16
mukhlim 14-Aug-13 22:21
Member 9841216 8-May-13 15:36
Hidayat Meman 28-Mar-13 8:09
siddiqali md 27-Mar-13 7:22
maryamsahar 15-Nov-12 3:51
liuchen242000 26-Jul-12 10:55
Shovra Das 23-Apr-12 18:58
onurag19 25-Mar-12 8:23
With The God 27-Jul-11 7:52
shikhar210289 18-Jul-11 2:55
Member 4584908 30-Mar-11 2:57
Dr TJ 20-Dec-10 4:26
LAPEC 17-Dec-10 10:34
LAPEC 17-Dec-10 10:28
nilu2009 2-Nov-10 6:29
gurunanak 7-Oct-10 15:36
ashlesha85 21-Sep-10 8:12
tdmeers 14-Apr-10 17:46
e-esi 12-Aug-09 3:31
Member 3510875 19-Jul-09 12:06
Kamran Shahid 30-May-09 8:25
Pratik.Patel 14-Feb-09 23:22
senthilkumarrrr 7-Dec-08 1:53
Last Visit: 10-Apr-14 15:52 Last Update: 10-Apr-14 12:42 Refresh 1 2 3 4 Next
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
circular dependency problem??
plz share full ADD UPDATE DELETE SELECT
AND SEARCH module in 3 layer
architecture
circular reference
My vote of 3
My vote of 4
My vote of 5
Update query
Thanks. But a little improvement is
needed.
Thanks!
c#
Great example
Nice Article
three tier best explantaion
My vote of 3
C# - How to call database records one-
by-one and display it in ListView?
C# - How to call database records one-
by-one and display it in ListView?
My vote of 4
My vote of 3
My vote of 4
My vote of 1
excelent
My vote of 1
My vote of 1
database part of 3rd tier?
3-tier

You might also like