From 7ad51a6ecd2f923de7fc1f046736a4383c5e64b8 Mon Sep 17 00:00:00 2001 From: Argo-MacBookPro Date: Sun, 21 Oct 2018 10:02:59 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=E5=B7=A5=E7=A8=8B=EF=BC=9A?= =?UTF-8?q?=E5=88=A0=E9=99=A4Bootstrap.DataAccess.SQLServer=E5=B7=A5?= =?UTF-8?q?=E7=A8=8B=EF=BC=8C=E7=A7=BB=E5=8A=A8=E4=BB=A3=E7=A0=81=E5=88=B0?= =?UTF-8?q?=E7=88=B6=E7=B1=BBBootstrap.DataAccess=E7=B1=BB=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Bootstrap.Admin/Bootstrap.Admin.csproj | 1 - Bootstrap.Admin/appsettings.json | 2 +- .../Bootstrap.DataAccess.SQLServer.csproj | 17 - Bootstrap.DataAccess.SQLServer/Dict.cs | 168 ------- Bootstrap.DataAccess.SQLServer/Exceptions.cs | 95 ---- Bootstrap.DataAccess.SQLServer/Group.cs | 238 ---------- Bootstrap.DataAccess.SQLServer/Log.cs | 86 ---- Bootstrap.DataAccess.SQLServer/Menu.cs | 169 ------- Bootstrap.DataAccess.SQLServer/Message.cs | 114 ----- Bootstrap.DataAccess.SQLServer/Role.cs | 318 ------------- Bootstrap.DataAccess.SQLServer/Task.cs | 43 -- Bootstrap.DataAccess.SQLServer/User.cs | 421 ------------------ Bootstrap.DataAccess.SQLite/Group.cs | 2 +- Bootstrap.DataAccess.SQLite/Log.cs | 2 +- Bootstrap.DataAccess/Dict.cs | 121 ++++- Bootstrap.DataAccess/Exceptions.cs | 74 ++- Bootstrap.DataAccess/Group.cs | 194 +++++++- Bootstrap.DataAccess/Log.cs | 74 ++- Bootstrap.DataAccess/Menu.cs | 108 ++++- Bootstrap.DataAccess/Message.cs | 85 +++- Bootstrap.DataAccess/Role.cs | 266 ++++++++++- Bootstrap.DataAccess/Task.cs | 33 +- Bootstrap.DataAccess/User.cs | 402 +++++++++++++++-- BootstrapAdmin.sln | 6 - 24 files changed, 1263 insertions(+), 1776 deletions(-) delete mode 100644 Bootstrap.DataAccess.SQLServer/Bootstrap.DataAccess.SQLServer.csproj delete mode 100644 Bootstrap.DataAccess.SQLServer/Dict.cs delete mode 100644 Bootstrap.DataAccess.SQLServer/Exceptions.cs delete mode 100644 Bootstrap.DataAccess.SQLServer/Group.cs delete mode 100644 Bootstrap.DataAccess.SQLServer/Log.cs delete mode 100644 Bootstrap.DataAccess.SQLServer/Menu.cs delete mode 100644 Bootstrap.DataAccess.SQLServer/Message.cs delete mode 100644 Bootstrap.DataAccess.SQLServer/Role.cs delete mode 100644 Bootstrap.DataAccess.SQLServer/Task.cs delete mode 100644 Bootstrap.DataAccess.SQLServer/User.cs diff --git a/Bootstrap.Admin/Bootstrap.Admin.csproj b/Bootstrap.Admin/Bootstrap.Admin.csproj index b073db5d..4192c346 100644 --- a/Bootstrap.Admin/Bootstrap.Admin.csproj +++ b/Bootstrap.Admin/Bootstrap.Admin.csproj @@ -21,7 +21,6 @@ - diff --git a/Bootstrap.Admin/appsettings.json b/Bootstrap.Admin/appsettings.json index 5e38e0ab..ec8984e0 100644 --- a/Bootstrap.Admin/appsettings.json +++ b/Bootstrap.Admin/appsettings.json @@ -18,7 +18,7 @@ "DB": [ { "Enabled": false, - "Widget": "Bootstrap.DataAccess.SQLServer" + "Widget": "Bootstrap.DataAccess" }, { "Enabled": true, diff --git a/Bootstrap.DataAccess.SQLServer/Bootstrap.DataAccess.SQLServer.csproj b/Bootstrap.DataAccess.SQLServer/Bootstrap.DataAccess.SQLServer.csproj deleted file mode 100644 index ccd3dd38..00000000 --- a/Bootstrap.DataAccess.SQLServer/Bootstrap.DataAccess.SQLServer.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - netstandard2.0 - - - - - - - - - - - - - diff --git a/Bootstrap.DataAccess.SQLServer/Dict.cs b/Bootstrap.DataAccess.SQLServer/Dict.cs deleted file mode 100644 index 2cb95d6a..00000000 --- a/Bootstrap.DataAccess.SQLServer/Dict.cs +++ /dev/null @@ -1,168 +0,0 @@ -using Bootstrap.Security; -using Longbow.Cache; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Globalization; -using System.Linq; - -namespace Bootstrap.DataAccess.SQLServer -{ - /// - /// - /// - public class Dict : DataAccess.Dict - { - /// - /// 删除字典中的数据 - /// - /// 需要删除的IDs - /// - public override bool DeleteDict(IEnumerable value) - { - var ret = false; - var ids = string.Join(",", value); - string sql = string.Format(CultureInfo.InvariantCulture, "Delete from Dicts where ID in ({0})", ids); - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == value.Count(); - CacheCleanUtility.ClearCache(dictIds: ids); - } - return ret; - } - - /// - /// 保存新建/更新的字典信息 - /// - /// - /// - public override bool SaveDict(BootstrapDict dict) - { - bool ret = false; - if (dict.Category.Length > 50) dict.Category = dict.Category.Substring(0, 50); - if (dict.Name.Length > 50) dict.Name = dict.Name.Substring(0, 50); - if (dict.Code.Length > 50) dict.Code = dict.Code.Substring(0, 50); - string sql = dict.Id == 0 ? - "Insert Into Dicts (Category, Name, Code ,Define) Values (@Category, @Name, @Code, @Define)" : - "Update Dicts set Category = @Category, Name = @Name, Code = @Code, Define = @Define where ID = @ID"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ID", dict.Id)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Category", dict.Category)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Name", dict.Name)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Code", dict.Code)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Define", dict.Define)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - } - CacheCleanUtility.ClearCache(dictIds: dict.Id == 0 ? string.Empty : dict.Id.ToString()); - return ret; - } - /// - /// 保存网站个性化设置 - /// - /// - /// - /// - /// - public override bool SaveSettings(BootstrapDict dict) - { - var ret = false; - string sql = "Update Dicts set Code = @Code where Category = @Category and Name = @Name"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Name", dict.Name)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Code", dict.Code)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Category", dict.Category)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - } - CacheCleanUtility.ClearCache(dictIds: string.Empty); - return ret; - } - /// - /// 获取字典分类名称 - /// - /// - public override IEnumerable RetrieveCategories() - { - return CacheManager.GetOrAdd(RetrieveCategoryDataKey, key => - { - var ret = new List(); - string sql = "select distinct Category from Dicts"; - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - ret.Add((string)reader[0]); - } - } - return ret; - }); - } - /// - /// - /// - /// - public override string RetrieveWebTitle() - { - var settings = RetrieveDicts(); - return (settings.FirstOrDefault(d => d.Name == "网站标题" && d.Category == "网站设置" && d.Define == 0) ?? new BootstrapDict() { Code = "后台管理系统" }).Code; - } - /// - /// - /// - /// - public override string RetrieveWebFooter() - { - var settings = RetrieveDicts(); - return (settings.FirstOrDefault(d => d.Name == "网站页脚" && d.Category == "网站设置" && d.Define == 0) ?? new BootstrapDict() { Code = "2016 © 通用后台管理系统" }).Code; - } - /// - /// 获得系统中配置的可以使用的网站样式 - /// - /// - public override IEnumerable RetrieveThemes() - { - var data = RetrieveDicts(); - return data.Where(d => d.Category == "网站样式"); - } - /// - /// 获得网站设置中的当前样式 - /// - /// - public override string RetrieveActiveTheme() - { - var data = RetrieveDicts(); - var theme = data.Where(d => d.Name == "使用样式" && d.Category == "当前样式" && d.Define == 0).FirstOrDefault(); - return theme == null ? string.Empty : (theme.Code.Equals("site.css", StringComparison.OrdinalIgnoreCase) ? string.Empty : theme.Code); - } - /// - /// 获取头像路径 - /// - /// - public override BootstrapDict RetrieveIconFolderPath() - { - var data = RetrieveDicts(); - return data.FirstOrDefault(d => d.Name == "头像路径" && d.Category == "头像地址" && d.Define == 0) ?? new BootstrapDict() { Code = "~/images/uploader/" }; - } - /// - /// 获得默认的前台首页地址,默认为~/Home/Index - /// - /// - public override string RetrieveHomeUrl() - { - var settings = RetrieveDicts(); - return (settings.FirstOrDefault(d => d.Name == "前台首页" && d.Category == "网站设置" && d.Define == 0) ?? new BootstrapDict() { Code = "~/Home/Index" }).Code; - } - /// - /// - /// - /// - public override IEnumerable> RetrieveApps() - { - var settings = RetrieveDicts(); - return settings.Where(d => d.Category == "应用程序" && d.Define == 0).Select(d => new KeyValuePair(d.Code, d.Name)).OrderBy(d => d.Key); - } - } -} diff --git a/Bootstrap.DataAccess.SQLServer/Exceptions.cs b/Bootstrap.DataAccess.SQLServer/Exceptions.cs deleted file mode 100644 index 4874a82d..00000000 --- a/Bootstrap.DataAccess.SQLServer/Exceptions.cs +++ /dev/null @@ -1,95 +0,0 @@ -using Longbow.Cache; -using Longbow.Configuration; -using Longbow.Data; -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.Data; -using System.Data.Common; - -namespace Bootstrap.DataAccess.SQLServer -{ - /// - /// - /// - public class Exceptions : Bootstrap.DataAccess.Exceptions - { - /// - /// - /// - /// - /// - /// - public override void Log(Exception ex, NameValueCollection additionalInfo) - { - if (additionalInfo == null) - { - additionalInfo = new NameValueCollection - { - ["UserId"] = null, - ["UserIp"] = null, - ["ErrorPage"] = null - }; - } - var errorPage = additionalInfo["ErrorPage"] ?? (nameof(ex).Length > 50 ? nameof(ex).Substring(0, 50) : nameof(ex)); - var sql = "insert into Exceptions (AppDomainName, ErrorPage, UserID, UserIp, ExceptionType, Message, StackTrace, LogTime) values (@AppDomainName, @ErrorPage, @UserID, @UserIp, @ExceptionType, @Message, @StackTrace, GetDate())"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@AppDomainName", AppDomain.CurrentDomain.FriendlyName)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ErrorPage", errorPage)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", DbAccessFactory.ToDBValue(additionalInfo["UserId"]))); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserIp", DbAccessFactory.ToDBValue(additionalInfo["UserIp"]))); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ExceptionType", ex.GetType().FullName)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Message", ex.Message)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@StackTrace", DbAccessFactory.ToDBValue(ex.StackTrace))); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd); - CacheManager.Clear(RetrieveExceptionsDataKey); - ClearExceptions(); - } - } - /// - /// - /// - private static void ClearExceptions() - { - System.Threading.Tasks.Task.Run(() => - { - string sql = $"delete from Exceptions where LogTime < DATEADD(MONTH, -{ConfigurationManager.AppSettings["KeepExceptionsPeriod"]}, GETDATE())"; - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd); - }); - } - /// - /// 查询一周内所有异常 - /// - /// - public override IEnumerable RetrieveExceptions() - { - return CacheManager.GetOrAdd(RetrieveExceptionsDataKey, key => - { - string sql = "select * from Exceptions where DATEDIFF(Week, LogTime, GETDATE()) = 0 order by LogTime desc"; - List exceptions = new List(); - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - exceptions.Add(new Exceptions() - { - Id = (int)reader[0], - AppDomainName = (string)reader[1], - ErrorPage = reader.IsDBNull(2) ? string.Empty : (string)reader[2], - UserId = reader.IsDBNull(3) ? string.Empty : (string)reader[3], - UserIp = reader.IsDBNull(4) ? string.Empty : (string)reader[4], - ExceptionType = (string)reader[5], - Message = (string)reader[6], - StackTrace = (string)reader[7], - LogTime = (DateTime)reader[8], - }); - } - } - return exceptions; - }); - } - } -} diff --git a/Bootstrap.DataAccess.SQLServer/Group.cs b/Bootstrap.DataAccess.SQLServer/Group.cs deleted file mode 100644 index 4ce9bf71..00000000 --- a/Bootstrap.DataAccess.SQLServer/Group.cs +++ /dev/null @@ -1,238 +0,0 @@ -using Longbow.Cache; -using Longbow.Data; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; - -namespace Bootstrap.DataAccess.SQLServer -{ - /// - /// - /// - public class Group : Bootstrap.DataAccess.Group - { - /// - /// 查询所有群组信息 - /// - /// - /// - public override IEnumerable RetrieveGroups(int id = 0) - { - var ret = CacheManager.GetOrAdd(RetrieveGroupsDataKey, key => - { - string sql = "select * from Groups"; - List groups = new List(); - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - groups.Add(new Group() - { - Id = (int)reader[0], - GroupName = (string)reader[1], - Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2] - }); - } - } - return groups; - }); - return id == 0 ? ret : ret.Where(t => id == t.Id); - } - /// - /// 删除群组信息 - /// - /// - public override bool DeleteGroup(IEnumerable value) - { - bool ret = false; - var ids = string.Join(",", value); - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_DeleteGroups")) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ids", ids)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; - } - CacheCleanUtility.ClearCache(groupIds: value); - return ret; - } - /// - /// 保存新建/更新的群组信息 - /// - /// - /// - public override bool SaveGroup(Bootstrap.DataAccess.Group p) - { - bool ret = false; - if (p.GroupName.Length > 50) p.GroupName = p.GroupName.Substring(0, 50); - if (!string.IsNullOrEmpty(p.Description) && p.Description.Length > 500) p.Description = p.Description.Substring(0, 500); - string sql = p.Id == 0 ? - "Insert Into Groups (GroupName, Description) Values (@GroupName, @Description)" : - "Update Groups set GroupName = @GroupName, Description = @Description where ID = @ID"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ID", p.Id)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@GroupName", p.GroupName)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Description", DbAccessFactory.ToDBValue(p.Description))); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - } - CacheCleanUtility.ClearCache(groupIds: p.Id == 0 ? new List() : new List() { p.Id }); - return ret; - } - /// - /// 根据用户查询部门信息 - /// - /// - /// - public override IEnumerable RetrieveGroupsByUserId(int userId) - { - string key = string.Format("{0}-{1}", RetrieveGroupsByUserIdDataKey, userId); - var ret = CacheManager.GetOrAdd(key, k => - { - string sql = "select g.ID,g.GroupName,g.[Description],case ug.GroupID when g.ID then 'checked' else '' end [status] from Groups g left join UserGroup ug on g.ID=ug.GroupID and UserID=@UserID"; - List groups = new List(); - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", userId)); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - groups.Add(new Group() - { - Id = (int)reader[0], - GroupName = (string)reader[1], - Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2], - Checked = (string)reader[3] - }); - } - } - return groups; - }, RetrieveGroupsByUserIdDataKey); - return ret; - } - /// - /// 保存用户部门关系 - /// - /// - /// - /// - public override bool SaveGroupsByUserId(int id, IEnumerable groupIds) - { - var ret = false; - DataTable dt = new DataTable(); - dt.Columns.Add("UserID", typeof(int)); - dt.Columns.Add("GroupID", typeof(int)); - //判断用户是否选定角色 - groupIds.ToList().ForEach(groupId => dt.Rows.Add(id, groupId)); - using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) - { - try - { - //删除用户部门表中该用户所有的部门关系 - string sql = "delete from UserGroup where UserID=@UserID;"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", id)); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); - - // insert batch data into config table - using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) - { - bulk.BatchSize = 1000; - bulk.DestinationTableName = "UserGroup"; - bulk.ColumnMappings.Add("UserID", "UserID"); - bulk.ColumnMappings.Add("GroupID", "GroupID"); - bulk.WriteToServer(dt); - transaction.CommitTransaction(); - } - } - CacheCleanUtility.ClearCache(groupIds: groupIds, userIds: new List() { id }); - ret = true; - } - catch (Exception ex) - { - transaction.RollbackTransaction(); - throw ex; - } - } - return ret; - } - /// - /// 根据角色ID指派部门 - /// - /// - /// - public override IEnumerable RetrieveGroupsByRoleId(int roleId) - { - string k = string.Format("{0}-{1}", RetrieveGroupsByRoleIdDataKey, roleId); - return CacheManager.GetOrAdd(k, key => - { - List groups = new List(); - string sql = "select g.ID,g.GroupName,g.[Description],case rg.GroupID when g.ID then 'checked' else '' end [status] from Groups g left join RoleGroup rg on g.ID=rg.GroupID and RoleID=@RoleID"; - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", roleId)); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - groups.Add(new Group() - { - Id = (int)reader[0], - GroupName = (string)reader[1], - Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2], - Checked = (string)reader[3] - }); - } - } - return groups; - }, RetrieveGroupsByRoleIdDataKey); - } - /// - /// 根据角色ID以及选定的部门ID,保到角色部门表 - /// - /// - /// - /// - public override bool SaveGroupsByRoleId(int id, IEnumerable groupIds) - { - bool ret = false; - DataTable dt = new DataTable(); - dt.Columns.Add("GroupID", typeof(int)); - dt.Columns.Add("RoleID", typeof(int)); - groupIds.ToList().ForEach(groupId => dt.Rows.Add(groupId, id)); - using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) - { - try - { - //删除角色部门表该角色所有的部门 - string sql = "delete from RoleGroup where RoleID=@RoleID"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", id)); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); - //批插入角色部门表 - using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) - { - bulk.BatchSize = 1000; - bulk.ColumnMappings.Add("GroupID", "GroupID"); - bulk.ColumnMappings.Add("RoleID", "RoleID"); - bulk.DestinationTableName = "RoleGroup"; - bulk.WriteToServer(dt); - transaction.CommitTransaction(); - } - } - CacheCleanUtility.ClearCache(groupIds: groupIds, roleIds: new List() { id }); - ret = true; - } - catch (Exception ex) - { - transaction.RollbackTransaction(); - throw ex; - } - } - return ret; - } - } -} diff --git a/Bootstrap.DataAccess.SQLServer/Log.cs b/Bootstrap.DataAccess.SQLServer/Log.cs deleted file mode 100644 index 45392fed..00000000 --- a/Bootstrap.DataAccess.SQLServer/Log.cs +++ /dev/null @@ -1,86 +0,0 @@ -using Longbow.Cache; -using Longbow.Configuration; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Linq; - -namespace Bootstrap.DataAccess.SQLServer -{ - /// - /// - /// - public class Log : Bootstrap.DataAccess.Log - { - /// - /// 查询所有日志信息 - /// - /// - /// - public override IEnumerable RetrieveLogs(string tId = null) - { - var ret = CacheManager.GetOrAdd(RetrieveLogsDataKey, key => - { - string sql = "select * from Logs where DATEDIFF(Week, LogTime, GETDATE()) = 0"; - List logs = new List(); - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - logs.Add(new Log() - { - Id = (int)reader[0], - CRUD = (string)reader[1], - UserName = (string)reader[2], - LogTime = (DateTime)reader[3], - ClientIp = (string)reader[4], - ClientAgent = (string)reader[5], - RequestUrl = (string)reader[6] - }); - } - } - return logs; - }); - return string.IsNullOrEmpty(tId) ? ret : ret.Where(t => tId.Equals(t.Id.ToString(), StringComparison.OrdinalIgnoreCase)); - } - /// - /// 删除日志信息 - /// - /// - /// - private void DeleteLogAsync() - { - System.Threading.Tasks.Task.Run(() => - { - string sql = $"delete from Logs where LogTime < DATEADD(MONTH, -{ConfigurationManager.AppSettings["KeepLogsPeriod"]}, GETDATE())"; - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd); - }); - } - /// - /// 保存新增的日志信息 - /// - /// - /// - public override bool SaveLog(Bootstrap.DataAccess.Log p) - { - if (p == null) throw new ArgumentNullException("p"); - bool ret = false; - string sql = "Insert Into Logs (CRUD, UserName, LogTime, ClientIp, ClientAgent, RequestUrl) Values (@CRUD, @UserName, GetDate(), @ClientIp, @ClientAgent, @RequestUrl)"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@CRUD", p.CRUD)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserName", p.UserName)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ClientIp", p.ClientIp)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ClientAgent", p.ClientAgent)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RequestUrl", p.RequestUrl)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - } - CacheManager.Clear(RetrieveLogsDataKey); - DeleteLogAsync(); - return ret; - } - } -} diff --git a/Bootstrap.DataAccess.SQLServer/Menu.cs b/Bootstrap.DataAccess.SQLServer/Menu.cs deleted file mode 100644 index 36f1c226..00000000 --- a/Bootstrap.DataAccess.SQLServer/Menu.cs +++ /dev/null @@ -1,169 +0,0 @@ -using Bootstrap.Security; -using Longbow.Cache; -using Longbow.Data; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; - -namespace Bootstrap.DataAccess.SQLServer -{ - /// - /// - /// - public class Menu : Bootstrap.DataAccess.Menu - { - /// - /// 删除菜单信息 - /// - /// - public override bool DeleteMenu(IEnumerable value) - { - bool ret = false; - var ids = string.Join(",", value); - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_DeleteMenus")) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ids", ids)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; - } - CacheCleanUtility.ClearCache(menuIds: value); - return ret; - } - /// - /// 保存新建/更新的菜单信息 - /// - /// - /// - public override bool SaveMenu(BootstrapMenu p) - { - if (string.IsNullOrEmpty(p.Name)) return false; - bool ret = false; - if (p.Name.Length > 50) p.Name = p.Name.Substring(0, 50); - if (p.Icon != null && p.Icon.Length > 50) p.Icon = p.Icon.Substring(0, 50); - if (p.Url != null && p.Url.Length > 4000) p.Url = p.Url.Substring(0, 4000); - string sql = p.Id == 0 ? - "Insert Into Navigations (ParentId, Name, [Order], Icon, Url, Category, Target, IsResource, [Application]) Values (@ParentId, @Name, @Order, @Icon, @Url, @Category, @Target, @IsResource, @ApplicationCode)" : - "Update Navigations set ParentId = @ParentId, Name = @Name, [Order] = @Order, Icon = @Icon, Url = @Url, Category = @Category, Target = @Target, IsResource = @IsResource, Application = @ApplicationCode where ID = @ID"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ID", p.Id)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ParentId", p.ParentId)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Name", p.Name)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Order", p.Order)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Icon", DbAccessFactory.ToDBValue(p.Icon))); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Url", DbAccessFactory.ToDBValue(p.Url))); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Category", p.Category)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Target", p.Target)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@IsResource", p.IsResource)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ApplicationCode", p.ApplicationCode)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - } - CacheCleanUtility.ClearCache(menuIds: p.Id == 0 ? new List() : new List() { p.Id }); - return ret; - } - - /// - /// 查询某个角色所配置的菜单 - /// - /// - /// - public override IEnumerable RetrieveMenusByRoleId(int roleId) - { - string key = string.Format("{0}-{1}", RetrieveMenusByRoleIdDataKey, roleId); - return CacheManager.GetOrAdd(key, k => - { - var menus = new List(); - string sql = "select NavigationID from NavigationRole where RoleID = @RoleID"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", roleId)); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - menus.Add(new BootstrapMenu() - { - Id = (int)reader[0] - }); - } - } - } - return menus; - }, RetrieveMenusByRoleIdDataKey); - } - /// - /// 通过角色ID保存当前授权菜单 - /// - /// - /// - /// - public override bool SaveMenusByRoleId(int id, IEnumerable menuIds) - { - bool ret = false; - DataTable dt = new DataTable(); - dt.Columns.Add("RoleID", typeof(int)); - dt.Columns.Add("NavigationID", typeof(int)); - menuIds.ToList().ForEach(menuId => dt.Rows.Add(id, menuId)); - using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) - { - try - { - //删除菜单角色表该角色所有的菜单 - string sql = "delete from NavigationRole where RoleID=@RoleID"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", id)); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); - //批插入菜单角色表 - using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) - { - bulk.DestinationTableName = "NavigationRole"; - bulk.ColumnMappings.Add("RoleID", "RoleID"); - bulk.ColumnMappings.Add("NavigationID", "NavigationID"); - bulk.WriteToServer(dt); - transaction.CommitTransaction(); - } - } - CacheCleanUtility.ClearCache(menuIds: menuIds, roleIds: new List() { id }); - ret = true; - } - catch (Exception ex) - { - transaction.RollbackTransaction(); - throw ex; - } - } - return ret; - } - ///// - ///// - ///// - ///// - ///// - ///// - //public override IEnumerable RetrieveAllMenus(string userName, string activeUrl = null) => RetrieveAllMenus(DBAccessManager.DBAccess, userName, activeUrl); - ///// - ///// - ///// - ///// - ///// - ///// - //public override IEnumerable RetrieveAppMenus(string userName, string activeUrl = null) => RetrieveAppMenus(DBAccessManager.DBAccess, userName, activeUrl); - ///// - ///// - ///// - ///// - ///// - ///// - //public override IEnumerable RetrieveMenusByUserName(string userName, string activeUrl = null) => RetrieveMenusByUserName(DBAccessManager.DBAccess, userName, activeUrl); - ///// - ///// - ///// - ///// - ///// - ///// - //public override IEnumerable RetrieveSystemMenus(string userName, string activeUrl = null) => RetrieveSystemMenus(DBAccessManager.DBAccess, userName, activeUrl); - } -} diff --git a/Bootstrap.DataAccess.SQLServer/Message.cs b/Bootstrap.DataAccess.SQLServer/Message.cs deleted file mode 100644 index 676ea8f7..00000000 --- a/Bootstrap.DataAccess.SQLServer/Message.cs +++ /dev/null @@ -1,114 +0,0 @@ -using Longbow; -using Longbow.Cache; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Linq; - -namespace Bootstrap.DataAccess.SQLServer -{ - /// - /// - /// - public class Message : Bootstrap.DataAccess.Message - { - /// - /// 所有有关userName所有消息列表 - /// - /// - /// - private static IEnumerable RetrieveMessages(string userName) - { - var messageRet = CacheManager.GetOrAdd(RetrieveMessageDataKey, key => - { - string sql = "select m.*, d.Name, isnull(i.Code + u.Icon, '~/images/uploader/default.jpg'), u.DisplayName from [Messages] m left join Dicts d on m.Label = d.Code and d.Category = N'消息标签' and d.Define = 0 left join Dicts i on i.Category = N'头像地址' and i.Name = N'头像路径' and i.Define = 0 inner join Users u on m.[From] = u.UserName where [To] = @UserName or [From] = @UserName order by m.SendTime desc"; - List messages = new List(); - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserName", userName)); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - messages.Add(new Message() - { - Id = (int)reader[0], - Title = (string)reader[1], - Content = (string)reader[2], - From = (string)reader[3], - To = (string)reader[4], - SendTime = LgbConvert.ReadValue(reader[5], DateTime.MinValue), - Status = (string)reader[6], - Mark = (int)reader[7], - IsDelete = (int)reader[8], - Label = (string)reader[9], - LabelName = LgbConvert.ReadValue(reader[10], string.Empty), - FromIcon = (string)reader[11], - FromDisplayName = (string)reader[12] - }); - } - } - return messages; - - }); - return messageRet.OrderByDescending(n => n.SendTime); - } - /// - /// 收件箱 - /// - /// - public override IEnumerable Inbox(string userName) - { - var messageRet = RetrieveMessages(userName); - return messageRet.Where(n => n.To.Equals(userName, StringComparison.OrdinalIgnoreCase)); - } - /// - /// 发件箱 - /// - /// - /// - public override IEnumerable SendMail(string userName) - { - var messageRet = RetrieveMessages(userName); - return messageRet.Where(n => n.From.Equals(userName, StringComparison.OrdinalIgnoreCase)); - } - /// - /// 垃圾箱 - /// - /// - /// - public override IEnumerable Trash(string userName) - { - var messageRet = RetrieveMessages(userName); - return messageRet.Where(n => n.IsDelete == 1); - } - /// - /// 标旗 - /// - /// - /// - public override IEnumerable Flag(string userName) - { - var messageRet = RetrieveMessages(userName); - return messageRet.Where(n => n.Mark == 1); - } - /// - /// 获取Header处显示的消息列表 - /// - /// - /// - public override IEnumerable RetrieveMessagesHeader(string userName) - { - var messageRet = Inbox(userName); - messageRet.AsParallel().ForAll(n => - { - var ts = DateTime.Now - n.SendTime; - if (ts.TotalMinutes < 5) n.Period = "刚刚"; - else if (ts.Days > 0) n.Period = string.Format("{0}天", ts.Days); - else if (ts.Hours > 0) n.Period = string.Format("{0}小时", ts.Hours); - else if (ts.Minutes > 0) n.Period = string.Format("{0}分钟", ts.Minutes); - }); - return messageRet; - } - } -} diff --git a/Bootstrap.DataAccess.SQLServer/Role.cs b/Bootstrap.DataAccess.SQLServer/Role.cs deleted file mode 100644 index be025aa6..00000000 --- a/Bootstrap.DataAccess.SQLServer/Role.cs +++ /dev/null @@ -1,318 +0,0 @@ -using Longbow.Cache; -using Longbow.Data; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; - -namespace Bootstrap.DataAccess.SQLServer -{ - /// - /// - /// - public class Role : Bootstrap.DataAccess.Role - { - /// - /// 查询所有角色 - /// - /// - /// - public override IEnumerable RetrieveRoles(int id = 0) - { - var ret = CacheManager.GetOrAdd(RetrieveRolesDataKey, key => - { - string sql = "select * from Roles"; - var roles = new List(); - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - roles.Add(new Role() - { - Id = (int)reader[0], - RoleName = (string)reader[1], - Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2] - }); - } - } - return roles; - }); - return id == 0 ? ret : ret.Where(t => id == t.Id); - } - /// - /// 保存用户角色关系 - /// - /// - /// - /// - public override bool SaveRolesByUserId(int id, IEnumerable roleIds) - { - var ret = false; - DataTable dt = new DataTable(); - dt.Columns.Add("UserID", typeof(int)); - dt.Columns.Add("RoleID", typeof(int)); - //判断用户是否选定角色 - roleIds.ToList().ForEach(roleId => dt.Rows.Add(id, roleId)); - using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) - { - try - { - // delete user from config table - string sql = "delete from UserRole where UserID = @UserID;"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", id)); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); - if (dt.Rows.Count > 0) - { - // insert batch data into config table - using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) - { - bulk.DestinationTableName = "UserRole"; - bulk.ColumnMappings.Add("UserID", "UserID"); - bulk.ColumnMappings.Add("RoleID", "RoleID"); - bulk.WriteToServer(dt); - } - } - transaction.CommitTransaction(); - } - CacheCleanUtility.ClearCache(userIds: new List() { id }, roleIds: roleIds); - ret = true; - } - catch (Exception ex) - { - transaction.RollbackTransaction(); - throw ex; - } - } - return ret; - } - /// - /// 查询某个用户所拥有的角色 - /// - /// - public override IEnumerable RetrieveRolesByUserId(int userId) - { - string key = string.Format("{0}-{1}", RetrieveRolesByUserIdDataKey, userId); - return CacheManager.GetOrAdd(key, k => - { - List roles = new List(); - string sql = "select r.ID, r.RoleName, r.[Description], case ur.RoleID when r.ID then 'checked' else '' end [status] from Roles r left join UserRole ur on r.ID = ur.RoleID and UserID = @UserID"; - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", userId)); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - roles.Add(new Role() - { - Id = (int)reader[0], - RoleName = (string)reader[1], - Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2], - Checked = (string)reader[3] - }); - } - } - return roles; - }, RetrieveRolesByUserIdDataKey); - } - /// - /// 删除角色表 - /// - /// - public override bool DeleteRole(IEnumerable value) - { - bool ret = false; - var ids = string.Join(",", value); - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_DeleteRoles")) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ids", ids)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; - } - CacheCleanUtility.ClearCache(roleIds: value); - return ret; - } - /// - /// 保存新建/更新的角色信息 - /// - /// - /// - public override bool SaveRole(Bootstrap.DataAccess.Role p) - { - bool ret = false; - if (!string.IsNullOrEmpty(p.RoleName) && p.RoleName.Length > 50) p.RoleName = p.RoleName.Substring(0, 50); - if (!string.IsNullOrEmpty(p.Description) && p.Description.Length > 50) p.Description = p.Description.Substring(0, 500); - string sql = p.Id == 0 ? - "Insert Into Roles (RoleName, Description) Values (@RoleName, @Description)" : - "Update Roles set RoleName = @RoleName, Description = @Description where ID = @ID"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ID", p.Id)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleName", p.RoleName)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Description", DbAccessFactory.ToDBValue(p.Description))); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - } - CacheCleanUtility.ClearCache(roleIds: p.Id == 0 ? new List() : new List { p.Id }); - return ret; - } - /// - /// 查询某个菜单所拥有的角色 - /// - /// - /// - public override IEnumerable RetrieveRolesByMenuId(int menuId) - { - string key = string.Format("{0}-{1}", RetrieveRolesByMenuIdDataKey, menuId); - var ret = CacheManager.GetOrAdd(key, k => - { - string sql = "select r.ID, r.RoleName, r.[Description], case ur.RoleID when r.ID then 'checked' else '' end [status] from Roles r left join NavigationRole ur on r.ID = ur.RoleID and NavigationID = @NavigationID"; - List roles = new List(); - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@NavigationID", menuId)); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - roles.Add(new Role() - { - Id = (int)reader[0], - RoleName = (string)reader[1], - Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2], - Checked = (string)reader[3] - }); - } - } - return roles; - }, RetrieveRolesByMenuIdDataKey); - return ret; - } - /// - /// - /// - /// - /// - /// - public override bool SavaRolesByMenuId(int id, IEnumerable roleIds) - { - var ret = false; - DataTable dt = new DataTable(); - dt.Columns.Add("NavigationID", typeof(int)); - dt.Columns.Add("RoleID", typeof(int)); - //判断用户是否选定角色 - roleIds.ToList().ForEach(roleId => dt.Rows.Add(id, roleId)); - using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) - { - try - { - // delete role from config table - string sql = "delete from NavigationRole where NavigationID=@NavigationID;"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@NavigationID", id)); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); - - // insert batch data into config table - using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) - { - bulk.BatchSize = 1000; - bulk.DestinationTableName = "NavigationRole"; - bulk.ColumnMappings.Add("NavigationID", "NavigationID"); - bulk.ColumnMappings.Add("RoleID", "RoleID"); - bulk.WriteToServer(dt); - transaction.CommitTransaction(); - } - } - CacheCleanUtility.ClearCache(roleIds: roleIds, menuIds: new List() { id }); - ret = true; - } - catch (Exception ex) - { - transaction.RollbackTransaction(); - throw ex; - } - } - return ret; - } - /// - /// 根据GroupId查询和该Group有关的所有Roles - /// - /// - /// - public override IEnumerable RetrieveRolesByGroupId(int groupId) - { - string key = string.Format("{0}-{1}", RetrieveRolesByGroupIdDataKey, groupId); - return CacheManager.GetOrAdd(key, k => - { - List roles = new List(); - string sql = "select r.ID, r.RoleName, r.[Description], case ur.RoleID when r.ID then 'checked' else '' end [status] from Roles r left join RoleGroup ur on r.ID = ur.RoleID and GroupID = @GroupID"; - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@GroupID", groupId)); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - roles.Add(new Role() - { - Id = (int)reader[0], - RoleName = (string)reader[1], - Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2], - Checked = (string)reader[3] - }); - } - } - return roles; - }, RetrieveRolesByGroupIdDataKey); - } - - /// - /// 根据GroupId更新Roles信息,删除旧的Roles信息,插入新的Roles信息 - /// - /// - /// - /// - public override bool SaveRolesByGroupId(int id, IEnumerable roleIds) - { - var ret = false; - //构造表格 - DataTable dt = new DataTable(); - dt.Columns.Add("RoleID", typeof(int)); - dt.Columns.Add("GroupID", typeof(int)); - roleIds.ToList().ForEach(roleId => dt.Rows.Add(roleId, id)); - using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) - { - try - { - // delete user from config table - string sql = "delete from RoleGroup where GroupID=@GroupID"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@GroupID", id)); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); - - // insert batch data into config table - using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) - { - bulk.BatchSize = 1000; - bulk.DestinationTableName = "RoleGroup"; - bulk.ColumnMappings.Add("RoleID", "RoleID"); - bulk.ColumnMappings.Add("GroupID", "GroupID"); - bulk.WriteToServer(dt); - transaction.CommitTransaction(); - } - } - CacheCleanUtility.ClearCache(roleIds: roleIds, groupIds: new List() { id }); - ret = true; - } - catch (Exception ex) - { - transaction.RollbackTransaction(); - throw ex; - } - } - return ret; - } - } -} \ No newline at end of file diff --git a/Bootstrap.DataAccess.SQLServer/Task.cs b/Bootstrap.DataAccess.SQLServer/Task.cs deleted file mode 100644 index f9656ec5..00000000 --- a/Bootstrap.DataAccess.SQLServer/Task.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Longbow.Cache; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; - -namespace Bootstrap.DataAccess.SQLServer -{ - public class Task : Bootstrap.DataAccess.Task - { - /// - /// 查询所有任务 - /// - /// - public override IEnumerable RetrieveTasks() - { - return CacheManager.GetOrAdd(RetrieveTasksDataKey, key => - { - string sql = "select top 1000 t.*, u.DisplayName from Tasks t inner join Users u on t.UserName = u.UserName order by AssignTime desc"; - List tasks = new List(); - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - tasks.Add(new Task() - { - Id = (int)reader[0], - TaskName = (string)reader[1], - AssignName = (string)reader[2], - UserName = (string)reader[3], - TaskTime = (int)reader[4], - TaskProgress = (double)reader[5], - AssignTime = (DateTime)reader[6], - AssignDisplayName = (string)reader[7] - }); - } - } - return tasks; - }); - } - } -} diff --git a/Bootstrap.DataAccess.SQLServer/User.cs b/Bootstrap.DataAccess.SQLServer/User.cs deleted file mode 100644 index 3e7a80b1..00000000 --- a/Bootstrap.DataAccess.SQLServer/User.cs +++ /dev/null @@ -1,421 +0,0 @@ -using Bootstrap.Security; -using Longbow; -using Longbow.Cache; -using Longbow.Data; -using Longbow.Security; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; - - -namespace Bootstrap.DataAccess.SQLServer -{ - /// - /// 用户表实体类 - /// - public class User : Bootstrap.DataAccess.User - { - /// - /// 查询所有用户 - /// - /// - /// - public override IEnumerable RetrieveUsers() - { - return CacheManager.GetOrAdd(RetrieveUsersDataKey, key => - { - List users = new List(); - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, "select ID, UserName, DisplayName, RegisterTime, ApprovedTime, ApprovedBy, Description from Users Where ApprovedTime is not null"); - - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - users.Add(new User() - { - Id = (int)reader[0], - UserName = (string)reader[1], - DisplayName = (string)reader[2], - RegisterTime = (DateTime)reader[3], - ApprovedTime = LgbConvert.ReadValue(reader[4], DateTime.MinValue), - ApprovedBy = reader.IsDBNull(5) ? string.Empty : (string)reader[5], - Description = (string)reader[6] - }); - } - } - return users; - }); - } - /// - /// 查询所有的新注册用户 - /// - /// - public override IEnumerable RetrieveNewUsers() - { - return CacheManager.GetOrAdd(RetrieveNewUsersDataKey, key => - { - string sql = "select ID, UserName, DisplayName, RegisterTime, [Description] from Users Where ApprovedTime is null order by RegisterTime desc"; - List users = new List(); - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - users.Add(new User() - { - Id = (int)reader[0], - UserName = (string)reader[1], - DisplayName = (string)reader[2], - RegisterTime = (DateTime)reader[3], - Description = (string)reader[4] - }); - } - } - return users; - }); - } - /// - /// 删除用户 - /// - /// - public override bool DeleteUser(IEnumerable value) - { - bool ret = false; - var ids = string.Join(",", value); - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_DeleteUsers")) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ids", ids)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; - if (ret) CacheCleanUtility.ClearCache(userIds: value); - } - return ret; - } - /// - /// 保存新建 - /// - /// - /// - public override bool SaveUser(Bootstrap.DataAccess.User p) - { - var ret = false; - if (p.Id == 0 && p.Description.Length > 500) p.Description = p.Description.Substring(0, 500); - if (p.UserName.Length > 50) p.UserName = p.UserName.Substring(0, 50); - p.PassSalt = LgbCryptography.GenerateSalt(); - p.Password = LgbCryptography.ComputeHash(p.Password, p.PassSalt); - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_SaveUsers")) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@userName", p.UserName)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@password", p.Password)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@passSalt", p.PassSalt)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@displayName", p.DisplayName)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@approvedBy", DbAccessFactory.ToDBValue(p.ApprovedBy))); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@description", p.Description)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; - if (ret) CacheCleanUtility.ClearCache(userIds: p.Id == 0 ? new List() : new List() { p.Id }); - } - return ret; - } - /// - /// - /// - /// - /// - /// - /// - public override bool UpdateUser(int id, string password, string displayName) - { - bool ret = false; - string sql = "Update Users set Password = @Password, PassSalt = @PassSalt, DisplayName = @DisplayName where ID = @id"; - var passSalt = LgbCryptography.GenerateSalt(); - var newPassword = LgbCryptography.ComputeHash(password, passSalt); - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@id", id)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@DisplayName", displayName)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Password", newPassword)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@PassSalt", passSalt)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - if (ret) CacheCleanUtility.ClearCache(userIds: id == 0 ? new List() : new List() { id }); - } - return ret; - } - /// - /// - /// - /// - /// - /// - public override bool ApproveUser(int id, string approvedBy) - { - var ret = false; - var sql = "update Users set ApprovedTime = GETDATE(), ApprovedBy = @approvedBy where ID = @id"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@id", id)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@approvedBy", approvedBy)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - if (ret) CacheCleanUtility.ClearCache(userIds: new List() { id }); - } - return ret; - } - /// - /// - /// - /// - /// - /// - /// - public override bool RejectUser(int id, string rejectBy) - { - var ret = false; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_RejectUsers")) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@id", id)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@rejectedBy", rejectBy)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@rejectedReason", "未填写")); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; - if (ret) CacheCleanUtility.ClearCache(userIds: new List() { id }); - } - return ret; - } - /// - /// 通过roleId获取所有用户 - /// - /// - /// - public override IEnumerable RetrieveUsersByRoleId(int roleId) - { - string key = string.Format("{0}-{1}", RetrieveUsersByRoleIdDataKey, roleId); - return CacheManager.GetOrAdd(key, k => - { - List users = new List(); - string sql = "select u.ID, u.UserName, u.DisplayName, case ur.UserID when u.ID then 'checked' else '' end [status] from Users u left join UserRole ur on u.ID = ur.UserID and RoleID = @RoleID where u.ApprovedTime is not null"; - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", roleId)); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - users.Add(new User() - { - Id = (int)reader[0], - UserName = (string)reader[1], - DisplayName = (string)reader[2], - Checked = (string)reader[3] - }); - } - } - return users; - }, RetrieveUsersByRoleIdDataKey); - } - /// - /// 通过角色ID保存当前授权用户(插入) - /// - /// 角色ID - /// 用户ID数组 - /// - public override bool SaveUsersByRoleId(int id, IEnumerable userIds) - { - bool ret = false; - DataTable dt = new DataTable(); - dt.Columns.Add("RoleID", typeof(int)); - dt.Columns.Add("UserID", typeof(int)); - userIds.ToList().ForEach(userId => dt.Rows.Add(id, userId)); - using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) - { - try - { - //删除用户角色表该角色所有的用户 - string sql = "delete from UserRole where RoleID=@RoleID"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", id)); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); - //批插入用户角色表 - using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) - { - bulk.DestinationTableName = "UserRole"; - bulk.ColumnMappings.Add("RoleID", "RoleID"); - bulk.ColumnMappings.Add("UserID", "UserID"); - bulk.WriteToServer(dt); - transaction.CommitTransaction(); - } - } - CacheCleanUtility.ClearCache(userIds: userIds, roleIds: new List() { id }); - ret = true; - } - catch (Exception ex) - { - transaction.RollbackTransaction(); - throw ex; - } - } - return ret; - } - /// - /// 通过groupId获取所有用户 - /// - /// - /// - public override IEnumerable RetrieveUsersByGroupId(int groupId) - { - string key = string.Format("{0}-{1}", RetrieveUsersByGroupIdDataKey, groupId); - return CacheManager.GetOrAdd(key, k => - { - List users = new List(); - string sql = "select u.ID, u.UserName, u.DisplayName, case ur.UserID when u.ID then 'checked' else '' end [status] from Users u left join UserGroup ur on u.ID = ur.UserID and GroupID =@groupId where u.ApprovedTime is not null"; - DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@GroupID", groupId)); - using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - users.Add(new User() - { - Id = (int)reader[0], - UserName = (string)reader[1], - DisplayName = (string)reader[2], - Checked = (string)reader[3] - }); - } - } - return users; - }, RetrieveUsersByRoleIdDataKey); - } - /// - /// 通过部门ID保存当前授权用户(插入) - /// - /// GroupID - /// 用户ID数组 - /// - public override bool SaveUsersByGroupId(int id, IEnumerable userIds) - { - bool ret = false; - DataTable dt = new DataTable(); - dt.Columns.Add("UserID", typeof(int)); - dt.Columns.Add("GroupID", typeof(int)); - userIds.ToList().ForEach(userId => dt.Rows.Add(userId, id)); - using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) - { - try - { - //删除用户角色表该角色所有的用户 - string sql = "delete from UserGroup where GroupID = @GroupID"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@GroupID", id)); - DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); - //批插入用户角色表 - using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) - { - bulk.DestinationTableName = "UserGroup"; - bulk.ColumnMappings.Add("UserID", "UserID"); - bulk.ColumnMappings.Add("GroupID", "GroupID"); - bulk.WriteToServer(dt); - transaction.CommitTransaction(); - } - } - CacheCleanUtility.ClearCache(userIds: userIds, groupIds: new List() { id }); - ret = true; - } - catch (Exception ex) - { - transaction.RollbackTransaction(); - throw ex; - } - } - return ret; - } - /// - /// 根据用户名修改用户头像 - /// - /// - /// - /// - public override bool SaveUserIconByName(string userName, string iconName) - { - bool ret = false; - string sql = "Update Users set Icon = @iconName where UserName = @userName"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@iconName", iconName)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@userName", userName)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - if (ret) CacheCleanUtility.ClearCache(cacheKey: $"{RetrieveUsersDataKey}*"); - } - return ret; - } - /// - /// - /// - /// - /// - /// - public override bool SaveDisplayName(string userName, string displayName) - { - bool ret = false; - string sql = "Update Users set DisplayName = @DisplayName where UserName = @userName"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@DisplayName", displayName)); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@userName", userName)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - if (ret) CacheCleanUtility.ClearCache(cacheKey: $"{RetrieveUsersDataKey}*"); - } - return ret; - } - /// - /// 根据用户名更改用户皮肤 - /// - /// - /// - /// - public override bool SaveUserCssByName(string userName, string cssName) - { - bool ret = false; - string sql = "Update Users set Css = @cssName where UserName = @userName"; - using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) - { - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@cssName", DbAccessFactory.ToDBValue(cssName))); - cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@userName", userName)); - ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; - if (ret) CacheCleanUtility.ClearCache(cacheKey: $"{RetrieveUsersDataKey}*"); - } - return ret; - } - /// - /// - /// - /// - /// - public override BootstrapUser RetrieveUserByUserName(string userName) - { - var key = string.Format("{0}-{1}", RetrieveUsersByNameDataKey, userName); - return CacheManager.GetOrAdd(key, k => - { - BootstrapUser user = null; - var sql = "select UserName, DisplayName, case isnull(d.Code, '') when '' then '~/images/uploader/' else d.Code end + Icon Icon, u.Css from Users u left join Dicts d on d.Define = '0' and d.Category = N'头像地址' and Name = N'头像路径' where ApprovedTime is not null and UserName = @UserName"; - var db = DbAccessManager.DBAccess; - var cmd = db.CreateCommand(CommandType.Text, sql); - cmd.Parameters.Add(db.CreateParameter("@UserName", userName)); - using (DbDataReader reader = db.ExecuteReader(cmd)) - { - if (reader.Read()) - { - user = new BootstrapUser - { - UserName = (string)reader[0], - DisplayName = (string)reader[1], - Icon = (string)reader[2], - Css = reader.IsDBNull(3) ? string.Empty : (string)reader[3] - }; - } - } - return user; - }, RetrieveUsersByNameDataKey); - } - } -} diff --git a/Bootstrap.DataAccess.SQLite/Group.cs b/Bootstrap.DataAccess.SQLite/Group.cs index 4f62b99a..af4050c8 100644 --- a/Bootstrap.DataAccess.SQLite/Group.cs +++ b/Bootstrap.DataAccess.SQLite/Group.cs @@ -64,7 +64,7 @@ namespace Bootstrap.DataAccess.SQLite /// /// /// - public override bool SaveGroup(Bootstrap.DataAccess.Group p) + public override bool SaveGroup(DataAccess.Group p) { bool ret = false; if (p.GroupName.Length > 50) p.GroupName = p.GroupName.Substring(0, 50); diff --git a/Bootstrap.DataAccess.SQLite/Log.cs b/Bootstrap.DataAccess.SQLite/Log.cs index a9c04a93..b4aa4d38 100644 --- a/Bootstrap.DataAccess.SQLite/Log.cs +++ b/Bootstrap.DataAccess.SQLite/Log.cs @@ -65,7 +65,7 @@ namespace Bootstrap.DataAccess.SQLite /// /// /// - public override bool SaveLog(Bootstrap.DataAccess.Log p) + public override bool SaveLog(DataAccess.Log p) { if (p == null) throw new ArgumentNullException("p"); bool ret = false; diff --git a/Bootstrap.DataAccess/Dict.cs b/Bootstrap.DataAccess/Dict.cs index 232280b7..3a68f1a7 100644 --- a/Bootstrap.DataAccess/Dict.cs +++ b/Bootstrap.DataAccess/Dict.cs @@ -4,6 +4,8 @@ using Longbow.Cache; using System; using System.Collections.Generic; using System.Data; +using System.Data.Common; +using System.Linq; namespace Bootstrap.DataAccess { @@ -21,22 +23,48 @@ namespace Bootstrap.DataAccess /// public const string RetrieveDictsDataKey = "BootstrapDict-RetrieveDicts"; /// - /// - /// - /// - public virtual IEnumerable> RetrieveApps() => throw new NotImplementedException(); - /// /// 删除字典中的数据 /// /// 需要删除的IDs /// - public virtual bool DeleteDict(IEnumerable value) => throw new NotImplementedException(); + public virtual bool DeleteDict(IEnumerable value) + { + var ret = false; + var ids = string.Join(",", value); + string sql = $"Delete from Dicts where ID in ({ids})"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == value.Count(); + CacheCleanUtility.ClearCache(dictIds: ids); + } + return ret; + } /// /// 保存新建/更新的字典信息 /// /// /// - public virtual bool SaveDict(BootstrapDict dict) => throw new NotImplementedException(); + public virtual bool SaveDict(BootstrapDict dict) + { + bool ret = false; + if (dict.Category.Length > 50) dict.Category = dict.Category.Substring(0, 50); + if (dict.Name.Length > 50) dict.Name = dict.Name.Substring(0, 50); + if (dict.Code.Length > 50) dict.Code = dict.Code.Substring(0, 50); + string sql = dict.Id == 0 ? + "Insert Into Dicts (Category, Name, Code ,Define) Values (@Category, @Name, @Code, @Define)" : + "Update Dicts set Category = @Category, Name = @Name, Code = @Code, Define = @Define where ID = @ID"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ID", dict.Id)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Category", dict.Category)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Name", dict.Name)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Code", dict.Code)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Define", dict.Define)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + } + CacheCleanUtility.ClearCache(dictIds: dict.Id == 0 ? string.Empty : dict.Id.ToString()); + return ret; + } /// /// 保存网站个性化设置 /// @@ -44,42 +72,105 @@ namespace Bootstrap.DataAccess /// /// /// - public virtual bool SaveSettings(BootstrapDict dict) => throw new NotImplementedException(); + public virtual bool SaveSettings(BootstrapDict dict) + { + var ret = false; + string sql = "Update Dicts set Code = @Code where Category = @Category and Name = @Name"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Name", dict.Name)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Code", dict.Code)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Category", dict.Category)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + } + CacheCleanUtility.ClearCache(dictIds: string.Empty); + return ret; + } /// /// 获取字典分类名称 /// /// - public virtual IEnumerable RetrieveCategories() => throw new NotImplementedException(); + public virtual IEnumerable RetrieveCategories() + { + return CacheManager.GetOrAdd(RetrieveCategoryDataKey, key => + { + var ret = new List(); + string sql = "select distinct Category from Dicts"; + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + ret.Add((string)reader[0]); + } + } + return ret; + }); + } /// /// /// /// - public virtual string RetrieveWebTitle() => throw new NotImplementedException(); + public virtual string RetrieveWebTitle() + { + var settings = RetrieveDicts(); + return (settings.FirstOrDefault(d => d.Name == "网站标题" && d.Category == "网站设置" && d.Define == 0) ?? new BootstrapDict() { Code = "后台管理系统" }).Code; + } /// /// /// /// - public virtual string RetrieveWebFooter() => throw new NotImplementedException(); + public virtual string RetrieveWebFooter() + { + var settings = RetrieveDicts(); + return (settings.FirstOrDefault(d => d.Name == "网站页脚" && d.Category == "网站设置" && d.Define == 0) ?? new BootstrapDict() { Code = "2016 © 通用后台管理系统" }).Code; + } /// /// 获得系统中配置的可以使用的网站样式 /// /// - public virtual IEnumerable RetrieveThemes() => throw new NotImplementedException(); + public virtual IEnumerable RetrieveThemes() + { + var data = RetrieveDicts(); + return data.Where(d => d.Category == "网站样式"); + } /// /// 获得网站设置中的当前样式 /// /// - public virtual string RetrieveActiveTheme() => throw new NotImplementedException(); + public virtual string RetrieveActiveTheme() + { + var data = RetrieveDicts(); + var theme = data.Where(d => d.Name == "使用样式" && d.Category == "当前样式" && d.Define == 0).FirstOrDefault(); + return theme == null ? string.Empty : (theme.Code.Equals("site.css", StringComparison.OrdinalIgnoreCase) ? string.Empty : theme.Code); + } /// /// 获取头像路径 /// /// - public virtual BootstrapDict RetrieveIconFolderPath() => throw new NotImplementedException(); + public virtual BootstrapDict RetrieveIconFolderPath() + { + var data = RetrieveDicts(); + return data.FirstOrDefault(d => d.Name == "头像路径" && d.Category == "头像地址" && d.Define == 0) ?? new BootstrapDict() { Code = "~/images/uploader/" }; + } /// /// 获得默认的前台首页地址,默认为~/Home/Index /// /// - public virtual string RetrieveHomeUrl() => throw new NotImplementedException(); + public virtual string RetrieveHomeUrl() + { + var settings = RetrieveDicts(); + return (settings.FirstOrDefault(d => d.Name == "前台首页" && d.Category == "网站设置" && d.Define == 0) ?? new BootstrapDict() { Code = "~/Home/Index" }).Code; + } + /// + /// + /// + /// + public virtual IEnumerable> RetrieveApps() + { + var settings = RetrieveDicts(); + return settings.Where(d => d.Category == "应用程序" && d.Define == 0).Select(d => new KeyValuePair(d.Code, d.Name)).OrderBy(d => d.Key); + } /// /// 通过数据库获得所有字典表配置信息,缓存Key=DictHelper-RetrieveDicts /// diff --git a/Bootstrap.DataAccess/Exceptions.cs b/Bootstrap.DataAccess/Exceptions.cs index e83ec986..a75324e1 100644 --- a/Bootstrap.DataAccess/Exceptions.cs +++ b/Bootstrap.DataAccess/Exceptions.cs @@ -1,6 +1,11 @@ -using System; +using Longbow.Cache; +using Longbow.Configuration; +using Longbow.Data; +using System; using System.Collections.Generic; using System.Collections.Specialized; +using System.Data; +using System.Data.Common; namespace Bootstrap.DataAccess { @@ -53,17 +58,80 @@ namespace Bootstrap.DataAccess /// 获得/设置 时间描述 2分钟内为刚刚 /// public string Period { get; set; } + + private static void ClearExceptions() + { + System.Threading.Tasks.Task.Run(() => + { + string sql = $"delete from Exceptions where LogTime < DATEADD(MONTH, -{ConfigurationManager.AppSettings["KeepExceptionsPeriod"]}, GETDATE())"; + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd); + }); + } /// /// /// /// /// /// - public virtual void Log(Exception ex, NameValueCollection additionalInfo) => throw new NotImplementedException(); + public virtual void Log(Exception ex, NameValueCollection additionalInfo) + { + if (additionalInfo == null) + { + additionalInfo = new NameValueCollection + { + ["UserId"] = null, + ["UserIp"] = null, + ["ErrorPage"] = null + }; + } + var errorPage = additionalInfo["ErrorPage"] ?? (nameof(ex).Length > 50 ? nameof(ex).Substring(0, 50) : nameof(ex)); + var sql = "insert into Exceptions (AppDomainName, ErrorPage, UserID, UserIp, ExceptionType, Message, StackTrace, LogTime) values (@AppDomainName, @ErrorPage, @UserID, @UserIp, @ExceptionType, @Message, @StackTrace, GetDate())"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@AppDomainName", AppDomain.CurrentDomain.FriendlyName)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ErrorPage", errorPage)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", DbAccessFactory.ToDBValue(additionalInfo["UserId"]))); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserIp", DbAccessFactory.ToDBValue(additionalInfo["UserIp"]))); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ExceptionType", ex.GetType().FullName)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Message", ex.Message)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@StackTrace", DbAccessFactory.ToDBValue(ex.StackTrace))); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd); + CacheManager.Clear(RetrieveExceptionsDataKey); + ClearExceptions(); + } + } /// /// 查询一周内所有异常 /// /// - public virtual IEnumerable RetrieveExceptions() => throw new NotImplementedException(); + public virtual IEnumerable RetrieveExceptions() + { + return CacheManager.GetOrAdd(RetrieveExceptionsDataKey, key => + { + string sql = "select * from Exceptions where DATEDIFF(Week, LogTime, GETDATE()) = 0 order by LogTime desc"; + List exceptions = new List(); + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + exceptions.Add(new Exceptions() + { + Id = (int)reader[0], + AppDomainName = (string)reader[1], + ErrorPage = reader.IsDBNull(2) ? string.Empty : (string)reader[2], + UserId = reader.IsDBNull(3) ? string.Empty : (string)reader[3], + UserIp = reader.IsDBNull(4) ? string.Empty : (string)reader[4], + ExceptionType = (string)reader[5], + Message = (string)reader[6], + StackTrace = (string)reader[7], + LogTime = (DateTime)reader[8], + }); + } + } + return exceptions; + }); + } } } diff --git a/Bootstrap.DataAccess/Group.cs b/Bootstrap.DataAccess/Group.cs index 94f7c427..cdbb13b4 100644 --- a/Bootstrap.DataAccess/Group.cs +++ b/Bootstrap.DataAccess/Group.cs @@ -1,8 +1,11 @@ using Longbow.Cache; +using Longbow.Data; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; namespace Bootstrap.DataAccess { @@ -39,44 +42,221 @@ namespace Bootstrap.DataAccess /// /// /// - public virtual IEnumerable RetrieveGroups(int id = 0) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveGroups(int id = 0) + { + var ret = CacheManager.GetOrAdd(RetrieveGroupsDataKey, key => + { + string sql = "select * from Groups"; + List groups = new List(); + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + groups.Add(new Group() + { + Id = (int)reader[0], + GroupName = (string)reader[1], + Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2] + }); + } + } + return groups; + }); + return id == 0 ? ret : ret.Where(t => id == t.Id); + } /// /// 删除群组信息 /// /// - public virtual bool DeleteGroup(IEnumerable value) => throw new NotImplementedException(); + public virtual bool DeleteGroup(IEnumerable value) + { + bool ret = false; + var ids = string.Join(",", value); + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_DeleteGroups")) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ids", ids)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; + } + CacheCleanUtility.ClearCache(groupIds: value); + return ret; + } /// /// 保存新建/更新的群组信息 /// /// /// - public virtual bool SaveGroup(Group p) => throw new NotImplementedException(); + public virtual bool SaveGroup(Group p) + { + bool ret = false; + if (p.GroupName.Length > 50) p.GroupName = p.GroupName.Substring(0, 50); + if (!string.IsNullOrEmpty(p.Description) && p.Description.Length > 500) p.Description = p.Description.Substring(0, 500); + string sql = p.Id == 0 ? + "Insert Into Groups (GroupName, Description) Values (@GroupName, @Description)" : + "Update Groups set GroupName = @GroupName, Description = @Description where ID = @ID"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ID", p.Id)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@GroupName", p.GroupName)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Description", DbAccessFactory.ToDBValue(p.Description))); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + } + CacheCleanUtility.ClearCache(groupIds: p.Id == 0 ? new List() : new List() { p.Id }); + return ret; + } /// /// 根据用户查询部门信息 /// /// /// - public virtual IEnumerable RetrieveGroupsByUserId(int userId) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveGroupsByUserId(int userId) + { + string key = string.Format("{0}-{1}", RetrieveGroupsByUserIdDataKey, userId); + var ret = CacheManager.GetOrAdd(key, k => + { + string sql = "select g.ID,g.GroupName,g.[Description],case ug.GroupID when g.ID then 'checked' else '' end [status] from Groups g left join UserGroup ug on g.ID=ug.GroupID and UserID=@UserID"; + List groups = new List(); + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", userId)); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + groups.Add(new Group() + { + Id = (int)reader[0], + GroupName = (string)reader[1], + Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2], + Checked = (string)reader[3] + }); + } + } + return groups; + }, RetrieveGroupsByUserIdDataKey); + return ret; + } /// /// 保存用户部门关系 /// /// /// /// - public virtual bool SaveGroupsByUserId(int id, IEnumerable groupIds) => throw new NotImplementedException(); + public virtual bool SaveGroupsByUserId(int id, IEnumerable groupIds) + { + var ret = false; + DataTable dt = new DataTable(); + dt.Columns.Add("UserID", typeof(int)); + dt.Columns.Add("GroupID", typeof(int)); + //判断用户是否选定角色 + groupIds.ToList().ForEach(groupId => dt.Rows.Add(id, groupId)); + using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) + { + try + { + //删除用户部门表中该用户所有的部门关系 + string sql = "delete from UserGroup where UserID=@UserID;"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", id)); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); + + // insert batch data into config table + using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) + { + bulk.BatchSize = 1000; + bulk.DestinationTableName = "UserGroup"; + bulk.ColumnMappings.Add("UserID", "UserID"); + bulk.ColumnMappings.Add("GroupID", "GroupID"); + bulk.WriteToServer(dt); + transaction.CommitTransaction(); + } + } + CacheCleanUtility.ClearCache(groupIds: groupIds, userIds: new List() { id }); + ret = true; + } + catch (Exception ex) + { + transaction.RollbackTransaction(); + throw ex; + } + } + return ret; + } /// /// 根据角色ID指派部门 /// /// /// - public virtual IEnumerable RetrieveGroupsByRoleId(int roleId) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveGroupsByRoleId(int roleId) + { + string k = string.Format("{0}-{1}", RetrieveGroupsByRoleIdDataKey, roleId); + return CacheManager.GetOrAdd(k, key => + { + List groups = new List(); + string sql = "select g.ID,g.GroupName,g.[Description],case rg.GroupID when g.ID then 'checked' else '' end [status] from Groups g left join RoleGroup rg on g.ID=rg.GroupID and RoleID=@RoleID"; + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", roleId)); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + groups.Add(new Group() + { + Id = (int)reader[0], + GroupName = (string)reader[1], + Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2], + Checked = (string)reader[3] + }); + } + } + return groups; + }, RetrieveGroupsByRoleIdDataKey); + } /// /// 根据角色ID以及选定的部门ID,保到角色部门表 /// /// /// /// - public virtual bool SaveGroupsByRoleId(int id, IEnumerable groupIds) => throw new NotImplementedException(); + public virtual bool SaveGroupsByRoleId(int id, IEnumerable groupIds) + { + bool ret = false; + DataTable dt = new DataTable(); + dt.Columns.Add("GroupID", typeof(int)); + dt.Columns.Add("RoleID", typeof(int)); + groupIds.ToList().ForEach(groupId => dt.Rows.Add(groupId, id)); + using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) + { + try + { + //删除角色部门表该角色所有的部门 + string sql = "delete from RoleGroup where RoleID=@RoleID"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", id)); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); + //批插入角色部门表 + using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) + { + bulk.BatchSize = 1000; + bulk.ColumnMappings.Add("GroupID", "GroupID"); + bulk.ColumnMappings.Add("RoleID", "RoleID"); + bulk.DestinationTableName = "RoleGroup"; + bulk.WriteToServer(dt); + transaction.CommitTransaction(); + } + } + CacheCleanUtility.ClearCache(groupIds: groupIds, roleIds: new List() { id }); + ret = true; + } + catch (Exception ex) + { + transaction.RollbackTransaction(); + throw ex; + } + } + return ret; + } /// /// /// diff --git a/Bootstrap.DataAccess/Log.cs b/Bootstrap.DataAccess/Log.cs index a6ffb630..bf750cb1 100644 --- a/Bootstrap.DataAccess/Log.cs +++ b/Bootstrap.DataAccess/Log.cs @@ -1,10 +1,21 @@ -using System; +using Longbow.Cache; +using Longbow.Configuration; +using System; using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Linq; namespace Bootstrap.DataAccess { + /// + /// + /// public class Log { + /// + /// + /// protected const string RetrieveLogsDataKey = "LogHelper-RetrieveLogs"; /// /// 获得/设置 操作日志主键ID @@ -45,12 +56,69 @@ namespace Bootstrap.DataAccess /// /// /// - public virtual IEnumerable RetrieveLogs(string tId = null) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveLogs(string tId = null) + { + var ret = CacheManager.GetOrAdd(RetrieveLogsDataKey, key => + { + string sql = "select * from Logs where DATEDIFF(Week, LogTime, GETDATE()) = 0"; + List logs = new List(); + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + logs.Add(new Log() + { + Id = (int)reader[0], + CRUD = (string)reader[1], + UserName = (string)reader[2], + LogTime = (DateTime)reader[3], + ClientIp = (string)reader[4], + ClientAgent = (string)reader[5], + RequestUrl = (string)reader[6] + }); + } + } + return logs; + }); + return string.IsNullOrEmpty(tId) ? ret : ret.Where(t => tId.Equals(t.Id.ToString(), StringComparison.OrdinalIgnoreCase)); + } + /// + /// 删除日志信息 + /// + /// + /// + private void DeleteLogAsync() + { + System.Threading.Tasks.Task.Run(() => + { + string sql = $"delete from Logs where LogTime < DATEADD(MONTH, -{ConfigurationManager.AppSettings["KeepLogsPeriod"]}, GETDATE())"; + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd); + }); + } /// /// 保存新增的日志信息 /// /// /// - public virtual bool SaveLog(Log p) => throw new NotImplementedException(); + public virtual bool SaveLog(Log p) + { + if (p == null) throw new ArgumentNullException("p"); + bool ret = false; + string sql = "Insert Into Logs (CRUD, UserName, LogTime, ClientIp, ClientAgent, RequestUrl) Values (@CRUD, @UserName, GetDate(), @ClientIp, @ClientAgent, @RequestUrl)"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@CRUD", p.CRUD)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserName", p.UserName)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ClientIp", p.ClientIp)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ClientAgent", p.ClientAgent)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RequestUrl", p.RequestUrl)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + } + CacheManager.Clear(RetrieveLogsDataKey); + DeleteLogAsync(); + return ret; + } } } diff --git a/Bootstrap.DataAccess/Menu.cs b/Bootstrap.DataAccess/Menu.cs index 7fb0aa25..01884e2c 100644 --- a/Bootstrap.DataAccess/Menu.cs +++ b/Bootstrap.DataAccess/Menu.cs @@ -2,10 +2,12 @@ using Longbow; using Longbow.Cache; using Longbow.Configuration; +using Longbow.Data; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; +using System.Data.SqlClient; using System.Linq; namespace Bootstrap.DataAccess @@ -25,26 +27,124 @@ namespace Bootstrap.DataAccess /// 删除菜单信息 /// /// - public virtual bool DeleteMenu(IEnumerable value) => throw new NotImplementedException(); + public virtual bool DeleteMenu(IEnumerable value) + { + bool ret = false; + var ids = string.Join(",", value); + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_DeleteMenus")) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ids", ids)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; + } + CacheCleanUtility.ClearCache(menuIds: value); + return ret; + } /// /// 保存新建/更新的菜单信息 /// /// /// - public virtual bool SaveMenu(BootstrapMenu p) => throw new NotImplementedException(); + public virtual bool SaveMenu(BootstrapMenu p) + { + if (string.IsNullOrEmpty(p.Name)) return false; + bool ret = false; + if (p.Name.Length > 50) p.Name = p.Name.Substring(0, 50); + if (p.Icon != null && p.Icon.Length > 50) p.Icon = p.Icon.Substring(0, 50); + if (p.Url != null && p.Url.Length > 4000) p.Url = p.Url.Substring(0, 4000); + string sql = p.Id == 0 ? + "Insert Into Navigations (ParentId, Name, [Order], Icon, Url, Category, Target, IsResource, [Application]) Values (@ParentId, @Name, @Order, @Icon, @Url, @Category, @Target, @IsResource, @ApplicationCode)" : + "Update Navigations set ParentId = @ParentId, Name = @Name, [Order] = @Order, Icon = @Icon, Url = @Url, Category = @Category, Target = @Target, IsResource = @IsResource, Application = @ApplicationCode where ID = @ID"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ID", p.Id)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ParentId", p.ParentId)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Name", p.Name)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Order", p.Order)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Icon", DbAccessFactory.ToDBValue(p.Icon))); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Url", DbAccessFactory.ToDBValue(p.Url))); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Category", p.Category)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Target", p.Target)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@IsResource", p.IsResource)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ApplicationCode", p.ApplicationCode)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + } + CacheCleanUtility.ClearCache(menuIds: p.Id == 0 ? new List() : new List() { p.Id }); + return ret; + } + /// /// 查询某个角色所配置的菜单 /// /// /// - public virtual IEnumerable RetrieveMenusByRoleId(int roleId) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveMenusByRoleId(int roleId) + { + string key = string.Format("{0}-{1}", RetrieveMenusByRoleIdDataKey, roleId); + return CacheManager.GetOrAdd(key, k => + { + var menus = new List(); + string sql = "select NavigationID from NavigationRole where RoleID = @RoleID"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", roleId)); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + menus.Add(new BootstrapMenu() + { + Id = (int)reader[0] + }); + } + } + } + return menus; + }, RetrieveMenusByRoleIdDataKey); + } /// /// 通过角色ID保存当前授权菜单 /// /// /// /// - public virtual bool SaveMenusByRoleId(int id, IEnumerable menuIds) => throw new NotImplementedException(); + public virtual bool SaveMenusByRoleId(int id, IEnumerable menuIds) + { + bool ret = false; + DataTable dt = new DataTable(); + dt.Columns.Add("RoleID", typeof(int)); + dt.Columns.Add("NavigationID", typeof(int)); + menuIds.ToList().ForEach(menuId => dt.Rows.Add(id, menuId)); + using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) + { + try + { + //删除菜单角色表该角色所有的菜单 + string sql = "delete from NavigationRole where RoleID=@RoleID"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", id)); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); + //批插入菜单角色表 + using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) + { + bulk.DestinationTableName = "NavigationRole"; + bulk.ColumnMappings.Add("RoleID", "RoleID"); + bulk.ColumnMappings.Add("NavigationID", "NavigationID"); + bulk.WriteToServer(dt); + transaction.CommitTransaction(); + } + } + CacheCleanUtility.ClearCache(menuIds: menuIds, roleIds: new List() { id }); + ret = true; + } + catch (Exception ex) + { + transaction.RollbackTransaction(); + throw ex; + } + } + return ret; + } /// /// 通过当前用户名获得所有菜单,层次化后集合 /// diff --git a/Bootstrap.DataAccess/Message.cs b/Bootstrap.DataAccess/Message.cs index 7fc65de3..415866dd 100644 --- a/Bootstrap.DataAccess/Message.cs +++ b/Bootstrap.DataAccess/Message.cs @@ -1,5 +1,10 @@ -using System; +using Longbow; +using Longbow.Cache; +using System; using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Linq; namespace Bootstrap.DataAccess { @@ -66,33 +71,101 @@ namespace Bootstrap.DataAccess /// public string FromDisplayName { get; set; } /// + /// 所有有关userName所有消息列表 + /// + /// + /// + private static IEnumerable RetrieveMessages(string userName) + { + var messageRet = CacheManager.GetOrAdd(RetrieveMessageDataKey, key => + { + string sql = "select m.*, d.Name, isnull(i.Code + u.Icon, '~/images/uploader/default.jpg'), u.DisplayName from [Messages] m left join Dicts d on m.Label = d.Code and d.Category = N'消息标签' and d.Define = 0 left join Dicts i on i.Category = N'头像地址' and i.Name = N'头像路径' and i.Define = 0 inner join Users u on m.[From] = u.UserName where [To] = @UserName or [From] = @UserName order by m.SendTime desc"; + List messages = new List(); + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserName", userName)); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + messages.Add(new Message() + { + Id = (int)reader[0], + Title = (string)reader[1], + Content = (string)reader[2], + From = (string)reader[3], + To = (string)reader[4], + SendTime = LgbConvert.ReadValue(reader[5], DateTime.MinValue), + Status = (string)reader[6], + Mark = (int)reader[7], + IsDelete = (int)reader[8], + Label = (string)reader[9], + LabelName = LgbConvert.ReadValue(reader[10], string.Empty), + FromIcon = (string)reader[11], + FromDisplayName = (string)reader[12] + }); + } + } + return messages; + + }); + return messageRet.OrderByDescending(n => n.SendTime); + } + /// /// 收件箱 /// /// - public virtual IEnumerable Inbox(string userName) => throw new NotImplementedException(); + public virtual IEnumerable Inbox(string userName) + { + var messageRet = RetrieveMessages(userName); + return messageRet.Where(n => n.To.Equals(userName, StringComparison.OrdinalIgnoreCase)); + } /// /// 发件箱 /// /// /// - public virtual IEnumerable SendMail(string userName) => throw new NotImplementedException(); + public virtual IEnumerable SendMail(string userName) + { + var messageRet = RetrieveMessages(userName); + return messageRet.Where(n => n.From.Equals(userName, StringComparison.OrdinalIgnoreCase)); + } /// /// 垃圾箱 /// /// /// - public virtual IEnumerable Trash(string userName) => throw new NotImplementedException(); + public virtual IEnumerable Trash(string userName) + { + var messageRet = RetrieveMessages(userName); + return messageRet.Where(n => n.IsDelete == 1); + } /// /// 标旗 /// /// /// - public virtual IEnumerable Flag(string userName) => throw new NotImplementedException(); + public virtual IEnumerable Flag(string userName) + { + var messageRet = RetrieveMessages(userName); + return messageRet.Where(n => n.Mark == 1); + } /// /// 获取Header处显示的消息列表 /// /// /// - public virtual IEnumerable RetrieveMessagesHeader(string userName) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveMessagesHeader(string userName) + { + var messageRet = Inbox(userName); + messageRet.AsParallel().ForAll(n => + { + var ts = DateTime.Now - n.SendTime; + if (ts.TotalMinutes < 5) n.Period = "刚刚"; + else if (ts.Days > 0) n.Period = string.Format("{0}天", ts.Days); + else if (ts.Hours > 0) n.Period = string.Format("{0}小时", ts.Hours); + else if (ts.Minutes > 0) n.Period = string.Format("{0}分钟", ts.Minutes); + }); + return messageRet; + } } } diff --git a/Bootstrap.DataAccess/Role.cs b/Bootstrap.DataAccess/Role.cs index 09cb32a0..c79e2bd0 100644 --- a/Bootstrap.DataAccess/Role.cs +++ b/Bootstrap.DataAccess/Role.cs @@ -1,10 +1,13 @@ using Longbow; using Longbow.Cache; using Longbow.Configuration; +using Longbow.Data; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; namespace Bootstrap.DataAccess { @@ -40,56 +43,301 @@ namespace Bootstrap.DataAccess /// /// /// - public virtual IEnumerable RetrieveRoles(int id = 0) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveRoles(int id = 0) + { + var ret = CacheManager.GetOrAdd(RetrieveRolesDataKey, key => + { + string sql = "select * from Roles"; + var roles = new List(); + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + roles.Add(new Role() + { + Id = (int)reader[0], + RoleName = (string)reader[1], + Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2] + }); + } + } + return roles; + }); + return id == 0 ? ret : ret.Where(t => id == t.Id); + } /// /// 保存用户角色关系 /// /// /// /// - public virtual bool SaveRolesByUserId(int id, IEnumerable roleIds) => throw new NotImplementedException(); + public virtual bool SaveRolesByUserId(int id, IEnumerable roleIds) + { + var ret = false; + DataTable dt = new DataTable(); + dt.Columns.Add("UserID", typeof(int)); + dt.Columns.Add("RoleID", typeof(int)); + //判断用户是否选定角色 + roleIds.ToList().ForEach(roleId => dt.Rows.Add(id, roleId)); + using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) + { + try + { + // delete user from config table + string sql = "delete from UserRole where UserID = @UserID;"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", id)); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); + if (dt.Rows.Count > 0) + { + // insert batch data into config table + using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) + { + bulk.DestinationTableName = "UserRole"; + bulk.ColumnMappings.Add("UserID", "UserID"); + bulk.ColumnMappings.Add("RoleID", "RoleID"); + bulk.WriteToServer(dt); + } + } + transaction.CommitTransaction(); + } + CacheCleanUtility.ClearCache(userIds: new List() { id }, roleIds: roleIds); + ret = true; + } + catch (Exception ex) + { + transaction.RollbackTransaction(); + throw ex; + } + } + return ret; + } /// /// 查询某个用户所拥有的角色 /// /// - public virtual IEnumerable RetrieveRolesByUserId(int userId) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveRolesByUserId(int userId) + { + string key = string.Format("{0}-{1}", RetrieveRolesByUserIdDataKey, userId); + return CacheManager.GetOrAdd(key, k => + { + List roles = new List(); + string sql = "select r.ID, r.RoleName, r.[Description], case ur.RoleID when r.ID then 'checked' else '' end [status] from Roles r left join UserRole ur on r.ID = ur.RoleID and UserID = @UserID"; + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@UserID", userId)); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + roles.Add(new Role() + { + Id = (int)reader[0], + RoleName = (string)reader[1], + Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2], + Checked = (string)reader[3] + }); + } + } + return roles; + }, RetrieveRolesByUserIdDataKey); + } /// /// 删除角色表 /// /// - public virtual bool DeleteRole(IEnumerable value) => throw new NotImplementedException(); + public virtual bool DeleteRole(IEnumerable value) + { + bool ret = false; + var ids = string.Join(",", value); + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_DeleteRoles")) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ids", ids)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; + } + CacheCleanUtility.ClearCache(roleIds: value); + return ret; + } /// /// 保存新建/更新的角色信息 /// /// /// - public virtual bool SaveRole(Role p) => throw new NotImplementedException(); + public virtual bool SaveRole(Role p) + { + bool ret = false; + if (!string.IsNullOrEmpty(p.RoleName) && p.RoleName.Length > 50) p.RoleName = p.RoleName.Substring(0, 50); + if (!string.IsNullOrEmpty(p.Description) && p.Description.Length > 50) p.Description = p.Description.Substring(0, 500); + string sql = p.Id == 0 ? + "Insert Into Roles (RoleName, Description) Values (@RoleName, @Description)" : + "Update Roles set RoleName = @RoleName, Description = @Description where ID = @ID"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ID", p.Id)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleName", p.RoleName)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Description", DbAccessFactory.ToDBValue(p.Description))); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + } + CacheCleanUtility.ClearCache(roleIds: p.Id == 0 ? new List() : new List { p.Id }); + return ret; + } /// /// 查询某个菜单所拥有的角色 /// /// /// - public virtual IEnumerable RetrieveRolesByMenuId(int menuId) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveRolesByMenuId(int menuId) + { + string key = string.Format("{0}-{1}", RetrieveRolesByMenuIdDataKey, menuId); + var ret = CacheManager.GetOrAdd(key, k => + { + string sql = "select r.ID, r.RoleName, r.[Description], case ur.RoleID when r.ID then 'checked' else '' end [status] from Roles r left join NavigationRole ur on r.ID = ur.RoleID and NavigationID = @NavigationID"; + List roles = new List(); + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@NavigationID", menuId)); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + roles.Add(new Role() + { + Id = (int)reader[0], + RoleName = (string)reader[1], + Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2], + Checked = (string)reader[3] + }); + } + } + return roles; + }, RetrieveRolesByMenuIdDataKey); + return ret; + } /// /// /// /// /// /// - public virtual bool SavaRolesByMenuId(int id, IEnumerable roleIds) => throw new NotImplementedException(); + public virtual bool SavaRolesByMenuId(int id, IEnumerable roleIds) + { + var ret = false; + DataTable dt = new DataTable(); + dt.Columns.Add("NavigationID", typeof(int)); + dt.Columns.Add("RoleID", typeof(int)); + //判断用户是否选定角色 + roleIds.ToList().ForEach(roleId => dt.Rows.Add(id, roleId)); + using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) + { + try + { + // delete role from config table + string sql = "delete from NavigationRole where NavigationID=@NavigationID;"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@NavigationID", id)); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); + + // insert batch data into config table + using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) + { + bulk.BatchSize = 1000; + bulk.DestinationTableName = "NavigationRole"; + bulk.ColumnMappings.Add("NavigationID", "NavigationID"); + bulk.ColumnMappings.Add("RoleID", "RoleID"); + bulk.WriteToServer(dt); + transaction.CommitTransaction(); + } + } + CacheCleanUtility.ClearCache(roleIds: roleIds, menuIds: new List() { id }); + ret = true; + } + catch (Exception ex) + { + transaction.RollbackTransaction(); + throw ex; + } + } + return ret; + } /// /// 根据GroupId查询和该Group有关的所有Roles /// /// /// - public virtual IEnumerable RetrieveRolesByGroupId(int groupId) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveRolesByGroupId(int groupId) + { + string key = string.Format("{0}-{1}", RetrieveRolesByGroupIdDataKey, groupId); + return CacheManager.GetOrAdd(key, k => + { + List roles = new List(); + string sql = "select r.ID, r.RoleName, r.[Description], case ur.RoleID when r.ID then 'checked' else '' end [status] from Roles r left join RoleGroup ur on r.ID = ur.RoleID and GroupID = @GroupID"; + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@GroupID", groupId)); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + roles.Add(new Role() + { + Id = (int)reader[0], + RoleName = (string)reader[1], + Description = reader.IsDBNull(2) ? string.Empty : (string)reader[2], + Checked = (string)reader[3] + }); + } + } + return roles; + }, RetrieveRolesByGroupIdDataKey); + } + /// /// 根据GroupId更新Roles信息,删除旧的Roles信息,插入新的Roles信息 /// /// /// /// - public virtual bool SaveRolesByGroupId(int id, IEnumerable roleIds) => throw new NotImplementedException(); + public virtual bool SaveRolesByGroupId(int id, IEnumerable roleIds) + { + var ret = false; + //构造表格 + DataTable dt = new DataTable(); + dt.Columns.Add("RoleID", typeof(int)); + dt.Columns.Add("GroupID", typeof(int)); + roleIds.ToList().ForEach(roleId => dt.Rows.Add(roleId, id)); + using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) + { + try + { + // delete user from config table + string sql = "delete from RoleGroup where GroupID=@GroupID"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@GroupID", id)); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); + + // insert batch data into config table + using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) + { + bulk.BatchSize = 1000; + bulk.DestinationTableName = "RoleGroup"; + bulk.ColumnMappings.Add("RoleID", "RoleID"); + bulk.ColumnMappings.Add("GroupID", "GroupID"); + bulk.WriteToServer(dt); + transaction.CommitTransaction(); + } + } + CacheCleanUtility.ClearCache(roleIds: roleIds, groupIds: new List() { id }); + ret = true; + } + catch (Exception ex) + { + transaction.RollbackTransaction(); + throw ex; + } + } + return ret; + } /// /// /// diff --git a/Bootstrap.DataAccess/Task.cs b/Bootstrap.DataAccess/Task.cs index b204aa99..2780aca5 100644 --- a/Bootstrap.DataAccess/Task.cs +++ b/Bootstrap.DataAccess/Task.cs @@ -1,5 +1,8 @@ -using System; +using Longbow.Cache; +using System; using System.Collections.Generic; +using System.Data; +using System.Data.Common; namespace Bootstrap.DataAccess { @@ -42,6 +45,32 @@ namespace Bootstrap.DataAccess /// 查询所有任务 /// /// - public virtual IEnumerable RetrieveTasks() => throw new NotImplementedException(); + public virtual IEnumerable RetrieveTasks() + { + return CacheManager.GetOrAdd(RetrieveTasksDataKey, key => + { + string sql = "select top 1000 t.*, u.DisplayName from Tasks t inner join Users u on t.UserName = u.UserName order by AssignTime desc"; + List tasks = new List(); + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + tasks.Add(new Task() + { + Id = (int)reader[0], + TaskName = (string)reader[1], + AssignName = (string)reader[2], + UserName = (string)reader[3], + TaskTime = (int)reader[4], + TaskProgress = (double)reader[5], + AssignTime = (DateTime)reader[6], + AssignDisplayName = (string)reader[7] + }); + } + } + return tasks; + }); + } } } diff --git a/Bootstrap.DataAccess/User.cs b/Bootstrap.DataAccess/User.cs index 2b5e68b9..c4fb86c8 100644 --- a/Bootstrap.DataAccess/User.cs +++ b/Bootstrap.DataAccess/User.cs @@ -1,9 +1,14 @@ using Bootstrap.Security; +using Longbow; +using Longbow.Cache; +using Longbow.Data; using Longbow.Security; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; +using System.Data.SqlClient; +using System.Linq; namespace Bootstrap.DataAccess { @@ -89,43 +94,6 @@ namespace Bootstrap.DataAccess return !string.IsNullOrEmpty(passwordSalt) && oldPassword == LgbCryptography.ComputeHash(password, passwordSalt); } /// - /// 查询所有用户 - /// - /// - /// - public virtual IEnumerable RetrieveUsers() => throw new NotImplementedException(); - /// - /// 查询所有的新注册用户 - /// - /// - public virtual IEnumerable RetrieveNewUsers() => throw new NotImplementedException(); - /// - /// 删除用户 - /// - /// - public virtual bool DeleteUser(IEnumerable value) => throw new NotImplementedException(); - /// - /// 保存新建 - /// - /// - /// - public virtual bool SaveUser(User p) => throw new NotImplementedException(); - /// - /// - /// - /// - /// - /// - /// - public virtual bool UpdateUser(int id, string password, string displayName) => throw new NotImplementedException(); - /// - /// - /// - /// - /// - /// - public virtual bool ApproveUser(int id, string approvedBy) => throw new NotImplementedException(); - /// /// /// /// @@ -151,66 +119,404 @@ namespace Bootstrap.DataAccess return ret; } /// + /// 查询所有用户 + /// + /// + /// + public virtual IEnumerable RetrieveUsers() + { + return CacheManager.GetOrAdd(RetrieveUsersDataKey, key => + { + List users = new List(); + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, "select ID, UserName, DisplayName, RegisterTime, ApprovedTime, ApprovedBy, Description from Users Where ApprovedTime is not null"); + + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + users.Add(new User() + { + Id = (int)reader[0], + UserName = (string)reader[1], + DisplayName = (string)reader[2], + RegisterTime = (DateTime)reader[3], + ApprovedTime = LgbConvert.ReadValue(reader[4], DateTime.MinValue), + ApprovedBy = reader.IsDBNull(5) ? string.Empty : (string)reader[5], + Description = (string)reader[6] + }); + } + } + return users; + }); + } + /// + /// 查询所有的新注册用户 + /// + /// + public virtual IEnumerable RetrieveNewUsers() + { + return CacheManager.GetOrAdd(RetrieveNewUsersDataKey, key => + { + string sql = "select ID, UserName, DisplayName, RegisterTime, [Description] from Users Where ApprovedTime is null order by RegisterTime desc"; + List users = new List(); + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + users.Add(new User() + { + Id = (int)reader[0], + UserName = (string)reader[1], + DisplayName = (string)reader[2], + RegisterTime = (DateTime)reader[3], + Description = (string)reader[4] + }); + } + } + return users; + }); + } + /// + /// 删除用户 + /// + /// + public virtual bool DeleteUser(IEnumerable value) + { + bool ret = false; + var ids = string.Join(",", value); + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_DeleteUsers")) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@ids", ids)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; + if (ret) CacheCleanUtility.ClearCache(userIds: value); + } + return ret; + } + /// + /// 保存新建 + /// + /// + /// + public virtual bool SaveUser(User p) + { + var ret = false; + if (p.Id == 0 && p.Description.Length > 500) p.Description = p.Description.Substring(0, 500); + if (p.UserName.Length > 50) p.UserName = p.UserName.Substring(0, 50); + p.PassSalt = LgbCryptography.GenerateSalt(); + p.Password = LgbCryptography.ComputeHash(p.Password, p.PassSalt); + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_SaveUsers")) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@userName", p.UserName)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@password", p.Password)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@passSalt", p.PassSalt)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@displayName", p.DisplayName)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@approvedBy", DbAccessFactory.ToDBValue(p.ApprovedBy))); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@description", p.Description)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; + if (ret) CacheCleanUtility.ClearCache(userIds: p.Id == 0 ? new List() : new List() { p.Id }); + } + return ret; + } + /// + /// + /// + /// + /// + /// + /// + public virtual bool UpdateUser(int id, string password, string displayName) + { + bool ret = false; + string sql = "Update Users set Password = @Password, PassSalt = @PassSalt, DisplayName = @DisplayName where ID = @id"; + var passSalt = LgbCryptography.GenerateSalt(); + var newPassword = LgbCryptography.ComputeHash(password, passSalt); + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@id", id)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@DisplayName", displayName)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@Password", newPassword)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@PassSalt", passSalt)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + if (ret) CacheCleanUtility.ClearCache(userIds: id == 0 ? new List() : new List() { id }); + } + return ret; + } + /// + /// + /// + /// + /// + /// + public virtual bool ApproveUser(int id, string approvedBy) + { + var ret = false; + var sql = "update Users set ApprovedTime = GETDATE(), ApprovedBy = @approvedBy where ID = @id"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@id", id)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@approvedBy", approvedBy)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + if (ret) CacheCleanUtility.ClearCache(userIds: new List() { id }); + } + return ret; + } + /// /// /// /// /// /// /// - public virtual bool RejectUser(int id, string rejectBy) => throw new NotImplementedException(); + public virtual bool RejectUser(int id, string rejectBy) + { + var ret = false; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_RejectUsers")) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@id", id)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@rejectedBy", rejectBy)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@rejectedReason", "未填写")); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == -1; + if (ret) CacheCleanUtility.ClearCache(userIds: new List() { id }); + } + return ret; + } /// /// 通过roleId获取所有用户 /// /// /// - public virtual IEnumerable RetrieveUsersByRoleId(int roleId) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveUsersByRoleId(int roleId) + { + string key = string.Format("{0}-{1}", RetrieveUsersByRoleIdDataKey, roleId); + return CacheManager.GetOrAdd(key, k => + { + List users = new List(); + string sql = "select u.ID, u.UserName, u.DisplayName, case ur.UserID when u.ID then 'checked' else '' end [status] from Users u left join UserRole ur on u.ID = ur.UserID and RoleID = @RoleID where u.ApprovedTime is not null"; + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", roleId)); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + users.Add(new User() + { + Id = (int)reader[0], + UserName = (string)reader[1], + DisplayName = (string)reader[2], + Checked = (string)reader[3] + }); + } + } + return users; + }, RetrieveUsersByRoleIdDataKey); + } /// /// 通过角色ID保存当前授权用户(插入) /// /// 角色ID /// 用户ID数组 /// - public virtual bool SaveUsersByRoleId(int id, IEnumerable userIds) => throw new NotImplementedException(); + public virtual bool SaveUsersByRoleId(int id, IEnumerable userIds) + { + bool ret = false; + DataTable dt = new DataTable(); + dt.Columns.Add("RoleID", typeof(int)); + dt.Columns.Add("UserID", typeof(int)); + userIds.ToList().ForEach(userId => dt.Rows.Add(id, userId)); + using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) + { + try + { + //删除用户角色表该角色所有的用户 + string sql = "delete from UserRole where RoleID=@RoleID"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@RoleID", id)); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); + //批插入用户角色表 + using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) + { + bulk.DestinationTableName = "UserRole"; + bulk.ColumnMappings.Add("RoleID", "RoleID"); + bulk.ColumnMappings.Add("UserID", "UserID"); + bulk.WriteToServer(dt); + transaction.CommitTransaction(); + } + } + CacheCleanUtility.ClearCache(userIds: userIds, roleIds: new List() { id }); + ret = true; + } + catch (Exception ex) + { + transaction.RollbackTransaction(); + throw ex; + } + } + return ret; + } /// /// 通过groupId获取所有用户 /// /// /// - public virtual IEnumerable RetrieveUsersByGroupId(int groupId) => throw new NotImplementedException(); + public virtual IEnumerable RetrieveUsersByGroupId(int groupId) + { + string key = string.Format("{0}-{1}", RetrieveUsersByGroupIdDataKey, groupId); + return CacheManager.GetOrAdd(key, k => + { + List users = new List(); + string sql = "select u.ID, u.UserName, u.DisplayName, case ur.UserID when u.ID then 'checked' else '' end [status] from Users u left join UserGroup ur on u.ID = ur.UserID and GroupID =@groupId where u.ApprovedTime is not null"; + DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@GroupID", groupId)); + using (DbDataReader reader = DbAccessManager.DBAccess.ExecuteReader(cmd)) + { + while (reader.Read()) + { + users.Add(new User() + { + Id = (int)reader[0], + UserName = (string)reader[1], + DisplayName = (string)reader[2], + Checked = (string)reader[3] + }); + } + } + return users; + }, RetrieveUsersByRoleIdDataKey); + } /// /// 通过部门ID保存当前授权用户(插入) /// /// GroupID /// 用户ID数组 /// - public virtual bool SaveUsersByGroupId(int id, IEnumerable userIds) => throw new NotImplementedException(); + public virtual bool SaveUsersByGroupId(int id, IEnumerable userIds) + { + bool ret = false; + DataTable dt = new DataTable(); + dt.Columns.Add("UserID", typeof(int)); + dt.Columns.Add("GroupID", typeof(int)); + userIds.ToList().ForEach(userId => dt.Rows.Add(userId, id)); + using (TransactionPackage transaction = DbAccessManager.DBAccess.BeginTransaction()) + { + try + { + //删除用户角色表该角色所有的用户 + string sql = "delete from UserGroup where GroupID = @GroupID"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@GroupID", id)); + DbAccessManager.DBAccess.ExecuteNonQuery(cmd, transaction); + //批插入用户角色表 + using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction)) + { + bulk.DestinationTableName = "UserGroup"; + bulk.ColumnMappings.Add("UserID", "UserID"); + bulk.ColumnMappings.Add("GroupID", "GroupID"); + bulk.WriteToServer(dt); + transaction.CommitTransaction(); + } + } + CacheCleanUtility.ClearCache(userIds: userIds, groupIds: new List() { id }); + ret = true; + } + catch (Exception ex) + { + transaction.RollbackTransaction(); + throw ex; + } + } + return ret; + } /// /// 根据用户名修改用户头像 /// /// /// /// - public virtual bool SaveUserIconByName(string userName, string iconName) => throw new NotImplementedException(); + public virtual bool SaveUserIconByName(string userName, string iconName) + { + bool ret = false; + string sql = "Update Users set Icon = @iconName where UserName = @userName"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@iconName", iconName)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@userName", userName)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + if (ret) CacheCleanUtility.ClearCache(cacheKey: $"{RetrieveUsersDataKey}*"); + } + return ret; + } /// /// /// - /// + /// /// /// - public virtual bool SaveDisplayName(string userName, string displayName) => throw new NotImplementedException(); + public virtual bool SaveDisplayName(string userName, string displayName) + { + bool ret = false; + string sql = "Update Users set DisplayName = @DisplayName where UserName = @userName"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@DisplayName", displayName)); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@userName", userName)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + if (ret) CacheCleanUtility.ClearCache(cacheKey: $"{RetrieveUsersDataKey}*"); + } + return ret; + } /// /// 根据用户名更改用户皮肤 /// /// /// /// - public virtual bool SaveUserCssByName(string userName, string cssName) => throw new NotImplementedException(); + public virtual bool SaveUserCssByName(string userName, string cssName) + { + bool ret = false; + string sql = "Update Users set Css = @cssName where UserName = @userName"; + using (DbCommand cmd = DbAccessManager.DBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@cssName", DbAccessFactory.ToDBValue(cssName))); + cmd.Parameters.Add(DbAccessManager.DBAccess.CreateParameter("@userName", userName)); + ret = DbAccessManager.DBAccess.ExecuteNonQuery(cmd) == 1; + if (ret) CacheCleanUtility.ClearCache(cacheKey: $"{RetrieveUsersDataKey}*"); + } + return ret; + } /// /// /// - /// + /// /// - public virtual BootstrapUser RetrieveUserByUserName(string name) => throw new NotImplementedException(); + public virtual BootstrapUser RetrieveUserByUserName(string userName) + { + var key = string.Format("{0}-{1}", RetrieveUsersByNameDataKey, userName); + return CacheManager.GetOrAdd(key, k => + { + BootstrapUser user = null; + var sql = "select UserName, DisplayName, case isnull(d.Code, '') when '' then '~/images/uploader/' else d.Code end + Icon Icon, u.Css from Users u left join Dicts d on d.Define = '0' and d.Category = N'头像地址' and Name = N'头像路径' where ApprovedTime is not null and UserName = @UserName"; + var db = DbAccessManager.DBAccess; + var cmd = db.CreateCommand(CommandType.Text, sql); + cmd.Parameters.Add(db.CreateParameter("@UserName", userName)); + using (DbDataReader reader = db.ExecuteReader(cmd)) + { + if (reader.Read()) + { + user = new BootstrapUser + { + UserName = (string)reader[0], + DisplayName = (string)reader[1], + Icon = (string)reader[2], + Css = reader.IsDBNull(3) ? string.Empty : (string)reader[3] + }; + } + } + return user; + }, RetrieveUsersByNameDataKey); + } /// /// /// diff --git a/BootstrapAdmin.sln b/BootstrapAdmin.sln index 741e2e74..a5570aef 100644 --- a/BootstrapAdmin.sln +++ b/BootstrapAdmin.sln @@ -41,8 +41,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SQLite", "SQLite", "{523515 DatabaseScripts\SQLite\Install.sql = DatabaseScripts\SQLite\Install.sql EndProjectSection EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Bootstrap.DataAccess.SQLServer", "Bootstrap.DataAccess.SQLServer\Bootstrap.DataAccess.SQLServer.csproj", "{555BB7E8-36A4-4EDE-88A9-BEF3E6ACE71B}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -69,10 +67,6 @@ Global {BC18A24F-5C99-4DF5-803D-72A912BCBD57}.Debug|Any CPU.Build.0 = Debug|Any CPU {BC18A24F-5C99-4DF5-803D-72A912BCBD57}.Release|Any CPU.ActiveCfg = Release|Any CPU {BC18A24F-5C99-4DF5-803D-72A912BCBD57}.Release|Any CPU.Build.0 = Release|Any CPU - {555BB7E8-36A4-4EDE-88A9-BEF3E6ACE71B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {555BB7E8-36A4-4EDE-88A9-BEF3E6ACE71B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {555BB7E8-36A4-4EDE-88A9-BEF3E6ACE71B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {555BB7E8-36A4-4EDE-88A9-BEF3E6ACE71B}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE