浅谈C# WinForm中实现基于角色的权限菜单
作者:CodingMouse 日期:2008年12月14日
转载请注明文章来源:http://blog.csdn.net/CodingMouse/archive/2008/12/14/3515969.aspx
本博文完整源码已经上传,欢迎下载讨论:http://download.csdn.net/source/913308
基于角色的权限菜单功能的实现在有开发经验的程序员看来仅仅是小菜一碟,然而却让许多初学者苦不堪言。为此,我将我近期花了几天时间写的权限菜单写成文字贴上博客给初学者参考。由于自己也是一个正在努力学习的菜鸟,对问题的分析和见解必然不够透彻,还望过路的老师们多多批评为谢!
一、建立 SQL Server 数据库模型
1、原始方案 一共设立了五个实体模型: A、操作员(Operator):存储系统登录用户的名称、密码、启用状态等信息。 B、权限组(RightsGroup):存储系统权限分组(即:权限角色)的名称等信息。 C、权限关系(RightsRelation):用于将A项和B项之间的多对多关系拆解成两个一对多关系。 D、权限列表(RightsList):存储系统菜单项(即:权限项)的标题、内部名称、权限状态等信息。 E、权限组关系(RightGroupRelation):用于将B项和D项之间的多对多关系拆解成两个一对多关系。 通过上面的描述可以清楚看到,C项和E项仅仅是为了拆解多对多关系而设立,实体关系变得相对复杂了点。稍作考虑便知,既然是使用 C# WinForm + SQL Server 来完成这一功能,则可以考虑使用实体类来模拟数据库模型,并将实体类打包成泛型集合后存储到 SQL Server 数据库的 varBinary(max) 字段。这样便可以将原始方案的数据库模型缩减成三个实体模型,降低了关系的复杂程度。将原始方案稍作修改后即可得到如下改进方案。 2、改进方案 如上所述,改进后的方案仅包含如下三个实体模型: A、操作员(Operator):存储系统登录用户的名称、密码、启用状态、权限集合等信息。 B、权限组(RightsGroup):存储系统权限分组(即:权限角色)的名称、权限集合等信息。 C、权限关系(RightsRelation):用于将A项和B项之间的多对多关系拆解成两个一对多关系。 很容易看出,仅将原始方案的 E 项更改为 A项和 B 项的字段,即可将实体关系复杂度降低 40%。现在我们来看看改进方案的 SQL Server 数据库实现脚本代码:
view plaincopy to clipboardprint? -- 判断是否存在 操作员信息表(Operator),如果存在,则删除表 Operator if exists(Select * From SysObjects Where Name = 'Operator') Drop Table [Operator] Go -- 创建 操作员信息表(Operator) Create Table [Operator] ( -- 主键列,自动增长 标识种子为 1 [Id] int identity(1,1) Constraint [PK_OperatorId] Primary Key, -- 操作员姓名 [OperatorName] nVarChar(50) Constraint [UQ_OperatorName] Unique(OperatorName) Not Null, -- 密码 [Password] nVarChar(50) Constraint [CK_Password] Check(len([Password])>=6) Not Null, -- 操作员权限列表 [RightsList] varBinary(max) Null, -- 用户当前状态 [State] bit Constraint [DF_State] Default('true') Constraint [CK_State] Check([State] in ('true','false')) Not Null, ) Go -- 判断是否存在 权限组信息表(RightsGroup),如果存在,则删除表 RightsGroup if exists(Select * From SysObjects Where Name = 'RightsGroup') Drop Table [RightsGroup] Go -- 创建 权限组信息表(RightsGroup) Create Table [RightsGroup] ( -- 主键列,自动增长 标识种子为 1 [Id] int Identity(1,1) Constraint [PK_RightsGroupId] Primary Key, -- 权限组名称 [GroupName] nVarChar(50) Constraint[UQ_GroupName] Unique (GroupName) Not Null, -- 组权限列表 [GroupRightsList] varBinary(max) Null, ) Go -- 判断是否存在权限关系表(RightsRelation),如果存在,则删除表 RightsRelation if exists(Select * From SysObjects Where Name = 'RightsRelation') drop table [RightsRelation] Go -- 创建 权限关系表(RightsRelation) Create Table [RightsRelation] ( -- 主键列,自动增长 标识种子为 1 [Id] int Identity(1, 1) Constraint [PK_RightsRelationId] Primary Key, -- 操作员 Id [OperatorId] int Constraint [FK_OperatorId] Foreign Key References Operator([Id]) Not Null, -- 权限组 Id [RightsGroupId] int Constraint [FK_RightsGroupId] Foreign Key References RightsGroup([Id]) Not Null ) Go -- 判断是否存在 操作员信息表(Operator),如果存在,则删除表 Operator if exists(Select * From SysObjects Where Name = 'Operator') Drop Table [Operator] Go
-- 创建 操作员信息表(Operator) Create Table [Operator] ( -- 主键列,自动增长 标识种子为 1 [Id] int identity(1,1) Constraint [PK_OperatorId] Primary Key,
-- 操作员姓名 [OperatorName] nVarChar(50) Constraint [UQ_OperatorName] Unique(OperatorName) Not Null,
-- 密码 [Password] nVarChar(50) Constraint [CK_Password] Check(len([Password])>=6) Not Null,
-- 操作员权限列表 [RightsList] varBinary(max) Null,
-- 用户当前状态 [State] bit Constraint [DF_State] Default('true') Constraint [CK_State] Check([State] in ('true','false')) Not Null, ) Go
-- 判断是否存在 权限组信息表(RightsGroup),如果存在,则删除表 RightsGroup if exists(Select * From SysObjects Where Name = 'RightsGroup') Drop Table [RightsGroup] Go
-- 创建 权限组信息表(RightsGroup) Create Table [RightsGroup] ( -- 主键列,自动增长 标识种子为 1 [Id] int Identity(1,1) Constraint [PK_RightsGroupId] Primary Key, -- 权限组名称 [GroupName] nVarChar(50) Constraint[UQ_GroupName] Unique (GroupName) Not Null,
-- 组权限列表 [GroupRightsList] varBinary(max) Null, ) Go
-- 判断是否存在权限关系表(RightsRelation),如果存在,则删除表 RightsRelation if exists(Select * From SysObjects Where Name = 'RightsRelation') drop table [RightsRelation] Go
-- 创建 权限关系表(RightsRelation) Create Table [RightsRelation] ( -- 主键列,自动增长 标识种子为 1 [Id] int Identity(1, 1) Constraint [PK_RightsRelationId] Primary Key,
-- 操作员 Id [OperatorId] int Constraint [FK_OperatorId] Foreign Key References Operator([Id]) Not Null, -- 权限组 Id [RightsGroupId] int Constraint [FK_RightsGroupId] Foreign Key References RightsGroup([Id]) Not Null ) Go
二、建立实体类
建立了 SQL Server 数据库模型之后,我们开始建立实体类来作为权限管理的数据传输载体。 1、实体模型基类(ModelBase) C#源码清单:
view plaincopy to clipboardprint? using System; using System.Collections.Generic; using System.Text; namespace CodingMouse.CMHotelManager.Model { /// <summary> /// 实体模型基类 /// </summary> [Serializable] public class ModelBase { #region Private Members int _id; string _modelName; #endregion #region Public Properties /// <summary> /// 实体模型 ID /// </summary> public int Id { get { return _id; } set { _id = value; } } /// <summary> /// 实体模型名称 /// </summary> public string ModelName { get { return _modelName; } set { _modelName = value; } } #endregion #region Public Methods /// <summary> /// 无参构造 /// </summary> public ModelBase() { } /// <summary> /// 带参构造 /// </summary> /// <param name="id">实体模型 ID</param> /// <param name="modelName">实体模型名称</param> public ModelBase(int id, string modelName) { this.Id = id; this.ModelName = modelName; } #endregion } } using System; using System.Collections.Generic; using System.Text;
namespace CodingMouse.CMHotelManager.Model { /// <summary> /// 实体模型基类 /// </summary> [Serializable] public class ModelBase { #region Private Members int _id; string _modelName; #endregion
#region Public Properties /// <summary> /// 实体模型 ID /// </summary> public int Id { get { return _id; } set { _id = value; } } /// <summary> /// 实体模型名称 /// </summary> public string ModelName { get { return _modelName; } set { _modelName = value; } } #endregion
#region Public Methods /// <summary> /// 无参构造 /// </summary> public ModelBase() { }
/// <summary> /// 带参构造 /// </summary> /// <param name="id">实体模型 ID</param> /// <param name="modelName">实体模型名称</param> public ModelBase(int id, string modelName) { this.Id = id; this.ModelName = modelName; } #endregion } }
2、操作员实体类(Operator) C#源码清单:
view plaincopy to clipboardprint? using System; using System.Collections.Generic; using System.Text; namespace CodingMouse.CMHotelManager.Model { /// <summary> /// 操作员实体类 /// </summary> [Serializable] public class Operator : ModelBase { #region Private Members string _password; Dictionary<string, Rights> _rightsCollection; bool _state; #endregion #region Public Properties /// <summary> /// 操作员密码 /// </summary> public string Password { get { return _password; } set { _password = value; } } /// <summary> /// 权限集合(键值用于存储菜单/工具栏项的 Name 属性) /// </summary> public Dictionary<string, Rights> RightsCollection { get { return _rightsCollection; } set { _rightsCollection = value; } } /// <summary> /// 操作员状态 /// </summary> public bool State { get { return _state; } set { _state = value; } } #endregion #region Public Methods /// <summary> /// 无参构造(基类属性赋值说明:Id - 操作员 ID / ModelName - 操作员名称) /// </summary> public Operator() { } /// <summary> /// 带参构造 /// </summary> /// <param name="operatorId">操作员 ID</param> /// <param name="name">操作员名称</param> /// <param name="password">操作员密码</param> /// <param name="rightsCollection">权限集合(键值用于存储菜单/工具栏项的 Name 属性)</param> /// <param name="state">操作员状态</param> public Operator( int operatorId, string name, string password, Dictionary<string, Rights> rightsCollection, bool state) : base(operatorId, name) { this.Password = password; this.RightsCollection = rightsCollection; this.State = state; } #endregion } } using System; using System.Collections.Generic; using System.Text;
namespace CodingMouse.CMHotelManager.Model { /// <summary> /// 操作员实体类 /// </summary> [Serializable] public class Operator : ModelBase { #region Private Members string _password; Dictionary<string, Rights> _rightsCollection; bool _state; #endregion
#region Public Properties /// <summary> /// 操作员密码 /// </summary> public string Password { get { return _password; } set { _password = value; } } /// <summary> /// 权限集合(键值用于存储菜单/工具栏项的 Name 属性) /// </summary> public Dictionary<string, Rights> RightsCollection { get { return _rightsCollection; } set { _rightsCollection = value; } } /// <summary> /// 操作员状态 /// </summary> public bool State { get { return _state; } set { _state = value; } } #endregion
#region Public Methods /// <summary> /// 无参构造(基类属性赋值说明:Id - 操作员 ID / ModelName - 操作员名称) /// </summary> public Operator() { }
/// <summary> /// 带参构造 /// </summary> /// <param name="operatorId">操作员 ID</param> /// <param name="name">操作员名称</param> /// <param name="password">操作员密码</param> /// <param name="rightsCollection">权限集合(键值用于存储菜单/工具栏项的 Name 属性)</param> /// <param name="state">操作员状态</param> public Operator( int operatorId, string name, string password, Dictionary<string, Rights> rightsCollection, bool state) : base(operatorId, name) { this.Password = password; this.RightsCollection = rightsCollection; this.State = state; } #endregion } }
3、权限组实体类(RightsGroup) C#源码清单:
view plaincopy to clipboardprint? using System; using System.Collections.Generic; using System.Text; namespace CodingMouse.CMHotelManager.Model { /// <summary> /// 权限组实体类 /// </summary> [Serializable] public class RightsGroup : ModelBase { #region Private Members Dictionary<string, Rights> _groupRightsCollection; #endregion #region Public Properties /// <summary> /// 组权限集合 /// </summary> public Dictionary<string, Rights> GroupRightsCollection { get { return _groupRightsCollection; } set { _groupRightsCollection = value; } } #endregion #region Public Methods /// <summary> /// 无参构造(基类属性赋值说明:Id - 权限组 ID / ModelName - 权限组名称) /// </summary> public RightsGroup() { } /// <summary> /// 带参构造 /// </summary> /// <param name="groupId">权限组 ID</param> /// <param name="groupName">权限组名称</param> /// <param name="groupRightsCollection">组权限集合</param> public RightsGroup( int groupId, string groupName, Dictionary<string, Rights> groupRightsCollection) : base(groupId, groupName) { this.GroupRightsCollection = groupRightsCollection; } #endregion } } using System; using System.Collections.Generic; using System.Text;
namespace CodingMouse.CMHotelManager.Model { /// <summary> /// 权限组实体类 /// </summary> [Serializable] public class RightsGroup : ModelBase { #region Private Members Dictionary<string, Rights> _groupRightsCollection; #endregion
#region Public Properties /// <summary> /// 组权限集合 /// </summary> public Dictionary<string, Rights> GroupRightsCollection { get { return _groupRightsCollection; } set { _groupRightsCollection = value; } } #endregion
#region Public Methods /// <summary> /// 无参构造(基类属性赋值说明:Id - 权限组 ID / ModelName - 权限组名称) /// </summary> public RightsGroup() { } /// <summary> /// 带参构造 /// </summary> /// <param name="groupId">权限组 ID</param> /// <param name="groupName">权限组名称</param> /// <param name="groupRightsCollection">组权限集合</param> public RightsGroup( int groupId, string groupName, Dictionary<string, Rights> groupRightsCollection) : base(groupId, groupName) { this.GroupRightsCollection = groupRightsCollection; } #endregion } }
4、权限关系实体类(RightsRelation) C#源码清单:
view plaincopy to clipboardprint? using System; using System.Collections.Generic; using System.Text; namespace CodingMouse.CMHotelManager.Model { /// <summary> /// 权限关系实体类 /// </summary> [Serializable] public class RightsRelation { #region Private Members int _id; int _operatorId; string _operatorName; int _rightsGroupId; string rightsGroupName; #endregion #region Public Properties /// <summary> /// 权限关系 ID /// </summary> public int Id { get { return _id; } set { _id = value; } } /// <summary> /// 操作员 ID /// </summary> public int OperatorId { get { return _operatorId; } set { _operatorId = value; } } /// <summary> /// 操作员名称(便于在 WinForm 的 DataGridView 控件中实现数据绑定) /// </summary> public string OperatorName { get { return _operatorName; } set { _operatorName = value; } } /// <summary> /// 权限组 ID /// </summary> public int RightsGroupId { get { return _rightsGroupId; } set { _rightsGroupId = value; } } /// <summary> /// 权限组名称(便于在 WinForm 的 DataGridView 控件中实现数据绑定) /// </summary> public string RightsGroupName { get { return rightsGroupName; } set { rightsGroupName = value; } } #endregion #region Public Methods /// <summary> /// 无参构造 /// </summary> public RightsRelation() { } /// <summary> /// 带参构造 /// </summary> /// <param name="id">权限关系 ID</param> /// <param name="operatorId">操作员 ID</param> /// <param name="operatorName">操作员名称</param> /// <param name="rightsGroupId">权限组 ID</param> /// <param name="rightsGroupName">权限组名称</param> public RightsRelation( int id, int operatorId, string operatorName, int rightsGroupId, string rightsGroupName) { this.Id = id; this.OperatorId = operatorId; this.OperatorName = operatorName; this.RightsGroupId = rightsGroupId; this.RightsGroupName = rightsGroupName; } #endregion } } using System; using System.Collections.Generic; using System.Text;
namespace CodingMouse.CMHotelManager.Model { /// <summary> /// 权限关系实体类 /// </summary> [Serializable] public class RightsRelation { #region Private Members int _id; int _operatorId; string _operatorName; int _rightsGroupId; string rightsGroupName; #endregion
#region Public Properties /// <summary> /// 权限关系 ID /// </summary> public int Id { get { return _id; } set { _id = value; } } /// <summary> /// 操作员 ID /// </summary> public int OperatorId { get { return _operatorId; } set { _operatorId = value; } } /// <summary> /// 操作员名称(便于在 WinForm 的 DataGridView 控件中实现数据绑定) /// </summary> public string OperatorName { get { return _operatorName; } set { _operatorName = value; } } /// <summary> /// 权限组 ID /// </summary> public int RightsGroupId { get { return _rightsGroupId; } set { _rightsGroupId = value; } } /// <summary> /// 权限组名称(便于在 WinForm 的 DataGridView 控件中实现数据绑定) /// </summary> public string RightsGroupName { get { return rightsGroupName; } set { rightsGroupName = value; } } #endregion
#region Public Methods /// <summary> /// 无参构造 /// </summary> public RightsRelation() { } /// <summary> /// 带参构造 /// </summary> /// <param name="id">权限关系 ID</param> /// <param name="operatorId">操作员 ID</param> /// <param name="operatorName">操作员名称</param> /// <param name="rightsGroupId">权限组 ID</param> /// <param name="rightsGroupName">权限组名称</param> public RightsRelation( int id, int operatorId, string operatorName, int rightsGroupId, string rightsGroupName) { this.Id = id; this.OperatorId = operatorId; this.OperatorName = operatorName; this.RightsGroupId = rightsGroupId; this.RightsGroupName = rightsGroupName; } #endregion } }
三、具体代码实现
采用多层开发模式有助于降低耦合度,便于程序维护。所以,我们的本文的具体代码实现也使用了多层开发模式。限于篇幅,只列举出具体的代码实现类源码。同时,也是由于本文并不是讲解多层开发的文章,所以对于完成本文的主题功能所涉及的简单工厂、抽象工厂、接口定义、数据库访问等类的源码就不再一一罗列。 (一)数据访问层 1、操作员数据访问操作类(OperatorService) C#源码清单:
view plaincopy to clipboardprint? using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Runtime.Serialization.Formatters.Binary; using DBUtility = CodingMouse.CMHotelManager.DBUtility; using IDAL = CodingMouse.CMHotelManager.IDAL; using Model = CodingMouse.CMHotelManager.Model; namespace CodingMouse.CMHotelManager.DAL { /// <summary> /// 操作员数据访问操作类 /// </summary> public class OperatorService : IDAL.IOperatorService { #region IOperatorService 成员 /// <summary> /// 根据操作员名称和密码获取操作员实体 /// </summary> /// <param name="name">操作员名称</param> /// <param name="pwd">操作员密码</param> /// <returns>操作员实体</returns> public Model.Operator GetOperatorInfoByName(string name, string pwd) { //SQL命令 string sqltxt = string.Format("Select Id, OperatorName, Password, RightsList, State From Operator Where OperatorName = '{0}' And Password = '{1}'", name, pwd); //创建操作员实体 Model.Operator tmpOperator = new Model.Operator(); // 转换数据库存储的 二进制数据为 Byte[] 数组 以便进而转换为操作员权限集合 // 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqltxt, conn); conn.Open(); using (SqlDataReader myReader = cmd.ExecuteReader( CommandBehavior.CloseConnection | CommandBehavior.SingleResult | CommandBehavior.SingleRow)) { if (myReader.Read()) { //将数据集转换成实体集合 tmpOperator.Id = Convert.ToInt32(myReader["Id"]); tmpOperator.ModelName = Convert.ToString(myReader["OperatorName"]); tmpOperator.Password = Convert.ToString(myReader["Password"]); tmpOperator.State = Convert.ToBoolean(myReader["State"]); // 读取权限集合 System.Data.SqlTypes.SqlBytes bytes = myReader.GetSqlBytes(3); // 只能指定列序号 // 将流反序列化为权限集合对象 BinaryFormatter bf = new BinaryFormatter(); if (!bytes.IsNull) tmpOperator.RightsCollection = (bf.Deserialize(bytes.Stream) as Dictionary<string, Model.Rights>); //else // throw new Exception(string.Format("操作员 [{0}] 没有任何权限,禁止登录!", tmpOperator.ModelName)); } else //如果没有读取到内容则抛出异常 throw new Exception("登录名称或用户密码不正确!"); } } // 如果操作员已经被禁用 if (!tmpOperator.State) throw new Exception(string.Format("操作员 [{0}] 已被禁用,请与管理员联系!", tmpOperator.ModelName)); // 返回结果 return tmpOperator; } /// <summary> /// 添加操作员 /// </summary> /// <param name="addOperator">要添加的操作员实体</param> /// <returns>True:成功/False:失败</returns> public bool AddOperator(Model.Operator addOperator) { // 验证密码长度 if (addOperator.Password.Trim().Length < 6) throw new Exception("用户密码长度不能小于六位!"); // 转换操作员权限集合为数据库可存取的 Byte[] 数组 MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, addOperator.RightsCollection); byte[] rigthsByteArray = new byte[(int)(ms.Length)]; ms.Position = 0; ms.Read(rigthsByteArray, 0, (int)(ms.Length)); ms.Close(); // 拼接 SQL 命令 string sqlTxt = "Insert Into Operator (OperatorName, Password, RightsList, State) Values " + "(@OperatorName, @Password, @RightsList, @State)"; // 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqlTxt, conn); SqlParameter prm1 = new SqlParameter("@OperatorName", SqlDbType.NVarChar, 50); prm1.Value = addOperator.ModelName; SqlParameter prm2 = new SqlParameter("@Password", SqlDbType.NVarChar, 50); prm2.Value = addOperator.Password; SqlParameter prm3 = new SqlParameter("@RightsList", SqlDbType.VarBinary, rigthsByteArray.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, rigthsByteArray); SqlParameter prm4 = new SqlParameter("@State", SqlDbType.Bit); prm4.Value = addOperator.State; cmd.Parameters.AddRange(new SqlParameter[] { prm1, prm2, prm3, prm4 }); conn.Open(); if (cmd.ExecuteNonQuery() >= 1) return true; else return false; } } /// <summary> /// 删除操作员 /// </summary> /// <param name="id">要删除的操作员 ID</param> /// <returns>True:成功/False:失败</returns> public bool DeleteOperatorByID(int id) { // 删除单个信息 SQL 命令 string sqlTxt = string.Format("Delete From Operator Where Id = {0}", id); // 创建 SQL 执行对象 DBUtility.AbstractDBProvider dbProvider = DBUtility.AbstractDBProvider.Instance(); // 执行 删除操作 int rowsAffected; dbProvider.RunCommand(sqlTxt, out rowsAffected); if (rowsAffected >= 1) return true; else return false; } /// <summary> /// 修改操作员 /// </summary> /// <param name="currentOperator">要修改的操作员实体</param> /// <returns>True:成功/False:失败</returns> public bool ModifyOperator(Model.Operator currentOperator) { // 验证密码长度 if (currentOperator.Password.Trim().Length < 6) throw new Exception("用户密码长度不能小于六位!"); // 转换操作员权限集合为数据库可存取的 Byte[] 数组 MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, currentOperator.RightsCollection); byte[] rigthsByteArray = new byte[(int)(ms.Length)]; ms.Position = 0; ms.Read(rigthsByteArray, 0, (int)(ms.Length)); ms.Close(); // 拼接 SQL 命令 string sqlTxt = "Update Operator Set OperatorName = @OperatorName, " + "Password = @Password, RightsList = @RightsList, State = @State Where Id = @Id"; // 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using(SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqlTxt, conn); SqlParameter prm1 = new SqlParameter("@OperatorName", SqlDbType.NVarChar, 50); prm1.Value = currentOperator.ModelName; SqlParameter prm2 = new SqlParameter("@Password", SqlDbType.NVarChar, 50); prm2.Value = currentOperator.Password; SqlParameter prm3 = new SqlParameter("@RightsList", SqlDbType.VarBinary, rigthsByteArray.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, rigthsByteArray); SqlParameter prm4 = new SqlParameter("@State", SqlDbType.Bit); prm4.Value = currentOperator.State; SqlParameter prm5 = new SqlParameter("@Id", SqlDbType.Int); prm5.Value = currentOperator.Id; cmd.Parameters.AddRange(new SqlParameter[] { prm1, prm2, prm3, prm4, prm5 }); conn.Open(); if (cmd.ExecuteNonQuery() >= 1) return true; else return false; } } /// <summary> /// 获取所有操作员信息 /// </summary> /// <returns>操作员实体集合</returns> public Dictionary<string, Model.Operator> GetAllOperatorInfo() { //SQL命令 string sqltxt = "Select Id, OperatorName, Password, RightsList, State From Operator"; //创建操作员实体集合 Dictionary<string, Model.Operator> operatorCollection = new Dictionary<string, Model.Operator>(); //定义操作员实体 Model.Operator tmpOperator = null; // 转换数据库存储的 二进制数据为 Byte[] 数组 以便进而转换为操作员权限集合 // 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqltxt, conn); conn.Open(); using (SqlDataReader myReader = cmd.ExecuteReader( CommandBehavior.CloseConnection)) { while (myReader.Read()) { // 创建操作员实体 tmpOperator = new Model.Operator(); //将数据集转换成实体集合 tmpOperator.Id = Convert.ToInt32(myReader["Id"]); tmpOperator.ModelName = Convert.ToString(myReader["OperatorName"]); tmpOperator.Password = Convert.ToString(myReader["Password"]); tmpOperator.State = Convert.ToBoolean(myReader["State"]); // 读取权限集合 System.Data.SqlTypes.SqlBytes bytes = myReader.GetSqlBytes(3); // 只能指定列序号 // 将流反序列化为权限集合对象 BinaryFormatter bf = new BinaryFormatter(); if (!bytes.IsNull) tmpOperator.RightsCollection = (bf.Deserialize(bytes.Stream) as Dictionary<string, Model.Rights>); // 添加到操作员实体集合 operatorCollection.Add(tmpOperator.ModelName, tmpOperator); } } } // 返回结果 return operatorCollection; } /// <summary> /// 根据操作员名称校验操作员是否存在 /// </summary> /// <param name="operatorName">操作员名称</param> /// <returns>True:存在/Flase:不存在</returns> public bool CheckOperatorExist(string operatorName) { //创建查询信息的 SQL string sqlTxt = string.Format( "Select Count(*) From Operator Where OperatorName = '{0}'", operatorName); //创建SQL执行对象 DBUtility.AbstractDBProvider dbProvider = DBUtility.AbstractDBProvider.Instance(); //执行查询操作 int result = Convert.ToInt32(dbProvider.RunCommand(sqlTxt)); if (result >= 1) return true; else return false; } #endregion } } using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Runtime.Serialization.Formatters.Binary; using DBUtility = CodingMouse.CMHotelManager.DBUtility; using IDAL = CodingMouse.CMHotelManager.IDAL; using Model = CodingMouse.CMHotelManager.Model;
namespace CodingMouse.CMHotelManager.DAL { /// <summary> /// 操作员数据访问操作类 /// </summary> public class OperatorService : IDAL.IOperatorService {
#region IOperatorService 成员
/// <summary> /// 根据操作员名称和密码获取操作员实体 /// </summary> /// <param name="name">操作员名称</param> /// <param name="pwd">操作员密码</param> /// <returns>操作员实体</returns> public Model.Operator GetOperatorInfoByName(string name, string pwd) { //SQL命令 string sqltxt = string.Format("Select Id, OperatorName, Password, RightsList, State From Operator Where OperatorName = '{0}' And Password = '{1}'", name, pwd);
//创建操作员实体 Model.Operator tmpOperator = new Model.Operator();
// 转换数据库存储的 二进制数据为 Byte[] 数组 以便进而转换为操作员权限集合 // 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqltxt, conn); conn.Open();
using (SqlDataReader myReader = cmd.ExecuteReader( CommandBehavior.CloseConnection | CommandBehavior.SingleResult | CommandBehavior.SingleRow)) { if (myReader.Read()) { //将数据集转换成实体集合 tmpOperator.Id = Convert.ToInt32(myReader["Id"]); tmpOperator.ModelName = Convert.ToString(myReader["OperatorName"]); tmpOperator.Password = Convert.ToString(myReader["Password"]); tmpOperator.State = Convert.ToBoolean(myReader["State"]);
// 读取权限集合 System.Data.SqlTypes.SqlBytes bytes = myReader.GetSqlBytes(3); // 只能指定列序号 // 将流反序列化为权限集合对象 BinaryFormatter bf = new BinaryFormatter(); if (!bytes.IsNull) tmpOperator.RightsCollection = (bf.Deserialize(bytes.Stream) as Dictionary<string, Model.Rights>); //else // throw new Exception(string.Format("操作员 [{0}] 没有任何权限,禁止登录!", tmpOperator.ModelName)); } else //如果没有读取到内容则抛出异常 throw new Exception("登录名称或用户密码不正确!"); } } // 如果操作员已经被禁用 if (!tmpOperator.State) throw new Exception(string.Format("操作员 [{0}] 已被禁用,请与管理员联系!", tmpOperator.ModelName)); // 返回结果 return tmpOperator; }
/// <summary> /// 添加操作员 /// </summary> /// <param name="addOperator">要添加的操作员实体</param> /// <returns>True:成功/False:失败</returns> public bool AddOperator(Model.Operator addOperator) { // 验证密码长度 if (addOperator.Password.Trim().Length < 6) throw new Exception("用户密码长度不能小于六位!"); // 转换操作员权限集合为数据库可存取的 Byte[] 数组 MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, addOperator.RightsCollection); byte[] rigthsByteArray = new byte[(int)(ms.Length)]; ms.Position = 0; ms.Read(rigthsByteArray, 0, (int)(ms.Length)); ms.Close();
// 拼接 SQL 命令 string sqlTxt = "Insert Into Operator (OperatorName, Password, RightsList, State) Values " + "(@OperatorName, @Password, @RightsList, @State)";
// 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqlTxt, conn); SqlParameter prm1 = new SqlParameter("@OperatorName", SqlDbType.NVarChar, 50); prm1.Value = addOperator.ModelName; SqlParameter prm2 = new SqlParameter("@Password", SqlDbType.NVarChar, 50); prm2.Value = addOperator.Password; SqlParameter prm3 = new SqlParameter("@RightsList", SqlDbType.VarBinary, rigthsByteArray.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, rigthsByteArray); SqlParameter prm4 = new SqlParameter("@State", SqlDbType.Bit); prm4.Value = addOperator.State;
cmd.Parameters.AddRange(new SqlParameter[] { prm1, prm2, prm3, prm4 }); conn.Open();
if (cmd.ExecuteNonQuery() >= 1) return true; else return false; } }
/// <summary> /// 删除操作员 /// </summary> /// <param name="id">要删除的操作员 ID</param> /// <returns>True:成功/False:失败</returns> public bool DeleteOperatorByID(int id) { // 删除单个信息 SQL 命令 string sqlTxt = string.Format("Delete From Operator Where Id = {0}", id); // 创建 SQL 执行对象 DBUtility.AbstractDBProvider dbProvider = DBUtility.AbstractDBProvider.Instance(); // 执行 删除操作 int rowsAffected; dbProvider.RunCommand(sqlTxt, out rowsAffected);
if (rowsAffected >= 1) return true; else return false; }
/// <summary> /// 修改操作员 /// </summary> /// <param name="currentOperator">要修改的操作员实体</param> /// <returns>True:成功/False:失败</returns> public bool ModifyOperator(Model.Operator currentOperator) { // 验证密码长度 if (currentOperator.Password.Trim().Length < 6) throw new Exception("用户密码长度不能小于六位!"); // 转换操作员权限集合为数据库可存取的 Byte[] 数组 MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, currentOperator.RightsCollection); byte[] rigthsByteArray = new byte[(int)(ms.Length)]; ms.Position = 0; ms.Read(rigthsByteArray, 0, (int)(ms.Length)); ms.Close();
// 拼接 SQL 命令 string sqlTxt = "Update Operator Set OperatorName = @OperatorName, " + "Password = @Password, RightsList = @RightsList, State = @State Where Id = @Id";
// 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using(SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqlTxt, conn); SqlParameter prm1 = new SqlParameter("@OperatorName", SqlDbType.NVarChar, 50); prm1.Value = currentOperator.ModelName; SqlParameter prm2 = new SqlParameter("@Password", SqlDbType.NVarChar, 50); prm2.Value = currentOperator.Password; SqlParameter prm3 = new SqlParameter("@RightsList", SqlDbType.VarBinary, rigthsByteArray.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, rigthsByteArray); SqlParameter prm4 = new SqlParameter("@State", SqlDbType.Bit); prm4.Value = currentOperator.State; SqlParameter prm5 = new SqlParameter("@Id", SqlDbType.Int); prm5.Value = currentOperator.Id;
cmd.Parameters.AddRange(new SqlParameter[] { prm1, prm2, prm3, prm4, prm5 }); conn.Open();
if (cmd.ExecuteNonQuery() >= 1) return true; else return false; } }
/// <summary> /// 获取所有操作员信息 /// </summary> /// <returns>操作员实体集合</returns> public Dictionary<string, Model.Operator> GetAllOperatorInfo() { //SQL命令 string sqltxt = "Select Id, OperatorName, Password, RightsList, State From Operator"; //创建操作员实体集合 Dictionary<string, Model.Operator> operatorCollection = new Dictionary<string, Model.Operator>(); //定义操作员实体 Model.Operator tmpOperator = null;
// 转换数据库存储的 二进制数据为 Byte[] 数组 以便进而转换为操作员权限集合 // 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqltxt, conn); conn.Open();
using (SqlDataReader myReader = cmd.ExecuteReader( CommandBehavior.CloseConnection)) { while (myReader.Read()) { // 创建操作员实体 tmpOperator = new Model.Operator(); //将数据集转换成实体集合 tmpOperator.Id = Convert.ToInt32(myReader["Id"]); tmpOperator.ModelName = Convert.ToString(myReader["OperatorName"]); tmpOperator.Password = Convert.ToString(myReader["Password"]); tmpOperator.State = Convert.ToBoolean(myReader["State"]);
// 读取权限集合 System.Data.SqlTypes.SqlBytes bytes = myReader.GetSqlBytes(3); // 只能指定列序号 // 将流反序列化为权限集合对象 BinaryFormatter bf = new BinaryFormatter(); if (!bytes.IsNull) tmpOperator.RightsCollection = (bf.Deserialize(bytes.Stream) as Dictionary<string, Model.Rights>);
// 添加到操作员实体集合 operatorCollection.Add(tmpOperator.ModelName, tmpOperator); } } }
// 返回结果 return operatorCollection; }
/// <summary> /// 根据操作员名称校验操作员是否存在 /// </summary> /// <param name="operatorName">操作员名称</param> /// <returns>True:存在/Flase:不存在</returns> public bool CheckOperatorExist(string operatorName) { //创建查询信息的 SQL string sqlTxt = string.Format( "Select Count(*) From Operator Where OperatorName = '{0}'", operatorName); //创建SQL执行对象 DBUtility.AbstractDBProvider dbProvider = DBUtility.AbstractDBProvider.Instance(); //执行查询操作 int result = Convert.ToInt32(dbProvider.RunCommand(sqlTxt));
if (result >= 1) return true; else return false; }
#endregion } }
2、权限组数据访问操作类(RightsGroupService) C#源码清单:
view plaincopy to clipboardprint? using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Runtime.Serialization.Formatters.Binary; using DBUtility = CodingMouse.CMHotelManager.DBUtility; using IDAL = CodingMouse.CMHotelManager.IDAL; using Model = CodingMouse.CMHotelManager.Model; namespace CodingMouse.CMHotelManager.DAL { /// <summary> /// 权限组数据访问操作类 /// </summary> public class RightsGroupService : IDAL.IRightsGroupService { #region IRightsGroupService 成员 /// <summary> /// 获取所有权限组信息 /// </summary> /// <returns>权限组实体集合</returns> public Dictionary<string, Model.RightsGroup> GetAllRightsGroupInfo() { //SQL命令 string sqltxt = "Select Id, GroupName, GroupRightsList From RightsGroup"; //创建权限组实体集合 Dictionary<string, Model.RightsGroup> rightsGroupCollection = new Dictionary<string, Model.RightsGroup>(); //定义权限组实体 Model.RightsGroup tmpRightsGroup = null; // 转换数据库存储的 二进制数据为 Byte[] 数组 以便进而转换为权限组权限集合 // 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqltxt, conn); conn.Open(); using (SqlDataReader myReader = cmd.ExecuteReader( CommandBehavior.CloseConnection)) { while (myReader.Read()) { // 创建权限组实体 tmpRightsGroup = new Model.RightsGroup(); //将数据集转换成实体集合 tmpRightsGroup.Id = Convert.ToInt32(myReader["Id"]); tmpRightsGroup.ModelName = Convert.ToString(myReader["GroupName"]); // 读取权限集合 System.Data.SqlTypes.SqlBytes bytes = myReader.GetSqlBytes(2); // 只能指定列序号 // 将流反序列化为权限集合对象 BinaryFormatter bf = new BinaryFormatter(); if (!bytes.IsNull) tmpRightsGroup.GroupRightsCollection = (bf.Deserialize(bytes.Stream) as Dictionary<string, Model.Rights>); // 添加到权限组实体集合 rightsGroupCollection.Add(tmpRightsGroup.ModelName, tmpRightsGroup); } } } // 返回结果 return rightsGroupCollection; } /// <summary> /// 添加权限组 /// </summary> /// <param name="addRightsGroup">要添加的权限组实体</param> /// <returns>True:成功/False:失败</returns> public bool AddRightsGroup(Model.RightsGroup addRightsGroup) { // 转换权限组权限集合为数据库可存取的 Byte[] 数组 MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, addRightsGroup.GroupRightsCollection); byte[] rigthsByteArray = new byte[(int)(ms.Length)]; ms.Position = 0; ms.Read(rigthsByteArray, 0, (int)(ms.Length)); ms.Close(); // 拼接 SQL 命令 string sqlTxt = "Insert Into RightsGroup (GroupName, GroupRightsList) Values " + "(@GroupName, @GroupRightsList)"; // 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqlTxt, conn); SqlParameter prm1 = new SqlParameter("@GroupName", SqlDbType.NVarChar, 50); prm1.Value = addRightsGroup.ModelName; SqlParameter prm2 = new SqlParameter("@GroupRightsList", SqlDbType.VarBinary, rigthsByteArray.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, rigthsByteArray); cmd.Parameters.AddRange(new SqlParameter[] { prm1, prm2 }); conn.Open(); if (cmd.ExecuteNonQuery() >= 1) return true; else return false; } } /// <summary> /// 删除权限组 /// </summary> /// <param name="id">要删除的权限组 ID</param> /// <returns>True:成功/False:失败</returns> public bool DeleteRightsGroupByID(int id) { // 删除单个信息 SQL 命令 string sqlTxt = string.Format("Delete From RightsGroup Where Id = {0}", id); // 创建 SQL 执行对象 DBUtility.AbstractDBProvider dbProvider = DBUtility.AbstractDBProvider.Instance(); // 执行 删除操作 int rowsAffected; dbProvider.RunCommand(sqlTxt, out rowsAffected); if (rowsAffected >= 1) return true; else return false; } /// <summary> /// 修改权限组 /// </summary> /// <param name="currentRightsGroup">要修改的权限组实体</param> /// <returns>True:成功/False:失败</returns> public bool ModifyRightsGroup(Model.RightsGroup currentRightsGroup) { // 转换权限组权限集合为数据库可存取的 Byte[] 数组 MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, currentRightsGroup.GroupRightsCollection); byte[] rigthsByteArray = new byte[(int)(ms.Length)]; ms.Position = 0; ms.Read(rigthsByteArray, 0, (int)(ms.Length)); ms.Close(); // 拼接 SQL 命令 string sqlTxt = "Update RightsGroup Set GroupName = @GroupName, GroupRightsList = @GroupRightsList Where Id = @Id"; // 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using (SqlConnection conn = new SqlConnection(connectionString)) { SqlCommand cmd = new SqlCommand(sqlTxt, conn); SqlParameter prm1 = new SqlParameter("@GroupName", SqlDbType.NVarChar, 50); prm1.Value = currentRightsGroup.ModelName; SqlParameter prm2 = new SqlParameter("@GroupRightsList", SqlDbType.VarBinary, rigthsByteArray.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, rigthsByteArray); SqlParameter prm3 = new SqlParameter("@Id", SqlDbType.Int); prm3.Value = currentRightsGroup.Id; cmd.Parameters.AddRange(new SqlParameter[] { prm1, prm2, prm3 }); conn.Open(); if (cmd.ExecuteNonQuery() >= 1) return true; else return false; } } /// <summary> /// 根据权限组名称校验权限组是否已经存在 /// </summary> /// <param name="rightsGroupName">权限组名称</param> /// <returns>True:存在/False:不存在</returns> public bool CheckRightsGroupExist(string rightsGroupName) { //SQL命令 string sqlTxt = string.Format("Select Count(*) From RightsGroup Where GroupName = '{0}'", rightsGroupName); //创建SQL执行对象 DBUtility.AbstractDBProvider dbProvider = DBUtility.AbstractDBProvider.Instance(); //执行查询操作 int result = Convert.ToInt32(dbProvider.RunCommand(sqlTxt)); if (result >= 1) return true; else return false; } #endregion } } using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Runtime.Serialization.Formatters.Binary; using DBUtility = CodingMouse.CMHotelManager.DBUtility; using IDAL = CodingMouse.CMHotelManager.IDAL; using Model = CodingMouse.CMHotelManager.Model;
namespace CodingMouse.CMHotelManager.DAL { /// <summary> /// 权限组数据访问操作类 /// </summary> public class RightsGroupService : IDAL.IRightsGroupService { #region IRightsGroupService 成员
/// <summary> /// 获取所有权限组信息 /// </summary> /// <returns>权限组实体集合</returns> public Dictionary<string, Model.RightsGroup> GetAllRightsGroupInfo() { //SQL命令 string sqltxt = "Select Id, GroupName, GroupRightsList From RightsGroup"; //创建权限组实体集合 Dictionary<string, Model.RightsGroup> rightsGroupCollection = new Dictionary<string, Model.RightsGroup>(); //定义权限组实体 Model.RightsGroup tmpRightsGroup = null;
// 转换数据库存储的 二进制数据为 Byte[] 数组 以便进而转换为权限组权限集合 // 从配置文件读取连接字符串 string connectionString = ConfigurationManager.ConnectionStrings["SQLSERVER"].ConnectionString; // 执行 SQL 命令 using (SqlConn |
请发表评论