Click here to Skip to main content
15,881,413 members
Articles / Programming Languages / C#

A Tool to create N-Layer Architecture Classes

Rate me:
Please Sign up or sign in to vote.
4.87/5 (18 votes)
6 Jun 2016CPOL8 min read 67.8K   10.9K   126   23
This tool is used to create N-Layer Architecture classes.

Introduction

This is my ninth article in C#. This time, I have tried a new concept about N-Layer Architecture in C#.

What is N-Layer Architecture?

This is a very important topic to consider when developing an application. Many elements need to be considered when deciding on the architecture of the application, such as performance, scalability and future development issues. When you are deciding on which architecture to use, first decide on which of the three aforementioned elements you think is most valuable -- as some choices you make will impact on others. For example, some choices that boost performance will impact the scalability or future development of your design, etc.

Here we will talk generally about what n-Tier architecture is, and then we will have a look at different n-Tier architectures you can use to develop ASP.NET applications and issues that arise relating to performance, scalability and future development issues for each one.

Firstly, what is n-Tier architecture? N-Tier architecture refers to the architecture of an application that has at least 3 "logical" layers -- or parts -- that are separate. Each layer interacts with only the layer directly below, and has a specific function that it is responsible for.

Why use n-Tier architecture? Because each layer can be located on physically different servers with only minor code changes, hence they scale out and handle more server load. Also, what each layer does internally is completely hidden to other layers and this makes it possible to change or update one layer without recompiling or modifying other layers.

This is a very powerful feature of n-Tier architecture, as additional features or change to a layer can be done without redeploying the whole application. For example, by separating data access code from the business logic code, when the database servers change you only need to change the data access code. Because business logic code stays the same, the business logic code does not need to be modified or recompiled.

An n-Tier application usually has three tiers, and they are called the presentation tier, the business tier and the data tier. Let's have a look at what each tier is responsible for.

Presentation Layer

Presentation Layer is the layer responsible for displaying user interface and "driving" that interface using business tier classes and objects. In ASP.NET, it includes ASPX pages, user controls, server controls and sometimes security related classes and objects.

Business Tier

Business Tier is the layer responsible for accessing the data tier to retrieve, modify and delete data to and from the data tier and send the results to the presentation tier. This layer is also responsible for processing the data retrieved and sent to the presentation layer.

In ASP.NET, it includes using SqlClient or OleDb objects to retrieve, update and delete data from SQL Server or Access databases, and also passing the data retrieved to the presentation layer in a DataReader or DataSet object, or a custom collection object. It might also include the sending of just an integer, but the integer would have been calculated using the data in the data tier such as the number of records a table has.

BLL and DAL

Often this layer is divided into two sub layers: the Business Logic Layer (BLL), and the Data Access Layers (DAL). Business Logic Layers are above Data Access Layers, meaning BLL uses DAL classes and objects. DAL is responsible for accessing data and forwarding it to BLL.

In ASP.NET, it might be using SqlClient or OleDb to retrieve the data and sending it to BLL in the form of a DataSet or DataReader. BLL is responsible for preparing or processing the data retrieved and sends it to the presentation layer. In ASP.NET, it might be using the DataSet and DataReader objects to fill up a custom collection or process it to come up with a value, and then sending it to Presentation Layer. BLL sometimes works as just a transparent layer. For example, if you want to pass a DataSet or DataReader object directly to the presentation layer.

Data Tier

Data tier is the database or the source of the data itself. Often in .NET, it's an SQL Server or Access database, however it's not limited to just those. It could also be Oracle, mySQL or even XML. In this article, we will focus on SQL Server, as it has been proven to be the fastest database within a .NET Application.

nlayertool/app_arch.gif

Definition from Wikipedia!

Three-tier[3] is a client–server architecture in which the user interface, functional process logic ("business rules"), computer data storage and data access are developed and maintained as independent modules, most often on separate platforms.

The three-tier model is a software architecture and a software design pattern.

Apart from the usual advantages of modular software with well-defined interfaces, the three-tier architecture is intended to allow any of the three tiers to be upgraded or replaced independently as requirements or technology change. For example, a change of operating system in the presentation tier would only affect the user interface code.

Typically, the user interface runs on a desktop PC or workstation and uses a standard graphical user interface, functional process logic may consist of one or more separate modules running on a workstation or application server, and an RDBMS on a database server or mainframe contains the computer data storage logic. The middle tier may be multi-tiered itself (in which case the overall architecture is called an "n-tier architecture").

Three-tier architecture has the following three tiers:

Presentation tier: This is the topmost level of the application. The presentation tier displays information related to such services as browsing merchandise, purchasing, and shopping cart contents. It communicates with other tiers by outputting results to the browser/client tier and all other tiers in the network.

Application tier (business logic, logic tier, data access tier, or middle tier): The logic tier is pulled out from the presentation tier and, as its own layer, it controls an application’s functionality by performing detailed processing.

Data tier: This tier consists of database servers. Here information is stored and retrieved. This tier keeps data neutral and independent from application servers or business logic. Giving data its own tier also improves scalability and performance.

Basic Requirements

  • .NET Framework 3.5 and above
  • SQL Server 2000 and above

Description about the Tool

Basically to create classes for the n-layer architecture, we need write code considering the table structure and write codes for business logic and data access layers separately. Also if the database has some more number of tables, we need to spend more time in creating the classes for each and every table.

So to simplify this, I developed this tool. The tool creates the Data Object class (I named it as “Value Object”), business logic layer class, Data access layer class. The tool creates with basic functionalities. If we want to add any extra functionalities, we can edit it separately by opening it in any IDE (of course Visual Studio).

Ingredients of the Tool

  1. Class Generator Controls: This is a separate windows class library which contains all the components required to connect to the server, list of databases in the server, list of tables in the selected database. The location where the classes are to be created, the names of the namespace and the classes. 
  2. Class Generator Events: This is also a separate class library which handles all the events of the controls of the Class Generator Controls.

The classes are created in such a way that it can be used with Linq.

nlayertool/scr1.jpg

I have created all the required class libraries separately and then integrated them in the Class Generator Windows Application. You can get a clear picture about the controls, events by downloading the solutions.

Class Generator Controls

nlayertool/scr2.jpg

Class Generator Events

nlayertool/scr3.jpg

Workflow of the Tool

First, we need to provide the login credentials of the database including server name or IP, username and password and click connect button. If the connection is successful, it popups out a message out that the connection is successful. After the connection is established, the list of databases in the server is binding in the database combo box. The list of tables is binding in the tables list combo box for the selected database. Along with that the namespace name, class name is displayed in the respective textboxes. 

The name of the database is treated as the namespace name and the name of the layer (BLL, DAL, VO) is concated along with that. The name of the table is the name of the class. If we want to edit it, we can do it. Then the location where the files to be created is selected. Then the language of the class files, whether C# or VB.NET is selected. Then at last the "Generate Classes" button is clicked. Once clicked, the classes are created and the full path where the classes are created are displayed in the "Class File Path" Box.

Small Piece of Code

C#
public string CreateClassFiles()
{
	System.Text.StringBuilder resultBuilder = new System.Text.StringBuilder();
	resultBuilder.AppendLine(fileCreator.CreateVOClass());
	resultBuilder.AppendLine(fileCreator.CreateBLLClass());
	resultBuilder.AppendLine(fileCreator.CreateDALClass());
	resultBuilder.AppendLine("Files are created successfully.!");
	return resultBuilder.ToString();
}//Class Generate Button Click Event
private void btnClassGenerator_Click(object sender, EventArgs e)
{
	try
	{
		if (serverBox.IsValuesEmpty || locationBox.IsValuesEmpty 
				|| bllBox.IsValuesEmpty || dalBox.IsValuesEmpty 
				|| voBox.IsValuesEmpty)
			CommonFunctions.ShowMessageBox
				("Please enter all the required fields! ", 
				MessageBoxButtons.OK, MessageBoxIcon.Error);
		else
		{
			UIEntryStore uiEntryStore = new UIEntryStore();
			uiEntryStore.ServerInstance = serverBox.ServerInstance;
			uiEntryStore.ServerUsername = serverBox.ServerUsername;
			uiEntryStore.ServerPassword = serverBox.ServerPassword;
			uiEntryStore.DatabaseName = databaseBox.SelectedDatabase;
			uiEntryStore.TableName = databaseBox.SelectedTable;
			uiEntryStore.PrimaryKey = databaseBox.PrimaryKey;
			uiEntryStore.ColumnsInformation = 
				CommonFunctions.SqlServerEventHandler.
				GetTableColumns(databaseBox.SelectedDatabase, 
				databaseBox.SelectedTable);
			uiEntryStore.FileLocation = locationBox.FileLocation;
			uiEntryStore.VOClassName = voBox.ClassName;
			uiEntryStore.VONamespace = voBox.Namespace;
			uiEntryStore.VOParentDirectories = voBox.ParentDirectories;
			uiEntryStore.BLLClassName = bllBox.ClassName;
			uiEntryStore.BLLNamespace = bllBox.Namespace;
			uiEntryStore.BLLParentDirectories = 
						bllBox.ParentDirectories;
			uiEntryStore.DALClassName = dalBox.ClassName;
			uiEntryStore.DALNamespace = dalBox.Namespace;
			uiEntryStore.DALParentDirectories = 
						dalBox.ParentDirectories;
			uiEntryStore.ClassFileLanguage = 
				languageBox.IsCSSelected ? ClassLanguages.CSharp : 
				ClassLanguages.VisualBasic;
			ClassGeneratorButtonEvents buttonEvent = 
				new ClassGeneratorButtonEvents(this, uiEntryStore);
			this.classFilesInfoBox.DisplayText = 
				buttonEvent.CreateClassFiles();
		}
	}
	catch (Exception ex)
	{
		CommonFunctions.ShowMessageBox
			("Error occured while creating class files." + 
			Environment.NewLine + "Please debug the error: " + 
			ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
	}
}

Please view the complete code in the downloads.

Using of the Created Classes. Sample code

C#
//Selecting all the records.
ProductsBLL productsBLL = new ProductsBLL();
var products = productsBLL.SelectAll().OrderBy
		(p => p.ProductName);// Selecting a single record.
private Products GetProduct(int id)
{
     Products product = productsBLL.SelectAll().Find(p => p.ProductID == id);
     return product;
}

History

Version 2.0 - http://www.codeproject.com/Articles/1104994/A-Tool-to-create-N-Layer-Architecture-Classes-v

Conclusion

Thanks for reading this article. I expect feedback from you. You expect more from me.

License

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionSupport SQL Server Windows Authentication Pin
Brian C Hart17-Oct-17 17:44
professionalBrian C Hart17-Oct-17 17:44 
QuestionDependancy Pin
Member 1001439115-Jun-15 20:49
Member 1001439115-Jun-15 20:49 
QuestionNice work Prakash Pin
poiuytrewq1234987654327-Feb-14 23:16
poiuytrewq1234987654327-Feb-14 23:16 
SuggestionGreate work Pin
AJMAL SHAHZAD8-Jul-13 21:11
AJMAL SHAHZAD8-Jul-13 21:11 
QuestionClassGenerator: VONamesapce Pin
Dini Miller4-Jul-13 5:34
Dini Miller4-Jul-13 5:34 
QuestionCircular dependency Pin
dash5556-Nov-12 6:10
dash5556-Nov-12 6:10 
AnswerRe: Circular dependency Pin
Saleth Prakash6-Nov-12 23:56
Saleth Prakash6-Nov-12 23:56 
i think you are giving same reference to same project. it is not possible. ClassGeneratorControls library is refered to ClassGeneratorEvents library and to ClassGenerator library. it is not circular dependency. So please check clearly. Also for sql server 2008 r2 it is working fine. infact i have tested with sql server 2008 r2 only, for me it is working fine. Still you get the same issue try to connect by changing LoginSecure=false.
K.S. Prakash

GeneralRe: Circular dependency Pin
dash5557-Nov-12 5:06
dash5557-Nov-12 5:06 
GeneralRe: Circular dependency Pin
>Valero20-Aug-13 7:58
>Valero20-Aug-13 7:58 
AnswerRe: Circular dependency Pin
Hammad Ali Raza (Hadi)4-Jan-15 20:19
Hammad Ali Raza (Hadi)4-Jan-15 20:19 
GeneralA very good article Pin
Rahul Rajat Singh13-Aug-12 18:46
professionalRahul Rajat Singh13-Aug-12 18:46 
QuestionSQL Server 2008 r2 not supporting Pin
luckystarcse25-Apr-12 20:31
luckystarcse25-Apr-12 20:31 
AnswerRe: SQL Server 2008 r2 not supporting Pin
Saleth Prakash25-Apr-12 21:45
Saleth Prakash25-Apr-12 21:45 
QuestionRe: SQL Server 2008 r2 not supporting Pin
dash5556-Nov-12 6:25
dash5556-Nov-12 6:25 
GeneralMy vote of 5 Pin
ProEnggSoft26-Feb-12 23:31
ProEnggSoft26-Feb-12 23:31 
QuestionErorr Pin
hlinhbkhn1-Feb-12 21:16
hlinhbkhn1-Feb-12 21:16 
AnswerRe: Erorr Pin
Saleth Prakash1-Feb-12 21:30
Saleth Prakash1-Feb-12 21:30 
Bugsame problem Pin
lmik98982-Jun-12 19:53
lmik98982-Jun-12 19:53 
QuestionExcelent job!! Pin
FranCastillo8-Nov-11 7:08
FranCastillo8-Nov-11 7:08 
Questionmy vote 5 Pin
Yahya Mohammed Ammouri24-Sep-11 10:09
Yahya Mohammed Ammouri24-Sep-11 10:09 
QuestionNice job Pin
ipadilla18-Jul-11 20:46
ipadilla18-Jul-11 20:46 
GeneralMy vote of 5 Pin
Brijesh Kr18-Jul-11 17:50
Brijesh Kr18-Jul-11 17:50 
BugError Pin
papas_boy218-Jul-11 15:41
papas_boy218-Jul-11 15:41 

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.