Click here to Skip to main content
15,881,852 members
Articles / Web Development / ASP.NET

Understanding Multilayered Architecture in .NET

Rate me:
Please Sign up or sign in to vote.
4.78/5 (42 votes)
30 Jun 2014CPOL6 min read 108.8K   3.1K   122   41
This article focussses on understanding a basic multilayered architecture in C#.

Introduction

This article focuses on understanding a basic multilayered architecture in C#. The article describes how we can achieve a simple basic multilayered architecture in .NET.

My efforts in this article are to focus on next level programming in .NET for developing an enterprise application.  

A Practical Approach

Let's start developing a simple multilayered architecture in .NET. I use C# as my programming language, however, the programming language is not a bar at all, one can choose the same as per comfort of programming. The architecture which we are to implement has the following design as mentioned in Figure 2. We will start creating the architecture for a web application and later it can be converted into a Windows Applications too. We will make use of class libraries to physically seperate our layers. There for one Web Application/Project, one Business logic layer class library, one Data access layer class library and one Common layer class library can be included in the solution. Let's follow the implementation Step by Step,

Image 1

Figure 2.

Step 1: Add a Web Project (Presentation layer).

Open your Visual Studio and add a simple website to the solution, name it Presentation Layer.

Image 2

Your Development Environment may look like,

Image 3

Our Presentation Layer is the Web application, that will be exposed to the end user. The Web application includes Web Forms i.e. aspx pages, User Controls i.e. Ascx pages, Scrips (client side java scripts), Styles (CSS and custom styles for styling the page), Master Page(.master extension, for providing common functionality to group of desired pages, Configuration Files like web.config and app.config etc.). Let's setup our next projects and define them in seperate layers, Add three folders to your solution, Folders named, BusinessLogicLayer, DataAccessLayer and CommonLayer. Your solution will look like as below,

Image 4

Step 2: Add a Business Logic layer, Data Access Layer and Common Layer

Right-click the Business Logic Layer folder and add a C# class library project to it, call it BLL.csproj:

Image 5

Doing this will ad a C# class library project to our solution in the Businee Logic Layer Folder. Likewise add two more projects to Common Layer and DataAccessLayer folder respectively and call them Common.csproj and DAL.csproj projects. The Data Access Layer Project Contains the entities classes and objects to communicate with database, where as our common project contains properties, helper classes to communicate with all the three layers commonly. It contains the objects to be passed to and fro from presentation layer to data access layer commonly, and also acts as a mode of message passing between the layers. Now our solution would look like as below:

Image 6

Step 3

Create a database with a sample table and put some default values in it, for example I have created a database named "EkuBase" and created a simple Student table with following fields, StudentId, Name, Email, Address, Age, Country. The Create script of the table is as follows:

Image 7

Therefore, making studentid as primary key.

Step 4

Let's add classes to our projetcs, Add StudentBLL.cs, StudentDAL.cs, StudentEntity.cs to BLL, DAl and Common Layer respectively, make sure you qualify them with logical namespaces, so that its easy to recognize and use them.

BLL

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace BLL
{
    public class StudentBLL
    {
    }
}

DAL

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace DAL
{
    public class StudentDAL
    {
    }
}

Common

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace Common
{
    public class StudentEntity
    {
    }
}

Step 5

Add Connection String in web.config and a Helper class to DAL to interact with DataBase. In my case I am using SQL helper for ease.

Web.Config

    <connectionStrings> 
<add name="Connections" connectionString="Data Source=69B5ZR1\SQLEXPRESS;Initial
Catalog=EkuBase;Persist Security Info=True;User ID=akhil;Password=akhil" providerName="System.Data.SqlClient"/> 
    </connectionStrings>

And define the Connection String in your SQL Helper so that you dnt have to again and again create a connection and pass it to your method when you interact with database.

C#
public static readonly string CONN_STRING = ConfigurationManager.ConnectionStrings["Connections"].ConnectionString;

Add reference of System.Configuration to DAL project before reading the above connection string.

Step 6

Configure the solution and add DLL's to dependent layers. Since we need to seperate the business logic, presentation and data access, and we do not want presentation layer to directly interact with database nor the business logic, we add reference of business logic layer to our presentation layer and data access layer to the business logic layer and common layer to all the three layers. To achieve the same add a commonn DLL folder to the physical location of the Solution and give build path of all the three class projects to that DLL folder, doing this we can directly get access to DLL's of all the layers to the layers needed that DLL. We'll get the DLL's in that folder once we complite our project,

Image 8

Image 9

Figure 8

Do this for DAL and Common Layer as shown in Figure 8. After compiling all the projects we get DLL's in DLL folder created.

Image 10

Now add reference of Common.dll, BLL.dll to Presentation Layer, Common.dll, DAL.dll to BLL Layer, Common.dll to DAL layer and compile your solution. Now the code of BLL is accessible to Presentation Layer, and DAL is accessible to BLL, and Common is accessible to all three layers.

Step 7

Write methods to get the flow. Now we need to write some code to our layers to get the feel of flow between all the layers. Let's create a scenario. Suppose we need to get the details of all the students whose student IDs is less than 5. For that add some sample data to your Student table, about 7 rows would work (Figure 11),and add a gridview to Default.aspx in presentation layer to show the data.

Image 11

Figure 11

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>.
    </p>
    <p>
        You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
            title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
    </p>

    <div>
    <asp:GridView runat ="server" ID="grdStudent"></asp:GridView>
    </div>
    <div>
                   <asp:Label runat="server" ID="lblError" Font-Bold=true ForeColor=red ></asp:Label>
                  </div>
    
</asp:Content>

Now decorate your StudentEntity Class in Common layer with following code, to make properties for each column we are going to access from Student table:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public class StudentEntity
    {
        int studentID;

        public int StudentID
        {
            get { return studentID; }
            set { studentID = value; }
        }
        string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        string email;

        public string Email
        {
            get { return email; }
            set { email = value; }
        }
        string address;

        public string Address
        {
            get { return address; }
            set { address = value; }
        }
        int age;

        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        string country;

        public string Country
        {
            get { return country; }
            set { country = value; }
        }
    }
}

And StudentDAL with following code to call the data from database, we always write data interaction code in this layer only, making it as a protocol.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DAL
{
    public class StudentDAL
    {
        public DataSet FetchSelectedStudents()
        {
            string sqlCommand = "select * from Student where Studentid<5";
            DataSet dataSet = SqlHelper.ExecuteDataset(SqlHelper.CONN_STRING, CommandType.Text, sqlCommand);
            return dataSet;
        }

    }
}

Here we simply make a call to database to get students that have an ID less than 5.

We write following code to BLL class, where we perform validation check for the ID whether it is less or greater that 5, and correspondingly throw an error if it is greater than 5, which we show at our default.aspx page by setting the message to error label text.BLL, which makes a call to DAL to fetch the students, and passes to Presentation Layer, where data is shown in GridView.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using System.Data;
using Common;

namespace BLL
{
    public class StudentBLL
    {
        public DataTable GetStudentBelow5(StudentEntity student)
        {
            StudentDAL studentDAL = new StudentDAL();
            if (ValidateID(student.StudentID))
            {
                return studentDAL.FetchSelectedStudents().Tables[0];
            }
            return null;

        }

        private bool ValidateID(int studentID)
        {
            if (studentID > 5)
            {
                throw new ApplicationException("Id Should be less than 5");
            }
            return true;
        }
    }
}

and in Presentation layer we write code to bind our gridview else show error message in case of error returned from BLL.

Default.aspx.cs

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BLL;
using Common;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        StudentBLL studentBLL = new StudentBLL();
        StudentEntity studentEntity=new StudentEntity();
        studentEntity.StudentID=6;
        DataTable dTable = new DataTable();
        try
        {
            dTable = studentBLL.GetStudentBelow5(studentEntity);
            grdStudent.DataSource = dTable;
            grdStudent.DataBind();
        }
        catch (ApplicationException applicationException)
        {
            lblError.Text = applicationException.Message;
        }
    }
}

In the above code we specify student ID as 6 in Student Entity and pass it to BLL, when we run the code we get the following page with our error label set with the error message

Image 12

It clearly states that ID should be less than 5. Note that we do not get to DAL before the data is validated. Now change the student ID to 5 and see the result. We get the following page,

Image 13

Thus we get the clear result. Here we have seen how we communicated through different layers performing different roles to fetch the data.

Summary

In this article I discussed how to create a multilayered application in .NET. We can handle the Exceptions more intelligently at DAL and BLL, however, that was not the scope of the article so that part is skipped and I'll surely discuss this in my forthcoming articles. The article was a focus on development for beginners, who face challenges to create an architecture before starting development.

Happy Coding :-) .

License

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


Written By
Architect https://codeteddy.com/
India India
Akhil Mittal is two times Microsoft MVP (Most Valuable Professional) firstly awarded in 2016 and continued in 2017 in Visual Studio and Technologies category, C# Corner MVP since 2013, Code Project MVP since 2014, a blogger, author and likes to write/read technical articles, blogs, and books. Akhil is a technical architect and loves to work on complex business problems and cutting-edge technologies. He has an experience of around 15 years in developing, designing, and architecting enterprises level applications primarily in Microsoft Technologies. He has diverse experience in working on cutting-edge technologies that include Microsoft Stack, AI, Machine Learning, and Cloud computing. Akhil is an MCP (Microsoft Certified Professional) in Web Applications and Dot Net Framework.
Visit Akhil Mittal’s personal blog CodeTeddy (CodeTeddy ) for some good and informative articles. Following are some tech certifications that Akhil cleared,
• AZ-304: Microsoft Azure Architect Design.
• AZ-303: Microsoft Azure Architect Technologies.
• AZ-900: Microsoft Azure Fundamentals.
• Microsoft MCTS (70-528) Certified Programmer.
• Microsoft MCTS (70-536) Certified Programmer.
• Microsoft MCTS (70-515) Certified Programmer.

LinkedIn: https://www.linkedin.com/in/akhilmittal/
This is a Collaborative Group

780 members

Comments and Discussions

 
QuestionNice! Pin
IlumioApp29-Feb-16 2:18
professionalIlumioApp29-Feb-16 2:18 
AnswerRe: Nice! Pin
Akhil Mittal29-Feb-16 16:40
professionalAkhil Mittal29-Feb-16 16:40 
QuestionUse same architecture but with HTML Pin
Member 1235250825-Feb-16 15:32
Member 1235250825-Feb-16 15:32 
AnswerRe: Use same architecture but with HTML Pin
Akhil Mittal28-Feb-16 17:20
professionalAkhil Mittal28-Feb-16 17:20 
GeneralGretae Pin
Aladár Horváth14-Aug-15 0:26
professionalAladár Horváth14-Aug-15 0:26 
GeneralRe: Gretae Pin
Akhil Mittal14-Aug-15 1:56
professionalAkhil Mittal14-Aug-15 1:56 
GeneralRe: TAE Pin
neonego19-Aug-15 18:34
neonego19-Aug-15 18:34 
QuestionMy Vote 5 Pin
Dharmesh .S. Patil24-Jun-15 21:04
professionalDharmesh .S. Patil24-Jun-15 21:04 
AnswerRe: My Vote 5 Pin
Akhil Mittal24-Jun-15 22:24
professionalAkhil Mittal24-Jun-15 22:24 
GeneralMy vote of 5 Pin
CodeLancer12-Jul-14 2:50
CodeLancer12-Jul-14 2:50 
GeneralRe: My vote of 5 Pin
Akhil Mittal13-Jul-14 17:55
professionalAkhil Mittal13-Jul-14 17:55 
GeneralMy vote of 3 Pin
CatchExAs9-Jul-14 4:30
professionalCatchExAs9-Jul-14 4:30 
GeneralGreat article Pin
vJay Yadav6-Jul-14 19:04
professionalvJay Yadav6-Jul-14 19:04 
GeneralRe: Great article Pin
Akhil Mittal6-Jul-14 19:49
professionalAkhil Mittal6-Jul-14 19:49 
GeneralMy vote of 5 Pin
rediffAM5-Jul-14 4:42
rediffAM5-Jul-14 4:42 
GeneralRe: My vote of 5 Pin
Akhil Mittal5-Jul-14 23:52
professionalAkhil Mittal5-Jul-14 23:52 
GeneralNice article Pin
suhel_khan1-Jul-14 0:21
professionalsuhel_khan1-Jul-14 0:21 
GeneralRe: Nice article Pin
Akhil Mittal1-Jul-14 0:22
professionalAkhil Mittal1-Jul-14 0:22 
GeneralMy vote of 5 Pin
Chris Dis30-Jun-14 22:34
professionalChris Dis30-Jun-14 22:34 
GeneralRe: My vote of 5 Pin
Akhil Mittal30-Jun-14 22:36
professionalAkhil Mittal30-Jun-14 22:36 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun30-Jun-14 20:00
Humayun Kabir Mamun30-Jun-14 20:00 
GeneralRe: My vote of 5 Pin
Akhil Mittal30-Jun-14 21:24
professionalAkhil Mittal30-Jun-14 21:24 
GeneralMy vote of 5 Pin
Prachi_G29-Jun-14 21:23
Prachi_G29-Jun-14 21:23 
GeneralMy vote of 5 Pin
prashita gupta29-Jun-14 20:30
prashita gupta29-Jun-14 20:30 
GeneralRe: My vote of 5 Pin
Akhil Mittal29-Jun-14 20:32
professionalAkhil Mittal29-Jun-14 20:32 

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

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