1. 程式人生 > >手動搭建簡單的三層框架

手動搭建簡單的三層框架

第一、三層框架可以手動搭建,也可以用動軟程式碼生成器來實現,本文使用手動搭建來做,首先先建立一個ASP.Net應用程式ThreeLayerWebDemo,然後在解決方案下分別建立四個類庫BLL、DAL、Model、Common。

第二、在ThreeLayerWebDemo中新建一個資料夾News,在News資料夾下建立一個一般處理程式NewsList.ashx和一個NewsListTemp.html模板,並且將以上各個類庫裡的類名做更改,改為容易記且與類的功能屬性一致得名字。

NewsList.ashx程式碼如下:

using Model;
using System;
using System.Collections.Generic;
using System.IO; using System.Linq; using System.Text; using System.Web; namespace ThreeLayerDemo.News { /// <summary> /// NewsList 的摘要說明 /// </summary> public class NewsList : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType
= "text/html"; BLL.NewsInfoService NewsInfoService = new BLL.NewsInfoService();//引用BLL List<NewsInfo> getNews= NewsInfoService.GetAllNews();//獲得資料庫裡的新聞資訊 StringBuilder sb = new StringBuilder(); foreach (var item in getNews) {//dId, dTId, dName, dContent, dlnTime, dEditTime, disDeleted
sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td><a href='#'>操作</a></td></tr>", item.dId, item.dName, item.dContent, item.dlnTime, item.dEditTime, item.disDelete); } string TempString = File.ReadAllText(context.Request.MapPath("NewsListTemp.html")); string result= TempString.Replace("@trBody", sb.ToString()); context.Response.Write(result); } public bool IsReusable { get { return false; } } } }

 

NewListTemp.html模板中的程式碼如下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <meta charset="utf-8" />
</head>
<body>
   
    <table border="1" width="6">
        <tr>
         <th>dId</th><th>dName</th><th>dContent</th><th>dlnTime</th><th>dEditTime</th><th>disDeleted</th> <th>詳 情</th>           
        </tr>
        @trBody
    </table>
</body>
</html>


在以上一般處理程式NewsList中,當程式執行該程式碼時(該處的方法需要手動生成),則跳轉到BLL類庫下的NewsInfoService類中,並且在該類中生成GetAllNews()方法。

 BLL.NewsInfoService NewsInfoService = new BLL.NewsInfoService();//引用BLL
            List<NewsInfo> getNews= NewsInfoService.GetAllNews();//獲得資料庫裡的新聞資訊

NewsInfoService類中的程式碼如下:

using Model;
using DAL;
using System.Collections.Generic;
namespace BLL { public class NewsInfoService { private NewsInfoDal newsInfoDal = new NewsInfoDal();//為什麼要寫為Private public List<NewsInfo> GetAllNews() { return newsInfoDal.GetAllNews(); } } }


Model類庫下的NewsInfo類主要用於存放從資料庫中採集到的資料,用屬性來儲存,程式碼如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
    public class NewsInfo
    {
        //dId, dTId, dName, dContent, dlnTime, dEditTime, disDeleted
        public int dId { get; set; }
        public string dName { get; set; }
        public string dContent { get; set; }
        public DateTime dlnTime { get; set; }
        public DateTime dEditTime { get; set; }
        public int disDelete { get; set; }

       
       
    }
}

DAL類庫中的NewsInfoDAL這個類主要是用來建立資料庫連線、操作資料庫使用,在該類庫中還需要封裝一個SQLHelper類。
NewsInfoDAL.cs 中的程式碼如下所示:

using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class NewsInfoDal
    {
        List<NewsInfo> list = new List<NewsInfo>();
        public List<NewsInfo> GetAllNews()
        {
            string sql = "select dId,  dName, dContent, dlnTime, dEditTime, disDeleted from ContentInfo";
            //dId, dTId, dName, dContent, dlnTime, dEditTime, disDeleted
            using (SqlDataReader reader=SqlHelper.ExecuteReader(sql))
            {
                if (reader.HasRows)
                {
                   
                    while (reader.Read())
                    {
                        NewsInfo dt = new NewsInfo();
                        dt.dId = reader.GetInt32(0);
                        dt.dName = reader.GetString(1);
                        dt.dContent = reader.GetString(2);
                        dt.dlnTime = reader.GetDateTime(3);
                        dt.dEditTime = reader.GetDateTime(4);
                        dt.disDelete = reader.GetInt32(5);
                        list.Add(dt);
                    }
                     
                }
                return list;
            }
        }
    }
}

下面在DAL類庫下封裝一個SQLHelper

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
   public static class SqlHelper
    {
        //寫三個方法:增刪改,返回一個值,返回多行或多個值
        //將連線資料庫的字串寫在一個引用中
        private static readonly string constr = ConfigurationManager.ConnectionStrings
            ["Mysqlserver"].ConnectionString;//

        
        //寫一個方法來執行增刪改
        public static int ExecuteNonQuery(string sql,params SqlParameter[] pms)
        {
            using (SqlConnection con=new SqlConnection (constr))
            {
                using (SqlCommand cmd=new SqlCommand (sql,con))
                {
                    if(pms!=null)
                    {
                        cmd.Parameters.AddRange(pms);
                    }
                    con.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// 寫一個方法執行返回一個值的
        /// </summary>
        /// <returns></returns>
        public static object ExecuteScalar(string sql,params SqlParameter[] pms)
        {
            using (SqlConnection con=new SqlConnection (constr ))
            {
                using (SqlCommand cmd=new SqlCommand (sql,con))
                {
                    if(pms!=null)
                    {
                        cmd.Parameters.AddRange(pms);//把sql中的引數給執行命令
                    }
                    con.Open();
                    return cmd.ExecuteScalar();

                }
            }
        }

        /// <summary>
        /// 寫一個方法來返回多個值
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pms"></param>
        /// <returns></returns>
        public static SqlDataReader ExecuteReader(string sql,params SqlParameter[] pms)
        {
            SqlConnection con = new SqlConnection(constr);
            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                if (pms != null)
                {
                    cmd.Parameters.AddRange(pms);
                }
                try
                {
                    con.Open();
                    return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);//這樣返回值的時候就將連線物件關閉了
                }
                catch
                {
                    con.Close();
                    con.Dispose();
                    throw;

                }
                }
            
        }
           
    }
}

資料庫連線字串寫在Web.config中,(注意:在WinForm中則寫在App.config中)

<?xml version="1.0" encoding="utf-8"?>
<!--
  有關如何配置 ASP.NET 應用程式的詳細資訊,請訪問
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="Mysqlserver" connectionString="server=WIN7U-20170517Z;uid=sa;pwd=zhangyukui283166;
         database=2018Study"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
        type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
        preCondition="managedHandler"/>
    </modules>
  </system.webServer>
</configuration>