N-Tier Architecture

This tutorial will try to explain the logic behind the N-Tier architecture development and also to explain why is N-Tier architecture good to use in your web applications as well as to show you an example of how tiers in N-Tier architecture communicate with each other.

So what exactly is N-Tier Architecture?

N-Tier is an architecture of an application which has at least 3 separate layers that interact with each other. Each layer in N-Tier architecture can talk only to the layer below it. N in this case refers to an N number of layers. The picture below shows the way 3 layers typically communicate:


Presentation
Layer (Presentation Logic) makes a request to Business Layer which then forwards the request to Data Access Layer and returns the data to Presentation Logic. BAL (Business Access Layer) and DAL (Data Access Layers) represent the business logic of an application. Each of these layers has its own logic which is hidden from the other layers and this makes it really easy to update any logic necessary in any of the layers and update only that specific layer instead of recompiling the whole solution. This is a really strong point of N-Tier architecture because any changes or updates to a layer requires only that layer to be recompiled. Another good point of N-Tier archtiecture is that by separating Business Logic from Data Access Logic is that by moving to another Server type we only need to redesign the Data Access Layer's logic while the rest of the code and layers stay identically the same.

Presentation Layer

Presentation Layer in web application are actually .aspx pages together with all the server, custom and user controls. Presentation Layer talks to the Business Layer with a request to Load or Insert some new data to the database. Data can be encapsulated inside Business Objects for added security. Business Layer receives the request and forwards it to the Data Layer which makes a call to the database and sends back the data in raw form or again through some Business Object or a Generic List of Business Objects.

Business Access Layer

Business Layer is responsible for receiv
ing requests made by the Presentation Layer and forwarding those to the Data Layer and later returning parsed data back to Presentation Layer.

Data Access Layer

This layer is responsib
le for direct communication with the database (or any other form of data storage). It has a set of Get, Insert, Delete and Modify methods and it communicates only with business layer. Data retrieved from database can be sent back as DataSet, DataTable or through a single or a collection of custom Business Objects which will then be forwarded back to BAL and then Presentation Logic for further use.

Physically Separate Layers

It is also possible to separ
ate these layers physically instead of only "logically" however, separating layers physically has a direct impact on the speed of execution of the application since communication now involves another step of passing the data through the network to another layer. Physically separated layers also require some added methods to handle the communication in form of web services and remoting. So, having these layers physically separated has a strong impact on the application and that shouldn't be overlooked.



Example of N-Tier Architecture use

In the following example I will show you a simple scenario of N-Tier Architecture used to display a list of books that some online bookstore sells on their website through a set of strong-typed business objects.

This i
s the structure I will be using for the example:



So we have 3
classes here: Book.cs, BookBAL.cs and BookDAL.cs.

Book.c
s is a class that has a set of properties in which we will store data retrieved from the database and then use it later in the Presentation Layer. This is what the class Book looks like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Book
{
#region Private and Public Properties

private int _bookID = 0;
public int BookID
{
get {
return _bookID; }
set { _bookID = value; }
}
private string _category = string.Empty;
public string Category
{
get {
return _category; }
set { _category = value; }
}
private string _author = string.Empty;
public string Author
{
get {
return _author; }
set { _author = value; }
}
private string _serialno = string.Empty;
public string SerialNumber
{
get {
return _serialno; }
set { _serialno = value; }
}
private string _bookName = string.Empty;
public string BookName
{
get {
return _bookName; }
set { _bookName = value; }
}

#endregion

public Book()
{

}

#region Private and Public Methods

public static List<Book> GetAllBooks()
{
return BookBAL.GetAllBooks();
}

#endregion
}

We can see that the class has some properties like BookID
(the ID of the book in the database), Category to which the book belongs, Author, Serial and last but not least Book Name. We can also see public static method GetAllBooks(). This methods will call the Business Layer's public static method GetAllBooks() and Business Layer will forward this request further to Data Access Layer which will query the database for the list of all the books, create a collection of Book objects and return it back to Business Layer that will forward it back to Presentation Layer. It might sound complicated at first with all these layer interaction but believe me once you get to know it better you will just love N-Tier and the possibilities it gives you. Ok let's move on. The next class that we will examine is the Business Access Layer class called BookBAL.cs. It's a really simple and straightforward class with only 1 public method for now and that's GetAllBooks() which we saw inside the Book Business Object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class BookBAL
{
public BookBAL()
{

}

public static List<Book> GetAllBooks()
{
return BookDAL.GetAllBooks();
}
}

Simple, isn't it? What we can see here inside this class is just 1 simple method which calls the Data Layer's public static method GetAllBooks() and returns its response. That's all there's to it. Moving on to the Book Data Layer class.

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;

public class BookDAL
{
public BookDAL()
{

}

public static List<Book> GetAllBooks()
{
string _connString = ConfigurationManager.ConnectionStrings[
"databaseConnection"].ToString();

using (SqlConnection conn = new SqlConnection(_connString))
{
string queryString =
"SELECT * FROM Books";
SqlCommand comm =
new SqlCommand(queryString, conn);
SqlDataAdapter da =
new SqlDataAdapter(comm);
DataTable dt =
new DataTable();
da.
Fill(dt);

if (dt != null && dt.Rows.Count > 0)
{
List<Book> booksResult = new List<Book>();

foreach (DataRow row
in dt.Rows)
{
Book book =
new Book();
book.BookID =
Convert.ToInt32(row["BookID"].ToString());
book.Category = row[
"Category"].ToString();
book.SerialNumber = row[
"SerialNo"].ToString();
book.Author = row[
"Author"].ToString();
book.BookName = row[
"BookName"].ToString();

booksResult.
Add(book);
}

return booksResult;
}
else
{
return null;
}
}
}
}

Now this class has a bit more code but nothing too fancy. It's all
what you've seen before. We instantiate a connection to the server and execute a simple SELECT ALL query. After execution we check to see if the query returned any data and if it did we create a new generic collection of Book Business Objects. Then we parse through each record creating a new Book Business Object, populate the objects properties and add the object to the generic collection. After all the records are parsed we return the booksResult collection of objects back to Business Layer that forwards it further to Presentation Logic.

Now all that is left to do is use this collection and bind GridView to it so it display data. This again is really simple and if you've ever done databinding in codebehind this one is no different. First this is what our Default.aspx page looks like:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Generic Collection - Books Sample</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Bookstore Books</h1>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

and now our codebehind:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Book> ds = new List<Book>();
ds = Book.GetAllBooks();
GridView1.DataSource = ds;
GridView1.DataBind();
}
}

First we check to see if the page is loaded for the first time or the postback occurred. If it's loaded for the first time we bind our gridview with our custom collection of Book Business Objects. We instantiate a new List<Book> collection and call the static Book.GetAllBooks() method to assign a list of Book objects to our collection. Next we specify GridView's DataSource property and call the DataBind() method. If you run this example you will get something that looks like this:



I know it looks rather sloppy here but styling and additional functions for the gridview are out of scope of this article.

I hope that by reading this article you gained some insight as to how and why N-Tier Architecture is used and what are it's good points in development of applications. Feel free to comment and ask any questions regarding the topic. I will gladly try to help you understand the subject discussed here.

Best regards and happy coding!
Sasha Kotlo.

By Sasha Kotlo   Popularity  (6441 Views)
Picture
Biography - Sasha Kotlo
- C#.NET Developement - SQL Server Database Applications - N-Tier Architecture Developement - Object Oriented Programming - XHTML/CSS - Javascript, jQuery - Photoshop, Illustrator, After Effects
My Website