. NET layered Landing--a summary of computer room charge system

Source: Internet
Author: User
Tags connection pooling

Last year, I wrote a computer room fee system Landing summary article, that is standing on the basis of VB, direct Query database implementation of the landing. is a very early knowledge. If you want to know more, please see VB Query database Landing form--computer room Charge System Summary (a).

Today, I want to change an angle, in a different way, to achieve landing. First of all, the development tool I chose is vb.net, and the database is SQLSever2008. Secondly, I use three layers of thought, the interface, logic and data are separated, reducing the impact of each other. In the second, the interface layer is as concise as possible, all the algorithms and business logic are written to the logic layer, while using the interface and Factory mode as well as the appearance mode, reduce the dependence between each other, reduce the coupling. Finally, through the document and UML diagram, write code to achieve landing.

First of all, look at my design of the landing sequence diagram (if there are errors, please note that it is appreciated):


After seeing the picture, if you have some experience, I believe that the code is not a problem for you. Below, I put my code below, for reference only Oh! (Yes, the U-layer interface has not changed, if you want to know, see the connection blog).

The first is the entity layer code:

User entity layer:

Public Class UserInfo    private _userid As String    private _password As String public property        UserID as String
   get            Return _userid        end Get        Set (value as String)            _userid = value        End Set    End Property Public Property    PassWord as String        Get            Return _password        End Get        set (ByVal value as String)            _password = value        End Set    end Property   End Class

Worksheet entity layer:

<span style= "FONT-SIZE:18PX;" >imports systemimports system.data ' <summary> ' database table Opelinerecord corresponding entity class ' ' </summary>public class Opelinerecordentity private m_opercomprecordid As String private m_operatorid as String private m_landdate as Str ing Private m_landtime As String private m_outdate as String private m_outtime as String private m_status as S Tring Private M_computerid as String public Sub opelinerecordentity () M_opercomprecordid = "" M_operat        Orid = "M_landdate =" "M_landtime =" "M_outdate =" "M_outtime =" "M_status =" " M_computerid = "End Sub" <summary> "set or return value Opercomprecordid" "</summary> public P Roperty Opercomprecordid as String get Return m_opercomprecordid End get Set (value as Stri NG) M_opercomprecordid = value End Set End Property ' <summary> ' setting or return value Operatorid   ' </summary> public Property Operatorid as String get Return m_operatorid End get Set (value as String) M_operatorid = value End Set End Property ' <summary> ' setting or return value Landdate "' </summary> public property landdate as String Get return m_landdate E    nd Get Set (value as String) M_landdate = value End Set End Property ' <summary>        ' Set or return value Landtime ' </summary> public property landtime as String Get return m_landtime End Get Set (value as String) M_landtime = value End Set End Property ' &LT;SUMMARY&G    T        ' Set or return value Outdate ' </summary> public property outdate as String Get return m_outdate    End Get Set (value as String) M_outdate = value End Set End Property ' <summary> "' Set or return value Outtime    ' </summary> public Property outtime as String get Return m_outtime End get Set (value as String) M_outtime = value End Set End Property ' <summary> ' setting or return value Statu        S ' </summary> public property Status as String get Return m_status End get Set (value as String) M_status = value End Set End Property ' <summary> ' setting or return value compute Rid ' </summary> public property ComputerId as String Get Return m_computerid End G ET set (value as String) M_computerid = value End Set End Propertyend class</span>
Converting a DataTable to a generic type

<span style= "FONT-SIZE:18PX;" >imports System.Collections.Generic ' Increase the namespace of generics Imports system.reflectionpublic Class entityhelper public Shared Fu Nction converttolist (Of T as {New}) (ByVal DT as DataTable) as IList (Of T) ' converts a DataTable to a generic collection ' Note: 1,converttolist (O F t as {new} Here the new is used to constrain T, must have, otherwise new T will appear error ' 2,new constraints in C # and vb.net inside the wording is not the same, C # is used in the Where to add a constraint to the Dim MyL        ist as New List (of T) ' defines the final returned collection Dim myType As Type = GetType (T) ' Get the type of the entity class? Dim dr As DataRow ' define rowset Dim tempname as String = String.Empty ' defines a temporary variable ' to traverse all the data rows of the DataTable for every Dr in Dt. Rows Dim MyT As New T ' defines an object for an entity class Dim Propertys () as PropertyInfo = Myt.gettype ().                GetProperties () ' Defines the property collection Dim Pr as PropertyInfo ' to traverse all properties of the object for every Pr in Propertys Tempname = Pr.name ' assigns a property name to a temporary variable ' checks if the DataTable contains this column (the column name = = Property name of the object) if (dt.  Columns.contains (tempname)) Then ' Compare this property to the column name in the DataTable to see if the DataTable contains this property ' to determine if this property has a setter if (Pr.canwrite = False) T  Hen ' Determines whether this property is writable, if not writable, jumps out of this loop Continue for End if Dim value as Object = DR (Tempname) ' Defines an object-type variable to hold the value of the column If (value.    ToString <> DBNull.Value.ToString () Then ' if non-empty, the property assigned to the object Pr.setvalue (MyT, Value, nothing) ' During runtime, dynamically access an object's properties through reflection, end If End If Next mylist.add (MyT) ' added to the set Next return myList ' return entity collection End FunctionEnd class</span>

Then the interface layer Idal:

<span style= "FONT-SIZE:18PX;" >public Interface iuser    Function selectuser (ByVal User as entity. UserInfo) as List (of UserInfo)  End interface</span>
Layer D:

<span style= "FONT-SIZE:18PX;" >imports idalimports entityimports System.Data.SqlClientPublic Class userdal:implements idal. Iuser public Function selectuser (user as UserInfo) as List (of UserInfo) Implements Iuser.selectuser Dim Struseri D as String = user.        UserID Dim Helper As New Helper.sqlhelper Dim dt As New DataTable Dim mylist As List (of UserInfo) Dim strSQL As String = "SELECT * from Operatorinfo where [email protected] and state= ' use '" Dim sqlparams A S SqlParameter () = {New SqlParameter ("@UserID", strUserID)} ' declares and instantiates parameters dt = Helper. ExecuteNonQuery (strSQL, CommandType.Text, Sqlparams) ' calls the SqlHelper () method in the Execselect class to execute the query and gets the return value MyList = Entityhelp Er.converttolist (of UserInfo) (DT) converts DT to generic collection Return MyList end Function End FunctionEnd Class </span> 

Add record

<span style= "FONT-SIZE:18PX;" >imports idalimports entityimports System.Data.SqlClientPublic Class userworklogdal:implements idal. Iuserworklog public Function Adduserworklog (Worklog as opelinerecordentity) as Boolean Implements iuserworklog.adduserw Orklog ' declares an Sqlhelper type Helper Dim helper As New Helper.sqlhelper Dim dt As New Integer ' declaration and instance SQL statement that needs to be executed Dim strSQL as String = "Insert into Opelinerecord (operatorid,landdate,landtime,computerid,status) Valu  Es (@OperatorID, @landDate, @landTime, @ComputerID, @Status) "' Declare a parameter array Dim sqlparams as SqlParameter () = {New SqlParameter ("@OperatorID", Worklog. Operatorid), New SqlParameter ("@LandDate", Worklog. landdate), New SqlParameter ("@LandTime", Worklog. Landtime), New SqlParameter ("@ComputerID", Worklog. ComputerId), New SQLParameter ("@Status", Worklog. Status} ' call the Execadddeleteuser () method in the SqlHelper class to perform the add information, get the return value, and return the DT = helper.        Execadddelupdate (strSQL, CommandType.Text, sqlparams) return dt If dt > 0 Then return True Else Return False End If End function</span>

Appearance:

<span style= "FONT-SIZE:18PX;" >public Class LOGINFAC public Function Login (ByVal User as entity. UserInfo) as String Dim userlogin as New BLL. Usermanager Userlogin. Isuserexit (user) If not userlogin. Isuserexit (user) then Throw the New Exception ("Incorrect password") End If userlogin. Checkpwdisright (user) If userlogin. Checkpwdisright (user) = False then Throw New Exception ("Incorrect password") End if ' Determine if user is logged on system Dim US Erwork as New entity. Opelinerecordentity Dim WORKBLL as New BLL. Userworklogmanager Userwork. Operatorid = user. UserID Userwork. Landdate = DateTime.Now.ToString ("Yyyy/mm/dd") userwork. Landtime = DateTime.Now.ToString ("hh:mm") Userwork.computerid = System.Net.Dns.GetHostName () userwork. Status = "On duty" ' Add login information workbll. Addworklog (userwork) End functionend class</span>

SqlHelper Layer:

<span style= "FONT-SIZE:18PX;" > ' Get the connection string from the configuration file imports System.dataimports System.Data.SqlClient ' Imports System.Configuration ' Add a reference to the profile public Class Sqlhelper ' Call configuration file Private ReadOnly strconnection as String = Configuration.ConfigurationManager.AppSettings ( "ConnStr"). ToString ' parameter query ' return DataTable query out table public Function ExecuteNonQuery (ByVal cmdtext as String, ByVal Cmdtype As CommandType, ByVal Sqlparams as SqlParameter ()) as DataTable Using conn as New SqlConnection (strconnection) ' enables With connection pooling, you can automatically close the connection Dim cmd as SqlCommand = conn after use is complete. CreateCommand () ' Dim adp As SqlDataAdapter Dim ds as New DataSet cmd. CommandText = Cmdtext ' requires execution of SQL statement cmd. CommandType = Cmdtype ' gives the type cmd of the SQL statement. Parameters.addrange (sqlparams) ' parameter array, the number of arguments depends on the actual situation ADP = New SqlDataAdapter (cmd) Try c Onn. Open () ADP. Fill (ds) ' Return cmd.        ExecuteNonQuery ()        Return ds.        Tables (0) Catch ex as Exception Return nothing Throw ex End Try End Using End Function ' parameter additions and deletions change public function execadddelupdate (ByVal cmdtext as String, ByVal Cmdtype as Comma  Ndtype, ByVal Sqlparams as SqlParameter ()) as Integer Using conn as New SqlConnection (strconnection) Dim cmd as SqlCommand = conn. CreateCommand () Dim adp As SqlDataAdapter Dim ds as New DataSet cmd. CommandText = Cmdtext cmd. CommandType = Cmdtype cmd. Parameters.addrange (sqlparams) ADP = New SqlDataAdapter (CMD) Try Conn. Open () ADP. Fill (DS) Return ds.        Tables.count Catch ex as Exception Return nothing Throw ex End Try End Using End FunctionEnd class</span>

Factory Floor:

<span style= "FONT-SIZE:18PX;" >imports system.reflectionimports [idal]public Class bdfactory    ' Private Shared ReadOnly db as String = Configurati On. Configurationmanager.appsettings ("dbstring")    ' private shared ReadOnly assemblyname = db + ' DAL '    private shared ReadOnly assemblyname = "Sqldal" public    Function Createuserdao () as Idal.  Iuser        ' Dim className As String = AssemblyName + "." + db + "Userdal"        Dim className As String = AssemblyName + "." + "Userdal"        Return CType (Assembly.Load (AssemblyName). CreateInstance (ClassName), Iuser)   ' return to Iuser    End Function </span>

<span style= "FONT-SIZE:18PX;" >public Function Createuserworklogdao () as Idal. Iuserworklog        Dim strinstance as String = AssemblyName + "." + "Userworklogdal" "     object to instantiate (assembly with the same name as namespace)          Return CType (Assembly.Load (AssemblyName). CreateInstance (strinstance), iuserworklog)   ' return to Iuserworklog    End function</span>

B Layer:

Add on-Machine record

<span style= "FONT-SIZE:18PX;" >imports factoryimports entitypublic Class userworklogmanager    Private ReadOnly Factory as Factory.bdfactory = New Factory.bdfactory    Dim iu as Idal. Iuserworklog    ' declares and instantiates the variable Iuser: Call factory. The Createuserdao () method returns the Iuser    ' Add user work record public    function Addworklog (ByVal Worklog as entity. opelinerecordentity) as a Boolean        IU = factory. Createuserworklogdao ()        Dim dt as Integer        dt = IU. Adduserworklog (worklog)        if dt > 0 then            return True        Else            return False        end If    End Function</span>
query whether the user has the correct password

<span style= "FONT-SIZE:18PX;" >imports entitypublic Class Usermanager Private ReadOnly Factory as Factory.bdfactory = New factory.bdfactory () D Im Iuser as Idal. Iuser public Function isuserexit (ByVal User as entity. UserInfo) as a Boolean Dim IU as Idal. Iuser Dim MyList as List (of UserInfo) IU = factory. Createuserdao () MyList = IU. Selectuser (user) If mylist. Count = 0 Then return False Else return True end If end Function public Func tion Checkpwdisright (ByVal User as entity. UserInfo) as a Boolean Dim IU as Idal. Iuser Dim MyList as List (of UserInfo) IU = factory. Createuserdao () MyList = IU. Selectuser (user) If Trim (mylist (0). PassWord) <> user.        PassWord then Throw New Exception ("Input password incorrect") return False Else return True End If End function</span>
and finally the U-layer

<span style= "FONT-SIZE:18PX;"  >public Class frmlogin Private Sub btnok_click (sender as Object, e as EventArgs) Handles btnok.click Dim User As New entity. UserInfo ' instantiation of user user. UserID = txtUsername.Text user. PassWord = txtPassword.Text If TxtUserName.Text.Trim (). Length > Then MessageBox.Show ("cannot exceed 20 digits", "hint") Exit Sub End if if txtUserName.            Text.trim () = "Then MessageBox.Show (" Enter user name "," Prompt ", MessageBoxButtons.OK, Messageboxicon.exclamation) Exit Sub ElseIf txtPassword.Text.Trim () = "Then MessageBox.Show (" Enter with password "," Prompt ", MessageBoxButtons. OK, messageboxicon.exclamation) Exit Sub End If Try ' call appearance Dim LOGINFAC as F Acade. LOGINFAC = New Facade.loginfac () Loginfac. Login (user) Me.hide () formain.show () Catch ex as Exception MsgBox (ex. Message, CType (vbOKOnly + Msgboxstyle.informatIon, MsgBoxStyle), "hint") End Try end Sub End class</span> 
Ok system end, there may be a slight problem, careful will certainly be resolved (because in the process of pasting, may be inattentive, you know ...) For the first time, the code and logic are not simple and difficult, so why do we continue?

I do not know if the reader has such a question. In fact, very simple, although the code and logic trouble, but the performance of the system is better, logic is more clear, at the same time, reduce the burden of U-layer, work materialized. Similarly, compatibility extensibility is better and robustness is increased. More suitable for cooperative development. This is a small system, if it is a large system, is not the advantage will be more obvious!

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.