!43 增加功能:增加 Nullable 检查

This commit is contained in:
Argo 2019-11-12 10:57:08 +08:00
parent 8cbfa0b7f5
commit 2d29f1a784
107 changed files with 679 additions and 586 deletions

View File

@ -7,23 +7,6 @@
<LangVersion>latest</LangVersion>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)src\Keys\Longbow.Utility.snk</AssemblyOriginatorKeyFile>
<DocumentationFile>$(MSBuildThisFileDirectory)$(OutDir)$(MSBuildProjectName).xml</DocumentationFile>
</PropertyGroup>
<Target Condition=" $(IsWebProject) == true " Name="PostPublish" AfterTargets="Publish">
<Message Text="Publish lic file -> $(PublishDir)" Importance="high" />
<Copy Condition="'$(OS)' == 'Windows_NT'" DestinationFolder="$(PublishDir)" SourceFiles="$(MSBuildThisFileDirectory)src\admin\keys\Longbow.lic" SkipUnchangedFiles="true" />
<Copy Condition="'$(OS)' == 'UNIX'" DestinationFolder="$(PublishDir)" SourceFiles="$(MSBuildThisFileDirectory)src/admin/keys/Longbow.lic" SkipUnchangedFiles="true" />
<Message Text="Publish db file -> $(PublishDir)" Importance="high" />
<Copy Condition="'$(OS)' == 'Windows_NT'" DestinationFolder="$(PublishDir)" SourceFiles="$(MSBuildThisFileDirectory)src\admin\Bootstrap.Admin\BootstrapAdmin.db" SkipUnchangedFiles="true" />
<Copy Condition="'$(OS)' == 'UNIX'" DestinationFolder="$(PublishDir)" SourceFiles="$(MSBuildThisFileDirectory)src/admin/Bootstrap.Admin/BootstrapAdmin.db" SkipUnchangedFiles="true" />
</Target>
<Target Condition=" $(IsWebProject) == true " Name="PostBuild" AfterTargets="PostBuildEvent">
<Message Text="Copy lic file -> $(TargetDir)" Importance="high" />
<Copy Condition="'$(OS)' == 'Windows_NT'" DestinationFolder="$(TargetDir)" SourceFiles="$(MSBuildThisFileDirectory)src\admin\keys\Longbow.lic" SkipUnchangedFiles="true" />
<Message Text="Copy db file -> $(TargetDir)" Importance="high" />
<Copy Condition="'$(OS)' == 'UNIX'" DestinationFolder="$(TargetDir)" SourceFiles="$(MSBuildThisFileDirectory)src/admin/keys/Longbow.lic" SkipUnchangedFiles="true" />
</Target>
</Project>

29
src/Directory.Build.props Normal file
View File

@ -0,0 +1,29 @@
<Project>
<Import Project="..\Directory.Build.props" />
<PropertyGroup>
<PackageProjectUrl>https://gitee.com/LongbowGroup/$(MsBuildProjectName)</PackageProjectUrl>
<RepositoryUrl>https://gitee.com/LongbowGroup/$(MsBuildProjectName).git</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<Nullable>enable</Nullable>
<DocumentationFile>$(TargetDir)$(MSBuildProjectName).xml</DocumentationFile>
</PropertyGroup>
<Target Condition=" $(IsWebProject) == true " Name="PostPublish" AfterTargets="Publish">
<Message Text="Publish lic file -> $(PublishDir)" Importance="high" />
<Copy Condition="'$(OS)' == 'Windows_NT'" DestinationFolder="$(PublishDir)" SourceFiles="$(MSBuildThisFileDirectory)admin\keys\Longbow.lic" SkipUnchangedFiles="true" />
<Copy Condition="'$(OS)' == 'UNIX'" DestinationFolder="$(PublishDir)" SourceFiles="$(MSBuildThisFileDirectory)admin/keys/Longbow.lic" SkipUnchangedFiles="true" />
<Message Text="Publish db file -> $(PublishDir)" Importance="high" />
<Copy Condition="'$(OS)' == 'Windows_NT'" DestinationFolder="$(PublishDir)" SourceFiles="$(MSBuildThisFileDirectory)admin\Bootstrap.Admin\BootstrapAdmin.db" SkipUnchangedFiles="true" />
<Copy Condition="'$(OS)' == 'UNIX'" DestinationFolder="$(PublishDir)" SourceFiles="$(MSBuildThisFileDirectory)admin/Bootstrap.Admin/BootstrapAdmin.db" SkipUnchangedFiles="true" />
</Target>
<Target Condition=" $(IsWebProject) == true " Name="PostBuild" AfterTargets="PostBuildEvent">
<Message Text="Copy lic file -> $(TargetDir)" Importance="high" />
<Copy Condition="'$(OS)' == 'Windows_NT'" DestinationFolder="$(TargetDir)" SourceFiles="$(MSBuildThisFileDirectory)admin\keys\Longbow.lic" SkipUnchangedFiles="true" />
<Message Text="Copy db file -> $(TargetDir)" Importance="high" />
<Copy Condition="'$(OS)' == 'UNIX'" DestinationFolder="$(TargetDir)" SourceFiles="$(MSBuildThisFileDirectory)admin/keys/Longbow.lic" SkipUnchangedFiles="true" />
</Target>
</Project>

View File

@ -10,7 +10,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Longbow.Logging" Version="3.0.2-beta1" />
<PackageReference Include="Longbow.Logging" Version="3.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="4.0.0" />
<PackageReference Include="Sentry.AspNetCore" Version="2.0.0-beta6" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc4" />

View File

@ -73,7 +73,7 @@ namespace Bootstrap.Admin.Controllers
/// <param name="appId"></param>
/// <returns></returns>
[HttpGet]
public ActionResult Login([FromQuery]string appId = null)
public ActionResult Login([FromQuery]string? appId = null)
{
if (DictHelper.RetrieveSystemModel())
{
@ -111,11 +111,14 @@ namespace Bootstrap.Admin.Controllers
Description = "手机用户",
App = provider.Options.App
};
UserHelper.Save(user);
// 根据配置文件设置默认角色
var roles = RoleHelper.Retrieves().Where(r => provider.Options.Roles.Any(rl => rl.Equals(r.RoleName, StringComparison.OrdinalIgnoreCase))).Select(r => r.Id);
RoleHelper.SaveByUserId(user.Id, roles);
if (UserHelper.Save(user) && !string.IsNullOrEmpty(user.Id))
{
// 根据配置文件设置默认角色
var roles = RoleHelper.Retrieves().Where(r => provider.Options.Roles.Any(rl => rl.Equals(r.RoleName, StringComparison.OrdinalIgnoreCase))).Select(r => r.Id);
#pragma warning disable CS8620 // 由于引用类型的可为 null 性差异,实参不能用于形参。
RoleHelper.SaveByUserId(user.Id, roles);
#pragma warning restore CS8620 // 由于引用类型的可为 null 性差异,实参不能用于形参。
}
}
}
return auth ? await SignInAsync(phone, true, MobileSchema) : RedirectLogin();

View File

@ -67,7 +67,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <summary>
///
/// </summary>
public IEnumerable<string> Polylines { get; set; }
public IEnumerable<string> Polylines { get; set; } = new List<string>();
/// <summary>
///

View File

@ -62,15 +62,18 @@ namespace Bootstrap.Admin.Controllers.Api
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine().Replace("<", "&lt;").Replace(">", "&gt;");
if (line == "General Information ") sb.AppendFormat("<h4><b>{0}</b></h4>", line);
else if (line.StartsWith("TimeStamp:")) sb.AppendFormat("<div class='logTs'>{0}</div>", line);
else if (line.EndsWith("Exception Information")) sb.AppendFormat("<div class='logExcep'>{0}</div>", line);
else if (line.StartsWith("Message:")) sb.AppendFormat("<div class='logMsg'>{0}</div>", line);
else if (line.StartsWith("ErrorSql:")) sb.AppendFormat("<div class='logSql'>{0}</div>", line);
else if (line.StartsWith("Exception Type: Longbow.Data.DBAccessException")) sb.AppendFormat("<div class='logDbExcep'>{0}</div>", line);
else if (line.StartsWith("StackTrace Information")) sb.AppendFormat("<b>{0}</b><br>", line);
else sb.AppendFormat("{0}<br>", line);
var line = reader.ReadLine()?.Replace("<", "&lt;").Replace(">", "&gt;");
if (!string.IsNullOrEmpty(line))
{
if (line == "General Information ") sb.AppendFormat("<h4><b>{0}</b></h4>", line);
else if (line.StartsWith("TimeStamp:")) sb.AppendFormat("<div class='logTs'>{0}</div>", line);
else if (line.EndsWith("Exception Information")) sb.AppendFormat("<div class='logExcep'>{0}</div>", line);
else if (line.StartsWith("Message:")) sb.AppendFormat("<div class='logMsg'>{0}</div>", line);
else if (line.StartsWith("ErrorSql:")) sb.AppendFormat("<div class='logSql'>{0}</div>", line);
else if (line.StartsWith("Exception Type: Longbow.Data.DBAccessException")) sb.AppendFormat("<div class='logDbExcep'>{0}</div>", line);
else if (line.StartsWith("StackTrace Information")) sb.AppendFormat("<b>{0}</b><br>", line);
else sb.AppendFormat("{0}<br>", line);
}
}
}
return new JsonResult(sb.ToString());
@ -84,7 +87,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <summary>
///
/// </summary>
public string FileName { get; set; }
public string FileName { get; set; } = "";
}
}
}

View File

@ -27,7 +27,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <param name="color"></param>
/// <returns></returns>
[HttpGet]
public async Task<ActionResult> Issues([FromServices]GiteeHttpClient client, [FromQuery]string userName = "LongbowEnterprise", [FromQuery]string repoName = "BootstrapAdmin", [FromQuery]string label = "custom badge", [FromQuery]string color = "orange")
public async Task<ActionResult> Issues([FromServices]GiteeHttpClient client, [FromQuery]string? userName = "LongbowEnterprise", [FromQuery]string? repoName = "BootstrapAdmin", [FromQuery]string? label = "custom badge", [FromQuery]string? color = "orange")
{
var ret = await GetJsonAsync(() => client.HttpClient.GetStringAsync($"https://gitee.com/{userName}/{repoName}/issues"), content =>
{
@ -50,7 +50,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <param name="color"></param>
/// <returns></returns>
[HttpGet]
public async Task<ActionResult> Pulls([FromServices]GiteeHttpClient client, [FromQuery]string userName = "LongbowEnterprise", [FromQuery]string repoName = "BootstrapAdmin", [FromQuery]string label = "custom badge", [FromQuery]string color = "orange")
public async Task<ActionResult> Pulls([FromServices]GiteeHttpClient client, [FromQuery]string? userName = "LongbowEnterprise", [FromQuery]string? repoName = "BootstrapAdmin", [FromQuery]string? label = "custom badge", [FromQuery]string? color = "orange")
{
var ret = await GetJsonAsync(() => client.HttpClient.GetStringAsync($"https://gitee.com/{userName}/{repoName}/pulls"), content =>
{
@ -72,7 +72,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <param name="color"></param>
/// <returns></returns>
[HttpGet]
public async Task<ActionResult> Releases([FromServices]GiteeHttpClient client, [FromQuery]string userName = "LongbowEnterprise", [FromQuery]string repoName = "BootstrapAdmin", [FromQuery]string label = "custom badge", [FromQuery]string color = "orange")
public async Task<ActionResult> Releases([FromServices]GiteeHttpClient client, [FromQuery]string? userName = "LongbowEnterprise", [FromQuery]string? repoName = "BootstrapAdmin", [FromQuery]string? label = "custom badge", [FromQuery]string? color = "orange")
{
var ret = await GetJsonAsync(() => client.HttpClient.GetStringAsync($"https://gitee.com/{userName}/{repoName}/releases"), content =>
{
@ -93,7 +93,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <param name="color"></param>
/// <returns></returns>
[HttpGet]
public async Task<ActionResult> Builds([FromServices]GiteeHttpClient client, [FromQuery]string userName = "ArgoZhang", [FromQuery]string projName = "bootstrapadmin", [FromQuery]string branchName = "master", [FromQuery]string label = "custom badge", [FromQuery]string color = "orange")
public async Task<ActionResult> Builds([FromServices]GiteeHttpClient client, [FromQuery]string? userName = "ArgoZhang", [FromQuery]string? projName = "bootstrapadmin", [FromQuery]string? branchName = "master", [FromQuery]string? label = "custom badge", [FromQuery]string? color = "orange")
{
var ret = await GetJsonAsync(() => client.HttpClient.GetAsJsonAsync<AppveyorBuildResult>($"https://ci.appveyor.com/api/projects/{userName}/{projName}/branch/{branchName}", null, new CancellationTokenSource(10000).Token), content =>
{
@ -126,7 +126,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <summary>
/// Appveyor 编译版本实例
/// </summary>
public Build Build { get; set; }
public Build Build { get; set; } = new Build();
}
private class Build
@ -134,7 +134,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <summary>
/// Build 版本信息
/// </summary>
public string Version { get; set; }
public string Version { get; set; } = "";
}
}
}

View File

@ -50,7 +50,7 @@ namespace Bootstrap.Admin.Controllers
/// </summary>
/// <returns></returns>
[HttpPost]
public BootstrapUser RetrieveUserByUserName([FromBody]string userName)
public BootstrapUser? RetrieveUserByUserName([FromBody]string userName)
{
return UserHelper.RetrieveUserByUserName(userName);
}
@ -63,6 +63,7 @@ namespace Bootstrap.Admin.Controllers
[HttpPost]
public IEnumerable<BootstrapMenu> RetrieveAppMenus([FromBody]AppMenuOption args)
{
if (string.IsNullOrEmpty(args.AppId) || string.IsNullOrEmpty(args.UserName)) return new BootstrapMenu[0];
return MenuHelper.RetrieveAppMenus(args.AppId, args.UserName, args.Url);
}
}

View File

@ -32,7 +32,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <param name="user"></param>
/// <returns></returns>
[HttpPost]
public string Post([FromBody]User user)
public string? Post([FromBody]User user)
{
var token = string.Empty;
string userName = user.UserName;
@ -59,7 +59,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// </summary>
/// <returns></returns>
[HttpOptions]
public string Options()
public string? Options()
{
return null;
}

View File

@ -42,7 +42,7 @@ namespace Bootstrap.Admin.Controllers.Api
value.Browser = $"{agent.Browser?.Name} {agent.Browser?.Version}";
value.OS = $"{agent.OS?.Name} {agent.OS?.Version}";
value.City = ipLocator.Locate(value.Ip);
value.UserName = User.Identity.Name;
value.UserName = User.Identity.Name ?? string.Empty;
return LogHelper.Save(value);
}
}

View File

@ -38,15 +38,19 @@ namespace Bootstrap.Admin.Controllers
public bool Put([FromBody]User value)
{
var ret = false;
if (value.UserStatus == UserStates.ApproveUser)
var userName = User.Identity.Name;
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(value.Id))
{
ret = UserHelper.Approve(value.Id, User.Identity.Name);
}
else if (value.UserStatus == UserStates.RejectUser)
{
ret = UserHelper.Reject(value.Id, User.Identity.Name);
if (value.UserStatus == UserStates.ApproveUser)
{
ret = UserHelper.Approve(value.Id, userName);
}
else if (value.UserStatus == UserStates.RejectUser)
{
ret = UserHelper.Reject(value.Id, userName);
}
}
return ret;
}
}
}
}

View File

@ -56,7 +56,7 @@ namespace Bootstrap.Admin.Controllers.Api
apps = apps.Take(6);
apps.AsParallel().ForAll(n =>
{
n.ExceptionType = n.ExceptionType.Split('.').Last();
n.ExceptionType = n.ExceptionType?.Split('.').Last();
var ts = DateTime.Now - n.LogTime;
if (ts.TotalMinutes < 5) n.Period = "刚刚";
else if (ts.Days > 0) n.Period = string.Format("{0}天", ts.Days);

View File

@ -72,7 +72,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <summary>
///
/// </summary>
public string Ip { get; set; }
public string? Ip { get; set; }
/// <summary>
///
@ -108,7 +108,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// </summary>
public void Reset()
{
if (dispatcher != null) dispatcher.Change(TimeSpan.FromSeconds(30), Timeout.InfiniteTimeSpan);
dispatcher.Change(TimeSpan.FromSeconds(30), Timeout.InfiniteTimeSpan);
}
#region Impletement IDispose
@ -123,7 +123,6 @@ namespace Bootstrap.Admin.Controllers.Api
if (dispatcher != null)
{
dispatcher.Dispose();
dispatcher = null;
}
}
}

View File

@ -44,7 +44,7 @@ namespace Bootstrap.Admin.Controllers.Api
fileSize = new FileInfo(filePath).Length;
var iconName = $"{fileName}?v={DateTime.Now.Ticks}";
previewUrl = Url.Content($"{webSiteUrl}{iconName}");
UserHelper.SaveUserIconByName(userName, iconName);
if (!string.IsNullOrEmpty(userName)) UserHelper.SaveUserIconByName(userName, iconName);
return new JsonResult(new
{
@ -64,7 +64,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <summary>
///
/// </summary>
public string Key { get; set; }
public string Key { get; set; } = "";
}
/// <summary>
@ -96,7 +96,7 @@ namespace Bootstrap.Admin.Controllers.Api
}
var iconName = $"{fileName}?v={DateTime.Now.Ticks}";
previewUrl = Url.Content($"{webSiteUrl}{iconName}");
UserHelper.SaveUserIconByName(userName, iconName);
if (!string.IsNullOrEmpty(userName)) UserHelper.SaveUserIconByName(userName, iconName);
}
return new JsonResult(new
{

View File

@ -25,9 +25,14 @@ namespace Bootstrap.Admin.Controllers.Api
public ActionResult Get([FromQuery]string name, [FromServices]IHubContext<TaskLogHub> hub)
{
var sche = TaskServicesManager.Get(name);
sche.Triggers.First().PulseCallback = t => SendTaskLog(sche, name, hub);
SendTaskLog(sche, name, hub);
return Ok(true);
var ret = false;
if (sche != null)
{
sche.Triggers.First().PulseCallback = t => SendTaskLog(sche, name, hub);
SendTaskLog(sche, name, hub);
ret = true;
}
return Ok(ret);
}
private Task SendTaskLog(IScheduler sche, string name, IHubContext<TaskLogHub> hub)

View File

@ -38,7 +38,7 @@ namespace Bootstrap.Admin.Controllers.Api
[HttpPost("{id}")]
public IEnumerable<object> Post(string id, [FromQuery]string type)
{
IEnumerable<object> ret = null;
IEnumerable<object> ret = new string[0];
switch (type)
{
case "role":
@ -68,7 +68,7 @@ namespace Bootstrap.Admin.Controllers.Api
[ButtonAuthorize(Url = "~/Admin/Users", Auth = "add,edit")]
public bool Post([FromBody]User value)
{
var ret = false;
bool ret;
if (string.IsNullOrEmpty(value.Id))
{
value.Description = string.Format("管理员{0}创建用户", User.Identity.Name);
@ -124,7 +124,7 @@ namespace Bootstrap.Admin.Controllers.Api
/// <returns></returns>
[AllowAnonymous]
[HttpOptions]
public string Options()
public string? Options()
{
return null;
}

View File

@ -18,7 +18,7 @@ namespace Bootstrap.Admin.HealthChecks
{
private readonly IConfiguration _configuration;
private readonly IHttpContextAccessor _httpContextAccessor;
private static readonly Func<IConfiguration, string, string> ConnectionStringResolve = (c, name) => string.IsNullOrEmpty(name)
private static readonly Func<IConfiguration, string, string?> ConnectionStringResolve = (c, name) => string.IsNullOrEmpty(name)
? c.GetSection("ConnectionStrings").GetChildren().FirstOrDefault()?.Value
: c.GetConnectionString(name);
@ -42,13 +42,13 @@ namespace Bootstrap.Admin.HealthChecks
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
var db = _configuration.GetSection("DB").GetChildren()
.Select(config => new
.Select(config => new DbOption()
{
Enabled = bool.TryParse(config["Enabled"], out var en) ? en : false,
ProviderName = config["ProviderName"],
Widget = config["Widget"],
ConnectionString = ConnectionStringResolve(config.GetSection("ConnectionStrings").Exists() ? config : _configuration, string.Empty)
}).FirstOrDefault(i => i.Enabled) ?? new
}).FirstOrDefault(i => i.Enabled) ?? new DbOption()
{
Enabled = true,
ProviderName = Longbow.Data.DatabaseProviderType.SqlServer.ToString(),
@ -64,12 +64,11 @@ namespace Bootstrap.Admin.HealthChecks
var roles = string.Empty;
var displayName = string.Empty;
var healths = false;
Exception error = null;
Exception? error = null;
try
{
DbContextManager.Exception = null;
var user = UserHelper.RetrieveUserByUserName(userName);
displayName = user?.DisplayName;
displayName = user?.DisplayName ?? string.Empty;
roles = string.Join(",", RoleHelper.RetrievesByUserName(userName) ?? new string[0]);
menusCount = MenuHelper.RetrieveMenusByUserName(userName)?.Count() ?? 0;
dictsCount = DictHelper.RetrieveDicts()?.Count() ?? 0;
@ -79,32 +78,41 @@ namespace Bootstrap.Admin.HealthChecks
{
error = ex;
}
var data = new Dictionary<string, object>()
var data = new Dictionary<string, object?>()
{
{ "ConnectionString", db.ConnectionString },
{ "Reference", DbContextManager.Create<Dict>()?.GetType().Assembly.FullName ?? db.Widget },
{ "DbType", db?.ProviderName },
{ "Dicts", dictsCount },
{ "LoginName", loginUser },
{ "LoginName", userName },
{ "DisplayName", displayName },
{ "Roles", roles },
{ "Navigations", menusCount }
};
if (string.IsNullOrEmpty(db.ConnectionString))
if (string.IsNullOrEmpty(db?.ConnectionString))
{
// 未启用连接字符串
data["ConnectionString"] = "未配置数据库连接字符串";
return Task.FromResult(HealthCheckResult.Unhealthy("Error", null, data));
}
if (error != null || DbContextManager.Exception != null)
if (DbContextManager.Exception != null) error = DbContextManager.Exception;
if (error != null)
{
data.Add("Exception", (DbContextManager.Exception ?? error).Message);
return Task.FromResult(HealthCheckResult.Unhealthy("Error", error ?? DbContextManager.Exception, data));
data.Add("Exception", error.Message);
return Task.FromResult(HealthCheckResult.Unhealthy("Error", error, data));
}
return healths ? Task.FromResult(HealthCheckResult.Healthy("Ok", data)) : Task.FromResult(HealthCheckResult.Degraded("Failed", null, data));
}
private class DbOption
{
public bool Enabled { get; set; }
public string? ProviderName { get; set; }
public string? Widget { get; set; }
public string? ConnectionString { get; set; }
}
}
}

View File

@ -41,7 +41,7 @@ namespace Bootstrap.Admin.HealthChecks
Task.WaitAll(urls.Select(url => Task.Run(async () =>
{
var sw = Stopwatch.StartNew();
Exception error = null;
Exception? error = null;
var result = await _client.HttpClient.GetAsJsonAsync<object>($"/api/Gitee/{url}", ex => error = ex, cancellationToken);
sw.Stop();
data.Add(url, error == null ? $"{result} Elapsed: {sw.Elapsed}" : $"{result} Elapsed: {sw.Elapsed} Exception: {error}");

View File

@ -12,7 +12,7 @@ namespace Bootstrap.Admin.Models
/// 默认构造函数
/// </summary>
/// <param name="appId"></param>
public AdminModel(string appId = null)
public AdminModel(string? appId = null)
{
if (string.IsNullOrEmpty(appId)) appId = BootstrapAppContext.AppId;

View File

@ -13,28 +13,28 @@
/// <summary>
///
/// </summary>
public string Title { get; set; }
public string Title { get; set; } = "";
/// <summary>
///
/// </summary>
public string Content { get; set; }
public string Content { get; set; } = "";
/// <summary>
///
/// </summary>
public string Image { get; set; }
public string Image { get; set; } = "";
/// <summary>
///
/// </summary>
public string Detail { get; set; }
public string Detail { get; set; } = "";
/// <summary>
///
/// </summary>
public string ReturnUrl { get; set; }
public string ReturnUrl { get; set; } = "";
/// <summary>
///

View File

@ -13,7 +13,7 @@ namespace Bootstrap.Admin.Models
/// 默认构造函数
/// </summary>
/// <param name="userName"></param>
public HeaderBarModel(string userName)
public HeaderBarModel(string? userName)
{
var user = UserHelper.RetrieveUserByUserName(userName);
if (user != null)
@ -42,31 +42,31 @@ namespace Bootstrap.Admin.Models
/// <summary>
/// 获得 当前用户登录名
/// </summary>
public string UserName { get; }
public string UserName { get; } = "";
/// <summary>
/// 获得 当前用户显示名称
/// </summary>
public string DisplayName { get; }
public string DisplayName { get; } = "";
/// <summary>
/// 获得 用户头像地址
/// </summary>
public string Icon { get; }
public string Icon { get; } = "";
/// <summary>
/// 获取 个人网站样式
/// </summary>
public string Css { get; }
public string Css { get; } = "";
/// <summary>
/// 获得 当前设置的默认应用
/// </summary>
public string AppId { get; }
public string AppId { get; } = "";
/// <summary>
/// 获得 当前样式
/// </summary>
public string ActiveCss { get; }
public string ActiveCss { get; } = "";
}
}

View File

@ -9,7 +9,7 @@
/// 构造函数
/// </summary>
/// <param name="userName"></param>
public LockModel(string userName) : base(userName)
public LockModel(string? userName) : base(userName)
{
}
@ -17,11 +17,11 @@
/// <summary>
/// 获得/设置 返回路径
/// </summary>
public string ReturnUrl { get; set; }
public string? ReturnUrl { get; set; }
/// <summary>
/// 获得/设置 认证方式 Cookie Mobile Gitee GitHub
/// </summary>
public string AuthenticationType { get; set; }
public string? AuthenticationType { get; set; }
}
}

View File

@ -11,7 +11,7 @@ namespace Bootstrap.Admin.Models
/// 默认构造函数
/// </summary>
/// <param name="appId"></param>
public LoginModel(string appId = null) : base(appId)
public LoginModel(string? appId = null) : base(appId)
{
ImageLibUrl = DictHelper.RetrieveImagesLibUrl();
}

View File

@ -18,7 +18,7 @@ namespace Bootstrap.Admin.Models
/// <summary>
/// 获得 头像文件名称
/// </summary>
public string FileName { get; }
public string FileName { get; } = "";
/// <summary>
/// 获得 是否为第三方用户

View File

@ -13,15 +13,18 @@ namespace Bootstrap.Admin.Query
/// <summary>
/// 字典分项
/// </summary>
public string Category { get; set; }
public string? Category { get; set; }
/// <summary>
/// 字典名称
/// </summary>
public string Name { get; set; }
public string? Name { get; set; }
/// <summary>
/// 字典种类
/// </summary>
public string Define { get; set; }
public string? Define { get; set; }
/// <summary>
/// 字典表查询
/// </summary>
@ -34,15 +37,15 @@ namespace Bootstrap.Admin.Query
var data = DictHelper.RetrieveDicts();
if (!string.IsNullOrEmpty(Category))
{
data = data.Where(t => t.Category.Contains(Category));
data = data.Where(t => t.Category?.Contains(Category) ?? false);
}
if (!string.IsNullOrEmpty(Name))
{
data = data.Where(t => t.Name.Contains(Name));
data = data.Where(t => t.Name?.Contains(Name) ?? false);
}
if (!string.IsNullOrEmpty(Define))
{
data = data.Where(t => t.Define.ToString() == Define);
data = data.Where(t => t.Define.ToString() == (Define ?? ""));
}
var ret = new QueryData<BootstrapDict>();
ret.total = data.Count();

View File

@ -5,20 +5,22 @@ using System.Linq;
namespace Bootstrap.Admin.Query
{
/// <summary>
///
/// 部门查询条件类
/// </summary>
public class QueryGroupOption : PaginationOption
{
/// <summary>
///
/// 获得/设置 部门名称
/// </summary>
public string GroupName { get; set; }
public string? GroupName { get; set; }
/// <summary>
///
/// 获得/设置 部门描述
/// </summary>
public string Description { get; set; }
public string? Description { get; set; }
/// <summary>
///
/// 部门查询数据方法
/// </summary>
/// <returns></returns>
public QueryData<object> RetrieveData()
@ -27,11 +29,11 @@ namespace Bootstrap.Admin.Query
var data = GroupHelper.Retrieves();
if (!string.IsNullOrEmpty(GroupName))
{
data = data.Where(t => t.GroupName.Contains(GroupName));
data = data.Where(t => t.GroupName?.Contains(GroupName) ?? false);
}
if (!string.IsNullOrEmpty(Description))
{
data = data.Where(t => t.Description.Contains(Description));
data = data.Where(t => t.Description?.Contains(Description) ?? false);
}
var ret = new QueryData<object>();
ret.total = data.Count();

View File

@ -5,27 +5,27 @@ using System;
namespace Bootstrap.Admin.Query
{
/// <summary>
///
/// 操作日志查询条件类
/// </summary>
public class QueryLogOption : PaginationOption
{
/// <summary>
///
/// 获得/设置 操作类型
/// </summary>
public string OperateType { get; set; }
public string? OperateType { get; set; }
/// <summary>
///
/// 获得/设置 开始时间
/// </summary>
public DateTime? OperateTimeStart { get; set; }
/// <summary>
///
/// 获得/设置 结束时间
/// </summary>
public DateTime? OperateTimeEnd { get; set; }
/// <summary>
///
/// 获得/设置 获取查询分页数据
/// </summary>
/// <returns></returns>
public QueryData<Log> RetrieveData()
@ -37,4 +37,4 @@ namespace Bootstrap.Admin.Query
return ret;
}
}
}
}

View File

@ -22,7 +22,7 @@ namespace Bootstrap.Admin.Query
/// <summary>
/// 登录IP地址
/// </summary>
public string LoginIP { get; set; }
public string? LoginIP { get; set; }
/// <summary>
///
@ -30,8 +30,6 @@ namespace Bootstrap.Admin.Query
/// <returns></returns>
public QueryData<LoginUser> RetrieveData()
{
if (string.IsNullOrEmpty(Order)) Order = "desc";
if (string.IsNullOrEmpty(Sort)) Sort = "LoginTime";
var data = LoginHelper.RetrievePages(this, StartTime, EndTime, LoginIP);
return new QueryData<LoginUser>
{

View File

@ -13,34 +13,34 @@ namespace Bootstrap.Admin.Query
/// <summary>
///
/// </summary>
public string Name { get; set; }
public string? Name { get; set; }
/// <summary>
///
/// </summary>
public string ParentName { get; set; }
public string? ParentName { get; set; }
/// <summary>
///
/// </summary>
public string Category { get; set; }
public string? Category { get; set; }
/// <summary>
///
/// </summary>
public string IsResource { get; set; }
public string? IsResource { get; set; }
/// <summary>
///
/// </summary>
public string AppId { get; set; }
public string? AppId { get; set; }
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public QueryData<object> RetrieveData(string userName)
public QueryData<object> RetrieveData(string? userName)
{
var data = MenuHelper.RetrieveMenusByUserName(userName);
if (!string.IsNullOrEmpty(ParentName))

View File

@ -5,20 +5,22 @@ using System.Linq;
namespace Bootstrap.Admin.Query
{
/// <summary>
///
/// 角色查询条件类
/// </summary>
public class QueryRoleOption : PaginationOption
{
/// <summary>
///
/// 角色名称
/// </summary>
public string RoleName { get; set; }
public string? RoleName { get; set; }
/// <summary>
///
/// 角色描述
/// </summary>
public string Description { get; set; }
public string? Description { get; set; }
/// <summary>
///
/// 角色数据
/// </summary>
/// <returns></returns>
public QueryData<object> RetrieveData()
@ -40,4 +42,4 @@ namespace Bootstrap.Admin.Query
return ret;
}
}
}
}

View File

@ -12,7 +12,7 @@ namespace Bootstrap.Admin.Query
/// <summary>
/// 获得/设置 用户登录名
/// </summary>
public string UserName { get; set; }
public string? UserName { get; set; }
/// <summary>
/// 获得/设置 开始时间
@ -30,7 +30,6 @@ namespace Bootstrap.Admin.Query
/// <returns></returns>
public QueryData<DBLog> RetrieveData()
{
if (string.IsNullOrEmpty(Order)) Order = "LogTime";
var data = LogHelper.RetrieveDBLogs(this, OperateTimeStart, OperateTimeEnd, UserName);
var ret = new QueryData<DBLog>();
ret.total = data.TotalItems;

View File

@ -22,7 +22,7 @@ namespace Bootstrap.Admin.Query
/// <summary>
/// 请求IP地址
/// </summary>
public string AccessIP { get; set; }
public string? AccessIP { get; set; }
/// <summary>
///

View File

@ -5,20 +5,22 @@ using System.Linq;
namespace Bootstrap.Admin.Query
{
/// <summary>
///
/// 用户维护查询条件类
/// </summary>
public class QueryUserOption : PaginationOption
{
/// <summary>
///
/// 获得/设置 用户登录名称
/// </summary>
public string Name { get; set; }
public string? Name { get; set; }
/// <summary>
///
/// 获得/设置 用户显示名称
/// </summary>
public string DisplayName { get; set; }
public string? DisplayName { get; set; }
/// <summary>
///
/// 获取用户分页数据
/// </summary>
/// <returns></returns>
public QueryData<object> RetrieveData()
@ -67,4 +69,4 @@ namespace Bootstrap.Admin.Query
return ret;
}
}
}
}

View File

@ -22,8 +22,8 @@ namespace Bootstrap.DataAccess.MongoDB
Id = d.Key,
AppName = d.Value
}).ToList();
var role = RoleHelper.Retrieves().Cast<Role>().FirstOrDefault(r => r.Id == roleId);
apps.ForEach(p => p.Checked = (role != null && (role.Apps.Contains(p.Id)) || role.RoleName.Equals("Administrators", StringComparison.OrdinalIgnoreCase)) ? "checked" : "");
var role = RoleHelper.Retrieves().Cast<Role>().FirstOrDefault(r => r.Id == roleId) ?? new Role();
apps.ForEach(p => p.Checked = (role.Apps.Contains(p.Id) || role.RoleName.Equals("Administrators", StringComparison.OrdinalIgnoreCase)) ? "checked" : "");
return apps;
}

View File

@ -5,8 +5,8 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Bootstrap.Security" Version="3.0.0" />
<PackageReference Include="MongoDB.Driver" Version="2.9.2" />
<PackageReference Include="Bootstrap.Security" Version="3.0.1" />
<PackageReference Include="MongoDB.Driver" Version="2.9.3" />
</ItemGroup>
<ItemGroup>

View File

@ -13,7 +13,7 @@ namespace Bootstrap.DataAccess.MongoDB
/// </summary>
internal static class DbManager
{
private static IMongoDatabase _db = null;
private static IMongoDatabase? _db = null;
private static bool _register = false;
private static readonly object _locker = new object();
@ -38,7 +38,9 @@ namespace Bootstrap.DataAccess.MongoDB
InitDb();
}
}
#pragma warning disable CS8603 // 可能的 null 引用返回。
return _db;
#pragma warning restore CS8603 // 可能的 null 引用返回。
}
}

View File

@ -41,7 +41,6 @@ namespace Bootstrap.DataAccess.MongoDB
{
if (string.IsNullOrEmpty(p.Id))
{
p.Id = null;
DbManager.Dicts.InsertOne(p);
p.Id = DbManager.Dicts.Find(d => d.Name == p.Name && d.Category == p.Category && d.Define == p.Define && d.Code == p.Code).FirstOrDefault().Id;
}

View File

@ -1,4 +1,4 @@
using Longbow.Web.Mvc;
using Longbow.Web.Mvc;
using MongoDB.Driver;
using PetaPoco;
using System;
@ -75,12 +75,9 @@ namespace Bootstrap.DataAccess.MongoDB
// sort
var sortBuilder = Builders<DataAccess.Exceptions>.Sort;
SortDefinition<DataAccess.Exceptions> sort = null;
var sort = po.Order == "asc" ? sortBuilder.Ascending(t => t.LogTime) : sortBuilder.Descending(t => t.LogTime);
switch (po.Sort)
{
case "LogTime":
sort = po.Order == "asc" ? sortBuilder.Ascending(t => t.LogTime) : sortBuilder.Descending(t => t.LogTime);
break;
case "ErrorPage":
sort = po.Order == "asc" ? sortBuilder.Ascending(t => t.ErrorPage) : sortBuilder.Descending(t => t.ErrorPage);
break;

View File

@ -13,7 +13,7 @@ namespace Bootstrap.DataAccess.MongoDB
/// <summary>
///
/// </summary>
public IEnumerable<string> Roles { get; set; }
public IEnumerable<string> Roles { get; set; } = new List<string>();
/// <summary>
///

View File

@ -20,7 +20,7 @@ namespace Bootstrap.DataAccess.MongoDB
/// <param name="endTime"></param>
/// <param name="opType"></param>
/// <returns></returns>
public override Page<DataAccess.Log> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string opType)
public override Page<DataAccess.Log> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string? opType)
{
var filterBuilder = Builders<DataAccess.Log>.Filter;
var filter = filterBuilder.Empty;
@ -31,7 +31,7 @@ namespace Bootstrap.DataAccess.MongoDB
// sort
var sortBuilder = Builders<DataAccess.Log>.Sort;
SortDefinition<DataAccess.Log> sort = null;
var sort = po.Order == "asc" ? sortBuilder.Ascending(t => t.LogTime) : sortBuilder.Descending(t => t.LogTime);
switch (po.Sort)
{
case "CRUD":
@ -40,9 +40,6 @@ namespace Bootstrap.DataAccess.MongoDB
case "UserName":
sort = po.Order == "asc" ? sortBuilder.Ascending(t => t.UserName) : sortBuilder.Descending(t => t.UserName);
break;
case "LogTime":
sort = po.Order == "asc" ? sortBuilder.Ascending(t => t.LogTime) : sortBuilder.Descending(t => t.LogTime);
break;
case "Ip":
sort = po.Order == "asc" ? sortBuilder.Ascending(t => t.Ip) : sortBuilder.Descending(t => t.Ip);
break;
@ -70,7 +67,7 @@ namespace Bootstrap.DataAccess.MongoDB
/// <param name="endTime"></param>
/// <param name="opType"></param>
/// <returns></returns>
public override IEnumerable<DataAccess.Log> RetrieveAll(DateTime? startTime, DateTime? endTime, string opType)
public override IEnumerable<DataAccess.Log> RetrieveAll(DateTime? startTime, DateTime? endTime, string? opType)
{
var filterBuilder = Builders<DataAccess.Log>.Filter;
var filter = filterBuilder.Empty;

View File

@ -31,7 +31,7 @@ namespace Bootstrap.DataAccess.MongoDB
/// <param name="endTime"></param>
/// <param name="ip"></param>
/// <returns></returns>
public override Page<DataAccess.LoginUser> RetrieveByPages(PaginationOption po, DateTime? startTime, DateTime? endTime, string ip)
public override Page<DataAccess.LoginUser> RetrieveByPages(PaginationOption po, DateTime? startTime, DateTime? endTime, string? ip)
{
var logs = RetrieveAll(startTime, endTime, ip);
return new Page<DataAccess.LoginUser>()
@ -49,7 +49,7 @@ namespace Bootstrap.DataAccess.MongoDB
/// 获取所有登录数据
/// </summary>
/// <returns></returns>
public override IEnumerable<DataAccess.LoginUser> RetrieveAll(DateTime? startTime, DateTime? endTime, string ip)
public override IEnumerable<DataAccess.LoginUser> RetrieveAll(DateTime? startTime, DateTime? endTime, string? ip)
{
var filterBuilder = Builders<DataAccess.LoginUser>.Filter;
var filter = filterBuilder.Empty;

View File

@ -40,8 +40,8 @@ namespace Bootstrap.DataAccess.MongoDB
var dicts = DictHelper.RetrieveDicts().Where(m => m.Category == "菜单");
menus.ForEach(m =>
{
m.CategoryName = dicts.FirstOrDefault(d => d.Code == m.Category)?.Name;
if (m.ParentId != "0") m.ParentName = menus.FirstOrDefault(p => p.Id == m.ParentId)?.Name;
m.CategoryName = dicts.FirstOrDefault(d => d.Code == m.Category)?.Name ?? "";
if (m.ParentId != "0") m.ParentName = menus.FirstOrDefault(p => p.Id == m.ParentId)?.Name ?? "";
});
return menus;
@ -56,7 +56,6 @@ namespace Bootstrap.DataAccess.MongoDB
{
if (string.IsNullOrEmpty(p.Id))
{
p.Id = null;
DbManager.Menus.InsertOne(p);
p.Id = DbManager.Menus.Find(m => m.Name == p.Name && m.Category == p.Category && m.ParentId == p.ParentId && m.Url == p.Url).FirstOrDefault().Id;
}

View File

@ -8,19 +8,18 @@ namespace Bootstrap.DataAccess.MongoDB
public class RejectUser
{
/// <summary>
/// 获得/设置 操作日志主键ID
///
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
///
/// </summary>
public string UserName { get; set; } = "";
/// <summary>
///
/// </summary>
public string UserName { get; set; }
/// <summary>
///
/// </summary>
public string DisplayName { get; set; }
public string DisplayName { get; set; } = "";
/// <summary>
///
@ -30,7 +29,7 @@ namespace Bootstrap.DataAccess.MongoDB
/// <summary>
///
/// </summary>
public string RejectedBy { get; set; }
public string RejectedBy { get; set; } = "";
/// <summary>
///
@ -40,6 +39,6 @@ namespace Bootstrap.DataAccess.MongoDB
/// <summary>
///
/// </summary>
public string RejectedReason { get; set; }
public string RejectedReason { get; set; } = "";
}
}

View File

@ -13,12 +13,12 @@ namespace Bootstrap.DataAccess.MongoDB
/// <summary>
/// 此角色关联的所有菜单
/// </summary>
public IEnumerable<string> Menus { get; set; }
public IEnumerable<string> Menus { get; set; } = new List<string>();
/// <summary>
/// 此角色关联的所有应用程序
/// </summary>
public IEnumerable<string> Apps { get; set; }
public IEnumerable<string> Apps { get; set; } = new List<string>();
/// <summary>
///
@ -130,7 +130,7 @@ namespace Bootstrap.DataAccess.MongoDB
{
var roles = RoleHelper.Retrieves().Cast<Role>().ToList();
roles.ForEach(r => r.Checked = (r.Menus != null && r.Menus.Contains(menuId)) ? "checked" : "");
roles.ForEach(r => r.Menus = null);
roles.ForEach(r => r.Menus = new List<string>());
return roles;
}

View File

@ -16,7 +16,7 @@ namespace Bootstrap.DataAccess.MongoDB
///
/// </summary>
/// <returns></returns>
public override Page<DataAccess.Trace> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string ip)
public override Page<DataAccess.Trace> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string? ip)
{
// filter
var filterBuilder = Builders<DataAccess.Trace>.Filter;
@ -28,12 +28,9 @@ namespace Bootstrap.DataAccess.MongoDB
// sort
var sortBuilder = Builders<DataAccess.Trace>.Sort;
SortDefinition<DataAccess.Trace> sort = null;
var sort = po.Order == "asc" ? sortBuilder.Ascending(t => t.LogTime) : sortBuilder.Descending(t => t.LogTime);
switch (po.Sort)
{
case "LogTime":
sort = po.Order == "asc" ? sortBuilder.Ascending(t => t.LogTime) : sortBuilder.Descending(t => t.LogTime);
break;
case "IP":
sort = po.Order == "asc" ? sortBuilder.Ascending(t => t.Ip) : sortBuilder.Descending(t => t.Ip);
break;
@ -73,7 +70,7 @@ namespace Bootstrap.DataAccess.MongoDB
/// <param name="endTime"></param>
/// <param name="ip"></param>
/// <returns></returns>
public override IEnumerable<DataAccess.Trace> RetrieveAll(DateTime? startTime, DateTime? endTime, string ip)
public override IEnumerable<DataAccess.Trace> RetrieveAll(DateTime? startTime, DateTime? endTime, string? ip)
{
var filterBuilder = Builders<DataAccess.Trace>.Filter;
var filter = filterBuilder.Empty;

View File

@ -1,4 +1,5 @@
using Bootstrap.Security;
using Bootstrap.Security.Mvc;
using Longbow.Security.Cryptography;
using MongoDB.Driver;
using System;
@ -15,19 +16,19 @@ namespace Bootstrap.DataAccess.MongoDB
/// <summary>
///
/// </summary>
public IEnumerable<string> Roles { get; set; }
public IEnumerable<string> Roles { get; set; } = new List<string>();
/// <summary>
///
/// </summary>
public IEnumerable<string> Groups { get; set; }
public IEnumerable<string> Groups { get; set; } = new List<string>();
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public override BootstrapUser RetrieveUserByUserName(string userName)
public override BootstrapUser? RetrieveUserByUserName(string userName)
{
var project = Builders<User>.Projection.Include(u => u.Id)
.Include(u => u.UserName)
@ -39,7 +40,7 @@ namespace Bootstrap.DataAccess.MongoDB
if (ret != null)
{
if (string.IsNullOrEmpty(ret.Icon)) ret.Icon = "default.jpg";
if (string.IsNullOrEmpty(ret.App)) ret.App = "0";
if (string.IsNullOrEmpty(ret.App)) ret.App = BootstrapAppContext.AppId;
}
return ret;
}
@ -118,8 +119,6 @@ namespace Bootstrap.DataAccess.MongoDB
RegisterTime = DateTime.Now,
ApprovedTime = user.ApprovedTime,
ApprovedBy = user.ApprovedBy,
Roles = new List<string>(),
Groups = new List<string>(),
Icon = user.Icon,
Description = user.Description,
IsReset = 0

View File

@ -14,17 +14,17 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 应用程序主键ID
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 获得/设置 群组名称
/// </summary>
public string AppName { get; set; }
public string AppName { get; set; } = "未设置";
/// <summary>
/// 获取/设置 用户群组关联状态 checked 标示已经关联 '' 标示未关联
/// </summary>
public string Checked { get; set; }
public string Checked { get; set; } = "";
/// <summary>
/// 根据角色ID指派部门

View File

@ -11,7 +11,7 @@ namespace Bootstrap.DataAccess
/// </summary>
public class AutoDB
{
private string _folder;
private string _folder = "";
/// <summary>
/// 数据库检查方法

View File

@ -5,22 +5,22 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Bootstrap.Security.DataAccess" Version="3.0.1-beta3" />
<PackageReference Include="Bootstrap.Security.Mvc" Version="3.0.2-beta6" />
<PackageReference Include="Longbow" Version="3.0.0" />
<PackageReference Include="Longbow.Cache" Version="3.0.1-beta2" />
<PackageReference Include="Longbow.Data" Version="3.0.1-beta1" />
<PackageReference Include="Longbow.GiteeAuth" Version="3.0.1-beta1" />
<PackageReference Include="Longbow.GitHubAuth" Version="3.0.1-beta1" />
<PackageReference Include="Longbow.OAuth" Version="3.0.1" />
<PackageReference Include="Bootstrap.Security.DataAccess" Version="3.0.1" />
<PackageReference Include="Bootstrap.Security.Mvc" Version="3.0.2" />
<PackageReference Include="Longbow" Version="3.0.1" />
<PackageReference Include="Longbow.Cache" Version="3.0.1" />
<PackageReference Include="Longbow.Data" Version="3.0.1" />
<PackageReference Include="Longbow.GiteeAuth" Version="3.0.1" />
<PackageReference Include="Longbow.GitHubAuth" Version="3.0.1" />
<PackageReference Include="Longbow.OAuth" Version="3.0.2" />
<PackageReference Include="Longbow.PetaPoco" Version="1.0.2" />
<PackageReference Include="Longbow.Security.Cryptography" Version="1.3.0" />
<PackageReference Include="Longbow.Tasks" Version="3.0.0" />
<PackageReference Include="Longbow.Web" Version="3.0.1-beta1" />
<PackageReference Include="Longbow.WeChatAuth" Version="3.0.0" />
<PackageReference Include="Longbow.Tasks" Version="3.0.1" />
<PackageReference Include="Longbow.Web" Version="3.0.1" />
<PackageReference Include="Longbow.WeChatAuth" Version="3.0.1" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="3.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.7.0" />
<PackageReference Include="PetaPoco.Extensions" Version="3.0.0" />
<PackageReference Include="PetaPoco.Extensions" Version="3.0.1" />
</ItemGroup>
</Project>

View File

@ -20,7 +20,7 @@ namespace Bootstrap.DataAccess
/// <param name="appIds"></param>
/// <param name="dictIds"></param>
/// <param name="cacheKey"></param>
public static void ClearCache(IEnumerable<string> roleIds = null, IEnumerable<string> userIds = null, IEnumerable<string> groupIds = null, IEnumerable<string> menuIds = null, IEnumerable<string> appIds = null, IEnumerable<string> dictIds = null, string cacheKey = null)
public static void ClearCache(IEnumerable<string>? roleIds = null, IEnumerable<string>? userIds = null, IEnumerable<string>? groupIds = null, IEnumerable<string>? menuIds = null, IEnumerable<string>? appIds = null, IEnumerable<string>? dictIds = null, string? cacheKey = null)
{
var cacheKeys = new List<string>();
var corsKeys = new List<string>();

View File

@ -10,20 +10,21 @@ namespace Bootstrap.DataAccess
[TableName("DBLogs")]
public class DBLog
{
/// <summary>
/// 获得/设置 主键ID
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 获得/设置 当前登陆名
/// </summary>
public string UserName { get; set; }
public string? UserName { get; set; }
/// <summary>
/// 获得/设置 数据库执行脚本
/// </summary>
public string SQL { get; set; }
public string SQL { get; set; } = "";
/// <summary>
/// 获取/设置 用户角色关联状态 checked 标示已经关联 '' 标示未关联
@ -38,8 +39,10 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="userName"></param>
/// <returns></returns>
public virtual Page<DBLog> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string userName)
public virtual Page<DBLog> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string? userName)
{
if (string.IsNullOrEmpty(po.Sort)) po.Sort = "LogTime";
if (string.IsNullOrEmpty(po.Order)) po.Order = "desc";
var sql = new Sql("select * from DBLogs");
if (startTime.HasValue) sql.Where("LogTime >= @0", startTime.Value);
if (endTime.HasValue) sql.Where("LogTime < @0", endTime.Value.AddDays(1).AddSeconds(-1));

View File

@ -10,18 +10,19 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 创建数据库实体类时发生异常实例
/// </summary>
public static Exception Exception { get; set; }
public static Exception? Exception { get; private set; }
/// <summary>
/// 根据配置文件动态创建数据库实体类方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Create<T>()
public static T? Create<T>() where T : class
{
T t = default;
T? t = default;
try
{
Exception = null;
t = Longbow.Data.DbContextManager.Create<T>();
}
catch (Exception ex)

View File

@ -20,7 +20,7 @@ namespace Bootstrap.DataAccess
/// <param name="keepAlive"></param>
/// <param name="enableLog">是否记录日志</param>
/// <returns></returns>
public static IDatabase Create(string connectionName = null, bool keepAlive = false, bool enableLog = true)
public static IDatabase Create(string? connectionName = null, bool keepAlive = false, bool enableLog = true)
{
if (Mappers.GetMapper(typeof(Exceptions), null) == null) Mappers.Register(typeof(Exceptions).Assembly, new BootstrapDataAccessConventionMapper());
var db = Longbow.Data.DbManager.Create(connectionName, keepAlive);

View File

@ -106,7 +106,7 @@ namespace Bootstrap.DataAccess
/// 获取头像路径
/// </summary>
/// <returns></returns>
public virtual string RetrieveIconFolderPath() => (DictHelper.RetrieveDicts().FirstOrDefault(d => d.Name == "头像路径" && d.Category == "头像地址" && d.Define == 0) ?? new BootstrapDict { Code = "~/images/uploader/" }).Code;
public virtual string? RetrieveIconFolderPath() => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Name == "头像路径" && d.Category == "头像地址" && d.Define == 0)?.Code;
/// <summary>
/// 获得默认的前台首页地址,默认为~/Home/Index
@ -168,20 +168,26 @@ namespace Bootstrap.DataAccess
/// 获得 IP地理位置
/// </summary>
/// <returns></returns>
public string RetrieveLocaleIPSvr() => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == "IP地理位置接口" && d.Define == 0)?.Code;
public string RetrieveLocaleIPSvr() => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == "IP地理位置接口" && d.Define == 0)?.Code ?? string.Empty;
/// <summary>
///
/// </summary>
/// <returns></returns>
public string RetrieveLocaleIPSvrCachePeriod() => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == "IP请求缓存时长" && d.Define == 0)?.Code;
public int RetrieveLocaleIPSvrCachePeriod()
{
var period = DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == "IP请求缓存时长" && d.Define == 0)?.Code;
var ret = 10;
if (!string.IsNullOrEmpty(period) && int.TryParse(period, out var svrPeriod)) ret = svrPeriod;
return ret;
}
/// <summary>
/// 获得 项目是否获取登录地点 默认为false
/// </summary>
/// <param name="ipSvr">服务提供名称</param>
/// <returns></returns>
public string RetrieveLocaleIPSvrUrl(string ipSvr) => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == ipSvr && d.Define == 0)?.Code;
public string? RetrieveLocaleIPSvrUrl(string ipSvr) => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == ipSvr && d.Define == 0)?.Code;
/// <summary>
/// 获得 访问日志保留时长 默认为1个月

View File

@ -16,42 +16,42 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 主键
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 获得/设置 主键
/// </summary>
public string AppDomainName { get; set; }
public string AppDomainName { get; set; } = "";
/// <summary>
/// 获得/设置 用户请求页面地址
/// </summary>
public string ErrorPage { get; set; }
public string ErrorPage { get; set; } = "";
/// <summary>
/// 获得/设置 用户 ID
/// </summary>
public string UserId { get; set; }
public string? UserId { get; set; }
/// <summary>
/// 获得/设置 用户 IP
/// </summary>
public string UserIp { get; set; }
public string? UserIp { get; set; }
/// <summary>
/// 获得/设置 异常类型
/// </summary>
public string ExceptionType { get; set; }
public string? ExceptionType { get; set; }
/// <summary>
/// 获得/设置 异常错误描述信息
/// </summary>
public string Message { get; set; }
public string Message { get; set; } = "";
/// <summary>
/// 获得/设置 异常堆栈信息
/// </summary>
public string StackTrace { get; set; }
public string? StackTrace { get; set; }
/// <summary>
/// 获得/设置 日志时间戳
@ -62,12 +62,12 @@ namespace Bootstrap.DataAccess
/// 获得/设置 时间描述 2分钟内为刚刚
/// </summary>
[ResultColumn]
public string Period { get; set; }
public string Period { get; set; } = "";
/// <summary>
/// 获得/设置 分类信息
/// </summary>
public string Category { get; set; }
public string Category { get; set; } = "";
private static void ClearExceptions() => System.Threading.Tasks.Task.Run(() =>
{
@ -94,7 +94,9 @@ namespace Bootstrap.DataAccess
category = "DB";
break;
}
#pragma warning disable CS8600 // 将 null 文本或可能的 null 值转换为非 null 类型。
loopEx = loopEx.InnerException;
#pragma warning restore CS8600 // 将 null 文本或可能的 null 值转换为非 null 类型。
}
try
{
@ -137,6 +139,8 @@ namespace Bootstrap.DataAccess
public virtual Page<Exceptions> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime)
{
if (string.IsNullOrEmpty(po.Sort)) po.Sort = "LogTime";
if (string.IsNullOrEmpty(po.Order)) po.Sort = "desc";
var sql = new Sql("select * from Exceptions");
if (startTime.HasValue) sql.Append("where LogTime > @0", startTime.Value);
if (endTime.HasValue) sql.Append("where LogTime < @0", endTime.Value.AddDays(1).AddSeconds(-1));

View File

@ -16,13 +16,13 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 群组描述
/// </summary>
public string Description { get; set; }
public string? Description { get; set; }
/// <summary>
/// 获取/设置 用户群组关联状态 checked 标示已经关联 '' 标示未关联
/// </summary>
[ResultColumn]
public string Checked { get; set; }
public string Checked { get; set; } = "";
/// <summary>
/// 查询所有群组信息
@ -64,7 +64,7 @@ namespace Bootstrap.DataAccess
public virtual bool Save(Group p)
{
DbManager.Create().Save(p);
return !p.Id.IsNullOrEmpty();
return true;
}
/// <summary>

View File

@ -23,7 +23,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public static IEnumerable<App> RetrievesByRoleId(string roleId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveAppsByRoleIdDataKey, roleId), key => DbContextManager.Create<App>().RetrievesByRoleId(roleId), RetrieveAppsByRoleIdDataKey);
public static IEnumerable<App> RetrievesByRoleId(string roleId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveAppsByRoleIdDataKey, roleId), key => DbContextManager.Create<App>()?.RetrievesByRoleId(roleId), RetrieveAppsByRoleIdDataKey) ?? new App[0];
/// <summary>
/// 根据角色ID以及选定的App ID保到角色应用表
@ -33,7 +33,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SaveByRoleId(string roleId, IEnumerable<string> appIds)
{
var ret = DbContextManager.Create<App>().SaveByRoleId(roleId, appIds);
var ret = DbContextManager.Create<App>()?.SaveByRoleId(roleId, appIds) ?? false;
if (ret) CacheCleanUtility.ClearCache(appIds: appIds, roleIds: new List<string>() { roleId });
return ret;
}
@ -43,6 +43,6 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<string> RetrievesByUserName(string userName) => CacheManager.GetOrAdd($"{DbHelper.RetrieveAppsByUserNameDataKey}-{userName}", key => DbContextManager.Create<App>().RetrievesByUserName(userName), RetrieveAppsByUserNameDataKey);
public static IEnumerable<string> RetrievesByUserName(string? userName) => string.IsNullOrEmpty(userName) ? new string[0] : CacheManager.GetOrAdd($"{DbHelper.RetrieveAppsByUserNameDataKey}-{userName}", key => DbContextManager.Create<App>()?.RetrievesByUserName(userName), RetrieveAppsByUserNameDataKey) ?? new string[0];
}
}

View File

@ -27,7 +27,7 @@ namespace Bootstrap.DataAccess
/// 获得所有字典项配置数据集合方法 内部使用了缓存,缓存值 BootstrapMenu-RetrieveMenus
/// </summary>
/// <returns></returns>
public static IEnumerable<BootstrapDict> RetrieveDicts() => CacheManager.GetOrAdd(RetrieveDictsDataKey, key => DbContextManager.Create<Dict>()?.RetrieveDicts());
public static IEnumerable<BootstrapDict> RetrieveDicts() => CacheManager.GetOrAdd(RetrieveDictsDataKey, key => DbContextManager.Create<Dict>()?.RetrieveDicts()) ?? new BootstrapDict[0];
private static IEnumerable<BootstrapDict> RetrieveProtectedDicts() => RetrieveDicts().Where(d => d.Define == 0 || d.Category == "测试平台");
@ -68,8 +68,8 @@ namespace Bootstrap.DataAccess
// 禁止删除系统数据与测试平台数据
if (RetrieveSystemModel() && RetrieveProtectedDicts().Any(d => value.Any(v => v == d.Id))) return true;
var ret = DbContextManager.Create<Dict>().Delete(value);
CacheCleanUtility.ClearCache(dictIds: value);
var ret = DbContextManager.Create<Dict>()?.Delete(value) ?? false;
if (ret) CacheCleanUtility.ClearCache(dictIds: value);
return ret;
}
@ -82,7 +82,7 @@ namespace Bootstrap.DataAccess
{
if (RetrieveSystemModel() && !string.IsNullOrEmpty(p.Id) && RetrieveProtectedDicts().Any(m => m.Id == p.Id)) return true;
var ret = DbContextManager.Create<Dict>().Save(p);
var ret = DbContextManager.Create<Dict>()?.Save(p) ?? false;
if (ret) CacheCleanUtility.ClearCache(dictIds: new List<string>());
return ret;
}
@ -97,9 +97,9 @@ namespace Bootstrap.DataAccess
if (!string.IsNullOrEmpty(name) && !name.Equals("None", StringComparison.OrdinalIgnoreCase))
{
var url = RetrieveLocaleIPSvrUrl(name);
op.Locator = string.IsNullOrEmpty(url) ? null : DefaultIPLocatorProvider.CreateLocator(name);
op.Locator = DefaultIPLocatorProvider.CreateLocator(name);
op.Url = string.IsNullOrEmpty(url) ? string.Empty : $"{url}{op.IP}";
if (int.TryParse(RetrieveLocaleIPSvrCachePeriod(), out var period) && period > 0) op.Period = period * 60 * 1000;
op.Period = RetrieveLocaleIPSvrCachePeriod() * 60 * 1000;
}
}
@ -110,7 +110,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SaveSettings(BootstrapDict dict)
{
var ret = DbContextManager.Create<Dict>().SaveSettings(dict);
var ret = DbContextManager.Create<Dict>()?.SaveSettings(dict) ?? false;
if (ret) CacheCleanUtility.ClearCache(dictIds: new List<string>());
return ret;
}
@ -119,101 +119,101 @@ namespace Bootstrap.DataAccess
/// 获取字典分类名称
/// </summary>
/// <returns></returns>
public static IEnumerable<string> RetrieveCategories() => CacheManager.GetOrAdd(RetrieveCategoryDataKey, key => DbContextManager.Create<Dict>().RetrieveCategories());
public static IEnumerable<string> RetrieveCategories() => CacheManager.GetOrAdd(RetrieveCategoryDataKey, key => DbContextManager.Create<Dict>()?.RetrieveCategories()) ?? new string[0];
/// <summary>
/// 获取站点 Title 配置信息
/// </summary>
/// <param name="appId"></param>
/// <returns></returns>
public static string RetrieveWebTitle(string appId) => DbContextManager.Create<Dict>().RetrieveWebTitle(appId);
public static string RetrieveWebTitle(string appId) => DbContextManager.Create<Dict>()?.RetrieveWebTitle(appId) ?? string.Empty;
/// <summary>
/// 获取站点 Footer 配置信息
/// </summary>
/// <param name="appId"></param>
/// <returns></returns>
public static string RetrieveWebFooter(string appId) => DbContextManager.Create<Dict>().RetrieveWebFooter(appId);
public static string RetrieveWebFooter(string appId) => DbContextManager.Create<Dict>()?.RetrieveWebFooter(appId) ?? string.Empty;
/// <summary>
/// 获得系统中配置的可以使用的网站样式
/// </summary>
/// <returns></returns>
public static IEnumerable<BootstrapDict> RetrieveThemes() => DbContextManager.Create<Dict>().RetrieveThemes();
public static IEnumerable<BootstrapDict> RetrieveThemes() => DbContextManager.Create<Dict>()?.RetrieveThemes() ?? new BootstrapDict[0];
/// <summary>
/// 获得网站设置中的当前样式
/// </summary>
/// <returns></returns>
public static string RetrieveActiveTheme() => DbContextManager.Create<Dict>().RetrieveActiveTheme();
public static string RetrieveActiveTheme() => DbContextManager.Create<Dict>()?.RetrieveActiveTheme() ?? string.Empty;
/// <summary>
/// 获取头像路径
/// </summary>
/// <returns></returns>
public static string RetrieveIconFolderPath() => DbContextManager.Create<Dict>().RetrieveIconFolderPath();
public static string RetrieveIconFolderPath() => DbContextManager.Create<Dict>()?.RetrieveIconFolderPath() ?? "~/images/uploader/";
/// <summary>
/// 获得默认的前台首页地址,默认为 ~/Home/Index
/// </summary>
/// <param name="appId">应用程序编码</param>
/// <returns></returns>
public static string RetrieveHomeUrl(string appId) => DbContextManager.Create<Dict>().RetrieveHomeUrl(appId);
public static string RetrieveHomeUrl(string appId) => DbContextManager.Create<Dict>()?.RetrieveHomeUrl(appId) ?? "~/Home/Index";
/// <summary>
/// 获取所有应用程序数据方法
/// </summary>
/// <returns></returns>
public static IEnumerable<KeyValuePair<string, string>> RetrieveApps() => DbContextManager.Create<Dict>().RetrieveApps();
public static IEnumerable<KeyValuePair<string, string>> RetrieveApps() => DbContextManager.Create<Dict>()?.RetrieveApps() ?? new KeyValuePair<string, string>[0];
/// <summary>
/// 程序异常时长 默认 1 个月
/// </summary>
/// <returns></returns>
public static int RetrieveExceptionsLogPeriod() => DbContextManager.Create<Dict>().RetrieveExceptionsLogPeriod();
public static int RetrieveExceptionsLogPeriod() => DbContextManager.Create<Dict>()?.RetrieveExceptionsLogPeriod() ?? 1;
/// <summary>
/// 获得操作日志保留时长 默认 12 个月
/// </summary>
/// <returns></returns>
public static int RetrieveLogsPeriod() => DbContextManager.Create<Dict>().RetrieveLogsPeriod();
public static int RetrieveLogsPeriod() => DbContextManager.Create<Dict>()?.RetrieveLogsPeriod() ?? 12;
/// <summary>
/// 获得登录日志保留时长 默认 12 个月
/// </summary>
/// <returns></returns>
public static int RetrieveLoginLogsPeriod() => DbContextManager.Create<Dict>().RetrieveLoginLogsPeriod();
public static int RetrieveLoginLogsPeriod() => DbContextManager.Create<Dict>()?.RetrieveLoginLogsPeriod() ?? 12;
/// <summary>
/// 获取登录认证Cookie保留时长 默认 7 天
/// </summary>
/// <returns></returns>
public static int RetrieveCookieExpiresPeriod() => DbContextManager.Create<Dict>().RetrieveCookieExpiresPeriod();
public static int RetrieveCookieExpiresPeriod() => DbContextManager.Create<Dict>()?.RetrieveCookieExpiresPeriod() ?? 7;
/// <summary>
/// 获取 IP 地址位置查询服务名称
/// </summary>
/// <returns></returns>
public static string RetrieveLocaleIPSvr() => DbContextManager.Create<Dict>().RetrieveLocaleIPSvr();
public static string RetrieveLocaleIPSvr() => DbContextManager.Create<Dict>()?.RetrieveLocaleIPSvr() ?? string.Empty;
/// <summary>
/// 通过 IP 地理位置查询服务名称获得请求地址方法
/// </summary>
/// <param name="ipSvr">ip地址请求服务名称</param>
/// <returns></returns>
public static string RetrieveLocaleIPSvrUrl(string ipSvr) => DbContextManager.Create<Dict>().RetrieveLocaleIPSvrUrl(ipSvr);
public static string RetrieveLocaleIPSvrUrl(string ipSvr) => DbContextManager.Create<Dict>()?.RetrieveLocaleIPSvrUrl(ipSvr) ?? string.Empty;
/// <summary>
/// 获取 IP 地理位置查询服务缓存时长
/// </summary>
/// <returns></returns>
public static string RetrieveLocaleIPSvrCachePeriod() => DbContextManager.Create<Dict>().RetrieveLocaleIPSvrCachePeriod();
public static int RetrieveLocaleIPSvrCachePeriod() => DbContextManager.Create<Dict>()?.RetrieveLocaleIPSvrCachePeriod() ?? 10;
/// <summary>
/// 访问日志保留时长 默认 1 个月
/// </summary>
/// <returns></returns>
public static int RetrieveAccessLogPeriod() => DbContextManager.Create<Dict>().RetrieveAccessLogPeriod();
public static int RetrieveAccessLogPeriod() => DbContextManager.Create<Dict>()?.RetrieveAccessLogPeriod() ?? 1;
/// <summary>
/// 获得 是否为演示系统 默认为 false 不是演示系统
@ -225,19 +225,19 @@ namespace Bootstrap.DataAccess
/// 获得验证码图床地址
/// </summary>
/// <returns></returns>
public static string RetrieveImagesLibUrl() => DbContextManager.Create<Dict>().RetrieveImagesLibUrl();
public static string RetrieveImagesLibUrl() => DbContextManager.Create<Dict>()?.RetrieveImagesLibUrl() ?? string.Empty;
/// <summary>
/// 获得数据区卡片标题是否显示
/// </summary>
/// <returns></returns>
public static bool RetrieveCardTitleStatus() => DbContextManager.Create<Dict>().RetrieveCardTitleStatus();
public static bool RetrieveCardTitleStatus() => DbContextManager.Create<Dict>()?.RetrieveCardTitleStatus() ?? true;
/// <summary>
/// 获得侧边栏状态 真时显示
/// 获得侧边栏状态 真时显示
/// </summary>
/// <returns></returns>
public static bool RetrieveSidebarStatus() => DbContextManager.Create<Dict>().RetrieveSidebarStatus();
public static bool RetrieveSidebarStatus() => DbContextManager.Create<Dict>()?.RetrieveSidebarStatus() ?? true;
/// <summary>
/// 获得是否允许短信验证码登录

View File

@ -32,7 +32,7 @@ namespace Bootstrap.DataAccess
/// 查询一周内所有异常
/// </summary>
/// <returns></returns>
public static IEnumerable<Exceptions> Retrieves() => CacheManager.GetOrAdd(RetrieveExceptionsDataKey, key => DbContextManager.Create<Exceptions>().Retrieves());
public static IEnumerable<Exceptions> Retrieves() => CacheManager.GetOrAdd(RetrieveExceptionsDataKey, key => DbContextManager.Create<Exceptions>()?.Retrieves()) ?? new Exceptions[0];
/// <summary>
///
@ -41,6 +41,6 @@ namespace Bootstrap.DataAccess
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <returns></returns>
public static Page<Exceptions> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime) => DbContextManager.Create<Exceptions>().RetrievePages(po, startTime, endTime);
public static Page<Exceptions> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime) => DbContextManager.Create<Exceptions>()?.RetrievePages(po, startTime, endTime) ?? new Page<Exceptions>() { Items = new List<Exceptions>() };
}
}

View File

@ -31,7 +31,7 @@ namespace Bootstrap.DataAccess
/// 查询所有群组信息
/// </summary>
/// <returns></returns>
public static IEnumerable<Group> Retrieves() => CacheManager.GetOrAdd(RetrieveGroupsDataKey, key => DbContextManager.Create<Group>().Retrieves());
public static IEnumerable<Group> Retrieves() => CacheManager.GetOrAdd(RetrieveGroupsDataKey, key => DbContextManager.Create<Group>()?.Retrieves()) ?? new Group[0];
/// <summary>
/// 删除群组信息
@ -39,7 +39,7 @@ namespace Bootstrap.DataAccess
/// <param name="values"></param>
public static bool Delete(IEnumerable<string> values)
{
var ret = DbContextManager.Create<Group>().Delete(values);
var ret = DbContextManager.Create<Group>()?.Delete(values) ?? false;
if (ret) CacheCleanUtility.ClearCache(groupIds: values);
return ret;
}
@ -51,7 +51,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool Save(Group p)
{
var ret = DbContextManager.Create<Group>().Save(p);
var ret = DbContextManager.Create<Group>()?.Save(p) ?? false;
if (ret) CacheCleanUtility.ClearCache(groupIds: string.IsNullOrEmpty(p.Id) ? new List<string>() : new List<string>() { p.Id });
return ret;
}
@ -60,7 +60,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public static IEnumerable<Group> RetrievesByUserId(string userId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveGroupsByUserIdDataKey, userId), k => DbContextManager.Create<Group>().RetrievesByUserId(userId), RetrieveGroupsByUserIdDataKey);
public static IEnumerable<Group> RetrievesByUserId(string userId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveGroupsByUserIdDataKey, userId), k => DbContextManager.Create<Group>()?.RetrievesByUserId(userId), RetrieveGroupsByUserIdDataKey) ?? new Group[0];
/// <summary>
/// 保存用户部门关系
@ -70,7 +70,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SaveByUserId(string userId, IEnumerable<string> groupIds)
{
var ret = DbContextManager.Create<Group>().SaveByUserId(userId, groupIds);
var ret = DbContextManager.Create<Group>()?.SaveByUserId(userId, groupIds) ?? false;
if (ret) CacheCleanUtility.ClearCache(groupIds: groupIds, userIds: new List<string>() { userId });
return ret;
}
@ -80,7 +80,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public static IEnumerable<Group> RetrievesByRoleId(string roleId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveGroupsByRoleIdDataKey, roleId), key => DbContextManager.Create<Group>().RetrievesByRoleId(roleId), RetrieveGroupsByRoleIdDataKey);
public static IEnumerable<Group> RetrievesByRoleId(string roleId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveGroupsByRoleIdDataKey, roleId), key => DbContextManager.Create<Group>()?.RetrievesByRoleId(roleId), RetrieveGroupsByRoleIdDataKey) ?? new Group[0];
/// <summary>
/// 根据角色ID以及选定的部门ID保到角色部门表
@ -90,7 +90,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SaveByRoleId(string roleId, IEnumerable<string> groupIds)
{
var ret = DbContextManager.Create<Group>().SaveByRoleId(roleId, groupIds);
var ret = DbContextManager.Create<Group>()?.SaveByRoleId(roleId, groupIds) ?? false;
if (ret) CacheCleanUtility.ClearCache(groupIds: groupIds, roleIds: new List<string>() { roleId });
return ret;
}
@ -100,6 +100,6 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<BootstrapGroup> RetrievesByUserName(string userName) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveGroupsByUserNameDataKey, userName), r => DbContextManager.Create<Group>().RetrievesByUserName(userName), RetrieveGroupsByUserNameDataKey);
public static IEnumerable<BootstrapGroup> RetrievesByUserName(string userName) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveGroupsByUserNameDataKey, userName), r => DbContextManager.Create<Group>()?.RetrievesByUserName(userName), RetrieveGroupsByUserNameDataKey) ?? new BootstrapGroup[0];
}
}

View File

@ -22,13 +22,13 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="opType"></param>
/// <returns></returns>
public static Page<Log> RetrievePages(PaginationOption op, DateTime? startTime, DateTime? endTime, string opType) => DbContextManager.Create<Log>().RetrievePages(op, startTime, endTime, opType);
public static Page<Log> RetrievePages(PaginationOption op, DateTime? startTime, DateTime? endTime, string? opType) => DbContextManager.Create<Log>()?.RetrievePages(op, startTime, endTime, opType) ?? new Page<Log>() { Items = new List<Log>() };
/// <summary>
/// 查询所有日志信息
/// </summary>
/// <returns></returns>
public static IEnumerable<Log> RetrieveAll(DateTime? startTime, DateTime? endTime, string opType) => DbContextManager.Create<Log>().RetrieveAll(startTime, endTime, opType);
public static IEnumerable<Log> RetrieveAll(DateTime? startTime, DateTime? endTime, string? opType) => DbContextManager.Create<Log>()?.RetrieveAll(startTime, endTime, opType) ?? new Log[0];
/// <summary>
/// 保存新增的日志信息
@ -38,7 +38,7 @@ namespace Bootstrap.DataAccess
public static bool Save(Log log)
{
log.LogTime = DateTime.Now;
return DbContextManager.Create<Log>().Save(log);
return DbContextManager.Create<Log>()?.Save(log) ?? false;
}
#region
@ -63,7 +63,7 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="userName"></param>
/// <returns></returns>
public static Page<DBLog> RetrieveDBLogs(PaginationOption op, DateTime? startTime, DateTime? endTime, string userName) => DbContextManager.Create<DBLog>().RetrievePages(op, startTime, endTime, userName);
public static Page<DBLog> RetrieveDBLogs(PaginationOption op, DateTime? startTime, DateTime? endTime, string? userName) => DbContextManager.Create<DBLog>()?.RetrievePages(op, startTime, endTime, userName) ?? new Page<DBLog>() { Items = new List<DBLog>() };
/// <summary>
/// 数据库脚本执行日志任务实体类

View File

@ -40,7 +40,7 @@ namespace Bootstrap.DataAccess
OS = $"{agent.OS?.Name} {agent.OS?.Version}",
Result = auth ? "登录成功" : "登录失败"
};
return DbContextManager.Create<LoginUser>().Log(loginUser);
return DbContextManager.Create<LoginUser>()?.Log(loginUser) ?? false;
}
/// <summary>
@ -50,7 +50,7 @@ namespace Bootstrap.DataAccess
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="ip"></param>
public static Page<LoginUser> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string ip) => DbContextManager.Create<LoginUser>().RetrieveByPages(po, startTime, endTime, ip);
public static Page<LoginUser> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string? ip) => DbContextManager.Create<LoginUser>()?.RetrieveByPages(po, startTime, endTime, ip) ?? new Page<LoginUser>() { Items = new List<LoginUser>() };
/// <summary>
/// 查询所有登录日志
@ -59,9 +59,9 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="ip"></param>
/// <returns></returns>
public static IEnumerable<LoginUser> RetrieveAll(DateTime? startTime, DateTime? endTime, string ip)
public static IEnumerable<LoginUser> RetrieveAll(DateTime? startTime, DateTime? endTime, string? ip)
{
return DbContextManager.Create<LoginUser>().RetrieveAll(startTime, endTime, ip);
return DbContextManager.Create<LoginUser>()?.RetrieveAll(startTime, endTime, ip) ?? new LoginUser[0];
}
}
}

View File

@ -42,16 +42,18 @@ namespace Bootstrap.DataAccess
// 系统菜单
var menus = RetrieveAllMenus("Admin");
#pragma warning disable CS8602 // 取消引用可能出现的空引用。
var menu = menus.FirstOrDefault(m => m.Id.Equals(p.Id, System.StringComparison.OrdinalIgnoreCase));
#pragma warning restore CS8602 // 取消引用可能出现的空引用。
if (menu != null && menu.Category == "0") return true;
// 演示系统
var appMenus = BootstrapAppContext.Configuration.GetSection("AppMenus").Get<ICollection<string>>();
if (appMenus.Any(m => m.Equals(menu.Name, System.StringComparison.OrdinalIgnoreCase))) return true;
if (appMenus.Any(m => m.Equals(menu?.Name, StringComparison.OrdinalIgnoreCase))) return true;
}
}
var ret = DbContextManager.Create<Menu>().Save(p);
var ret = DbContextManager.Create<Menu>()?.Save(p) ?? false;
if (ret) CacheCleanUtility.ClearCache(menuIds: string.IsNullOrEmpty(p.Id) ? new List<string>() : new List<string>() { p.Id });
return ret;
}
@ -73,10 +75,12 @@ namespace Bootstrap.DataAccess
// 演示系统
var appMenus = BootstrapAppContext.Configuration.GetSection("AppMenus").Get<ICollection<string>>();
var appIds = RetrieveAllMenus("Admin").Where(m => appMenus.Any(app => m.Name.Equals(app, System.StringComparison.OrdinalIgnoreCase))).Select(m => m.Id);
value = value.Where(m => !appIds.Any(app => app.Equals(m, System.StringComparison.OrdinalIgnoreCase)));
#pragma warning disable CS8602 // 取消引用可能出现的空引用。
value = value.Where(m => !appIds.Any(app => app.Equals(m, StringComparison.OrdinalIgnoreCase)));
#pragma warning restore CS8602 // 取消引用可能出现的空引用。
if (!value.Any()) return true;
}
var ret = DbContextManager.Create<Menu>().Delete(value);
var ret = DbContextManager.Create<Menu>()?.Delete(value) ?? false;
if (ret) CacheCleanUtility.ClearCache(menuIds: value);
return ret;
}
@ -86,14 +90,14 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<BootstrapMenu> RetrieveMenusByUserName(string userName) => RetrieveAllMenus(userName);
public static IEnumerable<BootstrapMenu> RetrieveMenusByUserName(string? userName) => RetrieveAllMenus(userName);
/// <summary>
/// 通过角色获取相关菜单集合
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public static IEnumerable<string> RetrieveMenusByRoleId(string roleId) => CacheManager.GetOrAdd($"{RetrieveMenusByRoleIdDataKey}-{roleId}", k => DbContextManager.Create<Menu>().RetrieveMenusByRoleId(roleId), RetrieveMenusByRoleIdDataKey);
public static IEnumerable<string> RetrieveMenusByRoleId(string roleId) => CacheManager.GetOrAdd($"{RetrieveMenusByRoleIdDataKey}-{roleId}", k => DbContextManager.Create<Menu>()?.RetrieveMenusByRoleId(roleId), RetrieveMenusByRoleIdDataKey) ?? new string[0];
/// <summary>
/// 保存指定角色的所有菜单
@ -103,7 +107,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SaveMenusByRoleId(string roleId, IEnumerable<string> menuIds)
{
var ret = DbContextManager.Create<Menu>().SaveMenusByRoleId(roleId, menuIds);
var ret = DbContextManager.Create<Menu>()?.SaveMenusByRoleId(roleId, menuIds) ?? false;
if (ret) CacheCleanUtility.ClearCache(menuIds: menuIds, roleIds: new List<string>() { roleId });
return ret;
}
@ -115,7 +119,7 @@ namespace Bootstrap.DataAccess
/// <param name="userName"></param>
/// <param name="activeUrl"></param>
/// <returns></returns>
public static IEnumerable<BootstrapMenu> RetrieveAppMenus(string appId, string userName, string activeUrl)
public static IEnumerable<BootstrapMenu> RetrieveAppMenus(string appId, string userName, string? activeUrl)
{
if (string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(userName)) return new BootstrapMenu[0];
@ -130,7 +134,7 @@ namespace Bootstrap.DataAccess
/// <param name="userName">当前登录的用户名</param>
/// <param name="activeUrl">当前访问菜单</param>
/// <returns></returns>
public static IEnumerable<BootstrapMenu> RetrieveSystemMenus(string userName, string activeUrl = null)
public static IEnumerable<BootstrapMenu> RetrieveSystemMenus(string userName, string? activeUrl = null)
{
if (string.IsNullOrEmpty(userName)) return new BootstrapMenu[0];
@ -143,7 +147,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<BootstrapMenu> RetrieveMenus(string userName)
public static IEnumerable<BootstrapMenu> RetrieveMenus(string? userName)
{
var menus = RetrieveAllMenus(userName);
return DbHelper.CascadeMenus(menus);
@ -154,7 +158,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<BootstrapMenu> RetrieveAllMenus(string userName) => CacheManager.GetOrAdd($"{RetrieveMenusAll}-{userName}", key => DbContextManager.Create<Menu>()?.RetrieveAllMenus(userName), RetrieveMenusAll);
public static IEnumerable<BootstrapMenu> RetrieveAllMenus(string? userName) => string.IsNullOrEmpty(userName) ? new BootstrapMenu[0] : CacheManager.GetOrAdd($"{RetrieveMenusAll}-{userName}", key => DbContextManager.Create<Menu>()?.RetrieveAllMenus(userName), RetrieveMenusAll) ?? new BootstrapMenu[0];
/// <summary>
/// 通过当前用户名与指定菜单路径获取此菜单下所有授权按钮集合 (userName, url, auths) => bool
@ -163,6 +167,6 @@ namespace Bootstrap.DataAccess
/// <param name="url">资源按钮所属菜单</param>
/// <param name="auths">资源授权码</param>
/// <returns></returns>
public static bool AuthorizateButtons(string userName, string url, string auths) => DbContextManager.Create<Menu>().AuthorizateButtons(userName, url, auths);
public static bool AuthorizateButtons(string userName, string url, string auths) => DbContextManager.Create<Menu>()?.AuthorizateButtons(userName, url, auths) ?? false;
}
}

View File

@ -18,41 +18,41 @@ namespace Bootstrap.DataAccess
/// 收件箱
/// </summary>
/// <param name="userName"></param>
public static IEnumerable<Message> Inbox(string userName) => DbContextManager.Create<Message>().Inbox(userName);
public static IEnumerable<Message> Inbox(string? userName) => string.IsNullOrEmpty(userName) ? new Message[0] : DbContextManager.Create<Message>()?.Inbox(userName) ?? new Message[0];
/// <summary>
/// 发件箱
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<Message> SendMail(string userName) => DbContextManager.Create<Message>().SendMail(userName);
public static IEnumerable<Message> SendMail(string? userName) => string.IsNullOrEmpty(userName) ? new Message[0] : DbContextManager.Create<Message>()?.SendMail(userName) ?? new Message[0];
/// <summary>
/// 垃圾箱
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<Message> Trash(string userName) => DbContextManager.Create<Message>().Trash(userName);
public static IEnumerable<Message> Trash(string? userName) => string.IsNullOrEmpty(userName) ? new Message[0] : DbContextManager.Create<Message>()?.Trash(userName) ?? new Message[0];
/// <summary>
/// 标旗
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<Message> Mark(string userName) => DbContextManager.Create<Message>().Mark(userName);
public static IEnumerable<Message> Mark(string? userName) => string.IsNullOrEmpty(userName) ? new Message[0] : DbContextManager.Create<Message>()?.Mark(userName) ?? new Message[0];
/// <summary>
/// 获取Header处显示的消息列表
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<Message> Retrieves(string userName) => CacheManager.GetOrAdd(RetrieveMessageDataKey, key => DbContextManager.Create<Message>().RetrieveHeaders(userName).OrderByDescending(n => n.SendTime));
public static IEnumerable<Message> Retrieves(string? userName) => (string.IsNullOrEmpty(userName) ? new Message[0] : CacheManager.GetOrAdd(RetrieveMessageDataKey, key => (DbContextManager.Create<Message>()?.RetrieveHeaders(userName) ?? new Message[0]))).OrderByDescending(n => n.SendTime);
/// <summary>
///
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
public static bool Save(Message msg) => DbContextManager.Create<Message>().Save(msg);
public static bool Save(Message msg) => DbContextManager.Create<Message>()?.Save(msg) ?? false;
}
}

View File

@ -51,7 +51,7 @@ namespace Bootstrap.DataAccess
}
#if NETCOREAPP3_0
private static T ToObject<T>(this System.Text.Json.JsonElement element) where T: OAuthUser
private static T? ToObject<T>(this System.Text.Json.JsonElement element) where T : OAuthUser
{
var user = new OAuthUser();
var target = element.EnumerateObject();
@ -83,11 +83,11 @@ namespace Bootstrap.DataAccess
{
ApprovedBy = "OAuth",
ApprovedTime = DateTime.Now,
DisplayName = user.Name,
UserName = user.Login,
DisplayName = user?.Name ?? "",
UserName = user?.Login ?? "",
Password = LgbCryptography.GenerateSalt(),
Icon = user.Avatar_Url,
Description = $"{context.Scheme.Name}({user.Id})"
Icon = user?.Avatar_Url ?? "",
Description = $"{context.Scheme.Name}({user?.Id})"
};
}
@ -98,14 +98,31 @@ namespace Bootstrap.DataAccess
/// <param name="roles"></param>
internal static void SaveUser(User newUser, IEnumerable<string> roles)
{
var uid = UserHelper.Retrieves().FirstOrDefault(u => u.UserName == newUser.UserName)?.Id;
if (uid != null) DbContextManager.Create<User>().Delete(new string[] { uid });
DbContextManager.Create<User>().Save(newUser);
// 根据配置文件设置默认角色
var roleIds = DbContextManager.Create<Role>().Retrieves().Where(r => roles.Any(rl => rl.Equals(r.RoleName, StringComparison.OrdinalIgnoreCase))).Select(r => r.Id);
DbContextManager.Create<Role>().SaveByUserId(newUser.Id, roleIds);
CacheCleanUtility.ClearCache(userIds: new string[0], roleIds: new string[0], cacheKey: $"{UserHelper.RetrieveUsersByNameDataKey}-{newUser.UserName}");
if (!string.IsNullOrEmpty(newUser.Id))
{
var uid = UserHelper.Retrieves().FirstOrDefault(u => u.UserName == newUser.UserName)?.Id;
var user = DbContextManager.Create<User>();
if (user != null)
{
if (!string.IsNullOrEmpty(uid)) user.Delete(new string[] { uid });
if (user.Save(newUser))
{
// 根据配置文件设置默认角色
var role = DbContextManager.Create<Role>();
if (role != null)
{
var roleIds = role.Retrieves().Where(r => roles.Any(rl => rl.Equals(r.RoleName, StringComparison.OrdinalIgnoreCase))).Select(r => r.Id);
if (roleIds.Any())
{
#pragma warning disable CS8620 // 由于引用类型的可为 null 性差异,实参不能用于形参。
role.SaveByUserId(newUser.Id, roleIds);
#pragma warning restore CS8620 // 由于引用类型的可为 null 性差异,实参不能用于形参。
CacheCleanUtility.ClearCache(userIds: new string[0], roleIds: new string[0], cacheKey: $"{UserHelper.RetrieveUsersByNameDataKey}-{newUser.UserName}");
}
}
}
}
}
}
}
}

View File

@ -14,7 +14,7 @@ namespace Bootstrap.DataAccess
public static bool Save(ResetUser user)
{
user.ResetTime = DateTime.Now;
return DbContextManager.Create<ResetUser>().Save(user);
return DbContextManager.Create<ResetUser>()?.Save(user) ?? false;
}
}
}

View File

@ -32,7 +32,7 @@ namespace Bootstrap.DataAccess
/// 查询所有角色
/// </summary>
/// <returns></returns>
public static IEnumerable<Role> Retrieves() => CacheManager.GetOrAdd(RetrieveRolesDataKey, key => DbContextManager.Create<Role>().Retrieves());
public static IEnumerable<Role> Retrieves() => CacheManager.GetOrAdd(RetrieveRolesDataKey, key => DbContextManager.Create<Role>()?.Retrieves()) ?? new Role[0];
/// <summary>
/// 保存用户角色关系
@ -48,11 +48,11 @@ namespace Bootstrap.DataAccess
{
var users = new string[] { "Admin", "User" };
var userIds = UserHelper.Retrieves().Where(u => users.Any(usr => usr.Equals(u.UserName, StringComparison.OrdinalIgnoreCase))).Select(u => u.Id);
if (userIds.Any(u => u.Equals(userId, StringComparison.OrdinalIgnoreCase))) ret = true;
if (userIds.Any(u => (u ?? string.Empty).Equals(userId, StringComparison.OrdinalIgnoreCase))) ret = true;
}
if (ret) return ret;
ret = DbContextManager.Create<Role>().SaveByUserId(userId, roleIds);
ret = DbContextManager.Create<Role>()?.SaveByUserId(userId, roleIds) ?? false;
if (ret) CacheCleanUtility.ClearCache(userIds: new List<string>() { userId }, roleIds: roleIds);
return ret;
}
@ -61,7 +61,7 @@ namespace Bootstrap.DataAccess
/// 查询某个用户所拥有的角色
/// </summary>
/// <returns></returns>
public static IEnumerable<Role> RetrievesByUserId(string userId) => CacheManager.GetOrAdd($"{RetrieveRolesByUserIdDataKey}-{userId}", key => DbContextManager.Create<Role>().RetrievesByUserId(userId), RetrieveRolesByUserIdDataKey);
public static IEnumerable<Role> RetrievesByUserId(string userId) => CacheManager.GetOrAdd($"{RetrieveRolesByUserIdDataKey}-{userId}", key => DbContextManager.Create<Role>()?.RetrievesByUserId(userId), RetrieveRolesByUserIdDataKey) ?? new Role[0];
/// <summary>
/// 删除角色表
@ -75,7 +75,7 @@ namespace Bootstrap.DataAccess
value = value.Where(v => !rs.Any(r => r.Id == v));
if (!value.Any()) return true;
var ret = DbContextManager.Create<Role>().Delete(value);
var ret = DbContextManager.Create<Role>()?.Delete(value) ?? false;
if (ret) CacheCleanUtility.ClearCache(roleIds: value);
return ret;
}
@ -92,7 +92,7 @@ namespace Bootstrap.DataAccess
var rs = Retrieves().Where(r => roles.Any(rl => rl.Equals(r.RoleName, StringComparison.OrdinalIgnoreCase)));
if (rs.Any(r => r.Id == p.Id)) return true;
var ret = DbContextManager.Create<Role>().Save(p);
var ret = DbContextManager.Create<Role>()?.Save(p) ?? false;
if (ret) CacheCleanUtility.ClearCache(roleIds: string.IsNullOrEmpty(p.Id) ? new List<string>() : new List<string> { p.Id });
return ret;
}
@ -102,7 +102,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="menuId"></param>
/// <returns></returns>
public static IEnumerable<Role> RetrievesByMenuId(string menuId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveRolesByMenuIdDataKey, menuId), key => DbContextManager.Create<Role>().RetrievesByMenuId(menuId), RetrieveRolesByMenuIdDataKey);
public static IEnumerable<Role> RetrievesByMenuId(string menuId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveRolesByMenuIdDataKey, menuId), key => DbContextManager.Create<Role>()?.RetrievesByMenuId(menuId), RetrieveRolesByMenuIdDataKey) ?? new Role[0];
/// <summary>
/// 通过指定菜单ID保存角色
@ -112,7 +112,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SavaByMenuId(string menuId, IEnumerable<string> roleIds)
{
var ret = DbContextManager.Create<Role>().SavaByMenuId(menuId, roleIds);
var ret = DbContextManager.Create<Role>()?.SavaByMenuId(menuId, roleIds) ?? false;
if (ret) CacheCleanUtility.ClearCache(roleIds: roleIds, menuIds: new List<string>() { menuId });
return ret;
}
@ -122,7 +122,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="groupId"></param>
/// <returns></returns>
public static IEnumerable<Role> RetrievesByGroupId(string groupId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveRolesByGroupIdDataKey, groupId), key => DbContextManager.Create<Role>().RetrievesByGroupId(groupId), RetrieveRolesByGroupIdDataKey);
public static IEnumerable<Role> RetrievesByGroupId(string groupId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveRolesByGroupIdDataKey, groupId), key => DbContextManager.Create<Role>()?.RetrievesByGroupId(groupId), RetrieveRolesByGroupIdDataKey) ?? new Role[0];
/// <summary>
/// 根据GroupId更新Roles信息删除旧的Roles信息插入新的Roles信息
@ -132,7 +132,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SaveByGroupId(string groupId, IEnumerable<string> roleIds)
{
var ret = DbContextManager.Create<Role>().SaveByGroupId(groupId, roleIds);
var ret = DbContextManager.Create<Role>()?.SaveByGroupId(groupId, roleIds) ?? false;
if (ret) CacheCleanUtility.ClearCache(roleIds: roleIds, groupIds: new List<string>() { groupId });
return ret;
}
@ -142,7 +142,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="userName">指定用户名</param>
/// <returns>角色名称集合</returns>
public static IEnumerable<string> RetrievesByUserName(string userName) => CacheManager.GetOrAdd(string.Format("{0}-{1}", DbHelper.RetrieveRolesByUserNameDataKey, userName), key => DbContextManager.Create<Role>()?.RetrievesByUserName(userName), DbHelper.RetrieveRolesByUserNameDataKey);
public static IEnumerable<string> RetrievesByUserName(string userName) => CacheManager.GetOrAdd(string.Format("{0}-{1}", DbHelper.RetrieveRolesByUserNameDataKey, userName), key => DbContextManager.Create<Role>()?.RetrievesByUserName(userName), DbHelper.RetrieveRolesByUserNameDataKey) ?? new string[0];
/// <summary>
/// 通过指定 Url 地址获得授权角色集合
@ -150,6 +150,6 @@ namespace Bootstrap.DataAccess
/// <param name="url">请求 Url 地址</param>
/// <param name="appId">应用程序Id</param>
/// <returns>角色名称集合</returns>
public static IEnumerable<string> RetrievesByUrl(string url, string appId) => CacheManager.GetOrAdd(string.Format("{0}-{1}-{2}", DbHelper.RetrieveRolesByUrlDataKey, url, appId), key => DbContextManager.Create<Role>().RetrievesByUrl(url, appId), DbHelper.RetrieveRolesByUrlDataKey);
public static IEnumerable<string> RetrievesByUrl(string url, string appId) => CacheManager.GetOrAdd(string.Format("{0}-{1}-{2}", DbHelper.RetrieveRolesByUrlDataKey, url, appId), key => DbContextManager.Create<Role>()?.RetrievesByUrl(url, appId), DbHelper.RetrieveRolesByUrlDataKey) ?? new string[0];
}
}

View File

@ -17,13 +17,13 @@ namespace Bootstrap.DataAccess
/// 查询所有任务
/// </summary>
/// <returns></returns>
public static IEnumerable<Task> Retrieves() => CacheManager.GetOrAdd(RetrieveTasksDataKey, key => DbContextManager.Create<Task>().Retrieves());
public static IEnumerable<Task> Retrieves() => CacheManager.GetOrAdd(RetrieveTasksDataKey, key => DbContextManager.Create<Task>()?.Retrieves()) ?? new Task[0];
/// <summary>
/// 保存任务方法
/// </summary>
/// <param name="task"></param>
/// <returns></returns>
public static bool Save(Task task) => DbContextManager.Create<Task>().Save(task);
public static bool Save(Task task) => DbContextManager.Create<Task>()?.Save(task) ?? false;
}
}

View File

@ -26,22 +26,23 @@ namespace Bootstrap.DataAccess
// user == null 以前登录过客户端保留了 Cookie 但是用户名可能被系统删除
// link bug: https://gitee.com/LongbowEnterprise/BootstrapAdmin/issues/I123MH
if (user == null) return;
v.UserName = user.UserName;
v.DisplayName = user.DisplayName;
DbContextManager.Create<Trace>().Save(new Trace
if (user != null)
{
Ip = v.Ip,
RequestUrl = v.RequestUrl,
LogTime = v.LastAccessTime,
City = v.Location,
Browser = v.Browser,
OS = v.OS,
UserName = v.UserName,
UserAgent = v.UserAgent,
Referer = v.Referer
});
v.UserName = user.UserName;
v.DisplayName = user.DisplayName;
DbContextManager.Create<Trace>()?.Save(new Trace
{
Ip = v.Ip,
RequestUrl = v.RequestUrl,
LogTime = v.LastAccessTime,
City = v.Location,
Browser = v.Browser,
OS = v.OS,
UserName = v.UserName,
UserAgent = v.UserAgent,
Referer = v.Referer
});
}
}
}
@ -64,7 +65,7 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="ip"></param>
/// <returns></returns>
public static Page<Trace> Retrieves(PaginationOption po, DateTime? startTime, DateTime? endTime, string ip) => DbContextManager.Create<Trace>().RetrievePages(po, startTime, endTime, ip);
public static Page<Trace> Retrieves(PaginationOption po, DateTime? startTime, DateTime? endTime, string? ip) => DbContextManager.Create<Trace>()?.RetrievePages(po, startTime, endTime, ip) ?? new Page<Trace>() { Items = new List<Trace>() };
/// <summary>
/// 获得指定IP历史访问记录
@ -73,6 +74,6 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="ip"></param>
/// <returns></returns>
public static IEnumerable<Trace> RetrieveAll(DateTime? startTime, DateTime? endTime, string ip) => DbContextManager.Create<Trace>().RetrieveAll(startTime, endTime, ip);
public static IEnumerable<Trace> RetrieveAll(DateTime? startTime, DateTime? endTime, string? ip) => DbContextManager.Create<Trace>()?.RetrieveAll(startTime, endTime, ip) ?? new Trace[0];
}
}

View File

@ -41,14 +41,14 @@ namespace Bootstrap.DataAccess
if (user.Password?.Length > 50) user.Password = user.Password.Substring(0, 50);
if (user.DisplayName?.Length > 20) user.DisplayName = user.DisplayName.Substring(0, 20);
var pattern = @"^[a-zA-Z0-9_@.]*$";
return user.UserName.IsNullOrEmpty() || Regex.IsMatch(user.UserName, pattern);
return Regex.IsMatch(user.UserName, pattern);
}
/// <summary>
/// 查询所有用户
/// </summary>
/// <returns></returns>
public static IEnumerable<User> Retrieves() => CacheManager.GetOrAdd(RetrieveUsersDataKey, key => DbContextManager.Create<User>().Retrieves());
public static IEnumerable<User> Retrieves() => CacheManager.GetOrAdd(RetrieveUsersDataKey, key => DbContextManager.Create<User>()?.Retrieves()) ?? new User[0];
/// <summary>
/// 认证方法
@ -56,13 +56,13 @@ namespace Bootstrap.DataAccess
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns>返回真表示认证通过</returns>
public static bool Authenticate(string userName, string password) => DbContextManager.Create<User>().Authenticate(userName, password);
public static bool Authenticate(string userName, string password) => DbContextManager.Create<User>()?.Authenticate(userName, password) ?? false;
/// <summary>
/// 查询所有的新注册用户
/// </summary>
/// <returns></returns>
public static IEnumerable<User> RetrieveNewUsers() => CacheManager.GetOrAdd(RetrieveNewUsersDataKey, key => DbContextManager.Create<User>().RetrieveNewUsers());
public static IEnumerable<User> RetrieveNewUsers() => CacheManager.GetOrAdd(RetrieveNewUsersDataKey, key => DbContextManager.Create<User>()?.RetrieveNewUsers()) ?? new User[0];
private static IEnumerable<User> RetrieveConstUsers()
{
@ -79,7 +79,7 @@ namespace Bootstrap.DataAccess
var admins = RetrieveConstUsers();
value = value.Where(v => !admins.Any(u => u.Id == v));
if (!value.Any()) return true;
var ret = DbContextManager.Create<User>().Delete(value);
var ret = DbContextManager.Create<User>()?.Delete(value) ?? false;
if (ret) CacheCleanUtility.ClearCache(userIds: value, cacheKey: RetrieveUsersByNameDataKey + "*");
return ret;
}
@ -92,7 +92,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SaveApp(string userName, string app)
{
var ret = DbContextManager.Create<User>().SaveApp(userName, app);
var ret = DbContextManager.Create<User>()?.SaveApp(userName, app) ?? false;
if (ret) CacheCleanUtility.ClearCache(cacheKey: $"{RetrieveUsersByNameDataKey}*");
return ret;
}
@ -107,7 +107,7 @@ namespace Bootstrap.DataAccess
if (!UserChecker(user)) return false;
if (DictHelper.RetrieveSystemModel() && !string.IsNullOrEmpty(user.Id) && RetrieveConstUsers().Any(u => u.Id == user.Id)) return true;
var ret = DbContextManager.Create<User>().Save(user);
var ret = DbContextManager.Create<User>()?.Save(user) ?? false;
if (ret) CacheCleanUtility.ClearCache(userIds: string.IsNullOrEmpty(user.Id) ? new List<string>() : new List<string>() { user.Id }, cacheKey: $"{RetrieveUsersByNameDataKey}-{user.UserName}");
return ret;
}
@ -124,7 +124,7 @@ namespace Bootstrap.DataAccess
if (!UserChecker(new User { Password = password, DisplayName = displayName })) return false;
if (DictHelper.RetrieveSystemModel() && RetrieveConstUsers().Any(v => v.Id == id)) return true;
var ret = DbContextManager.Create<User>().Update(id, password, displayName);
var ret = DbContextManager.Create<User>()?.Update(id, password, displayName) ?? false;
if (ret) CacheCleanUtility.ClearCache(userIds: string.IsNullOrEmpty(id) ? new List<string>() : new List<string>() { id }, cacheKey: $"{RetrieveUsersByNameDataKey}*");
return ret;
}
@ -137,7 +137,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool Approve(string id, string approvedBy)
{
var ret = DbContextManager.Create<User>().Approve(id, approvedBy);
var ret = DbContextManager.Create<User>()?.Approve(id, approvedBy) ?? false;
if (ret) CacheCleanUtility.ClearCache(userIds: new List<string>() { id });
return ret;
}
@ -155,7 +155,7 @@ namespace Bootstrap.DataAccess
if (DictHelper.RetrieveSystemModel()
&& RetrieveConstUsers().Any(u => userName.Equals(u.UserName, StringComparison.OrdinalIgnoreCase)))
return true;
return DbContextManager.Create<User>().ChangePassword(userName, password, newPass);
return DbContextManager.Create<User>()?.ChangePassword(userName, password, newPass) ?? false;
}
/// <summary>
@ -169,7 +169,7 @@ namespace Bootstrap.DataAccess
{
if (!UserChecker(new User { UserName = userName, Password = password })) return false;
if (DictHelper.RetrieveSystemModel() && RetrieveConstUsers().Any(u => userName.Equals(u.UserName, StringComparison.OrdinalIgnoreCase))) return true;
var ret = DbContextManager.Create<User>().ResetPassword(userName, password);
var ret = DbContextManager.Create<User>()?.ResetPassword(userName, password) ?? false;
if (ret) CacheCleanUtility.ClearCache(cacheKey: RetrieveUsersDataKey);
return ret;
}
@ -180,7 +180,7 @@ namespace Bootstrap.DataAccess
/// <param name="user"></param>
public static bool ForgotPassword(ResetUser user)
{
var ret = DbContextManager.Create<User>().ForgotPassword(user);
var ret = DbContextManager.Create<User>()?.ForgotPassword(user) ?? false;
if (ret) CacheCleanUtility.ClearCache(cacheKey: RetrieveUsersDataKey);
return ret;
}
@ -193,7 +193,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool Reject(string id, string rejectBy)
{
var ret = DbContextManager.Create<User>().Reject(id, rejectBy);
var ret = DbContextManager.Create<User>()?.Reject(id, rejectBy) ?? false;
if (ret) CacheCleanUtility.ClearCache(userIds: new List<string>() { id });
return ret;
}
@ -203,7 +203,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public static IEnumerable<User> RetrievesByRoleId(string roleId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveUsersByRoleIdDataKey, roleId), k => DbContextManager.Create<User>().RetrievesByRoleId(roleId), RetrieveUsersByRoleIdDataKey);
public static IEnumerable<User> RetrievesByRoleId(string roleId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveUsersByRoleIdDataKey, roleId), k => DbContextManager.Create<User>()?.RetrievesByRoleId(roleId), RetrieveUsersByRoleIdDataKey) ?? new User[0];
/// <summary>
/// 通过角色ID保存当前授权用户插入
@ -216,15 +216,15 @@ namespace Bootstrap.DataAccess
// 演示模式时禁止修改 Admin 对 Administrators 角色的移除操作
if (DictHelper.RetrieveSystemModel())
{
var adminRole = RoleHelper.Retrieves().FirstOrDefault(r => r.RoleName.Equals("Administrators", StringComparison.OrdinalIgnoreCase)).Id;
if (roleId.Equals(adminRole, StringComparison.OrdinalIgnoreCase))
var adminRole = RoleHelper.Retrieves().FirstOrDefault(r => r.RoleName.Equals("Administrators", StringComparison.OrdinalIgnoreCase))?.Id;
if (!string.IsNullOrEmpty(adminRole) && roleId.Equals(adminRole, StringComparison.OrdinalIgnoreCase))
{
var adminId = Retrieves().FirstOrDefault(u => u.UserName.Equals("Admin", StringComparison.OrdinalIgnoreCase)).Id;
userIds = userIds.Union(new string[] { adminId });
var adminId = Retrieves().FirstOrDefault(u => u.UserName.Equals("Admin", StringComparison.OrdinalIgnoreCase))?.Id;
if (!string.IsNullOrEmpty(adminId)) userIds = userIds.Union(new string[] { adminId });
}
}
var ret = DbContextManager.Create<User>().SaveByRoleId(roleId, userIds);
var ret = DbContextManager.Create<User>()?.SaveByRoleId(roleId, userIds) ?? false;
if (ret) CacheCleanUtility.ClearCache(userIds: userIds, roleIds: new List<string>() { roleId });
return ret;
}
@ -234,7 +234,7 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="groupId"></param>
/// <returns></returns>
public static IEnumerable<User> RetrievesByGroupId(string groupId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveUsersByGroupIdDataKey, groupId), k => DbContextManager.Create<User>().RetrievesByGroupId(groupId), RetrieveUsersByRoleIdDataKey);
public static IEnumerable<User> RetrievesByGroupId(string groupId) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveUsersByGroupIdDataKey, groupId), k => DbContextManager.Create<User>()?.RetrievesByGroupId(groupId), RetrieveUsersByRoleIdDataKey) ?? new User[0];
/// <summary>
/// 通过部门ID保存当前授权用户插入
@ -244,7 +244,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SaveByGroupId(string groupId, IEnumerable<string> userIds)
{
var ret = DbContextManager.Create<User>().SaveByGroupId(groupId, userIds);
var ret = DbContextManager.Create<User>()?.SaveByGroupId(groupId, userIds) ?? false;
if (ret) CacheCleanUtility.ClearCache(userIds: userIds, groupIds: new List<string>() { groupId });
return ret;
}
@ -257,7 +257,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SaveUserIconByName(string userName, string iconName)
{
var ret = DbContextManager.Create<User>().SaveUserIconByName(userName, iconName);
var ret = DbContextManager.Create<User>()?.SaveUserIconByName(userName, iconName) ?? false;
if (ret) CacheCleanUtility.ClearCache(cacheKey: $"{RetrieveUsersByNameDataKey}*");
return ret;
}
@ -271,7 +271,7 @@ namespace Bootstrap.DataAccess
public static bool SaveDisplayName(string userName, string displayName)
{
if (!UserChecker(new User { UserName = userName, DisplayName = displayName })) return false;
var ret = DbContextManager.Create<User>().SaveDisplayName(userName, displayName);
var ret = DbContextManager.Create<User>()?.SaveDisplayName(userName, displayName) ?? false;
if (ret) CacheCleanUtility.ClearCache(cacheKey: $"{RetrieveUsersByNameDataKey}*");
return ret;
}
@ -284,7 +284,7 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static bool SaveUserCssByName(string userName, string cssName)
{
var ret = DbContextManager.Create<User>().SaveUserCssByName(userName, cssName);
var ret = DbContextManager.Create<User>()?.SaveUserCssByName(userName, cssName) ?? false;
if (ret) CacheCleanUtility.ClearCache(cacheKey: $"{RetrieveUsersByNameDataKey}*");
return ret;
}
@ -294,20 +294,20 @@ namespace Bootstrap.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static BootstrapUser RetrieveUserByUserName(string userName) => CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveUsersByNameDataKey, userName), k => DbContextManager.Create<User>().RetrieveUserByUserName(userName), RetrieveUsersByNameDataKey);
public static BootstrapUser? RetrieveUserByUserName(string? userName) => string.IsNullOrEmpty(userName) ? null : CacheManager.GetOrAdd(string.Format("{0}-{1}", RetrieveUsersByNameDataKey, userName), k => DbContextManager.Create<User>()?.RetrieveUserByUserName(userName), RetrieveUsersByNameDataKey);
/// <summary>
/// 通过登录账号获得用户信息
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static ResetUser RetrieveResetUserByUserName(string userName) => DbContextManager.Create<ResetUser>().RetrieveUserByUserName(userName);
public static ResetUser? RetrieveResetUserByUserName(string userName) => DbContextManager.Create<ResetUser>()?.RetrieveUserByUserName(userName);
/// <summary>
/// 通过登录账户获得重置密码原因
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<KeyValuePair<DateTime, string>> RetrieveResetReasonsByUserName(string userName) => DbContextManager.Create<ResetUser>().RetrieveResetReasonsByUserName(userName);
public static IEnumerable<KeyValuePair<DateTime, string>> RetrieveResetReasonsByUserName(string userName) => DbContextManager.Create<ResetUser>()?.RetrieveResetReasonsByUserName(userName) ?? new KeyValuePair<DateTime, string>[0];
}
}

View File

@ -47,16 +47,16 @@ namespace Bootstrap.DataAccess
{
ApprovedBy = "OAuth",
ApprovedTime = DateTime.Now,
DisplayName = user.NickName,
UserName = user.UnionId,
DisplayName = user?.NickName ?? "",
UserName = user?.UnionId ?? "",
Password = LgbCryptography.GenerateSalt(),
Icon = user.HeadImgUrl,
Icon = user?.HeadImgUrl ?? "",
Description = $"{context.Scheme.Name}"
};
}
#if NETCOREAPP3_0
private static T ToObject<T>(this JsonElement element) where T : WeChatUser
private static T? ToObject<T>(this JsonElement element) where T : WeChatUser
{
var user = new WeChatUser();
var target = element.EnumerateObject();

View File

@ -14,12 +14,12 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 操作类型
/// </summary>
public string CRUD { get; set; }
public string CRUD { get; set; } = "";
/// <summary>
/// 获得/设置 请求数据
/// </summary>
public string RequestData { get; set; }
public string RequestData { get; set; } = "";
/// <summary>
/// 查询所有操作日志信息
@ -29,8 +29,10 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="opType"></param>
/// <returns></returns>
public virtual new Page<Log> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string opType)
public virtual new Page<Log> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string? opType)
{
if (string.IsNullOrEmpty(po.Order)) po.Order = "desc";
if (string.IsNullOrEmpty(po.Sort)) po.Sort = "LogTime";
var sql = new Sql("select * from Logs");
if (startTime.HasValue) sql.Where("LogTime >= @0", startTime.Value);
if (endTime.HasValue) sql.Where("LogTime < @0", endTime.Value.AddDays(1).AddSeconds(-1));
@ -48,7 +50,7 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="opType"></param>
/// <returns></returns>
public virtual new IEnumerable<Log> RetrieveAll(DateTime? startTime, DateTime? endTime, string opType)
public virtual new IEnumerable<Log> RetrieveAll(DateTime? startTime, DateTime? endTime, string? opType)
{
var sql = new Sql("select CRUD, UserName, LogTime, Ip, Browser, OS, City, RequestUrl, RequestData from Logs");
if (startTime.HasValue) sql.Where("LogTime >= @0", startTime.Value);

View File

@ -14,12 +14,12 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 Id
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 获得/设置 用户名
/// </summary>
public string UserName { get; set; }
public string UserName { get; set; } = "";
/// <summary>
/// 获得/设置 登录时间
@ -29,32 +29,32 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 登录IP地址
/// </summary>
public string Ip { get; set; }
public string Ip { get; set; } = "";
/// <summary>
/// 获得/设置 登录浏览器
/// </summary>
public string Browser { get; set; }
public string Browser { get; set; } = "";
/// <summary>
/// 获得/设置 登录操作系统
/// </summary>
public string OS { get; set; }
public string OS { get; set; } = "";
/// <summary>
/// 获得/设置 登录地点
/// </summary>
public string City { get; set; }
public string City { get; set; } = "";
/// <summary>
/// 获得/设置 登录是否成功
/// </summary>
public string Result { get; set; }
public string Result { get; set; } = "";
/// <summary>
/// 获得/设置 用户 UserAgent
/// </summary>
public string UserAgent { get; set; }
public string UserAgent { get; set; } = "";
/// <summary>
/// 保存登录用户数据
@ -63,8 +63,10 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public virtual bool Log(LoginUser user)
{
var db = DbManager.Create();
db.Save(user);
using (var db = DbManager.Create())
{
db.Save(user);
}
return true;
}
@ -76,28 +78,32 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="ip"></param>
/// <returns></returns>
public virtual Page<LoginUser> RetrieveByPages(PaginationOption po, DateTime? startTime, DateTime? endTime, string ip)
public virtual Page<LoginUser> RetrieveByPages(PaginationOption po, DateTime? startTime, DateTime? endTime, string? ip)
{
if (string.IsNullOrEmpty(po.Sort)) po.Sort = "LoginTime";
if (string.IsNullOrEmpty(po.Order)) po.Order = "desc";
var sql = new Sql("select * from LoginLogs");
if (startTime.HasValue) sql.Where("LoginTime >= @0", startTime.Value);
if (endTime.HasValue) sql.Where("LoginTime < @0", endTime.Value.AddDays(1));
if (!string.IsNullOrEmpty(ip)) sql.Where("ip = @0", ip);
sql.OrderBy($"{po.Sort} {po.Order}");
return DbManager.Create().Page<LoginUser>(po.PageIndex, po.Limit, sql);
using var db = DbManager.Create();
return db.Page<LoginUser>(po.PageIndex, po.Limit, sql);
}
/// <summary>
/// 获取所有登录数据
/// </summary>
/// <returns></returns>
public virtual IEnumerable<LoginUser> RetrieveAll(DateTime? startTime, DateTime? endTime, string ip)
public virtual IEnumerable<LoginUser> RetrieveAll(DateTime? startTime, DateTime? endTime, string? ip)
{
var sql = new Sql("select UserName, LoginTime, Ip, Browser, OS, City, Result from LoginLogs");
if (startTime.HasValue) sql.Where("LoginTime >= @0", startTime.Value);
if (endTime.HasValue) sql.Where("LoginTime < @0", endTime.Value.AddDays(1));
if (!string.IsNullOrEmpty(ip)) sql.Where("ip = @0", ip);
sql.OrderBy($"LoginTime");
return DbManager.Create().Fetch<LoginUser>(sql);
using var db = DbManager.Create();
return db.Fetch<LoginUser>(sql);
}
}
}

View File

@ -62,7 +62,9 @@ namespace Bootstrap.DataAccess
public virtual IEnumerable<string> RetrieveMenusByRoleId(string roleId)
{
var menus = DbManager.Create().Fetch<BootstrapMenu>("select NavigationID as Id from NavigationRole where RoleID = @0", roleId);
#pragma warning disable CS8619 // 值中的引用类型的为 Null 性与目标类型不匹配。
return menus.Select(m => m.Id);
#pragma warning restore CS8619 // 值中的引用类型的为 Null 性与目标类型不匹配。
}
/// <summary>

View File

@ -14,27 +14,27 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 消息主键 数据库自增
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; }
public string Title { get; set; } = "";
/// <summary>
/// 内容
/// </summary>
public string Content { get; set; }
public string Content { get; set; } = "";
/// <summary>
/// 发消息人
/// </summary>
public string From { get; set; }
public string From { get; set; } = "";
/// <summary>
/// 收消息人
/// </summary>
public string To { get; set; }
public string To { get; set; } = "";
/// <summary>
/// 消息发送时间
@ -44,7 +44,7 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 消息状态0-未读1-已读 和Dict表的通知消息关联
/// </summary>
public string Status { get; set; }
public string Status { get; set; } = "0";
/// <summary>
/// 标旗状态0-未标旗1-已标旗
@ -59,31 +59,31 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 消息标签0-一般1-紧要 和Dict表的消息标签关联
/// </summary>
public string Label { get; set; }
public string Label { get; set; } = "0";
/// <summary>
/// 获得/设置 标签名称
/// </summary>
[ResultColumn]
public string LabelName { get; set; }
public string LabelName { get; set; } = "";
/// <summary>
/// 获得/设置 时间描述 2分钟内为刚刚
/// </summary>
[ResultColumn]
public string Period { get; set; }
public string Period { get; set; } = "";
/// <summary>
/// 获得/设置 发件人头像
/// </summary>
[ResultColumn]
public string FromIcon { get; set; }
public string FromIcon { get; set; } = "";
/// <summary>
/// 获得/设置 发件人昵称
/// </summary>
[ResultColumn]
public string FromDisplayName { get; set; }
public string FromDisplayName { get; set; } = "";
/// <summary>
/// 所有有关userName所有消息列表

View File

@ -8,11 +8,11 @@
/// <summary>
///
/// </summary>
public string Message { get; set; }
public string Message { get; set; } = "";
/// <summary>
///
/// </summary>
public string Category { get; set; }
public string Category { get; set; } = "";
/// <summary>
///
/// </summary>

View File

@ -14,22 +14,22 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 用户主键ID
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
///
/// </summary>
public string UserName { get; set; }
public string UserName { get; set; } = "";
/// <summary>
///
/// </summary>
public string DisplayName { get; set; }
public string DisplayName { get; set; } = "";
/// <summary>
///
/// </summary>
public string Reason { get; set; }
public string Reason { get; set; } = "";
/// <summary>
///

View File

@ -15,23 +15,23 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 角色主键ID
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 获得/设置 角色名称
/// </summary>
public string RoleName { get; set; }
public string RoleName { get; set; } = "";
/// <summary>
/// 获得/设置 角色描述
/// </summary>
public string Description { get; set; }
public string Description { get; set; } = "";
/// <summary>
/// 获取/设置 用户角色关联状态 checked 标示已经关联 '' 标示未关联
/// </summary>
[ResultColumn]
public string Checked { get; set; }
public string Checked { get; set; } = "";
/// <summary>
/// 查询所有角色

View File

@ -13,28 +13,28 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获取/设置 任务ID
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 获取/设置 任务名称
/// </summary>
public string TaskName { get; set; }
public string TaskName { get; set; } = "";
/// <summary>
/// 获取/设置 分配人
/// </summary>
public string AssignName { get; set; }
public string AssignName { get; set; } = "";
/// <summary>
/// 获得/设置 分配人昵称
/// </summary>
[ResultColumn]
public string AssignDisplayName { get; set; }
public string AssignDisplayName { get; set; } = "";
/// <summary>
/// 获取/设置 完成任务人
/// </summary>
public string UserName { get; set; }
public string UserName { get; set; } = "";
/// <summary>
/// 获取/设置 任务所需时间(天)

View File

@ -1,4 +1,4 @@
using Longbow.Web.Mvc;
using Longbow.Web.Mvc;
using PetaPoco;
using System;
using System.Collections.Generic;
@ -14,12 +14,12 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 操作日志主键ID
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 获得/设置 用户名称
/// </summary>
public string UserName { get; set; }
public string UserName { get; set; } = "";
/// <summary>
/// 获得/设置 操作时间
@ -29,37 +29,37 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 客户端IP
/// </summary>
public string Ip { get; set; }
public string Ip { get; set; } = "";
/// <summary>
/// 获得/设置 客户端地点
/// </summary>
public string City { get; set; }
public string City { get; set; } = "";
/// <summary>
/// 获得/设置 客户端浏览器
/// </summary>
public string Browser { get; set; }
public string Browser { get; set; } = "";
/// <summary>
/// 获得/设置 客户端操作系统
/// </summary>
public string OS { get; set; }
public string OS { get; set; } = "";
/// <summary>
/// 获取/设置 请求网址
/// </summary>
public string RequestUrl { get; set; }
public string RequestUrl { get; set; } = "";
/// <summary>
/// 获得/设置 客户端 UserAgent
/// </summary>
public string UserAgent { get; set; }
public string UserAgent { get; set; } = "";
/// <summary>
/// 获得/设置 客户端 Referer
/// </summary>
public string Referer { get; set; }
public string Referer { get; set; } = "";
/// <summary>
/// 保存用户访问数据历史记录
@ -81,8 +81,10 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="ip"></param>
/// <returns></returns>
public virtual Page<Trace> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string ip)
public virtual Page<Trace> RetrievePages(PaginationOption po, DateTime? startTime, DateTime? endTime, string? ip)
{
if (string.IsNullOrEmpty(po.Order)) po.Order = "desc";
if (string.IsNullOrEmpty(po.Sort)) po.Sort = "LogTime";
var sql = new Sql("select * from Traces");
if (startTime.HasValue) sql.Where("LogTime > @0", startTime.Value);
if (endTime.HasValue) sql.Where("LogTime < @0", endTime.Value.AddDays(1).AddSeconds(-1));
@ -100,7 +102,7 @@ namespace Bootstrap.DataAccess
/// <param name="endTime"></param>
/// <param name="ip"></param>
/// <returns></returns>
public virtual IEnumerable<Trace> RetrieveAll(DateTime? startTime, DateTime? endTime, string ip)
public virtual IEnumerable<Trace> RetrieveAll(DateTime? startTime, DateTime? endTime, string? ip)
{
var sql = new Sql("select UserName, LogTime, IP, Browser, OS, City, RequestUrl from Traces");
if (startTime.HasValue) sql.Where("LogTime > @0", startTime.Value);

View File

@ -17,28 +17,28 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 用户主键ID
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 获取/设置 密码
/// </summary>
public string Password { get; set; }
public string Password { get; set; } = "";
/// <summary>
/// 获取/设置 密码盐
/// </summary>
public string PassSalt { get; set; }
public string PassSalt { get; set; } = "";
/// <summary>
/// 获取/设置 角色用户关联状态 checked 标示已经关联 '' 标示未关联
/// </summary>
[ResultColumn]
public string Checked { get; set; }
public string Checked { get; set; } = "";
/// <summary>
/// 获得/设置 用户注册时间
/// </summary>
public DateTime RegisterTime { get; set; }
public DateTime RegisterTime { get; set; } = DateTime.Now;
/// <summary>
/// 获得/设置 用户被批复时间
@ -48,12 +48,12 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获得/设置 用户批复人
/// </summary>
public string ApprovedBy { get; set; }
public string? ApprovedBy { get; set; }
/// <summary>
/// 获得/设置 用户的申请理由
/// </summary>
public string Description { get; set; }
public string Description { get; set; } = "";
/// <summary>
/// 获得/设置 用户当前状态 0 表示管理员注册用户 1 表示用户注册 2 表示更改密码 3 表示更改个人皮肤 4 表示更改显示名称 5 批复新用户注册操作
@ -65,13 +65,13 @@ namespace Bootstrap.DataAccess
/// 获得/设置 通知描述 2分钟内为刚刚
/// </summary>
[ResultColumn]
public string Period { get; set; }
public string? Period { get; set; }
/// <summary>
/// 获得/设置 新密码
/// </summary>
[ResultColumn]
public string NewPassword { get; set; }
public string NewPassword { get; set; } = "";
/// <summary>
/// 获得/设置 是否重置密码
@ -93,7 +93,7 @@ namespace Bootstrap.DataAccess
}
/// <summary>
///
/// 保存默认应用方法
/// </summary>
/// <param name="userName"></param>
/// <param name="app"></param>
@ -101,7 +101,7 @@ namespace Bootstrap.DataAccess
public virtual bool SaveApp(string userName, string app) => DbManager.Create().Update<User>("set App = @1 where UserName = @0", userName, app) == 1;
/// <summary>
///
/// 更改密码方法
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
@ -160,7 +160,7 @@ namespace Bootstrap.DataAccess
}
/// <summary>
///
/// 重置密码方法
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
@ -191,7 +191,7 @@ namespace Bootstrap.DataAccess
}
/// <summary>
///
/// 忘记密码方法
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
@ -244,7 +244,7 @@ namespace Bootstrap.DataAccess
}
/// <summary>
///
/// 通过新用户方法
/// </summary>
/// <param name="id"></param>
/// <param name="approvedBy"></param>
@ -252,7 +252,7 @@ namespace Bootstrap.DataAccess
public virtual bool Approve(string id, string approvedBy) => DbManager.Create().Update<User>("set ApprovedTime = @1, ApprovedBy = @2 where ID = @0", id, DateTime.Now, approvedBy) == 1;
/// <summary>
///
/// 拒绝新用户方法
/// </summary>
/// <param name="id"></param>
/// <param name="rejectBy"></param>
@ -356,7 +356,7 @@ namespace Bootstrap.DataAccess
public virtual bool SaveUserIconByName(string userName, string iconName) => DbManager.Create().Update<User>("set Icon = @1 where UserName = @0", userName, iconName) == 1;
/// <summary>
///
/// 保存显示名称方法
/// </summary>
/// <param name="userName"></param>
/// <param name="displayName"></param>
@ -372,14 +372,14 @@ namespace Bootstrap.DataAccess
public virtual bool SaveUserCssByName(string userName, string cssName) => DbManager.Create().Update<User>("set Css = @1 where UserName = @0", userName, cssName) == 1;
/// <summary>
///
/// 获得指定用户方法
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public virtual BootstrapUser RetrieveUserByUserName(string userName) => DbHelper.RetrieveUserByUserName(userName);
public virtual BootstrapUser? RetrieveUserByUserName(string userName) => DbHelper.RetrieveUserByUserName(userName);
/// <summary>
///
/// ToString 方法
/// </summary>
/// <returns></returns>
public override string ToString()
@ -389,32 +389,32 @@ namespace Bootstrap.DataAccess
}
/// <summary>
///
/// 用户状态枚举类型
/// </summary>
public enum UserStates
{
/// <summary>
///
/// 更改密码
/// </summary>
ChangePassword,
/// <summary>
///
/// 更改样式
/// </summary>
ChangeTheme,
/// <summary>
///
/// 更改显示名称
/// </summary>
ChangeDisplayName,
/// <summary>
///
/// 审批用户
/// </summary>
ApproveUser,
/// <summary>
///
/// 拒绝用户
/// </summary>
RejectUser,
/// <summary>
///
/// 保存默认应用
/// </summary>
SaveApp
}

View File

@ -5,7 +5,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MongoDB.Driver" Version="2.9.2" />
<PackageReference Include="MongoDB.Driver" Version="2.9.3" />
</ItemGroup>
<ItemGroup>

View File

@ -13,8 +13,8 @@ namespace Bootstrap.Client.DataAccess.MongoDB
/// </summary>
internal static class DbManager
{
private static IMongoDatabase _db = null;
private static bool _register = false;
private static IMongoDatabase? _db;
private static bool _register;
private static readonly object _locker = new object();
/// <summary>
@ -35,7 +35,7 @@ namespace Bootstrap.Client.DataAccess.MongoDB
InitClassMap();
}
if (_db == null)
InitDb("ba");
_db = InitDb("ba");
}
}
return _db;
@ -99,11 +99,11 @@ namespace Bootstrap.Client.DataAccess.MongoDB
}
#endregion
private static void InitDb(string name = null)
private static IMongoDatabase InitDb(string name)
{
var (connectString, databaseName) = Longbow.Data.DbManager.GetMongoDB(name);
var client = new MongoClient(connectString);
_db = client.GetDatabase(databaseName);
return client.GetDatabase(databaseName);
}
private static void InitClassMap()

View File

@ -11,6 +11,6 @@ namespace Bootstrap.Client.DataAccess.MongoDB
/// <summary>
/// 获得/设置 当前组授权角色数据集合
/// </summary>
public IEnumerable<string> Roles { get; set; }
public IEnumerable<string> Roles { get; set; } = new string[0];
}
}

View File

@ -44,8 +44,8 @@ namespace Bootstrap.Client.DataAccess.MongoDB
var dicts = DictHelper.RetrieveDicts().Where(m => m.Category == "菜单");
menus.ForEach(m =>
{
m.CategoryName = dicts.FirstOrDefault(d => d.Code == m.Category)?.Name;
if (m.ParentId != "0") m.ParentName = menus.FirstOrDefault(p => p.Id == m.ParentId)?.Name;
m.CategoryName = dicts.FirstOrDefault(d => d.Code == m.Category)?.Name ?? "";
if (m.ParentId != "0") m.ParentName = menus.FirstOrDefault(p => p.Id == m.ParentId)?.Name ?? "";
});
return menus;

View File

@ -13,22 +13,22 @@ namespace Bootstrap.Client.DataAccess.MongoDB
/// <summary>
/// 此角色关联的所有菜单
/// </summary>
public IEnumerable<string> Menus { get; set; }
public IEnumerable<string> Menus { get; set; } = new string[0];
/// <summary>
/// 此角色关联的所有应用程序
/// </summary>
public IEnumerable<string> Apps { get; set; }
public IEnumerable<string> Apps { get; set; } = new string[0];
/// <summary>
/// 获得/设置 角色主键ID
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 获得/设置 角色名称
/// </summary>
public string RoleName { get; set; }
public string RoleName { get; set; } = "";
/// <summary>
/// 通过指定登录名获取授权角色名称数据集合
@ -38,7 +38,7 @@ namespace Bootstrap.Client.DataAccess.MongoDB
public override IEnumerable<string> RetrievesByUserName(string userName)
{
var user = UserHelper.RetrieveUserByUserName(userName) as User;
return RoleHelper.Retrieves().Where(r => user.Roles.Any(ur => ur == r.Id)).Select(r => r.RoleName);
return user == null ? new string[0] : RoleHelper.Retrieves().Where(r => user.Roles.Any(ur => ur == r.Id)).Select(r => r.RoleName);
}
/// <summary>

View File

@ -13,7 +13,7 @@ namespace Bootstrap.Client.DataAccess.MongoDB
/// <summary>
/// 获得/设置 用户主键ID
/// </summary>
public string Id { get; set; }
public string? Id { get; set; }
/// <summary>
/// 获得/设置 用户被批复时间
@ -23,34 +23,38 @@ namespace Bootstrap.Client.DataAccess.MongoDB
/// <summary>
/// 获得/设置 用户授权角色ID集合
/// </summary>
public IEnumerable<string> Roles { get; set; }
public IEnumerable<string> Roles { get; set; } = new string[0];
/// <summary>
/// 获得/设置 用户授权组ID集合
/// </summary>
public IEnumerable<string> Groups { get; set; }
public IEnumerable<string> Groups { get; set; } = new string[0];
/// <summary>
/// 通过指定登录名获取 BootstrapUser 实例方法
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public override BootstrapUser RetrieveUserByUserName(string userName)
public override BootstrapUser? RetrieveUserByUserName(string? userName)
{
var project = Builders<User>.Projection.Include(u => u.Id)
.Include(u => u.UserName)
.Include(u => u.DisplayName)
.Include(u => u.Icon)
.Include(u => u.Css)
.Include(u => u.Roles)
.Include(u => u.Groups)
.Include(u => u.ApprovedTime)
.Include(u => u.App);
var ret = DbManager.Users.Find(user => user.UserName.ToLowerInvariant() == userName.ToLowerInvariant()).Project<User>(project).FirstOrDefault();
if (ret != null)
BootstrapUser? ret = null;
if (!string.IsNullOrEmpty(userName))
{
if (string.IsNullOrEmpty(ret.Icon)) ret.Icon = "default.jpg";
if (string.IsNullOrEmpty(ret.App)) ret.App = "0";
var project = Builders<User>.Projection.Include(u => u.Id)
.Include(u => u.UserName)
.Include(u => u.DisplayName)
.Include(u => u.Icon)
.Include(u => u.Css)
.Include(u => u.Roles)
.Include(u => u.Groups)
.Include(u => u.ApprovedTime)
.Include(u => u.App);
ret = DbManager.Users.Find(user => user.UserName.ToLowerInvariant() == userName.ToLowerInvariant()).Project<User>(project).FirstOrDefault();
if (ret != null)
{
if (string.IsNullOrEmpty(ret.Icon)) ret.Icon = "default.jpg";
if (string.IsNullOrEmpty(ret.App)) ret.App = "0";
}
}
return ret;
}

View File

@ -5,12 +5,12 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Bootstrap.Security.DataAccess" Version="3.0.1-beta3" />
<PackageReference Include="Bootstrap.Security.Mvc" Version="3.0.2-beta6" />
<PackageReference Include="Longbow" Version="3.0.0" />
<PackageReference Include="Longbow.Cache" Version="3.0.1-beta2" />
<PackageReference Include="Longbow.Data" Version="3.0.1-beta1" />
<PackageReference Include="Longbow.Web" Version="3.0.0" />
<PackageReference Include="Bootstrap.Security.DataAccess" Version="3.0.1" />
<PackageReference Include="Bootstrap.Security.Mvc" Version="3.0.2" />
<PackageReference Include="Longbow" Version="3.0.1" />
<PackageReference Include="Longbow.Cache" Version="3.0.1" />
<PackageReference Include="Longbow.Data" Version="3.0.1" />
<PackageReference Include="Longbow.Web" Version="3.0.1" />
<PackageReference Include="System.Data.SqlClient" Version="4.7.0" />
</ItemGroup>

View File

@ -15,7 +15,7 @@ namespace Bootstrap.Client.DataAccess
/// <param name="connectionName">配置文件中配置的数据库连接字符串名称</param>
/// <param name="keepAlive">是否保持连接,默认为 false</param>
/// <returns></returns>
public static IDatabase Create(string connectionName = null, bool keepAlive = false)
public static IDatabase Create(string? connectionName = null, bool keepAlive = false)
{
var db = Longbow.Data.DbManager.Create(connectionName, keepAlive);
db.ExceptionThrown += (sender, args) => args.Exception.Log(new NameValueCollection() { ["LastCmd"] = db.LastCommand });

View File

@ -32,20 +32,20 @@ namespace Bootstrap.Client.DataAccess
/// 获得 IP地理位置
/// </summary>
/// <returns></returns>
public string RetrieveLocaleIPSvr() => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == "IP地理位置接口" && d.Define == 0)?.Code;
public string RetrieveLocaleIPSvr() => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == "IP地理位置接口" && d.Define == 0)?.Code ?? "";
/// <summary>
/// 获取 IP 地理位置查询服务缓存时长
/// </summary>
/// <returns></returns>
public string RetrieveLocaleIPSvrCachePeriod() => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == "IP请求缓存时长" && d.Define == 0)?.Code;
public string RetrieveLocaleIPSvrCachePeriod() => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == "IP请求缓存时长" && d.Define == 0)?.Code ?? "";
/// <summary>
/// 获得 项目是否获取登录地点 默认为 false
/// </summary>
/// <param name="ipSvr">服务提供名称</param>
/// <returns></returns>
public string RetrieveLocaleIPSvrUrl(string ipSvr) => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == ipSvr && d.Define == 0)?.Code;
public string RetrieveLocaleIPSvrUrl(string ipSvr) => DictHelper.RetrieveDicts().FirstOrDefault(d => d.Category == "系统设置" && d.Name == ipSvr && d.Define == 0)?.Code ?? "";
/// <summary>
/// 获得 是否为演示系统 默认为 false 不是演示系统

View File

@ -15,6 +15,6 @@ namespace Bootstrap.Client.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<string> RetrievesByUserName(string userName) => CacheManager.GetOrAdd($"{DbHelper.RetrieveAppsByUserNameDataKey}-{userName}", key => DbContextManager.Create<App>().RetrievesByUserName(userName), DbHelper.RetrieveAppsByUserNameDataKey);
public static IEnumerable<string> RetrievesByUserName(string userName) => CacheManager.GetOrAdd($"{DbHelper.RetrieveAppsByUserNameDataKey}-{userName}", key => DbContextManager.Create<App>()?.RetrievesByUserName(userName), DbHelper.RetrieveAppsByUserNameDataKey) ?? new string[0];
}
}

View File

@ -22,97 +22,97 @@ namespace Bootstrap.Client.DataAccess
/// 获取所有字典表数据方法
/// </summary>
/// <returns></returns>
public static IEnumerable<BootstrapDict> RetrieveDicts() => CacheManager.GetOrAdd(RetrieveDictsDataKey, key => DbContextManager.Create<Dict>().RetrieveDicts());
public static IEnumerable<BootstrapDict> RetrieveDicts() => CacheManager.GetOrAdd(RetrieveDictsDataKey, key => DbContextManager.Create<Dict>()?.RetrieveDicts()) ?? new BootstrapDict[0];
/// <summary>
/// 获取站点 Title 配置信息
/// </summary>
/// <param name="appId">App 应用ID 默认为 0 表示后台管理程序</param>
/// <returns></returns>
public static string RetrieveWebTitle(string appId) => DbContextManager.Create<Dict>().RetrieveWebTitle(appId);
public static string RetrieveWebTitle(string appId) => DbContextManager.Create<Dict>()?.RetrieveWebTitle(appId) ?? "";
/// <summary>
/// 获取站点 Footer 配置信息
/// </summary>
/// <param name="appId">App 应用ID 默认为 0 表示后台管理程序</param>
/// <returns></returns>
public static string RetrieveWebFooter(string appId) => DbContextManager.Create<Dict>().RetrieveWebFooter(appId);
public static string RetrieveWebFooter(string appId) => DbContextManager.Create<Dict>()?.RetrieveWebFooter(appId) ?? "";
/// <summary>
/// 获得网站设置中的当前样式
/// </summary>
/// <returns></returns>
public static string RetrieveActiveTheme() => DbContextManager.Create<Dict>().RetrieveActiveTheme();
public static string RetrieveActiveTheme() => DbContextManager.Create<Dict>()?.RetrieveActiveTheme() ?? "";
/// <summary>
/// 获取 IP地理位置查询服务请求地址
/// </summary>
/// <returns></returns>
public static string RetrieveLocaleIPSvr() => DbContextManager.Create<Dict>().RetrieveLocaleIPSvr();
public static string RetrieveLocaleIPSvr() => DbContextManager.Create<Dict>()?.RetrieveLocaleIPSvr() ?? "";
/// <summary>
/// 通过 IP 地理位置查询服务名称获得请求地址方法
/// </summary>
/// <param name="ipSvr">ip地址请求服务名称</param>
/// <returns></returns>
public static string RetrieveLocaleIPSvrUrl(string ipSvr) => DbContextManager.Create<Dict>().RetrieveLocaleIPSvrUrl(ipSvr);
public static string RetrieveLocaleIPSvrUrl(string ipSvr) => DbContextManager.Create<Dict>()?.RetrieveLocaleIPSvrUrl(ipSvr) ?? "";
/// <summary>
/// 获取 IP 地理位置查询服务缓存时长
/// </summary>
/// <returns></returns>
public static string RetrieveLocaleIPSvrCachePeriod() => DbContextManager.Create<Dict>().RetrieveLocaleIPSvrCachePeriod();
public static string RetrieveLocaleIPSvrCachePeriod() => DbContextManager.Create<Dict>()?.RetrieveLocaleIPSvrCachePeriod() ?? "";
/// <summary>
/// 获得 是否为演示系统 默认为 false 不是演示系统
/// </summary>
/// <returns></returns>
public static bool RetrieveSystemModel() => DbContextManager.Create<Dict>().RetrieveSystemModel();
public static bool RetrieveSystemModel() => DbContextManager.Create<Dict>()?.RetrieveSystemModel() ?? false;
/// <summary>
/// 获得验证码图床地址
/// </summary>
/// <returns></returns>
public static string RetrieveImagesLibUrl() => DbContextManager.Create<Dict>().RetrieveImagesLibUrl();
public static string RetrieveImagesLibUrl() => DbContextManager.Create<Dict>()?.RetrieveImagesLibUrl() ?? "";
/// <summary>
/// 获取头像路径
/// </summary>
/// <returns></returns>
public static string RetrieveIconFolderPath() => DbContextManager.Create<Dict>().RetrieveIconFolderPath();
public static string RetrieveIconFolderPath() => DbContextManager.Create<Dict>()?.RetrieveIconFolderPath() ?? "";
/// <summary>
/// 获得数据区卡片标题是否显示
/// </summary>
/// <returns></returns>
public static bool RetrieveCardTitleStatus() => DbContextManager.Create<Dict>().RetrieveCardTitleStatus();
public static bool RetrieveCardTitleStatus() => DbContextManager.Create<Dict>()?.RetrieveCardTitleStatus() ?? true;
/// <summary>
/// 获得侧边栏状态 真时显示
/// 获得侧边栏状态 真时显示
/// </summary>
/// <returns></returns>
public static bool RetrieveSidebarStatus() => DbContextManager.Create<Dict>().RetrieveSidebarStatus();
public static bool RetrieveSidebarStatus() => DbContextManager.Create<Dict>()?.RetrieveSidebarStatus() ?? true;
/// <summary>
/// 获得系统设置地址
/// </summary>
/// <param name="appId">App 应用ID 默认为 0 表示后台管理程序</param>
/// <returns></returns>
public static string RetrieveSettingsUrl(string appId) => DbContextManager.Create<Dict>().RetrieveSettingsUrl(appId);
public static string RetrieveSettingsUrl(string appId) => DbContextManager.Create<Dict>()?.RetrieveSettingsUrl(appId) ?? "";
/// <summary>
/// 获得系统个人中心地址
/// </summary>
/// <param name="appId">App 应用ID 默认为 0 表示后台管理程序</param>
/// <returns></returns>
public static string RetrieveProfilesUrl(string appId) => DbContextManager.Create<Dict>().RetrieveProfilesUrl(appId);
public static string RetrieveProfilesUrl(string appId) => DbContextManager.Create<Dict>()?.RetrieveProfilesUrl(appId) ?? "";
/// <summary>
/// 获得系统通知地址地址
/// </summary>
/// <param name="appId">App 应用ID 默认为 0 表示后台管理程序</param>
/// <returns></returns>
public static string RetrieveNotisUrl(string appId) => DbContextManager.Create<Dict>().RetrieveNotisUrl(appId);
public static string RetrieveNotisUrl(string appId) => DbContextManager.Create<Dict>()?.RetrieveNotisUrl(appId) ?? "";
/// <summary>
/// 配置 IP 地理位置查询配置项 注入方法调用此方法
@ -124,7 +124,7 @@ namespace Bootstrap.Client.DataAccess
if (!string.IsNullOrEmpty(name) && !name.Equals("None", StringComparison.OrdinalIgnoreCase))
{
var url = RetrieveLocaleIPSvrUrl(name);
op.Locator = string.IsNullOrEmpty(url) ? null : DefaultIPLocatorProvider.CreateLocator(name);
op.Locator = DefaultIPLocatorProvider.CreateLocator(name);
op.Url = string.IsNullOrEmpty(url) ? string.Empty : $"{url}{op.IP}";
if (int.TryParse(RetrieveLocaleIPSvrCachePeriod(), out var period) && period > 0) op.Period = period * 60 * 1000;
}

View File

@ -36,6 +36,6 @@ namespace Bootstrap.Client.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<BootstrapMenu> RetrieveAllMenus(string userName) => CacheManager.GetOrAdd($"{RetrieveMenusAll}-{userName}", key => DbContextManager.Create<Menu>().RetrieveAllMenus(userName), RetrieveMenusAll);
public static IEnumerable<BootstrapMenu> RetrieveAllMenus(string userName) => CacheManager.GetOrAdd($"{RetrieveMenusAll}-{userName}", key => DbContextManager.Create<Menu>()?.RetrieveAllMenus(userName), RetrieveMenusAll) ?? new BootstrapMenu[0];
}
}

View File

@ -15,7 +15,7 @@ namespace Bootstrap.Client.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static IEnumerable<string> RetrievesByUserName(string userName) => CacheManager.GetOrAdd(string.Format("{0}-{1}", DbHelper.RetrieveRolesByUserNameDataKey, userName), key => DbContextManager.Create<Role>().RetrievesByUserName(userName), DbHelper.RetrieveRolesByUserNameDataKey);
public static IEnumerable<string> RetrievesByUserName(string userName) => CacheManager.GetOrAdd(string.Format("{0}-{1}", DbHelper.RetrieveRolesByUserNameDataKey, userName), key => DbContextManager.Create<Role>()?.RetrievesByUserName(userName), DbHelper.RetrieveRolesByUserNameDataKey) ?? new string[0];
/// <summary>
///
@ -23,6 +23,6 @@ namespace Bootstrap.Client.DataAccess
/// <param name="url"></param>
/// <param name="appId"></param>
/// <returns></returns>
public static IEnumerable<string> RetrievesByUrl(string url, string appId) => CacheManager.GetOrAdd(string.Format("{0}-{1}-{2}", DbHelper.RetrieveRolesByUrlDataKey, url, appId), key => DbContextManager.Create<Role>().RetrievesByUrl(url, appId), DbHelper.RetrieveRolesByUrlDataKey);
public static IEnumerable<string> RetrievesByUrl(string url, string appId) => CacheManager.GetOrAdd(string.Format("{0}-{1}-{2}", DbHelper.RetrieveRolesByUrlDataKey, url, appId), key => DbContextManager.Create<Role>()?.RetrievesByUrl(url, appId), DbHelper.RetrieveRolesByUrlDataKey) ?? new string[0];
}
}

View File

@ -15,6 +15,6 @@ namespace Bootstrap.Client.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public static BootstrapUser RetrieveUserByUserName(string userName) => CacheManager.GetOrAdd(string.Format("{0}-{1}", DbHelper.RetrieveUsersByNameDataKey, userName), k => DbContextManager.Create<User>().RetrieveUserByUserName(userName), DbHelper.RetrieveUsersByNameDataKey);
public static BootstrapUser? RetrieveUserByUserName(string? userName) => string.IsNullOrEmpty(userName) ? null : CacheManager.GetOrAdd(string.Format("{0}-{1}", DbHelper.RetrieveUsersByNameDataKey, userName), k => DbContextManager.Create<User>()?.RetrieveUserByUserName(userName), DbHelper.RetrieveUsersByNameDataKey);
}
}

View File

@ -13,6 +13,6 @@ namespace Bootstrap.Client.DataAccess
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public virtual BootstrapUser RetrieveUserByUserName(string userName) => DbHelper.RetrieveUserByUserName(userName);
public virtual BootstrapUser? RetrieveUserByUserName(string userName) => DbHelper.RetrieveUserByUserName(userName);
}
}

View File

@ -6,7 +6,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Longbow.Logging" Version="3.0.2-beta1" />
<PackageReference Include="Longbow.Logging" Version="3.0.2" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="3.0.0" />
</ItemGroup>

View File

@ -19,59 +19,62 @@ namespace Bootstrap.Client.Models
public HeaderBarModel(ControllerBase controller)
{
var user = UserHelper.RetrieveUserByUserName(controller.User.Identity.Name);
DisplayName = user.DisplayName;
UserName = user.UserName;
SettingsUrl = DictHelper.RetrieveSettingsUrl(AppId);
ProfilesUrl = DictHelper.RetrieveProfilesUrl(AppId);
NotisUrl = DictHelper.RetrieveNotisUrl(AppId);
if (user != null)
{
DisplayName = user.DisplayName;
UserName = user.UserName;
SettingsUrl = DictHelper.RetrieveSettingsUrl(AppId);
ProfilesUrl = DictHelper.RetrieveProfilesUrl(AppId);
NotisUrl = DictHelper.RetrieveNotisUrl(AppId);
// set LogoutUrl
var config = controller.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
var authHost = config.GetBootstrapAdminAuthenticationOptions().AuthHost;
var uriBuilder = new UriBuilder(authHost);
uriBuilder.Path = uriBuilder.Path == "/" ? CookieAuthenticationDefaults.LogoutPath.Value : $"{uriBuilder.Path.TrimEnd('/')}{CookieAuthenticationDefaults.LogoutPath.Value}";
uriBuilder.Query = $"AppId={AppId}";
LogoutUrl = uriBuilder.ToString();
// set LogoutUrl
var config = controller.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
var authHost = config.GetBootstrapAdminAuthenticationOptions().AuthHost;
var uriBuilder = new UriBuilder(authHost);
uriBuilder.Path = uriBuilder.Path == "/" ? CookieAuthenticationDefaults.LogoutPath.Value : $"{uriBuilder.Path.TrimEnd('/')}{CookieAuthenticationDefaults.LogoutPath.Value}";
uriBuilder.Query = $"AppId={AppId}";
LogoutUrl = uriBuilder.ToString();
// set Icon
var icon = $"/{DictHelper.RetrieveIconFolderPath().Trim('~', '/')}/{user.Icon}";
Icon = user.Icon.Contains("://", StringComparison.OrdinalIgnoreCase) ? user.Icon : (string.IsNullOrEmpty(config.GetValue("SimulateUserName", string.Empty)) ? $"{authHost.TrimEnd('/')}{icon}" : "/images/admin.jpg");
if (!string.IsNullOrEmpty(user.Css)) Theme = user.Css;
// set Icon
var icon = $"/{DictHelper.RetrieveIconFolderPath().Trim('~', '/')}/{user.Icon}";
Icon = user.Icon.Contains("://", StringComparison.OrdinalIgnoreCase) ? user.Icon : (string.IsNullOrEmpty(config.GetValue("SimulateUserName", string.Empty)) ? $"{authHost.TrimEnd('/')}{icon}" : "/images/admin.jpg");
if (!string.IsNullOrEmpty(user.Css)) Theme = user.Css;
}
}
/// <summary>
///
/// </summary>
public string UserName { get; }
public string UserName { get; } = "";
/// <summary>
///
/// </summary>
public string DisplayName { get; }
public string DisplayName { get; } = "";
/// <summary>
/// 获得/设置 用户头像地址
/// </summary>
public string Icon { get; }
public string Icon { get; } = "";
/// <summary>
/// 获得/设置 设置网址
/// </summary>
public string SettingsUrl { get; }
public string SettingsUrl { get; } = "";
/// <summary>
/// 获得/设置 个人中心网址
/// </summary>
public string ProfilesUrl { get; }
public string ProfilesUrl { get; } = "";
/// <summary>
/// 获得 退出登录地址
/// </summary>
public string LogoutUrl { get; }
public string LogoutUrl { get; } = "";
/// <summary>
///
/// </summary>
public string NotisUrl { get; }
public string NotisUrl { get; } = "";
}
}

View File

@ -13,7 +13,7 @@
/// <summary>
/// 获得/设置 自动部署脚本文件
/// </summary>
public string DeployFile { get; set; }
public string DeployFile { get; set; } = "";
/// <summary>
/// 获得/设置 自动部署分支

View File

@ -18,7 +18,7 @@ namespace Bootstrap.Client.Tasks
public static class DeployTaskManager
{
private static BlockingCollection<GiteePushEventArgs> _pool = new BlockingCollection<GiteePushEventArgs>(new ConcurrentQueue<GiteePushEventArgs>());
private static IServiceCollection _services;
private static IServiceCollection? _services;
/// <summary>
/// IServiceCollection 实例
@ -33,18 +33,21 @@ namespace Bootstrap.Client.Tasks
public static void Add(GiteePushEventArgs args)
{
// 判断是否需要自动发布
var sp = _services.BuildServiceProvider();
var config = sp.GetRequiredService<IConfiguration>();
var logger = sp.GetRequiredService<ILogger<DeployController>>();
var option = config.GetSection<DeployOptions>().Get<DeployOptions>();
if (option.Enabled && !string.IsNullOrEmpty(option.DeployFile))
if (_services != null)
{
if (!_pool.IsAddingCompleted)
var sp = _services.BuildServiceProvider();
var config = sp.GetRequiredService<IConfiguration>();
var logger = sp.GetRequiredService<ILogger<DeployController>>();
var option = config.GetSection<DeployOptions>().Get<DeployOptions>();
if (option.Enabled && !string.IsNullOrEmpty(option.DeployFile))
{
_pool.Add(args);
}
if (!_pool.IsAddingCompleted)
{
_pool.Add(args);
}
RunAsync(logger, option).ConfigureAwait(false);
RunAsync(logger, option).ConfigureAwait(false);
}
}
}

Some files were not shown because too many files have changed in this diff Show More