Click here to Skip to main content
Click here to Skip to main content

Understand 3- Tier Architecture in C#

, 2 Oct 2013
Rate this:
Please Sign up or sign in to vote.
How to

Introduction

In this article we will learn to implement 3- Tier architecture in C#.NET application. 3-Tier architecture is very famous and well known buzz word in world of software development. If we analyze any traditional project then we will find that most of (at least 60-70 %) them has traditional N-Tier, basically 3-Tier architecture. It does not matter whether it is web or windows application, we can implement 3-Tier architecture in any type of environment.

Although it is very well known and common architecture but it’s not very clear to fresher developer or those who are very new in project development.

Why 3-Tier Architecture?

Still I can remember that, the first organization in my career was dealing with one small POS (Point of Sell) project. It was a windows application and there was no layered architecture. We coder people started to write all codes in behind of windows form. Problem started after few days. How? When our manager announced that we have to develop one web version of same product. Again we started to develop web pages from scratch and started to write all code. Totally mess.

So, this is the problem and the solution is tired architecture. If we separate our codes by layer then changes in one layer will not affect much to another one. Tomorrow if business demands, we can change UI very quickly by using existing code.

Difference between Tier and Layer

It is one confusing question for beginner. Few think that both are same. But they are not same. Tier represents different hardware box. Means the components are physically separated to different machines. But in case of layer all component remains in same system.

What are the Layers?

Theoretically it is N-Tier architecture. So, we can create as much layer as possible but basically people classify code in three different categories and put them in three different layers. So, for this article we will consider N-Tier architecture as 3-Tier architecture and try to implement one sample application.

Let’s discuss each and every Layer at first.

Presentation Layer/ UI Layer

This is the top most layer of application where user performs their activity. Let’s take example of any application where user needs to fill up one form. This form is nothing nut presentation layer. In windows application windows form is presentation layer and in web application web form belongs to presentation layer. Basically user’s input validation and rule processing performs in this layer.

Business Layer

This is on top of presentation layer. As the name suggest, most of the business operation performs here. For example, after collecting form data we want to validate them with our custom business rule. Basically we define classes and business entities in this layer.

Data Access Layer

It is on top of Business Logic Layer Data Access Layer presents. It contains methods that helps business layer to connect with database and perform CRUD operation. In data access layer generally all database related code and stuff belongs to. Sometimes people use platform independent data access layer to fetch data from different database vendor.

Let’s Implement

Before start with example one more question need to be clear. How we will pass data from one layer to another layer? Means in which form data from pass?

There are many solutions for this problem. For our example we will pass data through function parameter. In this example we will implement one small windows application to fetch data from database using 3-Tier architecture. In this example we will read data from single "Person" Table.

Code for Data Access Layer

Let’s start from Data access layer; we will create function to read data from database. Have a look on below code.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication1.DAL
{
    public class PersonDAL
    {
        public string ConString = 
            "Data Source=SOURAV-PC\\SQL_INSTANCE;Initial Catalog=test;Integrated Security=True";
        SqlConnection con = new SqlConnection();
        DataTable dt = new DataTable();
        public DataTable Read()
        {
            con.ConnectionString = ConString;
            if (ConnectionState.Closed == con.State)
                con.Open();
            SqlCommand cmd = new SqlCommand("select * from Person",con);
            try
            {
                SqlDataReader rd = cmd.ExecuteReader();
                dt.Load(rd);
                return dt;
            }
            catch
            {
                throw;
            }
        }
        public DataTable Read(Int16 Id)
        {
            con.ConnectionString = ConString;
            if (ConnectionState.Closed == con.State)
                con.Open();
            SqlCommand cmd = new SqlCommand("select * from Person where ID= "+ Id +"", con);
            try
            {
                SqlDataReader rd = cmd.ExecuteReader();
                dt.Load(rd);
                return dt;
            }
            catch
            {
                throw;
            }
        }
    }
}

We have created two overloaded function to read data. One function will not take any argument and other function will fetch data using ID.

Create Business Logic Layer

Now, we will create Business Logic Layer to communicate with both Presentation layer and Data access layer. Here is our code for Business layer.

using System; using System.Collections.Generic; using System.Data; using WindowsFormsApplication1.DAL;
 
namespace WindowsFormsApplication1.BLL
{
    public class PersonBLL
    {
        public DataTable GetPersons()
        {
            try
            {
                PersonDAL objdal = new PersonDAL();
                return objdal.Read();
            }
            catch
            {
                throw;
            }
        }
        public DataTable GetPersons(Int16 ID)
        {
            try
            {
                PersonDAL objdal = new PersonDAL();
                return objdal.Read(ID);
            }
            catch
            {
                throw;
            }
        }
       
    }
}

Create Presentation Layer.

This is the top most layer where user will interact with system. We will create simple windows for like below.

The form contains one datagrid one textbox and one button. In load event of form we will pull all data and it will show in datagrid. There is another operation, where user can able to fetch particular person by providing person ID. Have a look on below code.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApplication1.BLL;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                PersonBLL p = new PersonBLL();
                this.dataGridView1.DataSource = p.GetPersons(Convert.ToInt16(this.txtID.Text));
            }
            catch
            {
                MessageBox.Show("Error Occurred");
            }
        }
 
        private void Form1_Load(object sender, EventArgs e)
        { 
            try
            {
                PersonBLL p = new PersonBLL();
                this.dataGridView1.DataSource = p.GetPersons();
            }
            catch
            {
                MessageBox.Show("Error Occurred");
            }
        }
    }
}

Folder structure in solution explorer

Here is our sample folder stricture in solution explorer. We have created all layers in same solution. You may create separate solution for each layer.

Here is sample output in form load event.

If we want to search particular person, we have to provide ID.

Table Stricture

Here is our table structure. It contains three fields ID, name and surname.

Table Name:-Person

Conclusion

In this article we have discussed how to implement simple 3-tier architecture in C# application. Hope you have understood the concept.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sourav Kayal
Software Developer TIMKEN India research Institute
India India
I am software developer from INDIA, working in manufacturing domain. Beside my day to day development work, i like to learn new technology and update myself. I am passionate blogger and author in various technical community including dotnetfunda.com , c-sharpcorner.com and codeproject. My area of interest is modern web technology in Microsoft stack.
Follow on   LinkedIn

Comments and Discussions

 
Questionis it 3-Tiers or NOT? PinmemberMember 1087285816-Jun-14 22:08 
GeneralGreat Article PinmemberGurunatha Dogi14-Jun-14 21:13 
QuestionRegarding 3 tired application PinmemberArchana yalagi22-Apr-14 21:44 
GeneralMy vote of 2 PinmemberShubhada Fuge4-Apr-14 21:34 
Question3-Tier/ Layer PinmemberShubhada Fuge4-Apr-14 21:33 
QuestionThank you. PinmemberKaysikarline14-Jan-14 15:56 
GeneralThanks... Pinmemberpirateworks18-Dec-13 11:59 
GeneralMy vote of 4 PinmemberMarimuthu.K11-Nov-13 22:57 
Questiongenerates codes in 3 tier(3layer ) for application and web using c# PinmemberRahim Lotfi9-Nov-13 3:21 
GeneralMy vote of 1 PingroupAkhil_Mittal2-Oct-13 22:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 2 Oct 2013
Article Copyright 2013 by Sourav Kayal
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid