asp.net 3.三层架构

1.新建项目和类库

  CZBK.ItcastProject (空白项目)

  CZBK.ItcastProject.BLL (类库) -- 逻辑业务

  CZBK.ItcastProject.Common (类库) -- 工具层

  CZBK.ItcastProject.DAL 

  CZBK.ItcastProject.Model

  CZBK.ItcastProject.WebApp -- web项目

2. DAL

2.1 SqlHelper类 :ADO.Net 连接数据库的相关

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace CZBK.ItcastProject.DAL
{
   public class SqlHelper
    {
       private static readonly string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
       public static DataTable GetDataTable(string sql,CommandType type,params SqlParameter[]pars)
       {
           using (SqlConnection conn = new SqlConnection(connStr))
           {
               using (SqlDataAdapter apter = new SqlDataAdapter(sql, conn))
               {
                   if (pars != null)
                   {
                       apter.SelectCommand.Parameters.AddRange(pars);
                   }
                   apter.SelectCommand.CommandType = type;
                   DataTable da = new DataTable();
                   apter.Fill(da);
                   return da;
               }
           }
       }

       public static int ExecuteNonquery(string sql, CommandType type, params SqlParameter[] pars)
       {
           using (SqlConnection conn = new SqlConnection(connStr))
           {
               using (SqlCommand cmd = new SqlCommand(sql, conn))
               {
                   if (pars != null)
                   {
                       cmd.Parameters.AddRange(pars);
                   }
                   cmd.CommandType = type;
                   conn.Open();
                   return cmd.ExecuteNonQuery();
               }
           }
       }
    }
}

2.UserInfoDall类  针对表对象UserInfo的SQL语句操作,增删改查,还有将datatable转成对象

扫描二维码关注公众号,回复: 1776683 查看本文章
using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace CZBK.ItcastProject.DAL
{
    public class UserInfoDal
    {

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        public List<UserInfo> GetList()
        {
            string sql = "select * from UserInfo";
            DataTable da = SqlHelper.GetDataTable(sql, CommandType.Text);
            List<UserInfo> list = null;
            if (da.Rows.Count > 0)
            {
                list = new List<UserInfo>();
                UserInfo userInfo = null;
                foreach (DataRow row in da.Rows)
                {
                    userInfo = new UserInfo();
                    LoadEntity(userInfo, row);
                    list.Add(userInfo);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取一条用户信息 By ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserInfo GetDeail(int id)
        {
            string sql = "SELECT id,username,userpass,regtime,email FROM UserInfo where id = @id";
            SqlParameter [] pars ={
                                      new SqlParameter("@id",SqlDbType.Int)
                                  };
            pars[0].Value=id;
            DataTable dt = SqlHelper.GetDataTable(sql, CommandType.Text, pars);
            UserInfo instance = null;
            if(dt.Rows.Count>0)
            {
                instance = new UserInfo();
                LoadEntity(instance, dt.Rows[0]);
            }
            return instance;
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public int AddUserInfo(UserInfo userInfo)
        {
            string sql = "insert into UserInfo(UserName,UserPass,RegTime,Email) values(@UserName,@UserPass,@RegTime,@Email)";
            SqlParameter[] pars = { 
                                new SqlParameter("@UserName",SqlDbType.NVarChar,32),
                                  new SqlParameter("@UserPass",SqlDbType.NVarChar,32),
                                         new SqlParameter("@RegTime",SqlDbType.DateTime),
                                    new SqlParameter("@Email",SqlDbType.NVarChar,32)
                                  };
            pars[0].Value = userInfo.UserName;
            pars[1].Value = userInfo.UserPass;
            pars[2].Value = userInfo.RegTime;
            pars[3].Value = userInfo.Email;
            return SqlHelper.ExecuteNonquery(sql, CommandType.Text, pars);
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public int UpdateUserInfo(UserInfo userInfo)
        {
            string sql = "UPDATE UserInfo SET username = @username,userpass = @userpass,regtime = @regtime,email = @email WHERE id = @id";
            SqlParameter[] pars = {
                                       new SqlParameter("@username",SqlDbType.NVarChar,50),
                                       new SqlParameter("@userpass",SqlDbType.NVarChar,50),
                                       new SqlParameter("@regtime",SqlDbType.DateTime),
                                       new SqlParameter("@email",SqlDbType.NVarChar,50),
                                       new SqlParameter("@id",SqlDbType.Int)
                                   };
            pars[0].Value = userInfo.UserName;
            pars[1].Value = userInfo.UserPass;
            pars[2].Value = userInfo.RegTime;
            pars[3].Value = userInfo.Email;
            pars[4].Value = userInfo.Id;
            return SqlHelper.ExecuteNonquery(sql, CommandType.Text, pars);
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteUserInfo(int id)
        {
            string sql = "DELETE FROM UserInfo WHERE id = @id";
            SqlParameter[] pars ={
                                      new SqlParameter("@id",SqlDbType.Int)
                                  };
            pars[0].Value = id;
            return SqlHelper.ExecuteNonquery(sql, CommandType.Text, pars);
        }

        private void LoadEntity(UserInfo userInfo, DataRow row)
        {
            userInfo.UserName = row["UserName"] != DBNull.Value ? row["UserName"].ToString() : string.Empty;

            userInfo.UserPass = row["UserPass"] != DBNull.Value ? row["UserPass"].ToString() : string.Empty;
            userInfo.Email = row["Email"] != DBNull.Value ? row["Email"].ToString() : string.Empty;
            userInfo.Id = Convert.ToInt32(row["ID"]);
            userInfo.RegTime = row["RegTime"] != DBNull.Value ? Convert.ToDateTime(row["RegTime"]) : DateTime.Now;
        }

    }
}

3.Model 

3.1 UserInfo类

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

namespace CZBK.ItcastProject.Model
{
   public class UserInfo
    {
       public int Id { get; set; }
       public string UserName { get; set; }
       public string UserPass { get; set; }
       public DateTime RegTime { get; set; }
       public string Email { get; set; }
    }
}

4. Common

4.1 CacheControl类  --> .net框架 HttpRuntime.Cache缓存类的操作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;

namespace CZBK.ItcastProject.Common
{
    public class CacheControl
    {
        private static string devMode;

        public static TimeSpan DefaultCacheTime()
        {
            return new TimeSpan(5, 0, 0);
        }

        public static T Get<T>() where T : new()
        {
            string fullName = typeof(T).FullName;
            object cache = GetCache(fullName);
            if (cache == null)
            {
                T objObject = (T)Activator.CreateInstance(typeof(T));
                SetCache(fullName, objObject, DefaultCacheTime());
                return objObject;
            }
            return (T)cache;
        }

        public static object GetCache(string cacheKey)
        {
            if (devMode == "Y")
            {
                return null;
            }
            return HttpRuntime.Cache[cacheKey];
        }

        public static object GetObject(Type type)
        {
            string fullName = type.FullName;
            object cache = GetCache(fullName);
            if (cache == null)
            {
                object objObject = Activator.CreateInstance(type);
                SetCache(fullName, objObject, DefaultCacheTime());
                return objObject;
            }
            return cache;
        }

        public static object GetObject(Type type, Assembly dll)
        {
            string fullName = type.FullName;
            object cache = GetCache(fullName);
            if (cache == null)
            {
                object objObject = dll.CreateInstance(type.FullName, true);
                SetCache(fullName, objObject, DefaultCacheTime());
                return objObject;
            }
            return cache;
        }

        public static void RemoveCache(string cacheKey)
        {

            HttpRuntime.Cache.Remove(cacheKey);
        }

        public static void SetCache(string cacheKey, object objObject, TimeSpan slidingExpiration)
        {
            HttpRuntime.Cache.Insert(cacheKey, objObject, null, Cache.NoAbsoluteExpiration, slidingExpiration);
        }


    }
}

5.BLL 

5.1  UserInfoService类    UserInfo表对象的相关业务逻辑, 运用.net缓存Dal层的对象

using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CZBK.ItcastProject.DAL;
namespace CZBK.ItcastProject.BLL
{
   public class UserInfoService
    {
       UserInfoDal UserInfoDal = CZBK.ItcastProject.Common.CacheControl.Get<UserInfoDal>();

       /// <summary>
       /// 返回数据列表
       /// </summary>
       /// <returns></returns>
       public List<UserInfo> GetList()
       {
           return UserInfoDal.GetList();
       }

       /// <summary>
       /// 返回用户信息 一条
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
       public UserInfo GetDeail(int id)
       {
           return UserInfoDal.GetDeail(id);
       }

       /// <summary>
       /// 添加数据
       /// </summary>
       /// <param name="userInfo"></param>
       /// <returns></returns>
       public bool AddUserInfo(UserInfo userInfo)
       {
           return UserInfoDal.AddUserInfo(userInfo)>0;
       }

       /// <summary>
       /// 更新数据
       /// </summary>
       /// <param name="userInfo"></param>
       /// <returns></returns>
       public bool UpdateUserInfo(UserInfo userInfo)
       {
           return UserInfoDal.UpdateUserInfo(userInfo) > 0;
       }

       /// <summary>
       /// 删除数据
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
       public bool DeleteUserInfo(int id)
       {
           return UserInfoDal.DeleteUserInfo(id) > 0;
       }
    }
}

6. UI

6.1  用户列表

UserInfoList.ashx

using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace CZBK.ItcastProject.WebApp
{
    /// <summary>
    /// UserInfoList 的摘要说明
    /// </summary>
    public class UserInfoList : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
           context.Response.ContentType = "text/html";
           BLL.UserInfoService UserInfoService = CZBK.ItcastProject.Common.CacheControl.Get<BLL.UserInfoService>();
           List<UserInfo>list= UserInfoService.GetList();
           StringBuilder sb = new StringBuilder();
           foreach (UserInfo userInfo in list)
           {
              sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td><a href='ShowDetail.ashx?id={0}'>详细</a></td><td><a href='DeleteUser.ashx?id={0}' class='deletes'>删除</a></td><td><a href='ShowEdit.ashx?id={0}' class='edits'>编辑</a></td></tr>", userInfo.Id, userInfo.UserName, userInfo.UserPass, userInfo.Email, userInfo.RegTime);
           }
            //读取模板文件
           string filePath = context.Request.MapPath("UserInfoList.html");
           string fileCotent = File.ReadAllText(filePath);
           fileCotent = fileCotent.Replace("@tbody",sb.ToString());
           context.Response.Write(fileCotent);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

 UserInfoList.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link href="Css/tableStyle.css" rel="stylesheet" />
    <script src="Js/jquery-1.7.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $(".deletes").click(function () {
                if (!confirm("确定要删除吗?")) {
                    return false;
                }
            });

            $(".edits").click(function () {
                if (!confirm("确定要编辑吗?")) {
                    return false;
                }
            });
        });
    </script>
</head>
    
<body>
    <a href="AddUserInfo.html">添加</a>
    <table>
        <tr>
          <th>编号</th>
          <th>用户名</th>
          <th>密码</th>
          <th>邮箱</th>
          <th>时间</th>
          <th>详细</th>
          <th>删除</th>
          <th>编辑</th>
        </tr>
       @tbody

    </table>
</body>
</html>

6.2 添加用户

AddUser.ashx

using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CZBK.ItcastProject.WebApp
{
    /// <summary>
    /// AddUser 的摘要说明
    /// </summary>
    public class AddUser : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string userName=context.Request.Form["txtName"]; 
            string userPwd=context.Request.Form["txtPwd"];
            string userEmail=context.Request.Form["txtMail"];
            UserInfo userInfo = new UserInfo();
            userInfo.UserName = userName;
            userInfo.UserPass = userPwd;
            userInfo.Email = userEmail;
            userInfo.RegTime = DateTime.Now;
            BLL.UserInfoService UserInfoService = new BLL.UserInfoService();
            if (UserInfoService.AddUserInfo(userInfo))
            {
                context.Response.Redirect("UserInfoList.ashx");
            }
            else
            {
                context.Response.Redirect("Error.html");

            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

AddUserInfo.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>添加用户</title>
</head>
<body>
      <form method="post" action="AddUser.ashx">
        用户名:<input type="text" name="txtName" /><br />
        密码:<input type="password" name="txtPwd" /><br />
        邮箱:<input type="text" name="txtMail" /><br />
        <input type="submit" value="添加用户" />
    </form>
</body>
</html>

6.3 删除用户

DeleteUser.ashx

using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CZBK.ItcastProject.WebApp
{
    /// <summary>
    /// DeleteUser 的摘要说明
    /// </summary>
    public class DeleteUser : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            BLL.UserInfoService UserInfoService = CZBK.ItcastProject.Common.CacheControl.Get<BLL.UserInfoService>();
            string id = context.Request.QueryString["id"];
            int iid;
            if (int.TryParse(id, out iid))
            {
                if (UserInfoService.DeleteUserInfo(iid))
                {
                    context.Response.Redirect("UserInfoList.ashx");
                }
                else
                {
                    context.Response.Redirect("Error.html");
                }
            }
            else
            {
                context.Response.Redirect("Error.html");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

6.4 显示用户详细信息

ShowDetail.ashx

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using CZBK.ItcastProject.Model;

namespace CZBK.ItcastProject.WebApp
{
    /// <summary>
    /// ShowDetail 的摘要说明
    /// </summary>
    public class ShowDetail : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            //context.Response.Write("Hello World");
            BLL.UserInfoService UserInfoService = CZBK.ItcastProject.Common.CacheControl.Get<BLL.UserInfoService>();
            string id = context.Request.QueryString["id"];
            int iid;
            if (int.TryParse(id, out iid))
            {
                UserInfo instance = UserInfoService.GetDeail(Convert.ToInt32(id));
                //读取模板文件
                string filePath = context.Request.MapPath("ShowDetail.html");
                string fileCotent = File.ReadAllText(filePath);
                fileCotent = fileCotent.Replace("$username", instance.UserName).Replace("$pwd", instance.UserPass).Replace("$email", instance.Email);
                context.Response.Write(fileCotent);
            }
            else
            {
                context.Response.Redirect("Error.html");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

ShowDetail.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form>
        用户名:<input type="text" name="txtName" value="$username" readonly="readonly" /><br />
        密码:<input type="password" name="txtPwd" value="$pwd" readonly="readonly" /><br />
        邮箱:<input type="text" name="txtMail" value="$email" readonly="readonly" /><br />
    </form>
</body>
</html>

6.5 编辑用户

ShowEdit.ashx

using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace CZBK.ItcastProject.WebApp
{
    /// <summary>
    /// ShowEdit 的摘要说明
    /// </summary>
    public class ShowEdit : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            //context.Response.Write("Hello World");
            BLL.UserInfoService UserInfoService = CZBK.ItcastProject.Common.CacheControl.Get<BLL.UserInfoService>();
            string id = context.Request.QueryString["id"];
            int iid;
            if (int.TryParse(id, out iid))
            {
                UserInfo instance = UserInfoService.GetDeail(Convert.ToInt32(id));
                //读取模板文件
                string filePath = context.Request.MapPath("ShowEdit.html");
                string fileCotent = File.ReadAllText(filePath);
                fileCotent = fileCotent.Replace("$username", instance.UserName).Replace("$pwd", instance.UserPass).Replace("$email", instance.Email).Replace("$hid_id", id);
                context.Response.Write(fileCotent);
            }
            else
            {
                context.Response.Redirect("Error.html");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

ShowEdit.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form method="post" action="UpdateUser.ashx">
        用户名:<input type="text" name="txtName" value="$username" /><br />
        密码:<input type="password" name="txtPwd" value="$pwd" /><br />
        邮箱:<input type="text" name="txtMail" value="$email" /><br />
        <input type="hidden" name="hid_id" value="$hid_id" />
        <input type="submit" value="更新用户" />
    </form>
</body>
</html>

UpdateUser.ashx

using CZBK.ItcastProject.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CZBK.ItcastProject.WebApp
{
    /// <summary>
    /// UpdateUser 的摘要说明
    /// </summary>
    public class UpdateUser : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string userName = context.Request.Form["txtName"];
            string userPwd = context.Request.Form["txtPwd"];
            string userEmail = context.Request.Form["txtMail"];
            string id = context.Request.Form["hid_id"];
            UserInfo userInfo = new UserInfo();
            userInfo.Id = Convert.ToInt32(id);
            userInfo.UserName = userName;
            userInfo.UserPass = userPwd;
            userInfo.Email = userEmail;
            userInfo.RegTime = DateTime.Now;
            BLL.UserInfoService UserInfoService = new BLL.UserInfoService();
            if (UserInfoService.UpdateUserInfo(userInfo))
            {
                context.Response.Redirect("UserInfoList.ashx");
            }
            else
            {
                context.Response.Redirect("Error.html");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/youguess/p/9239159.html