- 浏览: 38967 次
- 性别:
文章分类
最新评论
Introduction
Copied from:
http://www.codeproject.com/Articles/36847/Three-Layer-Architecture-in-C-NET
Here in this article, I would like to cover the typical three layer architecture in C# .NET . It is a very useful approach for coding due to easy code maintenance.
Overview
First let me give you a small overview about the topic I would like to cover in this article.
- Tier vs. Layer
- Three Tier/Layer Architecture Design Components
- Demo: Three Layer Windows Application in C#.NET
1. Tier vs. Layer
1.1 Tier: Tier indicates a physical separation of components, which may mean different assemblies such as DLL, EXE, etc. on the same server or multiple servers.
As you can see in the above figure, Data Tier have no direction with Presentation Tier, but there is an intermediate Tier called Business Tier which is mainly responsible to pass the data from Data Tier to Presentation Tier and to add defined business logic to Data.
So, if we separate each Tier by its functionality, then we come to know the below conclusion:
1.2 Layer : Layer indicates logical separation of components, such as having distinct namespaces and classes for the Database Access Layer , Business Logic Layer and User Interface Layer .
2. Three Tier/Layer Architecture Design Components
As we have already seen, tier is the sum of all the physical components. We can separate the three tiers as Data Tier, Business Tier and Presentation Tier.
- Data Tier is basically the server which stores all the application’s data. Data tier contents Database Tables, XML Files and other means of storing Application Data.
- Business Tier is mainly working as the bridge between Data Tier and Presentation Tier. All the Data passes through the Business Tier before passing to the presentation Tier. Business Tier is the sum of Business Logic Layer , Data Access Layer and Value Object and other components used to add business logic.
- Presentation Tier is the tier in which the users interact with an application. Presentation Tier contents Shared UI code, Code Behind and Designers used to represent information to user.
The above figure is a mixture of Three Tier and Three Layer Architecture . Here, we can clearly see a different between Tier and Layer . Since each component is independent of each other, they are easily maintainable without changing the whole code.
This approach is really very important when several developers are working on the same project and some module needs to be re-used in another project. In a way, we can distribute work among developers and also maintain it in the future without much problems.
Testing is also a very important issue for Architecture when we are considering writing a test case for the project. Since it’s like a modular architecture , it’s very handy testing each module and to trace out bugs without going through the entire code.
3. Demo: 3 Layer Windows Application in C#.NET
Let’s go though from one module to other to have a better understanding of it.
dbConnection
This class is mainly used to do the database activity like Select, Update and Delete query to database. It also checks if the database connection is open or not. If database connection is not open, then it opens the connection and performs the database query. The database results are to be received and being passing in Data Table in this class.
This class takes the database setting from the app.config file so it’s really flexible to manage the database settings.
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace ThreeLayer Demo.Core { public class dbConnection { private SqlDataAdapter myAdapter; private SqlConnection conn; /// < constructor > /// Initialise Connection /// < / constructor > public dbConnection() { myAdapter = new SqlDataAdapter(); conn = new SqlConnection(ConfigurationManager.ConnectionStrings [" dbConnectionString" ].ConnectionString); } /// < method > /// Open Database Connection if Closed or Broken /// < / method > private SqlConnection openConnection() { if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken) { conn.Open(); } return conn; } /// < method > /// Select Query /// < / method > public DataTable executeSelectQuery(String _query, SqlParameter[] sqlParameter) { SqlCommand myCommand = new SqlCommand(); DataTable dataTable = new DataTable(); dataTable = null ; DataSet ds = new DataSet(); try { myCommand.Connection = openConnection(); myCommand.CommandText = _query; myCommand.Parameters.AddRange(sqlParameter); myCommand.ExecuteNonQuery(); myAdapter.SelectCommand = myCommand; myAdapter.Fill(ds); dataTable = ds.Tables[0 ]; } catch (SqlException e) { Console.Write(" Error - Connection.executeSelectQuery - Query: " + _query + " \nException: " + e.StackTrace.ToString()); return null ; } finally { } return dataTable; } /// < method > /// Insert Query /// < / method > public bool executeInsertQuery(String _query, SqlParameter[] sqlParameter) { SqlCommand myCommand = new SqlCommand(); try { myCommand.Connection = openConnection(); myCommand.CommandText = _query; myCommand.Parameters.AddRange(sqlParameter); myAdapter.InsertCommand = myCommand; myCommand.ExecuteNonQuery(); } catch (SqlException e) { Console.Write(" Error - Connection.executeInsertQuery - Query: " + _query + " \nException: \n" + e.StackTrace.ToString()); return false ; } finally { } return true ; } /// < method > /// Update Query /// < / method > public bool executeUpdateQuery(String _query, SqlParameter[] sqlParameter) { SqlCommand myCommand = new SqlCommand(); try { myCommand.Connection = openConnection(); myCommand.CommandText = _query; myCommand.Parameters.AddRange(sqlParameter); myAdapter.UpdateCommand = myCommand; myCommand.ExecuteNonQuery(); } catch (SqlException e) { Console.Write(" Error - Connection.executeUpdateQuery - Query: " + _query + " \nException: " + e.StackTrace.ToString()); return false ; } finally { } return true ; } } }
Database Access Layer
Database Access Layer
(DAO) builds the query based on received parameters from the Business Logic Layer
and passes it the dbConnection
class for execution. And simple return results from the dbConnection
class to Business Logic Layer
.
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; namespace ThreeLayer Demo.Core { public class UserDAO { private dbConnection conn; /// < constructor > /// Constructor UserDAO /// < / constructor > public UserDAO() { conn = new dbConnection(); } /// < method > /// Get User Email By Firstname or Lastname and return DataTable /// < / method > public DataTable searchByName(string _username) { string query = string .Format(" select * from [t01_user] where t01_firstname like @t01_firstname or t01_lastname like @t01_lastname " ); SqlParameter[] sqlParameters = new SqlParameter[2 ]; sqlParameters[0 ] = new SqlParameter(" @t01_firstname" , SqlDbType.VarChar); sqlParameters[0 ].Value = Convert.ToString(_username); sqlParameters[1 ] = new SqlParameter(" @t01_lastname" , SqlDbType.VarChar); sqlParameters[1 ].Value = Convert.ToString(_username); return conn.executeSelectQuery(query, sqlParameters); } /// < method > /// Get User Email By Id and return DataTable /// < / method > public DataTable searchById(string _id) { string query = " select * from [t01_id] where t01_id = @t01_id" ; SqlParameter[] sqlParameters = new SqlParameter[1 ]; sqlParameters[0 ] = new SqlParameter(" @t01_id" , SqlDbType.VarChar); sqlParameters[0 ].Value = Convert.ToString(_id); return conn.executeSelectQuery(query, sqlParameters); } } }
Value Object
Value Object is nothing more but a class with the contents GET
and SET
methods. It’s mainly used to pass Data from one class to another. It’s directly connected with Business Logic Layer
and Presentation Layer
. As you can see in the diagram object values are being SET in Business Logic Layer
and GET from Presentation Layer
.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ThreeLayer Demo.Core { public class UserVO { private int _idUser; private string _firstname; private string _lastname; private string _email; /// < constructor > /// Constructor UserVO /// < / constructor > public UserVO() { // // TODO: Add constructor logic here // } public int idUser { get { return _idUser; } set { _idUser = value; } } public string firstname { get { return _firstname; } set { _firstname = value; } } public string lastname { get { return _lastname; } set { _lastname = value; } } public string email { get { return _email; } set { _email = value; } } } }
Business Logic Layer
Business Logic Layer (BUS) works as a bridge between Presentation Layer and DAO. All the user values received from the presentation layer are being passed to BUS. The results received from the DAO are in row data in Data Table format but in BUS it’s converting into Value Objects (VO). Business Logic Layer (BUS) is the most important class in the whole architecture because it mainly contains all the business logic of the program. Whenever a user wants to update the business logic of the program only need to update this class.
using System; using System.Collections.Generic; using System.Text; using System.Data; namespace ThreeLayer Demo.Core { /// < summary > /// Summary description for UserBUS /// < / summary > public class UserBUS { private UserDAO _userDAO; /// < constructor > /// Constructor UserBUS /// < / constructor > public UserBUS() { _userDAO = new UserDAO(); } /// < method > /// Get User Email By Firstname or Lastname and return VO /// < / method > public UserVO getUserEmailByName(string name) { UserVO userVO = new UserVO(); DataTable dataTable = new DataTable(); dataTable = _userDAO.searchByName(name); foreach (DataRow dr in dataTable.Rows) { userVO.idUser = Int32 .Parse(dr[" t01_id" ].ToString()); userVO.firstname = dr[" t01_firstname" ].ToString(); userVO.lastname = dr[" t01_lastname" ].ToString(); userVO.email = dr[" t01_email" ].ToString(); } return userVO; } /// < method > /// Get User Email By Id and return DataTable /// < / method > public UserVO getUserById(string _id) { UserVO userVO = new UserVO(); DataTable dataTable = new DataTable(); dataTable = _userDAO.searchById(_id); foreach (DataRow dr in dataTable.Rows) { userVO.idUser = Int32 .Parse(dr[" t01_id" ].ToString()); userVO.firstname = dr[" t01_firstname" ].ToString(); userVO.lastname = dr[" t01_lastname" ].ToString(); userVO.email = dr[" t01_email" ].ToString(); } return userVO; } } }
Presentation Layer
Presentation Layer is the only layer which is directly connected with the user. So in this matter, it’s also a really important layer for marketing purposes. Presentation Layer is mainly used for getting user data and then passing it to Business Logic Layer for further procedure, and when data is received in Value Object then it’s responsible to represent value object in the appropriate form which user can understand.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using ThreeLayer Demo.Core; namespace ThreeLayer Demo { public partial class frmLogin : Form { private UserBUS _userBUS; public frmLogin() { InitializeComponent(); _userBUS = new UserBUS(); } private void btnSearch_Click(object sender, EventArgs e) { UserVO _userVO = new UserVO(); _userVO = _userBUS.getUserEmailByName(txtUsername.Text); if (_userVO.email == null ) MessageBox.Show(" No Match Found!" , " Not Found" , MessageBoxButtons.OK, MessageBoxIcon.Exclamation); else MessageBox.Show(_userVO.email ," Result" , MessageBoxButtons.OK,MessageBoxIcon.Information); } private void btnCancel_Click(object sender, EventArgs e) { Close(); } } }
Summary
Hope this explanation helps the beginner specially looking for a generic approach. There are also some methods which are far better than the architecture described above, mostly with skipping Database Access Layer and Value Object Class, and making it dynamically which is really handy for maintenance in case of frequent database change. I will try to post some in the near future.
Revision
- 31.05.2009: Initial version
- 02.06.2009: Using parameterized SQL queries
-
dbConnection
updated -
UserDAO
updated
-
发表评论
-
C# Tab
2012-06-06 00:25 627<!DOCTYPE html PUBLIC " ... -
UpdatePanel的用法详解
2012-06-06 00:04 789UpdatePanel的用法详解 今天用Upd ... -
具有 ADO.NET 和自定义对象的数据绑定应用程序
2012-05-27 09:41 1042具有 ADO.NET 和自定义对象的数据绑定应用程序 ... -
synchronized作用域
2012-05-24 02:09 742synchronized作用域 ... -
VS2008中新建网站(ASP.NET 网站)跟新建项目(ASP.NET Web 应用程序)的区别!
2012-05-22 15:23 1273VS2008中新建网站(ASP.NET 网站)跟新建项目(AS ... -
转)Using the ASP.Net Runtime for extending desktop applications with dynamic HTML
2012-05-22 14:36 2914Code for this article: ... -
Asp.Net 使用 GDI+ 绘制3D饼图入门篇源码
2012-05-22 14:31 730topn3dpie.aspx --------------- ...
相关推荐
Understanding the ASP.NET object model, classes, and n-tier application architecture Designing classes for maximum performance and reusability, one step at a time Mastering the nuts and bolts of ASP...
The CSLA framework supports 1–, 2– and n–tier models through the concept of mobile objects. This provides the flexibility to optimize performance, scalability, security, and fault tolerance with ...
例如Martin Fowler在《Patterns of Enterprise Application Architecture》一书中,将整个架构分为三个主要的层:表示层、领域层和数据源层。作为领域驱动设计的先驱Eric Evans,对业务逻辑层作了更细致地划分,细分...
Understanding ADO.NET Architecture 412 Differences between ADO and ADO.NET 414 XML Support 414 ADO.NET Configuration 415 Remoting in ADO.NET 415 Maintaining State 415 Using the XML Schema ...
nopCommerce 是一个由ASP.NET多层模式开发的开源电子商城系统,可以自行设置模板、配置灵活、功能强大,它内含一个目录前端和一个管理工具后端。前端包括用户注册、商品购买(可以进行评论)、投票、Blog等,后端有...
nopCommerce 是一个由ASP.NET多层模式开发的开源电子商城系统,可以自行设置模板、配置灵活、功能强大,它内含一个目录前端和一个管理工具后端。前端包括用户注册、商品购买(可以进行评论)、投票、Blog等,后端有...
Part 8 Examining .NET Application Architecture and Design 770 35 Using the Visual Studio 2008 Class Designer 772 Visualizing Code 772 Building an Object Model with the Class Designer 778 ...
Learn how to utilize Entity Framework, SQL Azure database, and other storage mechanisms to build out the data tier of your solution A step-by-step guide focused on delivering solutions to your cloud ...
PART I: Foundations//基础# Chapter 1: Introducing Borland Developers Studio 3.0//简介BDS3.0# Chapter 2: The Platforms: Win32 and Microsoft .NET//Win32以及MS.NET开发平台# Chapter 3: The Delphi Language...
NET是Rockford Lhotka基于.Net设计的一套N-tier分布式框架。 CSLA .NET包含如下功能: l n-Level undo capability 译:n层撤销功能 l Tracking broken business rules to determine whether an object is ...
Explains system linking and data flow, end user interface, system architecture based on Silverlight 4 and .NET 4, and more Includes coverage on integrating social networking and Facebook With this ...
The book then dives into a full 3 tier enterprise implementation of MVVM and takes you through the various options available and trade-offs for each approach. During your journey you will see how to ...
* Explains system linking and data flow, end user interface, system architecture based on Silverlight 4 and .NET 4, and more * Includes coverage on integrating social networking and Facebook With ...
Whereas, if three users transmit simultaneously, the bandwidth required will be 3Mbps which is more than the available bandwidth of the shared link. In this case, there will be queuing delay ...
Completely based on n-tier architecture Forms based authentication User management via Membership providers Role based security Profiles Themes Master pages New data source controls - ...
例如Martin Fowler在《Patterns of Enterprise Application Architecture》一书中,将整个架构分为三个主要的层:表示层、领域层和数据源层。作为领域驱动设计的先驱Eric Evans,对业务逻辑层作了更细致地划分,细分...
3.封装: 封装是把过程和数据包围起来,对数据的访问只能通过已定义的界面。面向对象计算始于这个基本概念,即现实世界可以被描绘成一系列完全自治、封装的对象,这些对象通过一个受保护的接口访问其他对象。 4. ...
3.封装: 封装是把过程和数据包围起来,对数据的访问只能通过已定义的界面。面向对象计算始于这个基本概念,即现实世界可以被描绘成一系列完全自治、封装的对象,这些对象通过一个受保护的接口访问其他对象。 4. 多...