diff --git a/README.md b/README.md
index 6a818617e5102cc3fbe780450e15bd9f87976162..c0e1a9e8f8c98ef22e91b2570c1db6f984548b34 100644
--- a/README.md
+++ b/README.md
@@ -42,8 +42,9 @@
- 租户管理(未实现,理论阶段)
-- .net4.5版地址:https://gitee.com/qian_wei_hong/WaterCloud/tree/net4.5
-- .netcore3.1版地址:https://gitee.com/qian_wei_hong/WaterCloud/tree/core3.1
+- .net5-SqlSugar版地址:https://gitee.com/qian_wei_hong/WaterCloud
+- .net4.5版地址:https://gitee.com/qian_wei_hong/WaterCloud/tree/net4.5-Chloe
+- .netcore3.1版地址:https://gitee.com/qian_wei_hong/WaterCloud/tree/core3.1-Chloe
- 项目演示地址:http://106.75.169.226:5000/ (账号:admin 密码:0000,数据库2个小时还原一次)
- 文档地址:https://gitee.com/qian_wei_hong/WaterCloud/wikis/pages
diff --git a/WaterCloud.Code/DistributedIDGenerator/Enums/SequentialGuidType.cs b/WaterCloud.Code/DistributedIDGenerator/Enums/SequentialGuidType.cs
new file mode 100644
index 0000000000000000000000000000000000000000..bfd1959aeb360d9c95b0ca77c4a843cb85993682
--- /dev/null
+++ b/WaterCloud.Code/DistributedIDGenerator/Enums/SequentialGuidType.cs
@@ -0,0 +1,40 @@
+// -----------------------------------------------------------------------------
+// 让 .NET 开发更简单,更通用,更流行。
+// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
+//
+// 框架名称:Furion
+// 框架作者:百小僧
+// 框架版本:2.7.9
+// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
+// Github:https://github.com/monksoul/Furion
+// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
+// -----------------------------------------------------------------------------
+
+using System.ComponentModel;
+
+namespace WaterCloud.Code
+{
+ ///
+ /// 连续 GUID 类型选项
+ ///
+ public enum SequentialGuidType
+ {
+ ///
+ /// 标准连续 GUID 字符串
+ ///
+ [Description("标准连续 GUID 字符串")]
+ SequentialAsString,
+
+ ///
+ /// Byte 数组类型的连续 `GUID` 字符串
+ ///
+ [Description("Byte 数组类型的连续 `GUID` 字符串")]
+ SequentialAsBinary,
+
+ ///
+ /// 连续部分在末尾展示
+ ///
+ [Description("连续部分在末尾展示")]
+ SequentialAtEnd
+ }
+}
\ No newline at end of file
diff --git a/WaterCloud.Code/DistributedIDGenerator/Generators/IDistributedIDGenerator.cs b/WaterCloud.Code/DistributedIDGenerator/Generators/IDistributedIDGenerator.cs
new file mode 100644
index 0000000000000000000000000000000000000000..341c2409139ebdf29d00258e82f4ef74460002d5
--- /dev/null
+++ b/WaterCloud.Code/DistributedIDGenerator/Generators/IDistributedIDGenerator.cs
@@ -0,0 +1,27 @@
+// -----------------------------------------------------------------------------
+// 让 .NET 开发更简单,更通用,更流行。
+// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
+//
+// 框架名称:Furion
+// 框架作者:百小僧
+// 框架版本:2.7.9
+// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
+// Github:https://github.com/monksoul/Furion
+// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
+// -----------------------------------------------------------------------------
+
+namespace WaterCloud.Code
+{
+ ///
+ /// 分布式 ID 生成器
+ ///
+ public interface IDistributedIDGenerator
+ {
+ ///
+ /// 生成逻辑
+ ///
+ ///
+ ///
+ object Create(object idGeneratorOptions = default);
+ }
+}
\ No newline at end of file
diff --git a/WaterCloud.Code/DistributedIDGenerator/Generators/SequentialGuidIDGenerator.cs b/WaterCloud.Code/DistributedIDGenerator/Generators/SequentialGuidIDGenerator.cs
new file mode 100644
index 0000000000000000000000000000000000000000..286a20de673ea279e1e18e29456326070a65ac88
--- /dev/null
+++ b/WaterCloud.Code/DistributedIDGenerator/Generators/SequentialGuidIDGenerator.cs
@@ -0,0 +1,86 @@
+// -----------------------------------------------------------------------------
+// 让 .NET 开发更简单,更通用,更流行。
+// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
+//
+// 框架名称:Furion
+// 框架作者:百小僧
+// 框架版本:2.7.9
+// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
+// Github:https://github.com/monksoul/Furion
+// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
+// -----------------------------------------------------------------------------
+
+using System;
+using System.Security.Cryptography;
+
+namespace WaterCloud.Code
+{
+ ///
+ /// 连续 GUID ID 生成器
+ /// 代码参考自:https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/blob/ebe011a6f1b2a2a9709fe558cfc7ed3215b55c37/src/EFCore.MySql/ValueGeneration/Internal/MySqlSequentialGuidValueGenerator.cs
+ ///
+ public class SequentialGuidIDGenerator : IDistributedIDGenerator
+ {
+ ///
+ /// 随机数生成器
+ ///
+ private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();
+
+ ///
+ /// 生成逻辑
+ ///
+ ///
+ ///
+ public object Create(object idGeneratorOptions = null)
+ {
+ // According to RFC 4122:
+ // dddddddd-dddd-Mddd-Ndrr-rrrrrrrrrrrr
+ // - M = RFC version, in this case '4' for random UUID
+ // - N = RFC variant (plus other bits), in this case 0b1000 for variant 1
+ // - d = nibbles based on UTC date/time in ticks
+ // - r = nibbles based on random bytes
+
+ var options = (idGeneratorOptions ?? new SequentialGuidSettings()) as SequentialGuidSettings;
+
+ var randomBytes = new byte[7];
+ _rng.GetBytes(randomBytes);
+ var ticks = (ulong)options.TimeNow.Ticks;
+
+ var uuidVersion = (ushort)4;
+ var uuidVariant = (ushort)0b1000;
+
+ var ticksAndVersion = (ushort)((ticks << 48 >> 52) | (ushort)(uuidVersion << 12));
+ var ticksAndVariant = (byte)((ticks << 60 >> 60) | (byte)(uuidVariant << 4));
+
+ if (options.LittleEndianBinary16Format)
+ {
+ var guidBytes = new byte[16];
+ var tickBytes = BitConverter.GetBytes(ticks);
+ if (BitConverter.IsLittleEndian)
+ {
+ Array.Reverse(tickBytes);
+ }
+
+ Buffer.BlockCopy(tickBytes, 0, guidBytes, 0, 6);
+ guidBytes[6] = (byte)(ticksAndVersion << 8 >> 8);
+ guidBytes[7] = (byte)(ticksAndVersion >> 8);
+ guidBytes[8] = ticksAndVariant;
+ Buffer.BlockCopy(randomBytes, 0, guidBytes, 9, 7);
+
+ return new Guid(guidBytes);
+ }
+
+ var guid = new Guid((uint)(ticks >> 32), (ushort)(ticks << 32 >> 48), ticksAndVersion,
+ ticksAndVariant,
+ randomBytes[0],
+ randomBytes[1],
+ randomBytes[2],
+ randomBytes[3],
+ randomBytes[4],
+ randomBytes[5],
+ randomBytes[6]);
+
+ return guid;
+ }
+ }
+}
\ No newline at end of file
diff --git a/WaterCloud.Code/DistributedIDGenerator/IDGen.cs b/WaterCloud.Code/DistributedIDGenerator/IDGen.cs
new file mode 100644
index 0000000000000000000000000000000000000000..d8944fd89605773461fb629c8927296af833c8c7
--- /dev/null
+++ b/WaterCloud.Code/DistributedIDGenerator/IDGen.cs
@@ -0,0 +1,45 @@
+// -----------------------------------------------------------------------------
+// 让 .NET 开发更简单,更通用,更流行。
+// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
+//
+// 框架名称:Furion
+// 框架作者:百小僧
+// 框架版本:2.7.9
+// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
+// Github:https://github.com/monksoul/Furion
+// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
+// -----------------------------------------------------------------------------
+
+using System;
+
+namespace WaterCloud.Code
+{
+ ///
+ /// ID 生成器
+ ///
+ public static class IDGen
+ {
+ ///
+ /// 生成唯一 ID
+ ///
+ ///
+ ///
+ ///
+ public static object NextID(object idGeneratorOptions)
+ {
+ return ((IDistributedIDGenerator)GlobalContext.ServiceProvider.GetService(typeof(IDistributedIDGenerator))).Create(idGeneratorOptions);
+ }
+
+ ///
+ /// 生成连续 GUID
+ ///
+ ///
+ ///
+ ///
+ public static Guid NextID(SequentialGuidType guidType = SequentialGuidType.SequentialAsString)
+ {
+ var sequentialGuid = GlobalContext.ServiceProvider.GetService(typeof(IDistributedIDGenerator)) as IDistributedIDGenerator;
+ return (Guid)sequentialGuid.Create();
+ }
+ }
+}
\ No newline at end of file
diff --git a/WaterCloud.Code/DistributedIDGenerator/Settings/SequentialGuidSettings.cs b/WaterCloud.Code/DistributedIDGenerator/Settings/SequentialGuidSettings.cs
new file mode 100644
index 0000000000000000000000000000000000000000..44a1ff4cc114872f594c0a82547c02fea85fb5cd
--- /dev/null
+++ b/WaterCloud.Code/DistributedIDGenerator/Settings/SequentialGuidSettings.cs
@@ -0,0 +1,32 @@
+// -----------------------------------------------------------------------------
+// 让 .NET 开发更简单,更通用,更流行。
+// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
+//
+// 框架名称:Furion
+// 框架作者:百小僧
+// 框架版本:2.7.9
+// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
+// Github:https://github.com/monksoul/Furion
+// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
+// -----------------------------------------------------------------------------
+
+using System;
+
+namespace WaterCloud.Code
+{
+ ///
+ /// 连续 GUID 配置
+ ///
+ public sealed class SequentialGuidSettings
+ {
+ ///
+ /// 当前时间
+ ///
+ public DateTimeOffset TimeNow { get; set; } = DateTimeOffset.UtcNow;
+
+ ///
+ /// LittleEndianBinary 16 格式化
+ ///
+ public bool LittleEndianBinary16Format { get; set; } = false;
+ }
+}
\ No newline at end of file
diff --git a/WaterCloud.Code/DistributedIDGenerator/ShortID/Internal/Constants.cs b/WaterCloud.Code/DistributedIDGenerator/ShortID/Internal/Constants.cs
new file mode 100644
index 0000000000000000000000000000000000000000..3c41ed7ddc20668a7657dde0984e77c11c28e47a
--- /dev/null
+++ b/WaterCloud.Code/DistributedIDGenerator/ShortID/Internal/Constants.cs
@@ -0,0 +1,35 @@
+// -----------------------------------------------------------------------------
+// 让 .NET 开发更简单,更通用,更流行。
+// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
+//
+// 框架名称:Furion
+// 框架作者:百小僧
+// 框架版本:2.7.9
+// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
+// Github:https://github.com/monksoul/Furion
+// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
+// -----------------------------------------------------------------------------
+
+namespace WaterCloud.Code
+{
+ ///
+ /// 短 ID 约束
+ ///
+ internal static class Constants
+ {
+ ///
+ /// 最小长度
+ ///
+ public const int MinimumAutoLength = 8;
+
+ ///
+ /// 最大长度
+ ///
+ public const int MaximumAutoLength = 14;
+
+ ///
+ /// 最小可选字符长度
+ ///
+ public const int MinimumCharacterSetLength = 50;
+ }
+}
\ No newline at end of file
diff --git a/WaterCloud.Code/DistributedIDGenerator/ShortID/Internal/RandomHelpers.cs b/WaterCloud.Code/DistributedIDGenerator/ShortID/Internal/RandomHelpers.cs
new file mode 100644
index 0000000000000000000000000000000000000000..742b10c7114bbba409997912fffd063ddd14ecd3
--- /dev/null
+++ b/WaterCloud.Code/DistributedIDGenerator/ShortID/Internal/RandomHelpers.cs
@@ -0,0 +1,46 @@
+// -----------------------------------------------------------------------------
+// 让 .NET 开发更简单,更通用,更流行。
+// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
+//
+// 框架名称:Furion
+// 框架作者:百小僧
+// 框架版本:2.7.9
+// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
+// Github:https://github.com/monksoul/Furion
+// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
+// -----------------------------------------------------------------------------
+
+using System;
+
+namespace WaterCloud.Code
+{
+ ///
+ /// 随机数帮助类
+ ///
+ internal static class RandomHelpers
+ {
+ ///
+ /// 随机数对象
+ ///
+ private static readonly Random Random = new();
+
+ ///
+ /// 线程锁
+ ///
+ private static readonly object ThreadLock = new();
+
+ ///
+ /// 生成线程安全的范围内随机数
+ ///
+ ///
+ ///
+ ///
+ public static int GenerateNumberInRange(int min, int max)
+ {
+ lock (ThreadLock)
+ {
+ return Random.Next(min, max);
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/WaterCloud.Code/DistributedIDGenerator/ShortID/Options/GenerationOptions.cs b/WaterCloud.Code/DistributedIDGenerator/ShortID/Options/GenerationOptions.cs
new file mode 100644
index 0000000000000000000000000000000000000000..1d7d5e32ba820d9e7f018405e30b36e1e7b9e234
--- /dev/null
+++ b/WaterCloud.Code/DistributedIDGenerator/ShortID/Options/GenerationOptions.cs
@@ -0,0 +1,38 @@
+// -----------------------------------------------------------------------------
+// 让 .NET 开发更简单,更通用,更流行。
+// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
+//
+// 框架名称:Furion
+// 框架作者:百小僧
+// 框架版本:2.7.9
+// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
+// Github:https://github.com/monksoul/Furion
+// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
+// -----------------------------------------------------------------------------
+
+
+namespace WaterCloud.Code
+{
+ ///
+ /// 短 ID 生成配置选项
+ ///
+ public class GenerationOptions
+ {
+ ///
+ /// 是否使用数字
+ /// 默认 false
+ ///
+ public bool UseNumbers { get; set; }
+
+ ///
+ /// 是否使用特殊字符
+ /// 默认 true
+ ///
+ public bool UseSpecialCharacters { get; set; } = true;
+
+ ///
+ /// 设置短 ID 长度
+ ///
+ public int Length { get; set; } = RandomHelpers.GenerateNumberInRange(Constants.MinimumAutoLength, Constants.MaximumAutoLength);
+ }
+}
\ No newline at end of file
diff --git a/WaterCloud.Code/DistributedIDGenerator/ShortID/ShortIDGen.cs b/WaterCloud.Code/DistributedIDGenerator/ShortID/ShortIDGen.cs
new file mode 100644
index 0000000000000000000000000000000000000000..4271d43e98237819e45e20ff0ed8bbcc083a8f61
--- /dev/null
+++ b/WaterCloud.Code/DistributedIDGenerator/ShortID/ShortIDGen.cs
@@ -0,0 +1,161 @@
+// -----------------------------------------------------------------------------
+// 让 .NET 开发更简单,更通用,更流行。
+// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
+//
+// 框架名称:Furion
+// 框架作者:百小僧
+// 框架版本:2.7.9
+// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
+// Github:https://github.com/monksoul/Furion
+// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
+// -----------------------------------------------------------------------------
+
+using System;
+using System.Linq;
+using System.Text;
+
+namespace WaterCloud.Code
+{
+ ///
+ /// 短 ID 生成核心代码
+ /// 代码参考自:https://github.com/bolorundurowb/shortid
+ ///
+ public static class ShortIDGen
+ {
+ ///
+ /// 短 ID 生成器期初数据
+ ///
+ private static Random _random = new();
+
+ private const string Bigs = "ABCDEFGHIJKLMNPQRSTUVWXY";
+ private const string Smalls = "abcdefghjklmnopqrstuvwxyz";
+ private const string Numbers = "0123456789";
+ private const string Specials = "_-";
+ private static string _pool = $"{Smalls}{Bigs}";
+
+ ///
+ /// 线程安全锁
+ ///
+ private static readonly object ThreadLock = new();
+
+ ///
+ /// 生成目前比较主流的短 ID
+ /// 包含字母、数字,不包含特殊字符
+ /// 默认生成 8 位
+ ///
+ ///
+ public static string NextID()
+ {
+ return NextID(new GenerationOptions
+ {
+ UseNumbers = true,
+ UseSpecialCharacters = false,
+ Length = 8
+ });
+ }
+
+ ///
+ /// 生成短 ID
+ ///
+ ///
+ ///
+ public static string NextID(GenerationOptions options)
+ {
+ // 配置必填
+ if (options == null)
+ {
+ throw new ArgumentNullException(nameof(options));
+ }
+
+ // 判断生成的长度是否小于规定的长度,规定为 8
+ if (options.Length < Constants.MinimumAutoLength)
+ {
+ throw new ArgumentException(
+ $"The specified length of {options.Length} is less than the lower limit of {Constants.MinimumAutoLength} to avoid conflicts.");
+ }
+
+ var characterPool = _pool;
+ var poolBuilder = new StringBuilder(characterPool);
+
+ // 是否包含数字
+ if (options.UseNumbers)
+ {
+ poolBuilder.Append(Numbers);
+ }
+
+ // 是否包含特殊字符
+ if (options.UseSpecialCharacters)
+ {
+ poolBuilder.Append(Specials);
+ }
+
+ var pool = poolBuilder.ToString();
+
+ // 生成拼接
+ var output = new char[options.Length];
+ for (var i = 0; i < options.Length; i++)
+ {
+ lock (ThreadLock)
+ {
+ var charIndex = _random.Next(0, pool.Length);
+ output[i] = pool[charIndex];
+ }
+ }
+
+ return new string(output);
+ }
+
+ ///
+ /// 设置参与运算的字符,最少 50 位
+ ///
+ ///
+ public static void SetCharacters(string characters)
+ {
+ if (string.IsNullOrWhiteSpace(characters))
+ {
+ throw new ArgumentException("The replacement characters must not be null or empty.");
+ }
+
+ var charSet = characters
+ .ToCharArray()
+ .Where(x => !char.IsWhiteSpace(x))
+ .Distinct()
+ .ToArray();
+
+ if (charSet.Length < Constants.MinimumCharacterSetLength)
+ {
+ throw new InvalidOperationException(
+ $"The replacement characters must be at least {Constants.MinimumCharacterSetLength} letters in length and without whitespace.");
+ }
+
+ lock (ThreadLock)
+ {
+ _pool = new string(charSet);
+ }
+ }
+
+ ///
+ /// 设置种子步长
+ ///
+ ///
+ public static void SetSeed(int seed)
+ {
+ lock (ThreadLock)
+ {
+ _random = new Random(seed);
+ }
+ }
+
+ ///
+ /// 重置所有配置
+ ///
+ public static void Reset()
+ {
+ lock (ThreadLock)
+ {
+ _random = new Random();
+ _pool = $"{Smalls}{Bigs}";
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/WaterCloud.Code/HttpWebClient.cs b/WaterCloud.Code/HttpWebClient.cs
new file mode 100644
index 0000000000000000000000000000000000000000..f5ff33f731bbe9da08f6b701002a9d1c41e4a7f4
--- /dev/null
+++ b/WaterCloud.Code/HttpWebClient.cs
@@ -0,0 +1,239 @@
+using System;
+using System.Collections.Generic;
+using System.Net.Http;
+using System.Threading.Tasks;
+
+namespace WaterCloud.Code
+{
+ public class HttpWebClient
+ {
+
+ private IHttpClientFactory _httpClientFactory;
+ public HttpWebClient(IHttpClientFactory httpClientFactory)
+ {
+ this._httpClientFactory = httpClientFactory;
+ }
+ ///
+ /// Get请求
+ ///
+ ///
+ ///
+ ///
+ ///
+ //public async Task GetAsync(string url, int timeoutSecond = 120)
+ //{
+ // var client = _httpClientFactory.CreateClient();
+ // #region 最好不要这样绑定header,
+ // //DefaultRequestHeaders是和httpClient绑定的,当完成当前请求后,其它请求从factory中获取时,还是会有绑定的header的
+ // //会造成错误
+ // //if (dicHeaders != null)
+ // //{
+ // // foreach (var header in dicHeaders)
+ // // {
+ // // client.DefaultRequestHeaders.Add(header.Key, header.Value);
+ // // }
+ // //}
+ // #endregion
+ // client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
+ // var response = await client.GetAsync(url);
+ // var result = await response.Content.ReadAsStringAsync();
+ // return result;
+ //}
+
+
+
+
+ ///
+ /// Get异步请求
+ ///
+ ///
+ ///
+ ///
+ ///
+ public async Task GetAsync(string url, Dictionary dicHeaders, int timeoutSecond = 120)
+ {
+ var client = _httpClientFactory.CreateClient();
+ var request = new HttpRequestMessage(HttpMethod.Get, url);
+ if (dicHeaders != null)
+ {
+ foreach (var header in dicHeaders)
+ {
+ request.Headers.Add(header.Key, header.Value);
+ }
+ }
+ client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
+ var response = await client.SendAsync(request);
+ if (response.IsSuccessStatusCode)
+ {
+ var result = await response.Content.ReadAsStringAsync();
+ return result;
+ }
+ else
+ {
+ throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
+
+ }
+ }
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public async Task PostAsync(string url, string requestString, Dictionary dicHeaders, int timeoutSecond)
+ {
+ var client = _httpClientFactory.CreateClient();
+ var requestContent = new StringContent(requestString);
+ if (dicHeaders != null)
+ {
+ foreach (var head in dicHeaders)
+ {
+ requestContent.Headers.Add(head.Key, head.Value);
+ }
+ }
+ client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
+ var response = await client.PostAsync(url, requestContent);
+ if (response.IsSuccessStatusCode)
+ {
+ var result = await response.Content.ReadAsStringAsync();
+ return result;
+ }
+ else
+ {
+ throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
+ }
+ }
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public async Task PutAsync(string url, string requestString, Dictionary dicHeaders, int timeoutSecond)
+ {
+ var client = _httpClientFactory.CreateClient();
+ var requestContent = new StringContent(requestString);
+ if (dicHeaders != null)
+ {
+ foreach (var head in dicHeaders)
+ {
+ requestContent.Headers.Add(head.Key, head.Value);
+ }
+ }
+ client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
+ var response = await client.PutAsync(url, requestContent);
+ if (response.IsSuccessStatusCode)
+ {
+ var result = await response.Content.ReadAsStringAsync();
+ return result;
+ }
+ else
+ {
+ throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
+ }
+ }
+
+ ///
+ /// Patch异步请求
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public async Task PatchAsync(string url, string requestString, Dictionary dicHeaders, int timeoutSecond)
+ {
+ var client = _httpClientFactory.CreateClient();
+ var requestContent = new StringContent(requestString);
+ if (dicHeaders != null)
+ {
+ foreach (var head in dicHeaders)
+ {
+ requestContent.Headers.Add(head.Key, head.Value);
+ }
+ }
+ client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
+ var response = await client.PatchAsync(url, requestContent);
+ if (response.IsSuccessStatusCode)
+ {
+ var result = await response.Content.ReadAsStringAsync();
+ return result;
+ }
+ else
+ {
+ throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
+ }
+ }
+ public async Task DeleteAsync(string url, Dictionary dicHeaders, int timeoutSecond)
+ {
+ var client = _httpClientFactory.CreateClient();
+ var request = new HttpRequestMessage(HttpMethod.Delete, url);
+ if (dicHeaders != null)
+ {
+ foreach (var head in dicHeaders)
+ {
+ request.Headers.Add(head.Key, head.Value);
+ }
+ }
+ client.Timeout = TimeSpan.FromSeconds(timeoutSecond);
+ var response = await client.SendAsync(request);
+ if (response.IsSuccessStatusCode)
+ {
+ var result = await response.Content.ReadAsStringAsync();
+ return result;
+ }
+ else
+ {
+ throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
+ }
+ }
+ ///
+ /// 异步请求(通用)
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ public async Task ExecuteAsync(string url, HttpMethod method, string requestString, Dictionary dicHeaders, int timeoutSecond = 120)
+ {
+ var client = _httpClientFactory.CreateClient();
+ var request = new HttpRequestMessage(method, url)
+ {
+ Content = new StringContent(requestString),
+ };
+ if (dicHeaders != null)
+ {
+ foreach (var header in dicHeaders)
+ {
+ request.Headers.Add(header.Key, header.Value);
+ }
+ }
+ var response = await client.SendAsync(request);
+ if (response.IsSuccessStatusCode)
+ {
+ var result = await response.Content.ReadAsStringAsync();
+ return result;
+ }
+ else
+ {
+ throw new CustomerHttpException($"接口请求错误,错误代码{response.StatusCode},错误原因{response.ReasonPhrase}");
+ }
+ }
+
+ }
+ public class CustomerHttpException : Exception
+ {
+ public CustomerHttpException() : base()
+ { }
+ public CustomerHttpException(string message) : base(message)
+ {
+
+ }
+ }
+}
diff --git a/WaterCloud.Code/Model/SystemConfig.cs b/WaterCloud.Code/Model/SystemConfig.cs
index 9ae59dc0a5cf59f3a7d0c5dc4a012baf6cd4bce1..aa6ce499d6d5790cedae3b46fe6b3f3261ce95de 100644
--- a/WaterCloud.Code/Model/SystemConfig.cs
+++ b/WaterCloud.Code/Model/SystemConfig.cs
@@ -62,8 +62,12 @@ namespace WaterCloud.Code.Model
public string MainProgram { get; set; }
public bool? LocalLAN { get; set; }
///
- /// 雪花id配置
+ /// 项目前缀
///
- public int WorkId { get; set; }
- }
+ public string ProjectPrefix { get; set; }
+ ///
+ /// 重置密码
+ ///
+ public bool? ReviseSysem { get; set; }
+ }
}
diff --git a/WaterCloud.Code/Operator/OperatorProvider.cs b/WaterCloud.Code/Operator/OperatorProvider.cs
index 37cb82a29171a862f6ddf71103fe90a1f5173c8a..d2e4ec1a9cfad2d1860847ffbe264f6d9fe2a3fe 100644
--- a/WaterCloud.Code/Operator/OperatorProvider.cs
+++ b/WaterCloud.Code/Operator/OperatorProvider.cs
@@ -15,11 +15,12 @@ namespace WaterCloud.Code
public class OperatorProvider
{
//登录信息保存方式
- private string LoginProvider = GlobalContext.SystemConfig.LoginProvider;
+ private static string LoginProvider = GlobalContext.SystemConfig.LoginProvider;
//是否允许一个账户在多处登录
- private bool LoginMultiple = GlobalContext.SystemConfig.LoginMultiple;
+ private static bool LoginMultiple = GlobalContext.SystemConfig.LoginMultiple;
//缓存过期时间
- private int LoginExpire = GlobalContext.SystemConfig.LoginExpire;
+ private static int LoginExpire = GlobalContext.SystemConfig.LoginExpire;
+ private static string projectPrefix = GlobalContext.SystemConfig.ProjectPrefix;
public static OperatorProvider Provider
{
get { return new OperatorProvider(); }
@@ -30,17 +31,17 @@ namespace WaterCloud.Code
///
/// 缓存操作类
///
- private string cacheKeyOperator = "watercloud_operator_";// +登录者token
- private string cacheKeyToken = "watercloud_token_";// +登录者token
- private string cacheKeyError = "watercloud_error_";// + Mark
+ private string cacheKeyOperator = projectPrefix + "_operator_";// +登录者token
+ private string cacheKeyToken = projectPrefix + "_token_";// +登录者token
+ private string cacheKeyError = projectPrefix + "_error_";// + Mark
///
/// 秘钥
///
- private string LoginUserToken = "watercloud_Token";
+ private string LoginUserToken = projectPrefix + "_Token";
///
/// 标记登录的浏览器
///
- private string LoginUserMarkKey = "watercloud_Mark";
+ private string LoginUserMarkKey = projectPrefix + "_Mark";
public string GetProvider(string key)
{
switch (LoginProvider)
@@ -295,32 +296,14 @@ namespace WaterCloud.Code
OperatorModel operatorInfo = await CacheHelper.Get(cacheKeyOperator + loginMark);
if (operatorInfo != null)
{
- if (operatorInfo.LoginToken == token || LoginProvider == Define.PROVIDER_WEBAPI)
+ Dictionary tokenMarkList = await CacheHelper.Get>(cacheKeyToken + operatorInfo.UserId);
+ if ((token == operatorInfo.LoginToken || LoginProvider == Define.PROVIDER_WEBAPI) && tokenMarkList.ContainsKey(operatorInfo.loginMark) && tokenMarkList[operatorInfo.loginMark] == operatorInfo.LoginToken)
{
- //TimeSpan span = (TimeSpan)(DateTime.Now - operatorInfo.LoginTime);
- ////超时
- //if (span.TotalHours >= 12)// 登录操作过12小时移除
- //{
- // operatorResult.stateCode = 0;
- // Dictionary tokenMarkList = await CacheHelper.Get>(cacheKeyToken + operatorInfo.UserId);
- // tokenMarkList.Remove(loginMark);
- // await CacheHelper.Set(cacheKeyToken + operatorInfo.UserId, tokenMarkList);
- // await CacheHelper.Remove(cacheKeyOperator + loginMark);
- //}
////账号被顶(排除admin)
- //else if (!LoginMultiple && !operatorInfo.IsSystem && token != await CacheHelper.Get(cacheKeyOperator + facilityMark + operatorInfo.UserId))
- if (!LoginMultiple && !operatorInfo.IsSystem && token != await CacheHelper.Get(cacheKeyOperator + facilityMark + operatorInfo.UserId))
- {
- operatorResult.stateCode = -2;
- Dictionary tokenMarkList = await CacheHelper.Get>(cacheKeyToken + operatorInfo.UserId);
- tokenMarkList.Remove(loginMark);
- await CacheHelper.Set(cacheKeyToken + operatorInfo.UserId, tokenMarkList);
- await CacheHelper.Remove(cacheKeyOperator + loginMark);
- }
- else if (LoginProvider == Define.PROVIDER_WEBAPI && !operatorInfo.IsSystem && operatorInfo.LoginToken != await CacheHelper.Get(cacheKeyOperator + facilityMark + operatorInfo.UserId))
+ if (!LoginMultiple && !operatorInfo.IsSystem && operatorInfo.LoginToken != await CacheHelper.Get(cacheKeyOperator + facilityMark + operatorInfo.UserId))
{
operatorResult.stateCode = -2;
- Dictionary tokenMarkList = await CacheHelper.Get>(cacheKeyToken + operatorInfo.UserId);
+ tokenMarkList = await CacheHelper.Get>(cacheKeyToken + operatorInfo.UserId);
tokenMarkList.Remove(loginMark);
await CacheHelper.Set(cacheKeyToken + operatorInfo.UserId, tokenMarkList);
await CacheHelper.Remove(cacheKeyOperator + loginMark);
diff --git a/WaterCloud.Code/Snowflake/Generators/DefaultIDGenerator.cs b/WaterCloud.Code/Snowflake/Generators/DefaultIDGenerator.cs
deleted file mode 100644
index d4521137d9e76464151db021e1d8ab70b76471e5..0000000000000000000000000000000000000000
--- a/WaterCloud.Code/Snowflake/Generators/DefaultIDGenerator.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-using System;
-using System.Threading;
-
-namespace WaterCloud.Code
-{
- ///
- /// 默认实现
- ///
- public class DefaultIDGenerator : IIDGenerator
- {
- ///
- /// 雪花算法接口实例
- ///
- private ISnowflakeWorker InternalSnowflakeWorker { get; set; }
-
- ///
- /// 构造函数
- ///
- ///
- public DefaultIDGenerator(IDGeneratorOptions options)
- {
- if (options == null)
- {
- throw new ApplicationException("options error.");
- }
-
- if (options.BaseTime < DateTime.Now.AddYears(-50) || options.BaseTime > DateTime.Now)
- {
- throw new ApplicationException("BaseTime error.");
- }
-
- if (options.SeqBitLength + options.WorkerIdBitLength > 22)
- {
- throw new ApplicationException("error:WorkerIdBitLength + SeqBitLength <= 22.");
- }
-
- var maxWorkerIdNumber = Math.Pow(2, options.WorkerIdBitLength) - 1;
- if (options.WorkerId < 0 || options.WorkerId > maxWorkerIdNumber)
- {
- throw new ApplicationException("WorkerId error. (range:[1, " + maxWorkerIdNumber + "].");
- }
-
- if (options.SeqBitLength < 2 || options.SeqBitLength > 21)
- {
- throw new ApplicationException("SeqBitLength error. (range:[2, 21]).");
- }
-
- var maxSeqNumber = Math.Pow(2, options.SeqBitLength) - 1;
- if (options.MaxSeqNumber < 0 || options.MaxSeqNumber > maxSeqNumber)
- {
- throw new ApplicationException("MaxSeqNumber error. (range:[1, " + maxSeqNumber + "].");
- }
-
- var maxValue = maxSeqNumber; // maxSeqNumber - 1;
- if (options.MinSeqNumber < 1 || options.MinSeqNumber > maxValue)
- {
- throw new ApplicationException("MinSeqNumber error. (range:[1, " + maxValue + "].");
- }
-
- InternalSnowflakeWorker = options.Method switch
- {
- 1 => new SnowflakeWorkerM1(options),
- 2 => new SnowflakeWorkerM2(options),
- _ => new SnowflakeWorkerM1(options),
- };
-
- if (options.Method == 1)
- {
- Thread.Sleep(500);
- }
- }
-
- ///
- /// 生成雪花 ID 过程中的异步事件
- ///
- public Action GenIdActionAsync
- {
- get => InternalSnowflakeWorker.GenAction;
- set => InternalSnowflakeWorker.GenAction = value;
- }
-
- ///
- /// 生成新的 long 类型数据
- ///
- ///
- public long NewLong()
- {
- return InternalSnowflakeWorker.NextId();
- }
- }
-}
\ No newline at end of file
diff --git a/WaterCloud.Code/Snowflake/Generators/IIDGenerator.cs b/WaterCloud.Code/Snowflake/Generators/IIDGenerator.cs
deleted file mode 100644
index df1b0523938949b575909d97cf0edbc26d457867..0000000000000000000000000000000000000000
--- a/WaterCloud.Code/Snowflake/Generators/IIDGenerator.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System;
-
-namespace WaterCloud.Code
-{
- ///
- /// 雪花 ID 生成器接口
- ///
- public interface IIDGenerator
- {
- ///
- /// 生成过程中产生的事件
- ///
- Action GenIdActionAsync { get; set; }
-
- ///
- /// 生成新的long型Id
- ///
- ///
- long NewLong();
- }
-}
\ No newline at end of file
diff --git a/WaterCloud.Code/Snowflake/IDGenerator.cs b/WaterCloud.Code/Snowflake/IDGenerator.cs
deleted file mode 100644
index 1236eaed1fe3c044ebab466e755f0460793ccf68..0000000000000000000000000000000000000000
--- a/WaterCloud.Code/Snowflake/IDGenerator.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-namespace WaterCloud.Code
-{
- ///
- /// 雪花 ID 生成器静态类
- ///
- public class IDGenerator
- {
- ///
- /// 私有化实例
- ///
- private static IIDGenerator instance = null;
-
- ///
- /// 获取单例实例
- ///
- public static IIDGenerator Instance => instance;
-
- ///
- /// 设置参数,建议程序初始化时执行一次
- ///
- ///
- public static void SetIdGenerator(IDGeneratorOptions options)
- {
- instance = new DefaultIDGenerator(options);
- }
-
- ///
- /// 生成新的Id
- /// 调用本方法前,请确保调用了 SetIdGenerator 方法做初始化。
- /// 否则将会初始化一个WorkerId为1的对象。
- ///
- ///
- public static long NextId()
- {
- if (instance == null)
- {
- instance = new DefaultIDGenerator(new IDGeneratorOptions() { WorkerId = 1 });
- }
-
- return instance.NewLong();
- }
- }
-}
\ No newline at end of file
diff --git a/WaterCloud.Code/Snowflake/Internal/OverCostActionArg.cs b/WaterCloud.Code/Snowflake/Internal/OverCostActionArg.cs
deleted file mode 100644
index 2573b925e0a802f960e56831b6be682104b158fe..0000000000000000000000000000000000000000
--- a/WaterCloud.Code/Snowflake/Internal/OverCostActionArg.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-
-namespace WaterCloud.Code
-{
- ///
- /// Id生成时回调参数
- ///
- public class OverCostActionArg
- {
- ///
- /// 事件类型
- /// 1-开始,2-结束,8-漂移
- ///
- public virtual int ActionType { get; set; }
-
- ///
- /// 时间戳
- ///
- public virtual long TimeTick { get; set; }
-
- ///
- /// 机器码
- ///
- public virtual ushort WorkerId { get; set; }
-
- ///
- /// 漂移计算次数
- ///
- public virtual int OverCostCountInOneTerm { get; set; }
-
- ///
- /// 漂移期间生产ID个数
- ///
- public virtual int GenCountInOneTerm { get; set; }
-
- ///
- /// 漂移周期
- ///
- public virtual int TermIndex { get; set; }
-
- ///
- /// 构造函数
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public OverCostActionArg(ushort workerId, long timeTick, int actionType = 0, int overCostCountInOneTerm = 0, int genCountWhenOverCost = 0, int index = 0)
- {
- ActionType = actionType;
- TimeTick = timeTick;
- WorkerId = workerId;
- OverCostCountInOneTerm = overCostCountInOneTerm;
- GenCountInOneTerm = genCountWhenOverCost;
- TermIndex = index;
- }
- }
-}
\ No newline at end of file
diff --git a/WaterCloud.Code/Snowflake/Options/IDGeneratorOptions.cs b/WaterCloud.Code/Snowflake/Options/IDGeneratorOptions.cs
deleted file mode 100644
index 0b418f0ec82819185c865bac52a07f1f8c81c41f..0000000000000000000000000000000000000000
--- a/WaterCloud.Code/Snowflake/Options/IDGeneratorOptions.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-using System;
-
-namespace WaterCloud.Code
-{
- ///
- /// 雪花 ID 生成器配置配置
- ///
- public class IDGeneratorOptions
- {
- ///
- /// 构造函数
- ///
- public IDGeneratorOptions()
- {
- }
-
- ///
- /// 构造函数
- ///
- ///
- public IDGeneratorOptions(ushort workerId)
- {
- WorkerId = workerId;
- }
-
- ///
- /// 雪花计算方法
- /// (1-漂移算法|2-传统算法),默认1
- ///
- public virtual short Method { get; set; } = 1;
-
- ///
- /// 开始时间(UTC格式)
- /// 不能超过当前系统时间
- ///
- public virtual DateTime BaseTime { get; set; } = new DateTime(2020, 2, 20, 2, 20, 2, 20, DateTimeKind.Utc);
-
- ///
- /// 机器码
- /// 与 WorkerIdBitLength 有关系
- /// (ushort类型,最大值65535,如果有更高要求,请修改数据类型,或联系作者)
- ///
- public virtual ushort WorkerId { get; set; } = 0;
-
- ///
- /// 机器码位长
- /// 范围:1-21(要求:序列数位长+机器码位长不超过22)。
- /// 建议范围:6-12。
- ///
- public virtual byte WorkerIdBitLength { get; set; } = 6;//10;
-
- ///
- /// 序列数位长
- /// 范围:2-21(要求:序列数位长+机器码位长不超过22)。
- /// 建议范围:6-14。
- ///
- public virtual byte SeqBitLength { get; set; } = 6;//10;
-
- ///
- /// 最大序列数(含)
- /// (由SeqBitLength计算的最大值)
- ///
- public virtual int MaxSeqNumber { get; set; } = 0;
-
- ///
- /// 最小序列数(含)
- /// 默认5,不小于1,不大于MaxSeqNumber
- ///
- public virtual ushort MinSeqNumber { get; set; } = 5;
-
- ///
- /// 最大漂移次数(含),
- /// 默认2000,推荐范围500-10000(与计算能力有关)
- ///
- public virtual int TopOverCostCount { get; set; } = 2000;
- }
-}
\ No newline at end of file
diff --git a/WaterCloud.Code/Snowflake/Workers/ISnowflakeWorker.cs b/WaterCloud.Code/Snowflake/Workers/ISnowflakeWorker.cs
deleted file mode 100644
index a4cc886e6a9709edc12286dfd6aaec38465a98e6..0000000000000000000000000000000000000000
--- a/WaterCloud.Code/Snowflake/Workers/ISnowflakeWorker.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-using System;
-
-namespace WaterCloud.Code
-{
- ///
- /// 雪花算法接口
- ///
- internal interface ISnowflakeWorker
- {
- ///
- /// 雪花 ID 生成事件
- ///
- Action GenAction { get; set; }
-
- ///
- /// 下一个 雪花 ID
- ///
- ///
- long NextId();
- }
-}
\ No newline at end of file
diff --git a/WaterCloud.Code/Snowflake/Workers/SnowflakeWorkerM1.cs b/WaterCloud.Code/Snowflake/Workers/SnowflakeWorkerM1.cs
deleted file mode 100644
index ec2718052b3d4fe0d06b2ae1b179ca138032f5cd..0000000000000000000000000000000000000000
--- a/WaterCloud.Code/Snowflake/Workers/SnowflakeWorkerM1.cs
+++ /dev/null
@@ -1,334 +0,0 @@
-using System;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace WaterCloud.Code
-{
- ///
- /// 雪花漂移算法
- ///
- internal class SnowflakeWorkerM1 : ISnowflakeWorker
- {
- ///
- /// 基础时间
- ///
- protected readonly DateTime BaseTime;
-
- ///
- /// 机器码
- ///
- protected readonly ushort WorkerId = 0;
-
- ///
- /// 机器码位长
- ///
- protected readonly byte WorkerIdBitLength = 0;
-
- ///
- /// 自增序列数位长
- ///
- protected readonly byte SeqBitLength = 0;
-
- ///
- /// 最大序列数(含)
- ///
- protected readonly int MaxSeqNumber = 0;
-
- ///
- /// 最小序列数(含)
- ///
- protected readonly ushort MinSeqNumber = 0;
-
- ///
- /// 最大漂移次数
- ///
- protected readonly int TopOverCostCount = 0;
-
- protected readonly byte _TimestampShift = 0;
- protected static object _SyncLock = new();
-
- protected ushort _CurrentSeqNumber;
- protected long _LastTimeTick = -1L;
- protected long _TurnBackTimeTick = -1L;
- protected byte _TurnBackIndex = 0;
-
- protected bool _IsOverCost = false;
- protected int _OverCostCountInOneTerm = 0;
- protected int _GenCountInOneTerm = 0;
- protected int _TermIndex = 0;
-
- ///
- /// 构造函数
- ///
- ///
- public SnowflakeWorkerM1(IDGeneratorOptions options)
- {
- WorkerId = options.WorkerId;
- WorkerIdBitLength = options.WorkerIdBitLength;
- SeqBitLength = options.SeqBitLength;
- MaxSeqNumber = options.MaxSeqNumber;
- MinSeqNumber = options.MinSeqNumber;
- TopOverCostCount = options.TopOverCostCount;
-
- if (options.BaseTime != DateTime.MinValue)
- {
- BaseTime = options.BaseTime;
- }
-
- if (WorkerId < 1)
- {
- WorkerId = (ushort)DateTime.Now.Millisecond;
- }
-
- if (SeqBitLength == 0)
- {
- SeqBitLength = 6;
- }
-
- if (WorkerIdBitLength == 0)
- {
- WorkerIdBitLength = 6;
- }
-
- if (MaxSeqNumber == 0)
- {
- MaxSeqNumber = (int)Math.Pow(2, SeqBitLength) - 1;
- }
-
- _TimestampShift = (byte)(WorkerIdBitLength + SeqBitLength);
- _CurrentSeqNumber = options.MinSeqNumber;
- }
-
- ///
- /// 雪花 ID 生成事件
- ///
- public Action GenAction { get; set; }
-
- ///
- /// 下一个 雪花 ID
- ///
- ///
- public virtual long NextId()
- {
- lock (_SyncLock)
- {
- return _IsOverCost ? NextOverCostId() : NextNormalId();
- }
- }
-
- private void DoGenIdAction(OverCostActionArg arg)
- {
- Task.Run(() =>
- {
- GenAction(arg);
- });
- }
-
- private void BeginOverCostAction(in long useTimeTick)
- {
- if (GenAction == null)
- {
- return;
- }
-
- DoGenIdAction(new OverCostActionArg(
- WorkerId,
- useTimeTick,
- 1,
- _OverCostCountInOneTerm,
- _GenCountInOneTerm,
- _TermIndex));
- }
-
- private void EndOverCostAction(in long useTimeTick)
- {
- if (_TermIndex > 10000)
- {
- _TermIndex = 0;
- }
-
- if (GenAction == null)
- {
- return;
- }
-
- DoGenIdAction(new OverCostActionArg(
- WorkerId,
- useTimeTick,
- 2,
- _OverCostCountInOneTerm,
- _GenCountInOneTerm,
- _TermIndex));
- }
-
- private void BeginTurnBackAction(in long useTimeTick)
- {
- if (GenAction == null)
- {
- return;
- }
-
- DoGenIdAction(new OverCostActionArg(
- WorkerId,
- useTimeTick,
- 8,
- 0,
- 0,
- _TurnBackIndex));
- }
-
- private void EndTurnBackAction(in long useTimeTick)
- {
- if (GenAction == null)
- {
- return;
- }
-
- DoGenIdAction(new OverCostActionArg(
- WorkerId,
- useTimeTick,
- 9,
- 0,
- 0,
- _TurnBackIndex));
- }
-
- private long NextOverCostId()
- {
- long currentTimeTick = GetCurrentTimeTick();
-
- if (currentTimeTick > _LastTimeTick)
- {
- EndOverCostAction(currentTimeTick);
-
- _LastTimeTick = currentTimeTick;
- _CurrentSeqNumber = MinSeqNumber;
- _IsOverCost = false;
- _OverCostCountInOneTerm = 0;
- _GenCountInOneTerm = 0;
-
- return CalcId(_LastTimeTick);
- }
-
- if (_OverCostCountInOneTerm >= TopOverCostCount)
- {
- EndOverCostAction(currentTimeTick);
-
- _LastTimeTick = GetNextTimeTick();
- _CurrentSeqNumber = MinSeqNumber;
- _IsOverCost = false;
- _OverCostCountInOneTerm = 0;
- _GenCountInOneTerm = 0;
-
- return CalcId(_LastTimeTick);
- }
-
- if (_CurrentSeqNumber > MaxSeqNumber)
- {
- _LastTimeTick++;
- _CurrentSeqNumber = MinSeqNumber;
- _IsOverCost = true;
- _OverCostCountInOneTerm++;
- _GenCountInOneTerm++;
-
- return CalcId(_LastTimeTick);
- }
-
- _GenCountInOneTerm++;
- return CalcId(_LastTimeTick);
- }
-
- private long NextNormalId()
- {
- long currentTimeTick = GetCurrentTimeTick();
-
- if (currentTimeTick < _LastTimeTick)
- {
- if (_TurnBackTimeTick < 1)
- {
- _TurnBackTimeTick = _LastTimeTick - 1;
- _TurnBackIndex++;
-
- // 每毫秒序列数的前5位是预留位,0用于手工新值,1-4是时间回拨次序
- // 最多4次回拨(防止回拨重叠)
- if (_TurnBackIndex > 4)
- {
- _TurnBackIndex = 1;
- }
-
- BeginTurnBackAction(_TurnBackTimeTick);
- }
-
- Thread.Sleep(10);
- return CalcTurnBackId(_TurnBackTimeTick);
- }
-
- // 时间追平时,_TurnBackTimeTick清零
- if (_TurnBackTimeTick > 0)
- {
- EndTurnBackAction(_TurnBackTimeTick);
- _TurnBackTimeTick = 0;
- }
-
- if (currentTimeTick > _LastTimeTick)
- {
- _LastTimeTick = currentTimeTick;
- _CurrentSeqNumber = MinSeqNumber;
-
- return CalcId(_LastTimeTick);
- }
-
- if (_CurrentSeqNumber > MaxSeqNumber)
- {
- BeginOverCostAction(currentTimeTick);
-
- _TermIndex++;
- _LastTimeTick++;
- _CurrentSeqNumber = MinSeqNumber;
- _IsOverCost = true;
- _OverCostCountInOneTerm = 1;
- _GenCountInOneTerm = 1;
-
- return CalcId(_LastTimeTick);
- }
-
- return CalcId(_LastTimeTick);
- }
-
- private long CalcId(in long useTimeTick)
- {
- var result = ((useTimeTick << _TimestampShift) +
- ((long)WorkerId << SeqBitLength) +
- (uint)_CurrentSeqNumber);
-
- _CurrentSeqNumber++;
- return result;
- }
-
- private long CalcTurnBackId(in long useTimeTick)
- {
- var result = ((useTimeTick << _TimestampShift) +
- ((long)WorkerId << SeqBitLength) + _TurnBackIndex);
-
- _TurnBackTimeTick--;
- return result;
- }
-
- protected virtual long GetCurrentTimeTick()
- {
- return (long)(DateTime.UtcNow - BaseTime).TotalMilliseconds;
- }
-
- protected virtual long GetNextTimeTick()
- {
- long tempTimeTicker = GetCurrentTimeTick();
-
- while (tempTimeTicker <= _LastTimeTick)
- {
- tempTimeTicker = GetCurrentTimeTick();
- }
-
- return tempTimeTicker;
- }
- }
-}
\ No newline at end of file
diff --git a/WaterCloud.Code/Snowflake/Workers/SnowflakeWorkerM2.cs b/WaterCloud.Code/Snowflake/Workers/SnowflakeWorkerM2.cs
deleted file mode 100644
index 42c8b694cbdf4b948db457fec65414c5e8b2c7cf..0000000000000000000000000000000000000000
--- a/WaterCloud.Code/Snowflake/Workers/SnowflakeWorkerM2.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-using System;
-
-namespace WaterCloud.Code
-{
- ///
- /// 常规雪花算法
- ///
- internal class SnowflakeWorkerM2 : SnowflakeWorkerM1
- {
- ///
- /// 构造函数
- ///
- ///
- public SnowflakeWorkerM2(IDGeneratorOptions options) : base(options)
- {
- }
-
- ///
- /// 下一个 雪花 ID
- ///
- ///
- public override long NextId()
- {
- lock (_SyncLock)
- {
- long currentTimeTick = GetCurrentTimeTick();
-
- if (_LastTimeTick == currentTimeTick)
- {
- if (_CurrentSeqNumber++ > MaxSeqNumber)
- {
- _CurrentSeqNumber = MinSeqNumber;
- currentTimeTick = GetNextTimeTick();
- }
- }
- else
- {
- _CurrentSeqNumber = MinSeqNumber;
- }
-
- if (currentTimeTick < _LastTimeTick)
- {
- throw new Exception(string.Format("Time error for {0} milliseconds", _LastTimeTick - currentTimeTick));
- }
-
- _LastTimeTick = currentTimeTick;
- var result = ((currentTimeTick << _TimestampShift) + ((long)WorkerId << SeqBitLength) + (uint)_CurrentSeqNumber);
-
- return result;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/WaterCloud.Code/Utils.cs b/WaterCloud.Code/Utils.cs
index d9b9eb98687a131bbf4ca19f7a3c4006ec777adc..a67cc889fc9609c3748e7552c58c1e1aa4f358ea 100644
--- a/WaterCloud.Code/Utils.cs
+++ b/WaterCloud.Code/Utils.cs
@@ -13,7 +13,7 @@ namespace WaterCloud.Code
///
public static string GuId()
{
- return Guid.NewGuid().ToString();
+ return IDGen.NextID().ToString();
}
///
/// 自动生成编号 201008251145409865
@@ -29,7 +29,7 @@ namespace WaterCloud.Code
#endregion
public static string GetGuid()
{
- return Guid.NewGuid().ToString().Replace("-", string.Empty).ToLower();
+ return IDGen.NextID().ToString().Replace("-", string.Empty).ToLower();
}
}
}
diff --git a/WaterCloud.CodeGenerator/Template/SingleTableTemplate.cs b/WaterCloud.CodeGenerator/Template/SingleTableTemplate.cs
index ba96bc3ff36f162bfd1146e8a51b2c154bdd6995..bce35f513fe67fcc1d8a81f8b27274e152626adf 100644
--- a/WaterCloud.CodeGenerator/Template/SingleTableTemplate.cs
+++ b/WaterCloud.CodeGenerator/Template/SingleTableTemplate.cs
@@ -16,16 +16,11 @@ namespace WaterCloud.CodeGenerator
{
public class SingleTableTemplate
{
- private string buttoncacheKey = "watercloud_modulebuttondata_";
- private string fieldscacheKey = "watercloud_modulefieldsdata_";
- private string cacheKey = "watercloud_moduleldata_";
- private string quickcacheKey = "watercloud_quickmoduledata_";
- private string initcacheKey = "watercloud_init_";
- private string authorizecacheKey = "watercloud_authorizeurldata_";// +权限
- private IRepositoryBase uniwork;
- public SingleTableTemplate(IDbContext context)
+ private string authorizecacheKey = GlobalContext.SystemConfig.ProjectPrefix + "_authorizeurldata_";// +权限
+ private IUnitOfWork unitwork;
+ public SingleTableTemplate(IUnitOfWork unitOfWork)
{
- uniwork = new RepositoryBase(context);
+ unitwork = unitOfWork;
}
#region GetBaseConfig
public BaseConfigModel GetBaseConfig(string path, string username, string tableName, string tableDescription, List tableFieldList)
@@ -194,6 +189,7 @@ namespace WaterCloud.CodeGenerator
sb.AppendLine("using System.Threading.Tasks;");
sb.AppendLine("using System.Collections.Generic;");
sb.AppendLine("using WaterCloud.Code;");
+ sb.AppendLine("using WaterCloud.DataBase;");
sb.AppendLine("using Chloe;");
sb.AppendLine("using WaterCloud.Domain." + baseConfigModel.OutputConfig.OutputModule + ";");
sb.AppendLine();
@@ -207,9 +203,9 @@ namespace WaterCloud.CodeGenerator
sb.AppendLine(" {");
if (baseConfigModel.PageIndex.IsCache == true)
{
- sb.AppendLine(" private string cacheKey = \"watercloud_" + baseConfigModel.FileConfig.ClassPrefix.ToLower() + "data_\";");
+ sb.AppendLine(" private string cacheKey = GlobalContext.SystemConfig.ProjectPrefix + \"_" + baseConfigModel.FileConfig.ClassPrefix.ToLower() + "data_\";");
}
- sb.AppendLine(" public " + baseConfigModel.FileConfig.ServiceName + "(IDbContext context) : base(context)");
+ sb.AppendLine(" public " + baseConfigModel.FileConfig.ServiceName + "(IUnitOfWork unitOfWork) : base(unitOfWork)");
sb.AppendLine(" {");
sb.AppendLine(" }");
@@ -718,7 +714,7 @@ namespace WaterCloud.CodeGenerator
sb.AppendLine(" { title: '操作', width: 130, toolbar: '#currentTableBar', align: \"center\", fixed: 'right' }");
break;
case 3:
- sb.AppendLine(" { title: '操作', width: 170, toolbar: '#currentTableBar', align: \"center\", fixed: 'right' }");
+ sb.AppendLine(" { title: '操作', width: 175, toolbar: '#currentTableBar', align: \"center\", fixed: 'right' }");
break;
default:
break;
@@ -765,7 +761,7 @@ namespace WaterCloud.CodeGenerator
sb.AppendLine(" { title: '操作', width: 130, toolbar: '#currentTableBar', align: \"center\", fixed: 'right' }");
break;
case 3:
- sb.AppendLine(" { title: '操作', width: 170, toolbar: '#currentTableBar', align: \"center\", fixed: 'right' }");
+ sb.AppendLine(" { title: '操作', width: 175, toolbar: '#currentTableBar', align: \"center\", fixed: 'right' }");
break;
default:
break;
@@ -1272,7 +1268,7 @@ namespace WaterCloud.CodeGenerator
string menuUrl = "/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + baseConfigModel.FileConfig.PageIndexName;
ModuleEntity moduleEntity = new ModuleEntity();
moduleEntity.Create();
- moduleEntity.F_Layers = (await uniwork.FindEntity(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule)).F_Layers + 1; ;
+ moduleEntity.F_Layers = (await unitwork.FindEntity(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule)).F_Layers + 1; ;
moduleEntity.F_FullName = baseConfigModel.FileConfig.ClassDescription;
moduleEntity.F_UrlAddress = menuUrl;
moduleEntity.F_EnCode = baseConfigModel.FileConfig.ClassPrefix;
@@ -1285,9 +1281,9 @@ namespace WaterCloud.CodeGenerator
moduleEntity.F_AllowDelete = false;
moduleEntity.F_EnabledMark = true;
moduleEntity.F_DeleteMark = false;
- moduleEntity.F_ParentId = (await uniwork.FindEntity(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule)).F_Id;
- var parentModule = await uniwork.FindEntity(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule);
- moduleEntity.F_SortCode = (uniwork.IQueryable(a => a.F_ParentId == parentModule.F_Id).Max(a => a.F_SortCode) ?? 0) + 1;
+ moduleEntity.F_ParentId = (await unitwork.FindEntity(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule)).F_Id;
+ var parentModule = await unitwork.FindEntity(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule);
+ moduleEntity.F_SortCode = (unitwork.IQueryable(a => a.F_ParentId == parentModule.F_Id).Max(a => a.F_SortCode) ?? 0) + 1;
List moduleButtonList = new List();
int sort = 0;
foreach (var item in baseConfigModel.PageIndex.ButtonList)
@@ -1340,21 +1336,14 @@ namespace WaterCloud.CodeGenerator
moduleFields.F_DeleteMark = false;
moduleFieldsList.Add(moduleFields);
}
- uniwork.BeginTrans();
- await uniwork.Insert(moduleEntity);
- await uniwork.Insert(moduleButtonList);
+ unitwork.BeginTrans();
+ await unitwork.Insert(moduleEntity);
+ await unitwork.Insert(moduleButtonList);
if (moduleFieldsList.Count > 0)
{
- await uniwork.Insert(moduleFieldsList);
+ await unitwork.Insert(moduleFieldsList);
}
- uniwork.Commit();
- await CacheHelper.Remove(fieldscacheKey + "list");
- await CacheHelper.Remove(buttoncacheKey + "list");
- await CacheHelper.Remove(cacheKey + "list");
- await CacheHelper.Remove(quickcacheKey + "list");
- await CacheHelper.Remove(initcacheKey + "list");
- await CacheHelper.Remove(initcacheKey + "modulebutton_list");
- await CacheHelper.Remove(initcacheKey + "modulefields_list");
+ unitwork.Commit();
await CacheHelper.Remove(authorizecacheKey + "list");
FileHelper.CreateFile(indexPath, codeIndex);
result.Add(new KeyValue { Key = "列表页", Value = indexPath, Description = "生成成功!" });
diff --git a/WaterCloud.Data/Repository/IRepositoryBase.T.cs b/WaterCloud.Data/Repository/IRepositoryBase.T.cs
index 03f32d81feafb60c78235b5f5f41d1d3b66de134..ef1b24f817b7f8d117848830f154584bb763174a 100644
--- a/WaterCloud.Data/Repository/IRepositoryBase.T.cs
+++ b/WaterCloud.Data/Repository/IRepositoryBase.T.cs
@@ -19,7 +19,8 @@ namespace WaterCloud.DataBase
/// 实体类型
public interface IRepositoryBase where TEntity : class, new()
{
- IDbContext GetDbContext();
+ IDbContext Db { get; }
+ IUnitOfWork unitOfWork { get; }
Task Insert(TEntity entity);
Task Insert(List entitys);
Task Update(TEntity entity);
@@ -28,8 +29,8 @@ namespace WaterCloud.DataBase
Task Delete(Expression> predicate);
Task FindEntity(object keyValue);
Task FindEntity(Expression> predicate);
- IQuery IQueryable();
- IQuery IQueryable(Expression> predicate);
+ IQuery IQueryable(LockType locktype = LockType.NoLock);
+ IQuery IQueryable(Expression> predicate, LockType locktype = LockType.NoLock);
Task> FindList(string strSql);
Task> FindList(string strSql, DbParam[] dbParameter);
Task> FindList(Pagination pagination);
diff --git a/WaterCloud.Data/Repository/IRepositoryBase.cs b/WaterCloud.Data/Repository/IUnitOfWork.cs
similarity index 93%
rename from WaterCloud.Data/Repository/IRepositoryBase.cs
rename to WaterCloud.Data/Repository/IUnitOfWork.cs
index 88a9887685d1f9bc09dc4a5ecd7cbfba6e72d414..3c9a8083f552d9531730f0d147703509802dafa2 100644
--- a/WaterCloud.Data/Repository/IRepositoryBase.cs
+++ b/WaterCloud.Data/Repository/IUnitOfWork.cs
@@ -1,155 +1,155 @@
-/*******************************************************************************
- * Copyright © 2020 WaterCloud.Framework 版权所有
- * Author: WaterCloud
- * Description: WaterCloud快速开发平台
- * Website:
-*********************************************************************************/
-using Chloe;
-using WaterCloud.Code;
-using System;
-using System.Collections.Generic;
-using System.Linq.Expressions;
-using System.Threading.Tasks;
-
-namespace WaterCloud.DataBase
-{
- public interface IRepositoryBase : IDisposable
- {
- IDbContext GetDbContext();
- IRepositoryBase BeginTrans();
- void Commit();
- void Rollback();
- ///
- /// 插入
- ///
- ///
- ///
- Task Insert(TEntity entity) where TEntity : class;
- ///
- /// 批量插入
- ///
- ///
- ///
- Task Insert(List entitys) where TEntity : class;
- ///
- /// 更新
- ///
- ///
- ///
- ///
- Task Update(TEntity entity) where TEntity : class;
- ///
- /// 批量更新
- ///
- ///
- ///
- ///
- ///
- Task Update(Expression> predicate, Expression> content) where TEntity : class;
- ///
- /// 删除
- ///
- ///
- ///
- ///
- Task Delete(TEntity entity) where TEntity : class;
- ///
- /// 批量删除
- ///
- ///
- ///
- ///
- Task Delete(Expression> predicate) where TEntity : class;
- ///
- /// 查询单个对象根据主键
- ///
- ///
- ///
- ///
- Task FindEntity(object keyValue) where TEntity : class;
- ///
- /// 查询单个对象根据条件
- ///
- ///
- ///
- ///
- Task FindEntity(Expression> predicate) where TEntity : class;
- ///
- /// 查询
- ///
- ///
- ///
- IQuery IQueryable() where TEntity : class;
- ///
- /// 查询根据条件
- ///
- ///
- ///
- ///
- IQuery IQueryable(Expression> predicate) where TEntity : class;
- ///
- /// SQL查询
- ///
- ///
- ///
- ///
- Task> FindList(string strSql) where TEntity : class;
- ///
- /// sql查询
- ///
- ///
- ///
- ///
- ///
- Task> FindList(string strSql, DbParam[] dbParameter) where TEntity : class;
- ///
- /// 查询根据分页
- ///
- ///
- ///
- ///
- Task> FindList(Pagination pagination) where TEntity : class, new();
- ///
- /// 查询根据条件和分页
- ///
- ///
- ///
- ///
- ///
- Task> FindList(Expression> predicate, Pagination pagination) where TEntity : class, new();
- ///
- /// 对IQuery参数分页
- ///
- ///
- ///
- ///
- ///
- Task> OrderList(IQuery query, Pagination pagination);
- ///
- /// soultable-后端筛选
- ///
- ///
- ///
- ///
- ///
- Task> OrderList(IQuery query, SoulPage pagination);
- ///
- /// 缓存单个对象
- ///
- ///
- ///
- ///
- ///
- ///
- Task CheckCache(string cacheKey, object keyValue, long old = 0) where TEntity : class;
- ///
- /// 缓存查询列表(大数据表谨慎使用)
- ///
- ///
- ///
- ///
- ///
- Task> CheckCacheList(string cacheKey, long old = 0) where TEntity : class;
-
- }
-}
+/*******************************************************************************
+ * Copyright © 2020 WaterCloud.Framework 版权所有
+ * Author: WaterCloud
+ * Description: WaterCloud快速开发平台
+ * Website:
+*********************************************************************************/
+using Chloe;
+using WaterCloud.Code;
+using System;
+using System.Collections.Generic;
+using System.Linq.Expressions;
+using System.Threading.Tasks;
+
+namespace WaterCloud.DataBase
+{
+ public interface IUnitOfWork : IDisposable
+ {
+ DbContext GetDbContext();
+ IUnitOfWork BeginTrans();
+ void Commit();
+ void Rollback();
+ ///
+ /// 插入
+ ///
+ ///
+ ///
+ Task Insert(TEntity entity) where TEntity : class;
+ ///
+ /// 批量插入
+ ///
+ ///
+ ///
+ Task Insert(List entitys) where TEntity : class;
+ ///
+ /// 更新
+ ///
+ ///
+ ///
+ ///
+ Task Update(TEntity entity) where TEntity : class;
+ ///
+ /// 批量更新
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task Update(Expression> predicate, Expression> content) where TEntity : class;
+ ///
+ /// 删除
+ ///
+ ///
+ ///
+ ///
+ Task Delete(TEntity entity) where TEntity : class;
+ ///
+ /// 批量删除
+ ///
+ ///
+ ///
+ ///
+ Task Delete(Expression> predicate) where TEntity : class;
+ ///
+ /// 查询单个对象根据主键
+ ///
+ ///
+ ///
+ ///
+ Task FindEntity(object keyValue) where TEntity : class;
+ ///
+ /// 查询单个对象根据条件
+ ///
+ ///
+ ///
+ ///
+ Task FindEntity(Expression> predicate) where TEntity : class;
+ ///
+ /// 查询
+ ///
+ ///
+ ///
+ IQuery IQueryable(LockType locktype = LockType.NoLock) where TEntity : class;
+ ///
+ /// 查询根据条件
+ ///
+ ///
+ ///
+ ///
+ IQuery IQueryable(Expression> predicate, LockType locktype = LockType.NoLock) where TEntity : class;
+ ///
+ /// SQL查询
+ ///
+ ///
+ ///
+ ///
+ Task> FindList(string strSql) where TEntity : class;
+ ///
+ /// sql查询
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task> FindList(string strSql, DbParam[] dbParameter) where TEntity : class;
+ ///
+ /// 查询根据分页
+ ///
+ ///
+ ///
+ ///
+ Task> FindList(Pagination pagination) where TEntity : class, new();
+ ///
+ /// 查询根据条件和分页
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task> FindList(Expression> predicate, Pagination pagination) where TEntity : class, new();
+ ///
+ /// 对IQuery参数分页
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task> OrderList(IQuery query, Pagination pagination);
+ ///
+ /// soultable-后端筛选
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task> OrderList(IQuery query, SoulPage pagination);
+ ///
+ /// 缓存单个对象
+ ///
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task CheckCache(string cacheKey, object keyValue, long old = 0) where TEntity : class;
+ ///
+ /// 缓存查询列表(大数据表谨慎使用)
+ ///
+ ///
+ ///
+ ///
+ ///
+ Task> CheckCacheList(string cacheKey, long old = 0) where TEntity : class;
+
+ }
+}
diff --git a/WaterCloud.Data/Repository/RepositoryBase.T.cs b/WaterCloud.Data/Repository/RepositoryBase.T.cs
index a28e969f46d268e29ffd5d2945d705bc9a8c1a83..4488fa399cbfc06bbc40f1a7ef6d802f62c68b90 100644
--- a/WaterCloud.Data/Repository/RepositoryBase.T.cs
+++ b/WaterCloud.Data/Repository/RepositoryBase.T.cs
@@ -21,34 +21,36 @@ namespace WaterCloud.DataBase
///
public class RepositoryBase : IRepositoryBase where TEntity : class, new()
{
- private IDbContext _context;
- public IDbContext GetDbContext()
- {
- return _context;
+ private readonly DbContext _dbBase;
+ private readonly IUnitOfWork _unitOfWork;
+ public IDbContext Db
+ {
+ get { return _dbBase; }
}
- public RepositoryBase(string ConnectStr, string providerName)
+ public IUnitOfWork unitOfWork
{
- _context = DBContexHelper.Contex(ConnectStr, providerName);
+ get { return _unitOfWork; }
}
- public RepositoryBase(IDbContext context)
+ public RepositoryBase(IUnitOfWork unitOfWork)
{
- _context = context;
+ _unitOfWork = unitOfWork;
+ _dbBase = unitOfWork.GetDbContext();
}
public async Task Insert(TEntity entity)
{
- return await _context.InsertAsync(entity);
+ return await _dbBase.InsertAsync(entity);
}
public async Task Insert(List entitys)
{
int i = 1;
- await _context.InsertRangeAsync(entitys);
+ await _dbBase.InsertRangeAsync(entitys);
return i;
}
public async Task Update(TEntity entity)
{
//反射对比更新对象变更
- TEntity newentity = _context.QueryByKey(entity);
- _context.TrackEntity(newentity);
+ TEntity newentity = _dbBase.QueryByKey(entity);
+ _dbBase.TrackEntity(newentity);
PropertyInfo[] newprops = newentity.GetType().GetProperties();
PropertyInfo[] props = entity.GetType().GetProperties();
foreach (PropertyInfo prop in props)
@@ -64,47 +66,47 @@ namespace WaterCloud.DataBase
}
}
}
- return await _context.UpdateAsync(newentity);
+ return await _dbBase.UpdateAsync(newentity);
}
public async Task Update(Expression> predicate, Expression> content)
{
- return await _context.UpdateAsync(predicate, content);
+ return await _dbBase.UpdateAsync(predicate, content);
}
public async Task Delete(TEntity entity)
{
- return await _context.DeleteAsync(entity);
+ return await _dbBase.DeleteAsync(entity);
}
public async Task Delete(Expression> predicate)
{
- return await _context.DeleteAsync(predicate);
+ return await _dbBase.DeleteAsync(predicate);
}
public async Task FindEntity(object keyValue)
{
- return await _context.QueryByKeyAsync(keyValue);
+ return await _dbBase.QueryByKeyAsync(keyValue);
}
public async Task FindEntity(Expression> predicate)
{
- return _context.Query().FirstOrDefault(predicate);
+ return _dbBase.Query().FirstOrDefault(predicate);
}
- public IQuery IQueryable()
+ public IQuery IQueryable(LockType locktype = LockType.NoLock)
{
- return _context.Query();
+ return _dbBase.Query(locktype);
}
- public IQuery IQueryable(Expression> predicate)
+ public IQuery IQueryable(Expression> predicate, LockType locktype = LockType.NoLock)
{
- return _context.Query().Where(predicate);
+ return _dbBase.Query(locktype).Where(predicate);
}
public async Task> FindList(string strSql)
{
- return await _context.SqlQueryAsync(strSql);
+ return await _dbBase.SqlQueryAsync(strSql);
}
public async Task> FindList(string strSql, DbParam[] dbParameter)
{
- return await _context.SqlQueryAsync(strSql, dbParameter);
+ return await _dbBase.SqlQueryAsync(strSql, dbParameter);
}
public async Task> FindList(Pagination pagination)
{
- var tempData = _context.Query();
+ var tempData = _dbBase.Query();
pagination.records = tempData.Count();
tempData = tempData.OrderBy(pagination.sort);
tempData = tempData.TakePage(pagination.page, pagination.rows);
@@ -112,7 +114,7 @@ namespace WaterCloud.DataBase
}
public async Task> FindList(Expression> predicate, Pagination pagination)
{
- var tempData = _context.Query().Where(predicate);
+ var tempData = _dbBase.Query().Where(predicate);
pagination.records = tempData.Count();
tempData = tempData.OrderBy(pagination.sort);
tempData = tempData.TakePage(pagination.page, pagination.rows);
@@ -151,7 +153,7 @@ namespace WaterCloud.DataBase
var cachedata =await CacheHelper.Get>(cacheKey);
if (cachedata == null || cachedata.Count() == 0)
{
- cachedata = _context.Query().ToList();
+ cachedata = _dbBase.Query().ToList();
await CacheHelper.Set(cacheKey, cachedata);
}
return cachedata;
@@ -161,7 +163,7 @@ namespace WaterCloud.DataBase
var cachedata = await CacheHelper.Get(cacheKey + keyValue);
if (cachedata == null)
{
- cachedata = await _context.QueryByKeyAsync(keyValue);
+ cachedata = await _dbBase.QueryByKeyAsync(keyValue);
if (cachedata != null)
{
await CacheHelper.Set(cacheKey + keyValue, cachedata);
diff --git a/WaterCloud.Data/Repository/RepositoryBase.cs b/WaterCloud.Data/Repository/UnitOfWork.cs
similarity index 88%
rename from WaterCloud.Data/Repository/RepositoryBase.cs
rename to WaterCloud.Data/Repository/UnitOfWork.cs
index f821b557f7b160fc45098e4f649aba2ca43ad68a..1e90441ea4ce3a6d1c3c01b0c6beaa7dfda660f6 100644
--- a/WaterCloud.Data/Repository/RepositoryBase.cs
+++ b/WaterCloud.Data/Repository/UnitOfWork.cs
@@ -1,264 +1,256 @@
-/*******************************************************************************
- * Copyright © 2020 WaterCloud.Framework 版权所有
- * Author: WaterCloud
- * Description: WaterCloud快速开发平台
- * Website:
-*********************************************************************************/
-using Chloe;
-using WaterCloud.Code;
-using System;
-using System.Collections.Generic;
-using System.Data;
-using System.Linq;
-using System.Linq.Expressions;
-using System.Reflection;
-using System.Threading.Tasks;
-
-namespace WaterCloud.DataBase
-{
- ///
- /// 仓储实现
- ///
- public class RepositoryBase : IRepositoryBase, IDisposable
- {
- private IDbContext _context;
- public RepositoryBase(IDbContext context)
- {
- _context = context;
- }
- public IDbContext GetDbContext()
- {
- return _context;
- }
- public RepositoryBase(string ConnectStr, string providerName)
- {
- _context = DBContexHelper.Contex(ConnectStr, providerName);
- }
- public IRepositoryBase BeginTrans()
- {
- if (_context.Session.CurrentTransaction == null)
- {
- _context.Session.BeginTransaction();
- }
- return this;
- }
- public void Commit()
- {
- try
- {
- if (_context.Session.CurrentTransaction != null)
- {
- _context.Session.CommitTransaction();
- }
- }
- catch (Exception)
- {
- this.Rollback();
- throw;
- }
- finally
- {
- this.Dispose();
- }
- }
- public void Dispose()
- {
- if (_context.Session.CurrentTransaction != null)
- {
- _context.Session.Dispose();
- }
- }
- public void Rollback()
- {
- if (_context.Session.CurrentTransaction != null)
- {
- _context.Session.RollbackTransaction();
- }
- this.Dispose();
- }
- public async Task Insert(TEntity entity) where TEntity : class
- {
- try
- {
- return await _context.InsertAsync(entity);
- }
- catch (Exception)
- {
- this.Rollback();
- throw;
- }
- }
- public async Task Insert(List entitys) where TEntity : class
- {
- try
- {
- await _context.InsertRangeAsync(entitys);
- return 1;
- }
- catch (Exception)
- {
- this.Rollback();
- throw;
- }
- }
- public async Task Update(TEntity entity) where TEntity : class
- {
- try
- {
- TEntity newentity = _context.QueryByKey(entity);
- _context.TrackEntity(newentity);
- PropertyInfo[] newprops = newentity.GetType().GetProperties();
- PropertyInfo[] props = entity.GetType().GetProperties();
- foreach (PropertyInfo prop in props)
- {
- if (prop.GetValue(entity, null) != null)
- {
- PropertyInfo item = newprops.Where(a => a.Name == prop.Name).FirstOrDefault();
- if (item != null)
- {
- item.SetValue(newentity, prop.GetValue(entity, null), null);
- if (prop.GetValue(entity, null).ToString() == " ")
- item.SetValue(newentity, null, null);
- }
- }
- }
- return await _context.UpdateAsync(newentity);
- }
- catch (Exception)
- {
- this.Rollback();
- throw;
- }
- }
- public async Task Update(Expression> predicate, Expression> content) where TEntity : class
- {
- try
- {
- return await _context.UpdateAsync(predicate, content);
- }
- catch (Exception)
- {
- this.Rollback();
- throw;
- }
-
- }
- public async Task Delete(TEntity entity) where TEntity : class
- {
- try
- {
- return await _context.DeleteAsync(entity);
- }
- catch (Exception)
- {
- this.Rollback();
- throw;
- }
-
- }
- public async Task Delete(Expression> predicate) where TEntity : class
- {
- try
- {
- return await _context.DeleteAsync(predicate);
- }
- catch (Exception)
- {
- this.Rollback();
- throw;
- }
- }
- public async Task FindEntity(object keyValue) where TEntity : class
- {
- return await _context.QueryByKeyAsync(keyValue);
- }
- public async Task FindEntity(Expression> predicate) where TEntity : class
- {
- return _context.Query().FirstOrDefault(predicate);
- }
- public IQuery IQueryable() where TEntity : class
- {
- return _context.Query();
- }
- public IQuery IQueryable(Expression> predicate) where TEntity : class
- {
- return _context.Query().Where(predicate);
- }
- public async Task> FindList(string strSql) where TEntity : class
- {
- return await _context.SqlQueryAsync(strSql);
- }
- public async Task> FindList(string strSql, DbParam[] dbParameter) where TEntity : class
- {
- return await _context.SqlQueryAsync(strSql, dbParameter);
- }
- public async Task> FindList(Pagination pagination) where TEntity : class, new()
- {
- var tempData = _context.Query();
- pagination.records = tempData.Count();
- tempData = tempData.OrderBy(pagination.sort);
- tempData = tempData.TakePage(pagination.page, pagination.rows);
- return tempData.ToList();
- }
- public async Task> FindList(Expression> predicate, Pagination pagination) where TEntity : class, new()
- {
- var tempData = _context.Query().Where(predicate);
- pagination.records = tempData.Count();
- tempData = tempData.OrderBy(pagination.sort);
- tempData = tempData.TakePage(pagination.page, pagination.rows);
- return tempData.ToList();
- }
- public async Task> OrderList(IQuery query, Pagination pagination)
- {
- var tempData = query;
- pagination.records = tempData.Count();
- tempData = tempData.OrderBy(pagination.sort);
- tempData = tempData.TakePage(pagination.page, pagination.rows);
- return tempData.ToList();
- }
- public async Task> OrderList(IQuery query, SoulPage