C # Three-tier architecture login instance

Source: Internet
Author: User

I have heard of the three-tier structure a long time ago. At that time, only the three-tier structure was known to separate the system interface from unrelated programs such as database operations. The original simple implementation is indeed the legendary three-tier structure.

First, let's take a look at the three layers. The presentation Layer (UI, User Interface), business logic Layer (BLL BusinessLogicLayer), and Data Access Layer (DAL Data Access Layer ). The division of Layer 3 is physical division.

The presentation layer (UI) is the main interface that the user can see.

The data access layer (DAL) is not difficult to understand. It is mainly responsible for adding, deleting, modifying, and querying data.

The business logic layer (BLL) serves as a bridge between the presentation layer and the data access layer. It mainly stores some business processes. That is, logic. The main function is to obtain data from the DAL and display it to the UI.

For example, the three-tier structure can be understood by hotel instances.

UI refers to the waiter, BLL is the cook, and DAL is the buyer.

In the eyes of customers, we can only see the Waiters serve them. I don't know how the background chefs and purchasers work. For the above three roles, no matter which part of the process has a problem, you only need to change an employee to open the business as usual.

The advantages of a three-tier architecture are separation of duties to reduce coupling.

Next, let's look at a login instance with a three-tier structure. First, you need to declare it. This instance has many bugs that need to be optimized. However, it is enough to demonstrate the three layers of thinking. It is just an instance.

Database Table:

Here is the data module diagram:

Careful readers will surely find that there is a Moudel in addition to the UI, BLL, and DAL. This Moudel does not belong to any layer, but exists to better link the three layers. This class is only stored and used together with the above three types. It plays a coordinating role. Moudel class, that is, entity class.

Below are the relationships between these layers.

Next, let's take a look at how they achieve their respective division of labor.

Entity class:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace Login. model {public class UserInfo // entity class, used to save user information {public int ID {get; set;} public string UserName {get; set;} public string Password {get; set ;}public string Email {get; set ;}}}


U layer:

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; namespace LoginUI {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void label1_Click (object sender, EventArgs e) {} private void btnLogin_Click (object sender, EventArgs e) {try {string userName = txtUserName. text. trim (); // retrieves the user interface data string password = txtPassword. text; Login. BLL. loginManager mgr = new Login. BLL. loginManager (); Login. model. userInfo user = mgr. userLogin (userName, password); // use User Interface data for search // if no problem exists, log on to MessageBox. show ("Login user:" + user. userName);} catch (Exception ex) // if an Exception occurs during login, the login fails {MessageBox. show (ex. message );}}}}


Layer B:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace Login. BLL // business logic layer {public class LoginManager {public Login. model. userInfo UserLogin (string userName, string Password) {// throw new NotImplementedException (); Login. DAL. userDAO uDAO = new Login. DAL. userDAO (); // create a user Login. model. userInfo user = uDAO. selectUser (userName, Passw Ord); // return the corresponding data through the content filled in the ui if (user! = Null) // if there is no data in the database, it is the first login. Add 10 points {Login. DAL. scoreDAO sDAO = new Login. DAL. scoreDAO (); sDAO. updateScore (userName, 10); return user;} else // if the user name does not exist in the Database, login fails {throw new Exception ("Login Failed ");}}}}



Layer D:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace Login. DAL // data access layer {class DbUtil // SQL statement used to save the linked Server {public static string ConnString = @ "Server = zc-pc; Database = Login; user ID = sa; Password = 123456 ";}}


Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. data; using System. data. sqlClient; namespace Login. DAL {public class UserDAO {public Login. model. userInfo SelectUser (string userName, string Password) // return a user {using (SqlConnection conn = new SqlConnection (DbUtil. connString) {// create a command object and add the command SqlCommand cmd = conn. CreateCommand (); cmd. commandText = @ "select id, UserName, Password, Email from users where UserName = @ UserName AND Password = @ Password"; cmd. commandType = CommandType. text; cmd. parameters. add (new SqlParameter ("@ userName", userName); cmd. parameters. add (new SqlParameter ("@ Password", Password); conn. open (); // Open the data link SqlDataReader reader = cmd. executeReader (); Login. model. userInfo user = null; // used to save read data While (reader. read () // start to Read data {if (user = null) // if not, a {user = new Login is regenerated. model. userInfo ();} user. ID = reader. getInt32 (0); user. userName = reader. getString (1); user. password = reader. getString (2); if (! Reader. IsDBNull (3) // do not require an email. You can also return {user. Email = reader. GetString (3) ;}} return user ;}}}}


Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. data. sqlClient; namespace Login. DAL {public class ScoreDAO // Add 10 points {public void UpdateScore (string userName, int value) {using (SqlConnection conn = new SqlConnection (DbUtil. connString) {SqlCommand cmd = conn. createCommand (); // create a command object cmd. commandText = @ "insert into scores (UserName, Score) Values (@ UserName, @ Score)"; // modify the Score table data cmd. parameters. add (new SqlParameter ("@ userName", userName); cmd. parameters. add (new SqlParameter ("@ Score", value); conn. open (); cmd. executeNonQuery ();}}}}

Next, let's take a look at the execution results:

Successful execution:

Input error message:

Although this is a small instance, it is enough to learn three layers. It is understandable that there is something wrong with writing.

Summary: for a program using a three-tier architecture, which layer has errors and changes. This greatly reduces system coupling. Of course, it is much easier to maintain hierarchical programs.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.