重构代码:重新编写header nav消息拉去方式,优先使用WebSocket然后使用WebLoop方式,重构新用户注册、批复、拒绝逻辑

This commit is contained in:
Argo-MacBookPro 2018-09-07 15:53:16 +08:00
parent ebd085b0f6
commit f3d3358b81
14 changed files with 351 additions and 311 deletions

View File

@ -13,7 +13,7 @@ namespace Bootstrap.Admin.Controllers
public class NewController : Controller
{
/// <summary>
///
/// 登录页面注册新用户remote validate调用
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
@ -23,13 +23,36 @@ namespace Bootstrap.Admin.Controllers
{
return BootstrapUser.RetrieveUserByUserName(userName) == null && !UserHelper.RetrieveNewUsers().Any(u => u.UserName == userName);
}
/// <summary>
/// 登录页面注册新用户提交按钮调用
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public bool Post([FromBody] User user)
{
var ret = UserHelper.SaveUser(user);
if (ret) NotificationHelper.PushMessage(new MessageBody() { Category = "Users", Message = string.Format("{0}-{1}", user.UserName, user.Description) });
return ret;
}
/// <summary>
/// 新用户授权/拒绝接口
/// </summary>
/// <returns></returns>
[HttpPut("{id}")]
public bool Put([FromBody]User value)
{
var ret = false;
if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Password) || string.IsNullOrEmpty(user.DisplayName) || string.IsNullOrEmpty(user.Description)) return ret;
return UserHelper.SaveUser(user);
if (value.UserStatus == UserStates.ApproveUser)
{
ret = UserHelper.ApproveUser(value.Id, User.Identity.Name);
}
else if (value.UserStatus == UserStates.RejectUser)
{
ret = UserHelper.RejectUser(value.Id, User.Identity.Name);
}
return ret;
}
}
}

View File

@ -5,6 +5,7 @@ using Longbow.Web.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
@ -36,15 +37,15 @@ namespace Bootstrap.Admin.Controllers.Api
if (User.IsInRole("Administrators")) return false;
var ret = false;
if (value.UserStatus == 3)
if (value.UserStatus == UserStates.ChangeTheme)
{
return UserHelper.SaveUserCssByName(value.UserName, value.Css);
}
if (value.UserName.Equals(User.Identity.Name, System.StringComparison.OrdinalIgnoreCase))
{
if (value.UserStatus == 1)
if (value.UserStatus == UserStates.ChangeDisplayName)
ret = BootstrapUser.SaveUserInfoByName(value.UserName, value.DisplayName);
else if (value.UserStatus == 2)
else if (value.UserStatus == UserStates.ChangePassword)
ret = BootstrapUser.ChangePassword(value.UserName, value.Password, value.NewPassword);
}
return ret;
@ -82,6 +83,7 @@ namespace Bootstrap.Admin.Controllers.Api
{
value.Description = string.Format("管理员{0}创建用户", User.Identity.Name);
value.ApprovedBy = User.Identity.Name;
value.ApprovedTime = DateTime.Now;
return UserHelper.SaveUser(value);
}
/// <summary>
@ -104,20 +106,6 @@ namespace Bootstrap.Admin.Controllers.Api
case "group":
ret = UserHelper.SaveUsersByGroupId(id, userIds);
break;
case "user":
// 此时 userIds 存储的信息是操作结果 1 标示同意 0 标示拒绝
var user = new User() { Id = id, UserStatus = 2 };
if (userIds == "1")
{
user.ApprovedBy = User.Identity.Name;
}
else
{
user.RejectedReason = "无原因";
user.RejectedBy = User.Identity.Name;
}
ret = UserHelper.SaveUser(user);
break;
default:
break;
}

View File

@ -0,0 +1,23 @@
using Bootstrap.DataAccess;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace Bootstrap.Admin.Controllers.Api
{
/// <summary>
///
/// </summary>
[Route("api/[controller]")]
public class WSController : Controller
{
/// <summary>
///
/// </summary>
/// <returns></returns>
[HttpPost]
public IEnumerable<MessageBody> Post()
{
return NotificationHelper.RetrieveMessages();
}
}
}

View File

@ -82,7 +82,7 @@ namespace Bootstrap.Admin
app.UseCookiePolicy();
app.UseAuthentication();
app.UseBootstrapRoleAuthorization();
app.UseWebSocketHandler(options => options.UseAuthentication = true);
app.UseWebSocketHandler(options => options.UseAuthentication = true, WSHelper.WebSocketMessageHandler);
app.UseCacheManagerCorsHandler();
app.UseMvc(routes =>
{

View File

@ -105,7 +105,7 @@
{
"Enabled": true,
"Key": "UserHelper-RetrieveNewUsers",
"Interval": 30,
"Interval": 600,
"SlidingExpiration": true,
"Desc": "新用户数据缓存"
},
@ -220,6 +220,13 @@
"Interval": 21600,
"SlidingExpiration": true,
"Desc": "Token 数据缓存"
},
{
"Enabled": true,
"Key": "NotificationHelper-PullNotificationsInterval",
"Interval": 10,
"SlidingExpiration": false,
"Desc": "全局消息提示轮询时间间隔"
}
]
}

View File

@ -42,28 +42,6 @@
});
return this;
},
pullNotification: function () {
var that = this;
var uri = "ws://" + window.location.host + $.formatUrl("WS");
var socket = new WebSocket(uri);
socket.onmessage = function (e) {
var result = JSON.parse(e.data);
for (index in result) {
var cate = result[index].Category;
var msg = result[index].Message;
switch (cate) {
case "Notification":
toastr.error(msg, "应用程序出现错误");
break;
case "Users":
toastr.info(msg, "新用户注册");
break;
}
}
if (result.length > 0) that.reloadWidget();
};
return this;
},
reloadWidget: function () {
if (this.length === 0) return this;
var that = this;
@ -134,7 +112,7 @@ $(function () {
"onclick": null,
"showDuration": "600",
"hideDuration": "2000",
"timeOut": "5000",
"timeOut": "4000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
@ -194,5 +172,25 @@ $(function () {
$('[data-toggle="dropdown"].dropdown-select').dropdown('select');
// load widget data
$('.header .nav').reloadWidget().pullNotification();
$('.header .nav').reloadWidget().socketHandler({
onmessage: function (e) {
var result = JSON.parse(e.data);
for (index in result) {
var cate = result[index].Category;
var msg = result[index].Message;
switch (cate) {
case "Notification":
toastr.error(msg, "应用程序出现错误");
break;
case "Users":
toastr.success(msg, "新用户注册");
break;
case "Exception":
toastr.warning(msg, "程序发生异常");
break;
}
}
if (result.length > 0) this.reloadWidget();
}
});
});

View File

@ -225,68 +225,6 @@
window.lgbSwal = $.lgbSwal;
// Roles
Role = {
url: 'api/Roles/',
title: "授权角色"
};
// Users
User = {
url: 'api/Users/',
title: "授权用户"
};
// Groups
Group = {
url: 'api/Groups/',
title: "授权部门"
};
// Menus
Menu = {
url: 'api/Menus/',
iconView: 'Admin/IconView',
title: "授权菜单"
};
// Exceptions
Exceptions = {
url: 'api/Exceptions/',
title: "程序异常日志"
};
// Dicts
Dicts = {
url: 'api/Dicts/'
};
// Profiles
Profiles = {
url: 'api/Profiles/'
};
// Settings
Settings = {
url: 'api/Settings/',
title: '网站设置'
};
// Messages
Messages = {
url: 'api/Messages/'
};
// Tasks
Tasks = {
url: 'api/Tasks/'
};
// Notifications
Notifications = {
url: 'api/Notifications/'
};
$.fn.extend({
fixCollapse: function () {
var $root = this;
@ -367,6 +305,77 @@
$('#' + $(this).attr('id').replace('tb_', 'btn_')).trigger("click");
}).insertBefore(this.parents('.bootstrap-table').find('.fixed-table-toolbar > .bs-bars'));
return this;
},
msgHandler: function (options) {
var settings = {
url: 'api/WS/',
interval: 10000,
sendMessage: '',
timerHandler: null,
onopen: function (e) { },
onmessage: function (e) { },
onclose: function (e) { },
errorHandler: function (e) { if (toastr && $.isFunction(toastr.error)) toastr.error("连接服务器失败!", "系统错误"); },
loop: function () {
var that = this;
var uri = window.location.protocol + "//" + window.location.host + $.formatUrl(settings.url);
$.bc({
url: uri,
id: this.sendMessage,
swal: false,
toastr: false,
callback: function (result) {
if (!result) {
that.errorHandler.call(that.target);
return;
}
that.onmessage.call(that.target, { data: JSON.stringify(result) });
}
});
if (this.timerHandler !== null) clearTimeout(this.timerHandler);
this.timerHandler = setTimeout(function () { that.loop(); }, that.interval);
}
};
$.extend(settings, options, { target: this });
settings.loop();
return this;
},
socketHandler: function (options) {
// WebSocket消息处理方法
var settings = {
url: 'WS',
interval: 30000,
sendMessage: 'keepalive',
timerHandler: null,
onopen: function (e) { },
onerror: function (e) { },
errorHandler: function (e) { if (window.toastr && $.isFunction(window.toastr.error)) toastr.error("连接服务器失败!", "系统错误"); },
onmessage: function (e) { },
onclose: function (e) { },
loop: function (socket) {
var that = this;
if (socket.readyState === 1) {
socket.send(this.sendMessage);
if (this.timerHandler !== null) clearTimeout(this.timerHandler);
this.timerHandler = setTimeout(function () { that.loop(socket); }, that.interval);
}
else {
this.errorHandler();
}
}
};
$.extend(settings, options, { target: this });
var uri = "ws://" + window.location.host + $.formatUrl(settings.url);
var socket = new WebSocket(uri);
socket.onopen = function (e) { settings.onopen.call(settings.target, e); settings.loop(socket); };
socket.onerror = function (e) {
settings.onerror.call(settings.target, e);
settings.target.msgHandler(options);
};
socket.onmessage = function (e) { settings.onmessage.call(settings.target, e); };
socket.onclose = function (e) { settings.onclose.call(settings.target, e); };
return this;
}
});
@ -386,4 +395,66 @@
});
}
});
// Roles
Role = {
url: 'api/Roles/',
title: "授权角色"
};
// Users
User = {
url: 'api/Users/',
title: "授权用户"
};
// Groups
Group = {
url: 'api/Groups/',
title: "授权部门"
};
// Menus
Menu = {
url: 'api/Menus/',
iconView: 'Admin/IconView',
title: "授权菜单"
};
// Exceptions
Exceptions = {
url: 'api/Exceptions/',
title: "程序异常日志"
};
// Dicts
Dicts = {
url: 'api/Dicts/'
};
// Profiles
Profiles = {
url: 'api/Profiles/'
};
// Settings
Settings = {
url: 'api/Settings/',
title: '网站设置'
};
// Messages
Messages = {
url: 'api/Messages/'
};
// Tasks
Tasks = {
url: 'api/Tasks/'
};
// Notifications
Notifications = {
url: 'api/Notifications/'
};
})(jQuery);

View File

@ -12,7 +12,7 @@
{ title: "注册时间", field: "RegisterTime" },
{
title: "操作", field: "Id", formatter: function (value, row, index, field) {
return $.format('<button class="btn btn-success" data-toggle="tooltip" data-id="{0}" data-result="1" title="同意授权"><i class="fa fa-check"></i></button> <button class="btn btn-danger" data-toggle="tooltip" data-id="{0}" data-result="0" title="拒绝授权"><i class="fa fa-remove"></i></button>', value);
return $.format('<button class="btn btn-success" data-toggle="tooltip" data-id="{0}" data-result="ApproveUser" title="同意授权"><i class="fa fa-check"></i></button> <button class="btn btn-danger" data-toggle="tooltip" data-id="{0}" data-result="RejectUser" title="拒绝授权"><i class="fa fa-remove"></i></button>', value);
}
}
]
@ -21,10 +21,11 @@
var id = $this.attr('data-id');
var result = $this.attr('data-result');
$.bc({
id: id, url: User.url, method: "PUT", data: { type: "user", userIds: result }, title: result === "1" ? "授权用户" : "拒绝用户",
id: id, url: 'api/New/', method: "PUT", data: { Id: id, UserStatus: result }, title: result === "ApproveUser" ? "授权用户" : "拒绝用户",
callback: function (result) {
if (!result) return;
$table.bootstrapTable('refresh');
$.pullNotification($('.header .nav').reloadWidget());
$('.header .nav').reloadWidget();
}
});
});

View File

@ -36,11 +36,11 @@
var data = dataBinder.get();
switch ($this.attr('data-method')) {
case 'password':
data.UserStatus = 2;
data.UserStatus = 'ChangePassword';
$.bc({ url: User.url, method: "PUT", data: data, title: "更改密码" });
break;
case 'user':
data.UserStatus = 1;
data.UserStatus = 'ChangeDisplayName';
$.bc({
url: User.url, method: "PUT", data: data, title: "修改用户显示名称",
callback: function (result) {
@ -51,7 +51,7 @@
});
break;
case 'css':
data.UserStatus = 3;
data.UserStatus = 'ChangeTheme';
$.bc({ url: User.url, method: "PUT", data: data, title: "保存样式" });
break;
}

View File

@ -1,13 +1,9 @@
using Longbow;
using Longbow.Cache;
using Longbow.Logging;
using Longbow.Cache;
using Longbow.Web.WebSockets;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Text;
namespace Bootstrap.DataAccess
{
@ -20,125 +16,41 @@ namespace Bootstrap.DataAccess
///
/// </summary>
internal const string RetrieveNotificationsDataKey = "NotificationHelper-RetrieveNotifications";
private const string PullNotificationsIntervalDataKey = "NotificationHelper-PullNotificationsInterval";
private static readonly List<MessageBody> MessagePool = new List<MessageBody>();
/// <summary>
///
/// </summary>
public static ConcurrentBag<MessageBody> MessagePool { get; } = new ConcurrentBag<MessageBody>();
/// <summary>
/// 新用户注册的通知的面板显示
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public static IEnumerable<Notification> RetrieveNotifications()
public static void PushMessage(MessageBody message)
{
var notifies = CacheManager.GetOrAdd(RetrieveNotificationsDataKey, key =>
{
string sql = "select * from Notifications";
List<Notification> notifications = new List<Notification>();
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
try
{
using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
{
while (reader.Read())
{
notifications.Add(new Notification()
{
Id = (int)reader[0],
Category = (string)reader[1],
Title = (string)reader[2],
Content = (string)reader[3],
RegisterTime = (DateTime)reader[4],
ProcessTime = LgbConvert.ReadValue(reader[5], DateTime.MinValue),
ProcessBy = LgbConvert.ReadValue(reader[6], string.Empty),
ProcessResult = LgbConvert.ReadValue(reader[7], string.Empty),
Status = (string)reader[8]
});
}
}
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return notifications;
MessagePool.Add(message);
CacheManager.Clear(PullNotificationsIntervalDataKey);
});
notifies.AsParallel().ForAll(n =>
{
var ts = DateTime.Now - n.RegisterTime;
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 notifies.OrderByDescending(n => n.RegisterTime);
// websocket message push
WebSocketServerManager.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new MessageBody[] { message }))));
}
/// <summary>
/// 点击某一行用户注册通知的处理成功操作
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static bool ProcessRegisterUser(string id)
public static IEnumerable<MessageBody> RetrieveMessages()
{
if (string.IsNullOrEmpty(id)) return false;
bool ret = false;
try
return CacheManager.GetOrAdd(PullNotificationsIntervalDataKey, key =>
{
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_ProcessRegisterUser"))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@id", id));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
}
CacheCleanUtility.ClearCache(notifyIds: id);
ret = true;
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="noti"></param>
/// <returns></returns>
public static bool SaveNotification(Notification noti)
{
if (string.IsNullOrEmpty(noti.Title) || string.IsNullOrEmpty(noti.Content)) return false;
bool ret = false;
try
{
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, "Insert into Notifications (Category, Title, Content, RegisterTime) values (N'2', @Title, @Content, GetDate())"))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@Title", noti.Title));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@Content", noti.Content));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
}
CacheCleanUtility.ClearCache(notifyIds: string.Empty);
ret = true;
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
}
return ret;
var msgs = new MessageBody[MessagePool.Count];
MessagePool.CopyTo(msgs, 0);
MessagePool.Clear();
return new List<MessageBody>(msgs);
});
}
}
/// <summary>
///
/// </summary>
public class MessageBody : IDisposable
public class MessageBody
{
/// <summary>
///
/// </summary>
public MessageBody()
{
timer = new Timer(state =>
{
var msg = this;
NotificationHelper.MessagePool.TryTake(out msg);
}, null, 5000, Timeout.Infinite);
}
private Timer timer = null;
/// <summary>
///
/// </summary>
@ -155,24 +67,5 @@ namespace Bootstrap.DataAccess
{
return string.Format("{0}-{1}", Category, Message);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (timer != null)
{
timer.Dispose();
timer = null;
}
}
}
/// <summary>
///
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}

View File

@ -41,9 +41,9 @@ namespace Bootstrap.DataAccess
/// </summary>
public string Description { get; set; }
/// <summary>
/// 获得/设置 用户当前状态 0 表示管理员注册用户 1 表示用户自己注册 2 表示管理员批复 3 表示更改个人皮肤 9 表示前台remote validate
/// 获得/设置 用户当前状态 0 表示管理员注册用户 1 表示用户注册 2 表示更改密码 3 表示更改个人皮肤 4 表示更改显示名称 5 批复新用户注册操作
/// </summary>
public int UserStatus { get; set; }
public UserStates UserStatus { get; set; }
/// <summary>
/// 获得/设置 通知描述 2分钟内为刚刚
/// </summary>
@ -73,4 +73,30 @@ namespace Bootstrap.DataAccess
return string.Format("{0} ({1})", UserName, DisplayName);
}
}
/// <summary>
///
/// </summary>
public enum UserStates
{
/// <summary>
///
/// </summary>
ChangePassword,
/// <summary>
///
/// </summary>
ChangeTheme,
/// <summary>
///
/// </summary>
ChangeDisplayName,
/// <summary>
///
/// </summary>
ApproveUser,
/// <summary>
///
/// </summary>
RejectUser
}
}

View File

@ -2,7 +2,6 @@
using Longbow;
using Longbow.Cache;
using Longbow.Data;
using Longbow.Logging;
using Longbow.Security;
using System;
using System.Collections.Generic;
@ -106,30 +105,63 @@ namespace Bootstrap.DataAccess
public static bool SaveUser(User p)
{
if (p.Id == 0 && p.Description.Length > 500) p.Description = p.Description.Substring(0, 500);
if (p.UserStatus != 2)
{
if (p.UserName.Length > 50) p.UserName = p.UserName.Substring(0, 50);
p.PassSalt = LgbCryptography.GenerateSalt();
p.Password = LgbCryptography.ComputeHash(p.Password, p.PassSalt);
}
bool ret = false;
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_SaveUsers"))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@id", p.Id));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@userName", DBAccessFactory.ToDBValue(p.UserName)));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@password", DBAccessFactory.ToDBValue(p.Password)));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@passSalt", DBAccessFactory.ToDBValue(p.PassSalt)));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@displayName", DBAccessFactory.ToDBValue(p.DisplayName)));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@description", DBAccessFactory.ToDBValue(p.Description)));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@userName", p.UserName));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@password", p.Password));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@passSalt", p.PassSalt));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@displayName", p.DisplayName));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@approvedBy", DBAccessFactory.ToDBValue(p.ApprovedBy)));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@rejectedBy", DBAccessFactory.ToDBValue(p.RejectedBy)));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@rejectedReason", DBAccessFactory.ToDBValue(p.RejectedReason)));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@userStatus", p.UserStatus));
object approvedTime = p.ApprovedTime;
if (p.ApprovedTime == DateTime.MinValue) approvedTime = DBNull.Value;
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@approvedTime", approvedTime));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@description", p.Description));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
}
CacheCleanUtility.ClearCache(userIds: p.Id == 0 ? string.Empty : p.Id.ToString());
ret = true;
if (p.UserStatus == 1) NotificationHelper.MessagePool.Add(new MessageBody() { Category = "Users", Message = string.Format("{0}-{1}", p.UserName, p.Description) });
return true;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="approvedBy"></param>
/// <returns></returns>
public static 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.SqlDBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@id", id));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@approvedBy", approvedBy));
ret = DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd) == 1;
}
CacheCleanUtility.ClearCache(userIds: id.ToString());
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <param name="rejectBy"></param>
/// <param name="reason"></param>
/// <returns></returns>
public static bool RejectUser(int id, string rejectBy)
{
var ret = false;
var sql = "update Users set RejectedTime = GETDATE(), RejectedBy = @rejectedBy, RejectedReason = @rejectedReason where ID = @id";
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@id", id));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@rejectedBy", rejectBy));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@rejectedReason", "未填写"));
ret = DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd) == 1;
}
CacheCleanUtility.ClearCache(userIds: id.ToString());
return ret;
}
/// <summary>

View File

@ -0,0 +1,19 @@
namespace Bootstrap.DataAccess
{
/// <summary>
///
/// </summary>
public static class WSHelper
{
/// <summary>
///
/// </summary>
/// <param name="socket"></param>
/// <param name="data"></param>
public static byte[] WebSocketMessageHandler(byte[] data)
{
return null;
}
}
}

View File

@ -174,16 +174,13 @@ GO
-- =============================================
CREATE PROCEDURE [dbo].[Proc_SaveUsers]
-- Add the parameters for the stored procedure here
@id int,
@userName varchar(50),
@password varchar(50),
@passSalt varchar(50),
@displayName nvarchar(50),
@approvedBy varchar(50) = null,
@description nvarchar(500),
@rejectedBy varchar(50) = null,
@rejectedReason nvarchar(500) = null,
@userStatus int = 0 --0 1 2
@approvedBy nvarchar(50),
@approvedTime datetime,
@description nvarchar(500)
WITH ENCRYPTION
AS
BEGIN
@ -192,50 +189,12 @@ BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
-- Insert statements for procedure here
if @userStatus = 2
begin
if @approvedBy is not null
update Users set ApprovedTime = GETDATE(), ApprovedBy = @approvedBy where ID = @id
else
update Users set RejectedTime = GETDATE(), RejectedBy = @rejectedBy, RejectedReason = @rejectedReason where ID = @id
end
else
if(not exists (select 1 from Users Where UserName = @userName))
begin
declare @approveTime datetime = null
if @userStatus = 0 set @approveTime = GETDATE()
if(@id = 0 and not exists (select 1 from Users Where UserName = @userName))
begin
Insert Into Users (UserName, [Password], PassSalt, DisplayName, RegisterTime, ApprovedTime, [Description]) values (@userName, @password, @passSalt, @displayName, GETDATE(), @approveTime, @description)
Insert Into Users (UserName, [Password], PassSalt, DisplayName, RegisterTime, ApprovedBy, ApprovedTime, [Description]) values (@userName, @password, @passSalt, @displayName, GETDATE(), @approvedBy, @approvedTime, @description)
insert into UserRole (UserID, RoleID) select @@IDENTITY, ID from Roles where RoleName = N'Default'
end
else
Update Users set [Password] = @password, PassSalt = @passSalt, DisplayName = @displayName where ID = @id
end
END
GO
Drop PROCEDURE Proc_ProcessRegisterUser
GO
-- =============================================
-- Author: XiaTiantian
-- Create date: 2016-11-10
-- Description:
-- =============================================
Create PROCEDURE Proc_ProcessRegisterUser
-- Add the parameters for the stored procedure here
@id int
WITH ENCRYPTION
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET XACT_ABORT ON;
-- Insert statements for procedure here
update Users set ApprovedTime=GETDATE() where UserName=(select Title from Notifications where ID=@id)
update Notifications set Status='1',ProcessTime=GETDATE(),ProcessResult='0' where ID=@id
END
GO