Asp. NET three-tier architecture detailed how to implement three-tier architecture _ practical skills

Source: Internet
Author: User
Tags abstract microsoft sql server

First, the database

/*==============================================================*/
/* DBMS name:   Microsoft SQL Server 2000          *
 
 
//*==============================================================*/if exists (select 1
      from sysobjects
      where id = object_id (' newscontent ')
      and  type = ' U ')
  drop table newscontent
 
 
Go /*==============================================================*//
* table:newscontent                      * *
/*=== ===========================================================*/
CREATE TABLE newscontent (
  ID      int       identity (1,1)  primary key,
  Title     nvarchar not   null,
  Content    ntext      Not NULL,
  adddate   datetime isn't     null,
 categoryid  int not       null

Second, the project document structure

Implementation steps are: 4-3-6-5-2-1


To implement the step process

1. Create model to realize business entity.

2, create idal, implement interface.

3, create Sqlserverdal, implement the method in the interface.

4, increase the configuration information in the web.config, for the Sqlserverdal assembly.

5, create dalfactory, return an instance of the assembly's specified class.

6. Create BLL, call Dalfactory, get an instance of the assembly-specified class, and complete the data manipulation method.

7, create the Web, call the BLL in the data operation method.

Attention:

1, the assembly name in the web.config must be the same as the output assembly name in Sqlserverdal.

2, dalfactory only need a dataaccess class, you can complete the creation of all the assembly instances.

3. After the project is created, be careful to modify the default namespace and assembly name for each purpose.

4, pay attention to modify the project dependencies in the solution.

5. Note that the project references are added to the solution.

Third, the process of access between the layers

1, pass in the value, convert the value to type (integer type).

2, create the BLL layer of Content.cs object C, through object C access to the BLL layer of Method Getcontentinfo (ID) Call BLL layer.

3, the BLL layer method Getcontentinfo (ID) to obtain the data access Layer Sqlserverdal instance, instantiate Idal layer Interface object Dal, this object is created by the factory layer Dalfactory, It then returns the method Dal.getcontentinfo (ID) of the content that the Idal layer passes in to the value.

4. The Data Factory accesses the Sqlserverdal layer through the Webdal string given in the Web.config configuration file, returns a complete path to the Sqlserverdal layer to the BLL layer.

5, to call the Sqlserverdal layer, the Sqlserverdal layer completes the assignment model layer of the object value is empty, given a parameter, call the Sqlserverdal layer of the SqlHelper ExecuteReader method, Read the data assignment for each field to an object that is defined as the model layer that is empty.

6, SqlHelper Execute SQL command, return a specified connection database recordset, where you need to reference the parameter type, provide to open the connection command execution ready to PrepareCommand.

7, return the model layer to the query to get a row of record value assigned to the Sqlserverdal layer of the model layer of the object CI, and then return this object to BLL.

8, back to the web layer of the BLL layer of the method call, the resulting object value assigned to the lable tag, displayed in the foreground to the interface

Iv. List of documents in the project

1. Dbutility Project

(1) ConnectionInfo.cs

Using System;
Using System.Configuration;
    Summary description of namespace Utility {///<summary>
    ///connectioninfo.
    ///</summary> Public
    class ConnectionInfo
    {public
       static string Getsqlserverconnectionstring ()
       {return
           configurationsettings.appsettings[' sqlconnstring ']}
    }


2. Sqlserverdal Project

(1) SqlHelper.cs abstract class

Using System;
Using System.Data;
Using System.Data.SqlClient;
 
Using Dbutility;
    Summary description of namespace Sqlserverdal {///<summary>///SqlHelper. </summary> public abstract class SqlHelper {public static readonly string conn_str = Connectioni Nfo.
 
       Getsqlserverconnectionstring ();
       <summary>///executes the SQL command using the provided function, returning a database recordset from the specified connection///</summary>///<remarks> For example:///SqlDataReader r = ExecuteReader (connstring, CommandType.StoredProcedure, "Publishorders", New SqlPar
       Ameter ("@prodid", 24)); </remarks>///<param name= "connectionString" >sqlconnection valid SQL connection string </param>/// ;p Aram Name= "CommandType" >commandtype:commandtype.text, commandtype.storedprocedure</param>///<param Name= "CommandText" >sql statement or stored procedure </param>///<param name= "commandparameters" parameter array >sqlparameter[ Param>///<returns>SqlDataReader: Recordset </returns> public static SqlDataReader ExecuteReader Execution Result (string connstring, commandtype cmd
           Type, String cmdtext, params sqlparameter[] cmdparms) {SqlCommand cmd = new SqlCommand ();
 
           SqlConnection conn = new SqlConnection (connstring); We use Try/catch here because if this method throws an exception, our goal is to close the database connection and throw the exception,///Because there will be no DataReader, thereafter Commandbehaviour.closeconnection
           will not work.
              try {preparecommand (CMD, conn, null, Cmdtype, Cmdtext, cmdparms); SqlDataReader rdr = cmd.
              ExecuteReader (commandbehavior.closeconnection); Cmd.
              Parameters.clear ();
           return RDR; catch {Conn.
              Close ();
           Throw
       ///<summary>///prepare to execute commands: Open database connection, command statement, set command type (SQL statement or stored procedure), function language. </summary>///<param name= "cmd" >sqlcommand component </param>///<pAram Name= "conn" >sqlconnection component </param>///<param name= "Trans" >sqltransaction component, available for Null</para m>///<param name= "cmdtype" > Statement type: CommandType.Text, commandtype.storedprocedure</param>///&L
       T;param name= "Cmdtext" >sql statement, can be stored procedure </param>///<param name= "cmdparms" >sql parameter array </param> private static void PrepareCommand (SqlCommand cmd, SqlConnection Conn, SqlTransaction Trans, CommandType Cmdtype, string Cmdtext, sqlparameter[] cmdparms) {if (conn. State!= ConnectionState.Open) Conn.
 
           Open (); Cmd.
           Connection = conn;
 
           Cmd.commandtext = Cmdtext; if (trans!= null) cmd.
 
           Transaction = trans;
 
           Cmd.commandtype = Cmdtype; if (cmdparms!= null) {foreach (SqlParameter parm in cmdparms) cmd.
           Parameters.Add (Parm);
 }
       }
    }
}

(2) Content.cs class

Using System;
Using System.Data;
Using System.Data.SqlClient;
Using Model;
 
Using Idal;
    Summary description of namespace Sqlserverdal {///<summary>///Content.
       </summary> public class Content:icontent {Private Const string parm_id = "@ID"; Private Const string sql_select_content = "Select ID, Title, CONTENT, Adddate, CategoryID from newscontent Where ID = @ID"
 
 
       ;
 
           Public ContentInfo getcontentinfo (int id) {//Creative article content class ContentInfo ci = null;
           Create a parameter SqlParameter parm = new SqlParameter (parm_id, Sqldbtype.bigint, 8); Assigns the ID value parm.
 
           Value = ID;
           using (SqlDataReader SDR = Sqlhelper.executereader (Sqlhelper.conn_str, CommandType.Text, Sql_select_content, Parm)) {if (SDR). Read ()) {ci = new ContentInfo (SDR). GetInt32 (0), SDR. GetString (1), SDR. GetString (2), SDR. GetDateTime (3), SDR. GetInt(4), SDR. GetInt32 (5), SDR.
              GetString (6));
       } return CI;



 }
    }
}

3, Model Project

(1) ContentInfo.cs

Using System;
    namespace Model {///<summary>///Class1 's summary description.
       </summary> public class ContentInfo {private int _id;
       private string _content;
       private string _title;
       private string _from;
       Private DateTime _adddate;
       private int _clsid;
 
       private int _tmpid; <summary>///article content constructor///</summary>///<param name= "id" > article Serial number Id</param&gt
       ; <param name= "Content" > Article contents </param>///<param name= "title" > article title </param>///< Param name= "from" > Article source </param>///<param name= "CLSID" > Article classification attribute id</param>///<param Name= "Tmpid" > Article Template Properties id</param> public contentinfo (int id,string title,string content,string from,datetime
           Adddate,int clsid,int tmpid) {this._id = ID;
           This._content = Content;
           This._title = Title; This._from = from;
           This._adddate = adddate;
           This._clsid = ClsID;
       This._tmpid = Tmpid;
       }//Property public int ID {get {_id;}
       public string Content {get {_content;}
       public string Title {get {_title;}
       public string from {get {_from;}
       Public DateTime Adddate {get {_adddate}
       public int ClsID {get {_clsid;}
       public int Tmpid {get {_tmpid;}
 
 }
 
 
 
    }
}

4. Idal Project

(1) Icontent.cs

Using System;
Using Model;
 
Namespace Idal
{
    ///<summary>
    ///article content Operations Interface
    ///</summary> public
    interface Icontent
    {
       ///<summary>
       ///Gets the content of the article.
       ///</summary>
       ///<param name= "id" > Article id</param>///
       Returns>
       contentinfo getcontentinfo (int id);
    }

5. Dalfactory Project

(1) Content.cs

Using System;
Using System.Reflection;
Using System.Configuration;
Using Idal;
 
Namespace Dalfactory
{
    ///<summary>
    ///Production mode implements the article interface.
    ///</summary> Public
    class Content
    {public
       static idal. Icontent Create ()
       {
           //* Here you can view the DAL interface class.
           string path = system.configuration.configurationsettings.appsettings["Webdal"]. ToString ();
           String className = path+ ". Content ";
          
           Return with the class combination specified by the configuration file
           (idal. icontent) Assembly.Load (path). CreateInstance (ClassName);}}




6. BLL Project

(1) Content.cs

Using System;
 
Using Model;
Using Idal;
    Summary description of namespace BLL {///<summary>
    ///Content.
    ///</summary> Public
    class Content
    {public
 
       contentinfo getcontentinfo (int id)
       {
 
           Obtain an article content instance from the data Access layer
           icontent dal = DALFactory.Content.Create ();
 
           Use the DAL to find the content of the article return
           dal. Getcontentinfo (ID);}}


7. Web Project

1), Web.config:

 <appSettings> 
<add key= "sqlconnstring" value= "Data source=localhost

; Persist security info=true;initial Catalog=newsdb;

User Id=sa; password= "/> <add key= webdal" value= "Sqlserverdal"/>  
 </appSettings>

2), webui.aspx

<%@ Page language= "C #" codebehind= "WebUI.aspx.cs" autoeventwireup= "false" inherits= "Web.webui"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" > <HTML> <HEAD> &LT;TITLE&GT;WEBUI&L t;/title> <meta name= "generator" content= "Microsoft Visual Studio. NET 7.1" > <meta name= "Code_la Nguage "content=" C # > <meta name= "vs_defaultClientScript" content= "JavaScript" > <meta name= "vs_t" Argetschema "content=" http://schemas.microsoft.com/intellisense/ie5 "> </HEAD> <body ms_positioning=" Gr
           Idlayout "> <form id=" Form1 "method=" POST "runat=" Server "> <font" > Arial "></FONT> <table width= "border=" "1" > <tr> <td style= "width:173px" >&nb sp;</td> <td>  <asp:label id= "lbltitle" runat= "Server" ></
           Asp:label></td>   </tr> <tr> <td style= "WIDTH:173PX; height:22px "> </td> <td style=" height:22px ">  <asp:la
                  Bel id= "Lbldatatime" runat= "Server" ></asp:Label></td> </tr> <tr> &LT;TD style= "width:173px" > </td> <td>  & Lt;asp:label id= "lblcontent" runat= "Server" ></asp:Label></td> </tr> <t
              r> <td style= "width:173px" > </td> <td> </td> </tr> <tr> <td style= "WIDTH:173PX; height:23px "> </td> <td style=" height:23px "> </td> </t r> <tr> <td style= "width:173px" &GT;&NBSP;&Lt;/td> <td> </td> </tr> <tr> &LT;TD style= "width:173px" > </td> <td> </td> </tr&gt
              ; <tr> <td style= "width:173px" > </td> <td> </td&gt
              ;
                  </tr> <tr> <td style= "width:173px" > </td>
              <td>  <asp:label id= "lblmsg" runat= "Server" >Label</asp:Label></td>
 </tr> </table> </form> </body> </HTML>

3), WebUI.aspx.cs background call display:

Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Web;
Using System.Web.SessionState;
Using System.Web.UI;
Using System.Web.UI.WebControls;
 
Using System.Web.UI.HtmlControls;
Using BLL;
 
Using Model;
    Summary description of namespace MyWeb {///<summary>///WebForm1. </summary> public class WebUI:System.Web.UI.Page {protected System.Web.UI.WebControls.Label lb
       Ltitle;
       protected System.Web.UI.WebControls.Label lbldatatime;
       protected System.Web.UI.WebControls.Label lblcontent;
 
       protected System.Web.UI.WebControls.Label lblmsg;
 
 
       Private ContentInfo CI; private void Page_Load (object sender, System.EventArgs e) {if (!
           Page.IsPostBack) {getcontent ("1");
       
           }} private void GetContent (string id) {int id = WebComponents.CleanString.GetInt (ID); Content c = new Content ();
           CI = c.getcontentinfo (ID); if (ci!=null) {this.lblTitle.Text = ci.
              Title; This.lblDataTime.Text = ci.
              Adddate.tostring ("Yyyy-mm-dd"); This.lblContent.Text = ci.
           Content;
           else {This.lblMsg.Text = "did not find this article";
           The code generated #region the Web Forms Designer override protected void OnInit (EventArgs e) {//
           CodeGen: This call is required for the ASP.net Web forms Designer.
           InitializeComponent (); Base.
       OnInit (e);
       ///<summary>///Designer supports the desired method-do not modify the contents of///this method using the Code editor. </summary> private void InitializeComponent () {this. Load + = new System.EventHandler (this.
 
       Page_Load);
 } #endregion}}

4), webcomponents items
(1) CleanString.cs

Using System;
 
Using System.Text;
    Summary description of namespace Myweb.webcomponents {///<summary>///cleanstring.
           </summary> public class CleanString {public static int GetInt (string inputstring) {
           try {return Convert.ToInt32 (inputstring);
           catch {return 0; } public static string Inputtext (string inputstring, int maxLength) {Stringbuilde
 
           R retVal = new StringBuilder (); Check incoming parameters for null or blank string if (inputstring!= null) && (inputstring!= stri Ng.
 
              Empty)) {inputstring = Inputstring.trim ();
              Chop the string incase the Client-side max length//fields are bypassed to prevent buffer over-runs if (Inputstring.length > maxLength) inputstring = inputstring.substring (0, maxLength);  Convert some harmful symbols incase the regular//expression the validators are for (int i = 0; i < inputstring.length;
                         i++) {switch (Inputstring[i]) {case ' "':
                         Retval.append ("" ");
                     Break
                         Case ' < ': Retval.append ("<");
                     Break
                         Case ' > ': Retval.append (">");
                     Break
                         Default:retVal.Append (Inputstring[i]);
                  Break
           }//Replace single quotes with white retval.replace ("'", "");
          
       return retval.tostring ();
 }
        
    }
}

Above is the entire content of the ASP.net three-tier architecture, hope to help everyone's study.

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.