【無私分享:從入門到精通ASP.NET MVC】從0開始,一塊兒搭框架、作項目(5.4) 登陸功能的實現,建立與登陸用戶相關的接口和實現類

索引html

【無私分享:從入門到精通ASP.NET MVC】從0開始,一塊兒搭框架、作項目 目錄索引

簡述算法

今天咱們建立幾個與登陸用戶相關的數據表的接口和實現類sql

項目準備json

咱們用的工具是:VS 2013 + SqlServer 2012 + IIS7.5cookie

但願你們對ASP.NET MVC有一個初步的理解,理論性的東西咱們不作過多解釋,有些地方不理解也不要緊,會用就好了,用的多了,用的久了,天然就理解了。oracle

項目開始框架

1、新建登陸用戶類Accountide

咱們在(5.2)中咱們登陸驗證直接返回了管理員實體類Domain.SYS_USER,可是在實際的後臺操做驗證中,咱們並不須要SYS_USER的許多屬性,同時咱們須要它的一些擴展屬性,咱們來新建一個管理員類,來具體的描述這個管理員,咱們在Service類庫下面新建一個管理類Account.cs工具

 

 

代碼:post

 1 using System.Collections.Generic;
 2 
 3 namespace Service
 4 {
 5     /// <summary>
 6     /// 通用用戶登陸類,簡單信息
 7     /// </summary>
 8     public class Account
 9     {
10         #region Attribute
11         /// <summary>
12         /// 主鍵
13         /// </summary>
14         public int Id { get; set; }
15         /// <summary>
16         /// 姓名
17         /// </summary>
18         public string Name { get; set; }
19         /// <summary>
20         /// 登陸的用戶名
21         /// </summary>
22         public string LogName { get; set; }
23         /// <summary>
24         /// 登陸密碼
25         /// </summary>
26         public string PassWord { get; set; }
27         /// <summary>
28         /// 是否管理員
29         /// </summary>
30         public bool IsAdmin { get; set; }
31         /// <summary>
32         /// 用戶頭像
33         /// </summary>
34         public string Face_Img { get; set; }
35         /// <summary>
36         /// 用戶主部門
37         /// </summary>
38         public Domain.SYS_DEPARTMENT DptInfo { get; set; }
39         /// <summary>
40         /// 用戶所在部門集合
41         /// </summary>
42         public List<Domain.SYS_DEPARTMENT> Dpt { get; set; }
43         /// <summary>
44         /// 權限集合
45         /// </summary>
46         public List<Domain.SYS_PERMISSION> Permissions { get; set; }
47         /// <summary>
48         /// 角色的集合
49         /// </summary>
50         public List<Domain.SYS_ROLE> Roles { get; set; }
51         /// <summary>
52         /// 用戶崗位集合
53         /// </summary>
54         public List<Domain.SYS_POST_USER> PostUser { get; set; }
55         /// <summary>
56         /// 用戶可操做的模塊集合
57         /// </summary>
58         public List<Domain.SYS_MODULE> Modules { get; set; }
59         #endregion
60     }
61 }
View Code

 

 

2、修改咱們的用戶管理接口IUserManage

修改咱們的用戶管理接口IUserManage 添加幾個方法:根據用戶ID獲取本職部門名稱、 刪除用戶、根據用戶構造用戶基本信息、從Cookie中獲取用戶信息

 

代碼:

 1  /// <summary>
 2         /// 根據用戶ID獲取本職部門名稱
 3         /// </summary>
 4         string GetUserDptName(int id);
 5         /// <summary>
 6         /// 刪除用戶
 7         /// </summary>
 8         bool Remove(int userId);
 9         /// <summary>
10         /// 根據用戶構造用戶基本信息
11         /// </summary>
12         Account GetAccountByUser(Domain.SYS_USER user);
13         /// <summary>
14         /// 從Cookie中獲取用戶信息
15         /// </summary>
16         Account GetAccountByCookie();
View Code

 

3、咱們分別建立幾個關聯表的接口和實現類

建立SYS_USERINFO(用戶檔案)、SYS_USER_ROLE(用戶角色)、SYS_USER_PERMISSION(用戶權限)、SYS_POST_USER(用戶崗位)、SYS_USER_DEPARTMENT(用戶部門)、SYS_PERMISSION(權限表)、SYS_DEPARTMENT(部門表)、SYS_MODULE(模塊表)的接口和實現類

這兩天沒怎麼發佈東西,一是工做太忙,二是我提早把這些東西都寫好了,測試了一下,可能寫的會有些不合理,但願你們指正,我先貼出來,註釋我都寫了,你們能夠先預想一下這些都是幹什麼用的,下一篇咱們完成咱們的登陸功能,使用到了這些東西就一目瞭然了。

IUserInfoManage、UserInfoManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Service.IService
 8 {
 9     public interface IUserInfoManage:IRepository<Domain.SYS_USERINFO>
10     {
11     }
12 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.ServiceImp
 7 {
 8     /// <summary>
 9     /// Service層用戶拓展信息接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public class UserInfoManage : RepositoryBase<Domain.SYS_USERINFO>,IService.IUserInfoManage
13     {
14     }
15 }
View Code

 

IUserRoleManage、UserRoleManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Service.IService
 8 {
 9     /// <summary>
10     /// Service層用戶與角色關係接口
11     /// add yuangang by 2016-05-19
12     /// </summary>
13     public interface IUserRoleManage:IRepository<Domain.SYS_USER_ROLE>
14     {
15         /// <summary>
16         /// 設置用戶角色
17         /// add yuangang by 2016-05-19
18         /// </summary>
19         /// <param name="userId">用戶ID</param>
20         /// <param name="roleId">角色ID字符串</param>
21         /// <returns></returns>
22         bool SetUserRole(int userId, string roleId);
23     }
24 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.ServiceImp
 7 {
 8     /// <summary>
 9     /// Service層用戶與角色關係接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public class UserRoleManage : RepositoryBase<Domain.SYS_USER_ROLE>,IService.IUserRoleManage
13     {
14         /// <summary>
15         /// 設置用戶角色
16         /// add yuangang by 2016-05-19
17         /// </summary>
18         /// <param name="userId">用戶ID</param>
19         /// <param name="roleId">角色ID字符串</param>
20         public bool SetUserRole(int userId, string roleId)
21         {
22             try
23             {
24                 //一、刪除用戶角色
25                 this.Delete(p => p.FK_USERID == userId);
26                 //二、設置當前用戶的角色
27                 if (string.IsNullOrEmpty(roleId)) return true;
28                 foreach (var entity in roleId.Split(',').Select(t => new Domain.SYS_USER_ROLE()
29                 {
30                     FK_USERID = userId,
31                     FK_ROLEID = int.Parse(t)
32                 }))
33                 {
34                     this.dbSet.Add(entity);
35                 }
36                 return this.Context.SaveChanges() > 0;
37             }
38             catch (Exception e) { throw e; }
39         }
40     }
41 }
View Code

 

IUserPermissionManage、UserPermissionManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// Service層用戶受權接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public interface IUserPermissionManage : IRepository<Domain.SYS_USER_PERMISSION>
13     {
14         /// <summary>
15         /// 設置用戶權限
16         /// add yuangang by 2016-05-19
17         /// </summary>
18         /// <param name="userId">用戶ID</param>
19         /// <param name="newper">權限字符串</param>
20         /// <param name="sysId">系統ID</param>
21         /// <returns></returns>
22         bool SetUserPermission(int userId, string newper, string sysId);
23     }
24 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using Service.IService;
 6 
 7 namespace Service.ServiceImp
 8 {
 9     /// <summary>
10     /// Service層用戶受權接口
11     /// add yuangang by 2016-05-19
12     /// </summary>
13     public class UserPermissionManage : RepositoryBase<Domain.SYS_USER_PERMISSION>,IService.IUserPermissionManage
14     {
15         IPermissionManage PermissionManage { get; set; }
16         /// <summary>
17         /// 保存用戶權限
18         /// </summary>
19         public bool SetUserPermission(int userId, string newper, string sysId)
20         {
21             try
22             {
23                 //一、獲取當前系統的模塊ID集合
24                 var permissionId = this.PermissionManage.GetPermissionIdBySysId(sysId).Cast<int>().ToList();
25                 //二、獲取用戶權限,是否存在,存在即刪除
26                 if (this.IsExist(p => p.FK_USERID == userId && permissionId.Any(e => e == p.FK_PERMISSIONID)))
27                 {
28                     //三、刪除用戶權限
29                     this.Delete(p => p.FK_USERID == userId && permissionId.Any(e => e == p.FK_PERMISSIONID));
30                 }
31                 //四、添加用戶權限
32                 var str = newper.Trim(',').Split(',');
33                 foreach (var per in str.Select(t => new Domain.SYS_USER_PERMISSION()
34                 {
35                     FK_USERID = userId,
36                     FK_PERMISSIONID = int.Parse(t)
37                 }))
38                 {
39                     this.dbSet.Add(per);
40                 }
41                 //五、Save
42                 return this.Context.SaveChanges() > 0;
43             }
44             catch (Exception e) { throw e; }
45         }
46     }
47 }
View Code

 

IPostUserManage、PostUserManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// 崗位用戶關係業務接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public interface IPostUserManage : IRepository<Domain.SYS_POST_USER>
13     {
14         /// <summary>
15         /// 根據崗位ID獲取人員集合,可傳遞多個崗位ID
16         /// </summary>
17         List<Domain.SYS_USER> GetUserListByPostId(string postId);
18         /// <summary>
19         /// 根據人員ID獲取崗位集合,可傳遞多個
20         /// </summary>
21         List<Domain.SYS_POST> GetPostListByUserId(string userId);
22         /// <summary>
23         /// 添加崗位人員關係
24         /// </summary>
25         /// <param name="userId">人員ID</param>
26         /// <param name="postId">崗位ID集合</param>
27         /// <returns></returns>
28         bool SavePostUser(int userId, string postId);
29         /// <summary>
30         /// 根據崗位集合獲取崗位名稱,部門-崗位模式        
31         /// </summary>
32         dynamic GetPostNameBySysPostUser(ICollection<Domain.SYS_POST_USER> collection);
33 
34     }
35 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.ServiceImp
 7 {
 8     /// <summary>
 9     /// 崗位人員關係業務實現類
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public class PostUserManage : RepositoryBase<Domain.SYS_POST_USER>, IService.IPostUserManage
13     {
14         /// <summary>
15         /// 根據崗位ID獲取人員列表
16         /// </summary>
17         public List<Domain.SYS_USER> GetUserListByPostId(string postId)
18         {
19             try
20             {
21                 string sql = @"select * from sys_user t where exists(select u.fk_userid from sys_post_user u
22                                 inner join sys_post_department p
23                                 on u.fk_post_departmentid=p.id
24                                 where t.id=u.fk_userid and p.fk_post_id in (" + postId + ")  group by u.fk_userid)";
25                 return this.SelectBySql<Domain.SYS_USER>(sql);
26             }
27             catch (Exception e) { throw e.InnerException; }
28         }
29         /// <summary>
30         /// 根據用戶ID獲取所持有的崗位集合
31         /// </summary>
32         public List<Domain.SYS_POST> GetPostListByUserId(string userId)
33         {
34             return this.LoadAll(p => userId.Contains(p.FK_USERID.ToString())).Select(p => p.SYS_POST_DEPARTMENT.SYS_POST).ToList();
35         }
36 
37         /// <summary>
38         /// 添加崗位人員關係
39         /// </summary>
40         /// <param name="userId">人員ID</param>
41         /// <param name="postId">崗位ID集合</param>
42         /// <returns></returns>
43         public bool SavePostUser(int userId, string postId)
44         {
45             try
46             {
47                 if (this.IsExist(p => p.FK_USERID == userId))
48                 {
49                     //存在以後再對比是否一致 
50                     var oldCount = this.LoadAll(p => p.FK_USERID == userId).Select(p => p.FK_POST_DEPARTMENTID).ToList().Cast<int>().ToList();
51                     var newpostId = postId.Trim(',').Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(p => int.Parse(p)).ToList();
52                     if (oldCount.Count == newpostId.Count && oldCount.All(newpostId.Contains)) return true;
53                     //刪除原有關係
54                     this.Delete(p => p.FK_USERID == userId);
55                 }
56                 if (!string.IsNullOrEmpty(postId))
57                 {
58                     //添加現有關係
59                     var list = postId.Split(',').Select(item => new Domain.SYS_POST_USER()
60                     {
61                         FK_USERID = userId,
62                         FK_POST_DEPARTMENTID =int.Parse(item)
63                     }).ToList();
64                     return this.SaveList(list) > 0;
65                 }
66                 return true;
67             }
68             catch (Exception e) { throw e.InnerException; }
69         }
70 
71         /// <summary>
72         /// 根據崗位集合獲取崗位名稱,部門-崗位模式        
73         /// </summary>
74         public dynamic GetPostNameBySysPostUser(ICollection<Domain.SYS_POST_USER> collection)
75         {
76             //崗位部門關係ID集合
77             string post_departmentid = collection.Select(p => p.FK_POST_DEPARTMENTID).Aggregate(string.Empty, (current, t) => current + "'" + t + "',").TrimEnd(',');
78             try
79             {
80                 string sql = @"select d.name+'-'+p.postname as postname,s.id from sys_department d inner join
81                         sys_post_department s on d.id=s.fk_department_id
82                         inner join sys_post p on p.id=s.fk_post_id 
83                         where s.id in (" + post_departmentid + ")";
84                 return this.ExecuteSqlQuery(sql);
85             }
86             catch (Exception e) { throw e.InnerException; }
87         }
88     }
89 }
View Code

 

IUserDepartmentManage、UserDepartmentManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// 用戶部門關係業務接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public interface IUserDepartmentManage : IRepository<Domain.SYS_USER_DEPARTMENT>
13     {
14         /// <summary>
15         /// 根據部門ID獲取當前部門的全部用戶集合
16         /// </summary>
17         List<Domain.SYS_USER> GetUserListByDptId(List<string> dptId);
18         /// <summary>
19         /// 根據用戶ID獲取所在的部門集合
20         /// </summary>
21         List<Domain.SYS_DEPARTMENT> GetDptListByUserId(int userId);
22         /// <summary>
23         /// 保存用戶部門關係
24         /// </summary>
25         /// <param name="userId">用戶ID</param>
26         /// <param name="dptId">部門ID集合</param>
27         /// <returns></returns>
28         bool SaveUserDpt(int userId, string dptId);
29     }
30 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.ServiceImp
 7 {
 8     /// <summary>
 9     /// 用戶部門關係業務實現類
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public class UserDepartmentManage:RepositoryBase<Domain.SYS_USER_DEPARTMENT>,IService.IUserDepartmentManage
13     {
14         /// <summary>
15         /// 根據部門ID獲取當前部門的全部用戶ID集合
16         /// </summary>
17         public List<Domain.SYS_USER> GetUserListByDptId(List<string> dptId)
18         {
19             return this.LoadAll(p => dptId.Contains(p.DEPARTMENT_ID)).Select(p => p.SYS_USER).ToList();
20         }
21         /// <summary>
22         /// 根據用戶ID獲取所在的部門ID集合
23         /// </summary>
24         public List<Domain.SYS_DEPARTMENT> GetDptListByUserId(int userId)
25         {
26             return this.LoadAll(p => p.USER_ID == userId).Select(p=>p.SYS_DEPARTMENT).ToList();
27         }
28 
29         /// <summary>
30         /// 保存用戶部門關係
31         /// </summary>
32         /// <param name="userId">用戶ID</param>
33         /// <param name="dptId">部門ID集合</param>
34         public bool SaveUserDpt(int userId, string dptId)
35         {
36             try
37             {
38                 //原始部門人員關係是否與當前設置一致,不一致從新構造
39                 if (this.IsExist(p => p.USER_ID == userId))
40                 {
41                     //存在以後再對比是否一致 
42                     var oldCount = this.LoadAll(p => p.USER_ID == userId && dptId.Contains(p.DEPARTMENT_ID)).Select(p => p.DEPARTMENT_ID).ToList();
43                     var newdptid = dptId.Split(',').OrderBy(c => c).ToList();
44                     if (oldCount.Count == newdptid.Count && oldCount.All(newdptid.Contains)) return true;
45                     //刪除原有關係
46                     this.Delete(p => p.USER_ID == userId);
47                 }
48                 if (!string.IsNullOrEmpty(dptId))
49                 {
50                     //添加現有關係
51                     var list = dptId.Split(',').Select(item => new Domain.SYS_USER_DEPARTMENT()
52                     {
53                         DEPARTMENT_ID = item,
54                         USER_ID = userId
55                     }).ToList();
56                     return this.SaveList(list) > 0;
57                 }
58                 return true;
59             }
60             catch (Exception e) { throw e.InnerException; }
61         }
62     }
63 }
View Code

 

IPermissionManage、PermissionManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// Service 受權驗證模塊對應接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public interface IPermissionManage : IRepository<Domain.SYS_PERMISSION>
13     {
14         /// <summary>
15         /// 根據系統ID獲取全部模塊的權限ID集合
16         /// </summary>
17         List<int> GetPermissionIdBySysId(string sysId);
18     }
19 }
View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Data.Common;
 4 using System.Data.SqlClient;
 5 using System.Linq;
 6 using System.Text;
 7 
 8 namespace Service.ServiceImp
 9 {
10     /// <summary>
11     /// Service 受權模塊關係處理類
12     /// add yuangang by 2016-05-19
13     /// </summary>
14     public class PermissionManage : RepositoryBase<Domain.SYS_PERMISSION>, IService.IPermissionManage
15     {
16         /// <summary>
17         /// 根據系統ID獲取全部模塊的權限ID集合
18         /// </summary>
19         public List<int> GetPermissionIdBySysId(string sysId)
20         {
21             try
22             {
23                 string sql = "select p.id from sys_permission p where exists(select 1 from sys_module t where t.fk_belongsystem=@sysid and t.id=p.moduleid)";
24                 DbParameter para = new SqlParameter("@sysid", sysId);
25                 return this.SelectBySql<int>(sql, para);
26             }
27             catch (Exception e)
28             {
29                 throw e;
30             }
31         }
32     }
33 }
View Code

 

IDepartmentManage、DepartmentManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// Service層部門管理接口
10     /// add yuangang by 2016-05-19
11     /// </summary>
12     public interface IDepartmentManage : IRepository<Domain.SYS_DEPARTMENT>
13     {
14         /// <summary>
15         /// 遞歸部門列表,返回按級別排序
16         /// add yuangang by 2016-05-19
17         /// </summary>
18         /// <param name="list"></param>
19         /// <returns></returns>
20         List<Domain.SYS_DEPARTMENT> RecursiveDepartment(List<Domain.SYS_DEPARTMENT> list);
21 
22         /// <summary>
23         /// 根據部門ID遞歸部門列表,返回子部門+本部門的對象集合
24         /// add yuangang by 2016-05-19
25         /// </summary>
26         List<Domain.SYS_DEPARTMENT> RecursiveDepartment(string parentId);
27         /// <summary>
28         /// 自動建立部門編號
29         /// add yuangang by 2016-05-19
30         /// </summary>
31         string CreateCode(string parentCode);
32 
33         /// <summary>
34         /// 部門是否存在下級部門
35         /// add huafg by 2015-06-03
36         /// </summary>
37         bool DepartmentIsExists(string idlist);
38 
39         /// <summary>
40         /// 根據部門ID獲取部門名稱,不存在返回空
41         /// </summary>
42         string GetDepartmentName(string id);
43         /// <summary>
44         /// 顯示錯層方法
45         /// </summary>
46         object GetDepartmentName(string name, decimal? level);
47         /// <summary>
48         /// 獲取部門父級列表
49         /// </summary>
50         System.Collections.IList GetDepartmentByDetail();
51 
52     }
53 }
View Code
  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using System.Linq;
  5 using System.Text;
  6 
  7 namespace Service.ServiceImp
  8 {
  9     /// <summary>
 10     /// Service層部門管理
 11     /// add yuangang by 2016-05-19
 12     /// </summary>
 13     public class DepartmentManage : RepositoryBase<Domain.SYS_DEPARTMENT>,IService.IDepartmentManage
 14     {
 15         /// <summary>
 16         /// 自動建立部門編號
 17         /// add yuangang by 2016-05-19
 18         /// <param name="parentId">上級部門ID 注:ID不是Code,數據表已改</param>
 19         /// </summary>
 20         public string CreateCode(string parentId)
 21         {
 22             string _strCode = string.Empty;
 23 
 24             #region 驗證上級部門code是否爲空,爲空返回,第一級部門的Code
 25             if (string.IsNullOrEmpty(parentId))
 26             {
 27                 //注意:Oracle存儲值爲空=null MsSql 空=空 null=null
 28                 var query = this.LoadAll(p => p.PARENTID == null || p.PARENTID == "").OrderBy(p => p.CODE).ToList();
 29                 if (!query.Any())
 30                 {
 31                     return "001";
 32                 }
 33                 //按照以前的邏輯,查漏補缺
 34                 for (int i = 1; i <= query.Count; i++)
 35                 {
 36                     string code = query[i - 1].CODE;
 37                     if (string.IsNullOrEmpty(code))
 38                     {
 39                         return FormatCode(i);
 40                     }
 41                     if (i != int.Parse(code))
 42                     {
 43                         return  FormatCode(i);
 44                     }
 45                 }
 46                 return  FormatCode(query.Count + 1);
 47             }
 48             #endregion
 49             
 50             #region 上級部門不爲空,返回當前上級部門下的部門Code
 51             
 52             /* *根據部門編號獲取下級部門 查詢條件爲:
 53              * 1.下級部門編號長度=當前部門編號+3 
 54              * 2.下級部門上級部門ID=當前部門ID
 55              * */
 56             var parentDpt = this.Get(p => p.ID == parentId);
 57             if (parentDpt != null)//上級部門存在
 58             {
 59                 //查詢同等級部門下的全部數據
 60                 var queryable = this.LoadAll(p => p.CODE.Length == parentDpt.CODE.Length + 3 && p.PARENTID == parentId).OrderBy(p=>p.CODE).ToList();
 61                 if (queryable.Any())
 62                 {
 63                     //須要驗證是否存在編號缺失的狀況 方法:遍歷下級部門列表,
 64                     //用部門編號去掉上級部門編號,而後轉化成數字和for循環的索引進行對比,遇到第一個不相等時,返回此編號,並跳出循環
 65                     for (int i = 1; i <= queryable.Count; i++)
 66                     {
 67                         string _code = queryable[i - 1].CODE;
 68                         _code = _code.Substring(parentDpt.CODE.Length);
 69                         int _intCode = 0;
 70                         Int32.TryParse(_code, out _intCode);
 71                         //下級部門編號中不存在
 72                         if (i != _intCode)
 73                         {
 74                             //返回此編號,並退出循環
 75                             _strCode = parentDpt.CODE + FormatCode(i);
 76                             return _strCode;
 77                         }
 78                     }
 79                     //不存在編號缺失狀況
 80                     _strCode = parentDpt.CODE + FormatCode(queryable.Count + 1);
 81                 }
 82                 else
 83                 {
 84                     _strCode = parentDpt.CODE + FormatCode(1);
 85                     return _strCode;
 86                 }
 87             }//上級部門不存在,返回空,這種狀況基本不會出現
 88             #endregion
 89 
 90             return _strCode;
 91         }
 92         /// <summary>
 93         /// 功能描述:根據傳入的數字 返回補碼後的3位部門編號
 94         /// 建立標號:add yuangang by 2016-05-19
 95         /// </summary>
 96         public string FormatCode(int dptCode)
 97         {
 98             try
 99             {
100                 string _strCode = string.Empty;
101                 //<=9 一位數
102                 if (dptCode <= 9 && dptCode >= 1)
103                 {
104                     return "00" + dptCode;
105                 }
106                 //<=99 兩位數
107                 else if (dptCode <= 99 && dptCode > 9)
108                 {
109                     return "0" + dptCode;
110                 }
111                 //<==999 三位數
112                 else if (dptCode <= 999 && dptCode > 99)
113                 {
114                     return _strCode;
115                 }
116                 return string.Empty;
117             }
118             catch (Exception ex)
119             {
120                 throw ex;
121             }
122         }
123 
124         /// <summary>
125         /// 驗證當前刪除的部門是否存在下級部門
126         /// </summary>
127         public bool DepartmentIsExists(string idlist)
128         {
129             return this.IsExist(p => idlist.Contains(p.PARENTID));
130         }
131 
132         /// <summary>
133         /// 遞歸部門列表,返回排序後的對象集合
134         /// add yuangang by 2016-05-19
135         /// </summary>
136         public List<Domain.SYS_DEPARTMENT> RecursiveDepartment(List<Domain.SYS_DEPARTMENT> list) 
137         {
138             var result = new List<Domain.SYS_DEPARTMENT>();
139             if (list.Count>0)
140             {
141                 ChildDepartment(list, result, null);
142             }
143             return result;
144         }
145 
146         /// <summary>
147         /// 根據部門ID遞歸部門列表,返回子部門+本部門的對象集合
148         /// add yuangang by 2016-05-19
149         /// </summary>
150         public List<Domain.SYS_DEPARTMENT> RecursiveDepartment(string parentId)
151         {
152             //原始數據
153             var list = this.LoadAll(null);
154             //新數據
155             var result = new List<Domain.SYS_DEPARTMENT>();
156             if (list.Any())
157             {
158                 result.AddRange(list.Where(p => p.ID == parentId).ToList());
159                 if(!string.IsNullOrEmpty(parentId))
160                     ChildDepartment(list.ToList(),result, parentId);
161                 else
162                     ChildDepartment(list.ToList(),result, null);//oracle使用null sql使用空
163             }
164             return result;
165         }
166 
167         private void ChildDepartment(List<Domain.SYS_DEPARTMENT> newlist ,List<Domain.SYS_DEPARTMENT> list,string id) 
168         {
169             var result = newlist.Where(p => p.PARENTID == id).OrderBy(p => p.CODE).ThenBy(p => p.SHOWORDER).ToList();
170             if (result.Any())
171             {
172                 for (int i = 0; i < result.Count(); i++)
173                 {
174                     list.Add(result[i]);
175                     ChildDepartment(newlist,list, result[i].ID);
176                 }
177             }
178         }
179 
180         /// <summary>
181         /// 根據部門ID獲取部門名稱,不存在返回空
182         /// </summary>
183         public string GetDepartmentName(string id)
184         {
185             var query = this.LoadAll(p => p.ID == id);
186             if (query == null || !query.Any())
187                 return "";
188             return query.First().NAME;
189         }
190 
191         /// <summary>
192         /// 顯示錯層方法
193         /// </summary>
194         public object GetDepartmentName(string name, decimal? level)
195         {
196             if (level > 1)
197             {
198                 string nbsp = "&nbsp;&nbsp;";
199                 for (int i = 0; i < level; i++)
200                 {
201                     nbsp += "&nbsp;&nbsp;";
202                 }
203                 name = nbsp + "|--" + name;
204             }
205             return name;
206         }
207 
208         /// <summary>
209         /// 獲取父級列表
210         /// </summary>
211         public IList GetDepartmentByDetail()
212         {
213             var list = RecursiveDepartment(this.LoadAll(null).ToList())
214                 .Select(p => new
215                 {
216                     id = p.ID,
217                     code=p.CODE,
218                     name = GetDepartmentName(p.NAME, p.BUSINESSLEVEL)
219                 }).ToList();
220 
221             return Common.JsonConverter.JsonClass(list);
222         }
223     }
224 }
View Code

 

IModuleManage、ModuleManage

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace Service.IService
 7 {
 8     /// <summary>
 9     /// Service模型處理接口
10     /// add yuangang by 2015-05-22
11     /// </summary>
12     public interface IModuleManage : IRepository<Domain.SYS_MODULE>
13     {
14         /// <summary>
15         /// 獲取用戶權限模塊集合
16         /// add yuangang by 2015-05-30
17         /// </summary>
18         /// <param name="userId">用戶ID</param>
19         /// <param name="permission">用戶受權集合</param>
20         /// <param name="siteId">站點ID</param>
21         /// <returns></returns>
22         List<Domain.SYS_MODULE> GetModule(int userId, List<Domain.SYS_PERMISSION> permission, string siteId);
23         /// <summary>
24         /// 遞歸模塊列表,返回按級別排序
25         /// add yuangang by 2015-06-03
26         /// </summary>
27         List<Domain.SYS_MODULE> RecursiveModule(List<Domain.SYS_MODULE> list);
28 
29         /// <summary>
30         /// 批量變動當前模塊下其餘模塊的級別
31         /// </summary>
32         bool MoreModifyModule(int moduleId, int levels);
33     }
34 }
View Code
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 
  6 namespace Service.ServiceImp
  7 {
  8     /// <summary>
  9     /// Service模型處理類
 10     /// add yuangang by 2015-05-22
 11     /// </summary>
 12     public class ModuleManage : RepositoryBase<Domain.SYS_MODULE>, IService.IModuleManage
 13     {
 14         /// <summary>
 15         /// 獲取用戶權限模塊集合
 16         /// add yuangang by 2015-05-30
 17         /// </summary>
 18         /// <param name="userId">用戶ID</param>
 19         /// <param name="permission">用戶受權集合</param>
 20         /// <param name="siteId">站點ID</param>
 21         /// <returns></returns>
 22         public List<Domain.SYS_MODULE> GetModule(int userId, List<Domain.SYS_PERMISSION> permission,string siteId)
 23         {
 24             //返回模塊
 25             var retmodule = new List<Domain.SYS_MODULE>();
 26             var permodule = new List<Domain.SYS_MODULE>();
 27             //權限轉模塊
 28             if (permission != null)
 29             {
 30                 permodule.AddRange(permission.Select(p => p.SYS_MODULE));
 31                 //去重
 32                 permodule = permodule.Distinct(new ModuleDistinct()).ToList();
 33             }
 34             //檢索顯示與系統
 35             //permodule = permodule.Where(p => p.ISSHOW == 1 && p.FK_BELONGSYSTEM.ToString() == siteId).ToList();
 36             //商城系統融入本系統再也不區分系統
 37             permodule = permodule.Where(p => p.ISSHOW == 1 ).ToList();
 38             //構造上級導航模塊
 39             //var prevModule = this.LoadListAll(p => p.FK_BELONGSYSTEM.ToString() == siteId);
 40             //商城系統融入本系統再也不區分系統
 41             var prevModule = this.LoadListAll(null);
 42             //反向遞歸算法構造模塊帶上級上上級模塊
 43             if (permodule.Count > 0)
 44             {
 45                 foreach (var item in permodule)
 46                 {
 47                     RecursiveModule(prevModule, retmodule, item.PARENTID);
 48                     retmodule.Add(item);
 49                 }
 50             }
 51             //去重
 52             retmodule = retmodule.Distinct(new ModuleDistinct()).ToList();
 53             //返回模塊集合
 54             return retmodule.OrderBy(p => p.LEVELS).ThenBy(p => p.SHOWORDER).ToList();
 55         }
 56 
 57         /// <summary>
 58         /// 反向遞歸模塊集合,可重複模塊數據,最後去重
 59         /// </summary>
 60         /// <param name="PrevModule">總模塊</param>
 61         /// <param name="retmodule">返回模塊</param>
 62         /// <param name="parentId">上級ID</param>
 63         private void RecursiveModule(List<Domain.SYS_MODULE> PrevModule, List<Domain.SYS_MODULE> retmodule, int? parentId)
 64         {
 65            var result = PrevModule.Where(p => p.ID == parentId);
 66             if (result != null)
 67             {
 68                 foreach (var item in result)
 69                 {
 70                     retmodule.Add(item);
 71                     RecursiveModule(PrevModule, retmodule, item.PARENTID);
 72                 }
 73             }
 74         }
 75 
 76         /// <summary>
 77         /// 遞歸模塊列表,返回按級別排序
 78         /// add yuangang by 2015-06-03
 79         /// </summary>
 80         public List<Domain.SYS_MODULE> RecursiveModule(List<Domain.SYS_MODULE> list)
 81         {
 82             List<Domain.SYS_MODULE> result = new List<Domain.SYS_MODULE>();
 83             if (list!=null && list.Count>0)
 84             {
 85                 ChildModule(list, result, 0);
 86             }
 87             return result;
 88         }
 89         /// <summary>
 90         /// 遞歸模塊列表
 91         /// add yuangang by 2015-06-03
 92         /// </summary>
 93         private void ChildModule(List<Domain.SYS_MODULE> list, List<Domain.SYS_MODULE> newlist, int parentId)
 94         {
 95             var result = list.Where(p => p.PARENTID == parentId).OrderBy(p => p.LEVELS).OrderBy(p => p.SHOWORDER).ToList();
 96             if (result.Count() > 0)
 97             {
 98                 for (int i = 0; i < result.Count(); i++)
 99                 {
100                     newlist.Add(result[i]);
101                     ChildModule(list, newlist, result[i].ID);
102                 }
103             }
104         }
105 
106         /// <summary>
107         /// 批量變動下級模塊的級別
108         /// </summary>
109         public bool MoreModifyModule(int moduleId, int levels)
110         {
111            //根據當前模塊ID獲取下級模塊的集合
112             var ChildModule = this.LoadAll(p => p.PARENTID == moduleId).ToList();
113             if (ChildModule.Any())
114             {
115                 foreach (var item in ChildModule)
116                 {
117                     item.LEVELS = levels + 1;
118                     this.Update(item);
119                     MoreModifyModule(item.ID, item.LEVELS);
120                 }
121             }
122             return true;
123         }
124 
125         /// <summary>
126         /// 獲取模板列表
127         /// </summary>
128         public dynamic LoadModuleInfo(int id)
129         {
130             return Common.JsonConverter.JsonClass(this.LoadAll(p=>p.PARENTID==id).OrderBy(p => p.ID).Select(p => new { p.ID, p.NAME }).ToList());
131         }
132     }
133   /// <summary>
134     /// 模型去重,很是重要
135     /// add yuangang by 2015-08-03
136     /// </summary>
137     public class ModuleDistinct : IEqualityComparer<Domain.SYS_MODULE> 
138     {
139         public bool Equals(Domain.SYS_MODULE x, Domain.SYS_MODULE y)
140         {
141             return x.ID == y.ID; 
142         }
143 
144         public int GetHashCode(Domain.SYS_MODULE obj)
145         {
146             return obj.ToString().GetHashCode();
147         }
148     }
149 }
View Code

 

3、咱們分修改UserManage實現類

修改咱們UserManage的IsAdmin方法

 1  /// <summary>
 2         /// 是否超級管理員
 3         /// </summary>
 4         public bool IsAdmin(int userId)
 5         {
 6             //經過用戶ID獲取角色
 7             Domain.SYS_USER entity = this.Get(p => p.ID == userId);
 8             if (entity == null) return false;
 9             var roles = entity.SYS_USER_ROLE.Select(p => new Domain.SYS_ROLE
10             {
11                 ID = p.SYS_ROLE.ID
12             });
13             return roles.ToList().Any(item => item.ID == ClsDic.DicRole["超級管理員"]);
14         }
View Code


/// 根據用戶ID刪除用戶相關記錄
/// 刪除原則:一、刪除用戶檔案
/// 二、刪除用戶角色關係
/// 三、刪除用戶權限關係
/// 四、刪除用戶崗位關係
/// 五、刪除用戶部門關係
/// 六、刪除用戶

 1 /// <summary>
 2         /// 根據用戶ID刪除用戶相關記錄
 3         /// 刪除原則:一、刪除用戶檔案
 4         ///           二、刪除用戶角色關係
 5         ///           三、刪除用戶權限關係
 6         ///           四、刪除用戶崗位關係
 7         ///           五、刪除用戶部門關係
 8         ///           六、刪除用戶
 9         /// </summary>
10         public bool Remove(int userId)
11         {
12             try
13             {
14                 //檔案
15                 if (this.UserInfoManage.IsExist(p => p.USERID == userId))
16                 {
17                     this.UserInfoManage.Delete(p => p.USERID == userId);
18                 }
19                 //用戶角色
20                 if (this.UserRoleManage.IsExist(p => p.FK_USERID == userId))
21                 {
22                     this.UserRoleManage.Delete(p => p.FK_USERID == userId);
23                 }
24                 //用戶權限
25                 if (this.UserPermissionManage.IsExist(p => p.FK_USERID == userId))
26                 {
27                     this.UserPermissionManage.Delete(p => p.FK_USERID == userId);
28                 }
29                 //用戶崗位
30                 if (this.PostUserManage.IsExist(p => p.FK_USERID == userId))
31                 {
32                     this.PostUserManage.Delete(p => p.FK_USERID == userId);
33                 }
34                 //用戶部門
35                 if (this.UserDepartmentManage.IsExist(p => p.USER_ID == userId))
36                 {
37                     this.UserDepartmentManage.Delete(p => p.USER_ID == userId);
38                 }
39                 //用戶自身
40                 if (this.IsExist(p => p.ID == userId))
41                 {
42                     this.Delete(p => p.ID == userId);
43                 }
44                 return true;
45             }
46             catch (Exception e) { throw e.InnerException; }
47         }
View Code

 

從Cookie中獲取用戶信息

 1 /// <summary>
 2         /// 從Cookie中獲取用戶信息
 3         /// </summary>
 4         public Account GetAccountByCookie()
 5         {
 6             var cookie = CookieHelper.GetCookie("cookie_rememberme");
 7             if (cookie != null)
 8             {
 9                 //驗證json的有效性
10                 if (!string.IsNullOrEmpty(cookie.Value))
11                 {
12                     //解密
13                     var cookievalue = new Common.CryptHelper.AESCrypt().Decrypt(cookie.Value);
14                     //是否爲json
15                     if (!JsonSplit.IsJson(cookievalue)) return null;
16                     try
17                     {
18                         var jsonFormat = Common.JsonConverter.ConvertJson(cookievalue);
19                         if (jsonFormat != null)
20                         {
21                             var users = UserLogin(jsonFormat.username, new Common.CryptHelper.AESCrypt().Decrypt(jsonFormat.password));
22                             if (users != null)
23                                 return GetAccountByUser(users);
24                         }
25                     }
26                     catch { return null; }
27                 }
28             }
29             return null;
30         }
View Code

 

根據用戶構造用戶基本信息

 1  /// <summary>
 2         /// 根據用戶構造用戶基本信息
 3         /// </summary>
 4         public Account GetAccountByUser(Domain.SYS_USER users)
 5         {
 6             if (users == null) return null;
 7             //用戶受權--->注意用戶的受權是包括角色權限與自身權限的
 8             var permission = GetPermissionByUser(users);
 9             //用戶角色
10             var role = users.SYS_USER_ROLE.Select(p => p.SYS_ROLE).ToList();
11             //用戶部門
12             var dpt = users.SYS_USER_DEPARTMENT.Select(p => p.SYS_DEPARTMENT).ToList();
13             //用戶崗位
14             var post = users.SYS_POST_USER.ToList();
15             //用戶主部門
16             var dptInfo = this.DepartmentManage.Get(p => p.ID == users.DPTID);
17             //用戶模塊
18             var module = permission.Select(p => p.SYS_MODULE).ToList().Distinct(new ModuleDistinct()).ToList();
19             Account account = new Account()
20             {
21                 Id = users.ID,
22                 Name = users.NAME,
23                 LogName = users.ACCOUNT,
24                 PassWord = users.PASSWORD,
25                 IsAdmin = IsAdmin(users.ID),
26                 DptInfo = dptInfo,
27                 Dpt = dpt,
28                 Face_Img = users.FACE_IMG,
29                 Permissions = permission,
30                 Roles = role,
31                 PostUser = post,
32                 Modules = module
33             };
34             return account;
35         }
View Code

 

根據用戶信息獲取用戶全部的權限

 1 /// <summary>
 2         /// 根據用戶信息獲取用戶全部的權限
 3         /// </summary>
 4         private List<Domain.SYS_PERMISSION> GetPermissionByUser(Domain.SYS_USER users)
 5         {
 6             //一、超級管理員擁有全部權限
 7             if (IsAdmin(users.ID))
 8                 return PermissionManage.LoadListAll(null);
 9             //二、普通用戶,合併當前用戶權限與角色權限
10             var perlist = new List<Domain.SYS_PERMISSION>();
11             //2.1合併用戶權限
12             perlist.AddRange(users.SYS_USER_PERMISSION.Select(p => p.SYS_PERMISSION).ToList());
13             //2.2合同角色權限
14             ////todo:經典多對多的數據查詢Linq方法
15             perlist.AddRange(users.SYS_USER_ROLE.Select(p => p.SYS_ROLE.SYS_ROLE_PERMISSION.Select(c => c.SYS_PERMISSION)).SelectMany(c => c.Select(e => e)).Cast<Domain.SYS_PERMISSION>().ToList());
16             //三、去重
17             ////todo:經過重寫IEqualityComparer<T>實現對象去重
18             perlist = perlist.Distinct(new PermissionDistinct()).ToList();
19             return perlist;
20         }
View Code

 

根據用戶ID獲取部門名稱

 1  /// <summary>
 2         /// 根據用戶ID獲取部門名稱
 3         /// </summary>
 4         public string GetUserDptName(int id)
 5         {
 6             if (id <= 0)
 7                 return "";
 8             var dptid = this.Get(p => p.ID == id).DPTID;
 9             return this.DepartmentManage.Get(p => p.ID == dptid).NAME;
10         }
View Code

 

3、權限去重,很是重要

 1  /// <summary>
 2     /// 權限去重,很是重要
 3     /// add yuangang by 2015-08-03
 4     /// </summary>
 5     public class PermissionDistinct : IEqualityComparer<Domain.SYS_PERMISSION>
 6     {
 7         public bool Equals(Domain.SYS_PERMISSION x, Domain.SYS_PERMISSION y)
 8         {
 9             return x.ID == y.ID;
10         }
11 
12         public int GetHashCode(Domain.SYS_PERMISSION obj)
13         {
14             return obj.ToString().GetHashCode();
15         }
16     }
View Code

 

須要的幫助類:【C#公共幫助類】 WebHelper幫助類

 

原創文章 轉載請尊重勞動成果 http://yuangang.cnblogs.com

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息