XFEExtension.NetCore.ServerInteractive
[DLL] Server interaction extension, including user identity verification and querying in conjunction with AutoConfig
关注
0
Fork
0
Star
0
返回提交历史
Added
XFEExtension.NetCore.ServerInteractive/Utilities/DataTable/XFEDataDictionaryTable.cs
+215
-0
Modified
XFEExtension.NetCore.ServerInteractive/Utilities/DataTable/XFEDataTableManagerBuilder.cs
+36
-0
XFEstudio/XFEExtension.NetCore.ServerInteractive
Add XFEDataDictionaryTable with ProfileDictionary support
Agent-Logs-Url: https://github.com/XFEstudio/XFEExtension.NetCore.ServerInteractive/sessions/77476766-6e3f-46fb-9e2f-9df6ef5d90af Co-authored-by: XFEstudio <132526994+XFEstudio@users.noreply.github.com>
f0ab11f
代码差异
2 个文件
+251
-0
@@ -0,0 +1,215 @@
1
using System.Net;
2
using System.Reflection;
3
using System.Text.Json;
4
using XFEExtension.NetCore.AutoConfig;
5
using XFEExtension.NetCore.Exceptions;
6
using XFEExtension.NetCore.ServerInteractive.Interfaces;
7
using XFEExtension.NetCore.ServerInteractive.Models;
8
using XFEExtension.NetCore.ServerInteractive.Models.ServerModels;
9
using XFEExtension.NetCore.ServerInteractive.Models.UserModels;
10
using XFEExtension.NetCore.ServerInteractive.Utilities.Helpers;
11
using XFEExtension.NetCore.StringExtension;
12
using XFEExtension.NetCore.XFETransform.JsonConverter;
13
14
namespace XFEExtension.NetCore.ServerInteractive.Utilities.DataTable;
15
16
/// <summary>
17
/// XFE数据字典表格
18
/// </summary>
19
/// <typeparam name="TValue">字典中值的类型</typeparam>
20
public class XFEDataDictionaryTable<TValue> : IXFEDataTable where TValue : IIdModel
21
{
22
/// <inheritdoc/>
23
public Func<IEnumerable<EncryptedUserLoginModel>> GetEncryptedUserLoginModelFunction { get; set; } = () => [];
24
/// <inheritdoc/>
25
public Func<IEnumerable<IUserInfo>> GetUsersFunction { get; set; } = () => [];
26
/// <summary>
27
/// 获取字典的方法
28
/// </summary>
29
public Func<ProfileDictionary<string, TValue>> GetTableFunction { get; set; } = () => [];
30
/// <summary>
31
/// 向字典中添加元素的方法
32
/// </summary>
33
public Action<string, TValue> AddToTableFunction { get; set; } = (_, _) => { };
34
/// <summary>
35
/// 从字典中移除元素的方法
36
/// </summary>
37
public Action<string> RemoveFromTableFunction { get; set; } = _ => { };
38
/// <summary>
39
/// 更改字典中元素的方法
40
/// </summary>
41
public Action<TValue> ChangeItemTableFunction { get; set; } = _ => { };
42
/// <inheritdoc/>
43
public string TableShowName { get; set; } = typeof(TValue).Name;
44
/// <inheritdoc/>
45
public string TableName { get; set; } = typeof(TValue).Name;
46
/// <inheritdoc/>
47
public string TableNameInRequest { get; set; }
48
/// <inheritdoc/>
49
public int GetPermissionLevel { get; set; }
50
/// <inheritdoc/>
51
public int RemovePermissionLevel { get; set; }
52
/// <inheritdoc/>
53
public int ChangePermissionLevel { get; set; }
54
/// <inheritdoc/>
55
public int AddPermissionLevel { get; set; }
56
/// <inheritdoc/>
57
public JsonSerializerOptions? JsonSerializerOptions { get; set; }
58
/// <inheritdoc/>
59
public JsonSerializerOptions? UserJsonSerializerOptions { get; set; }
60
61
/// <summary>
62
/// 创建字典表格并手动设置Get Set方法等
63
/// </summary>
64
public XFEDataDictionaryTable() => TableNameInRequest = $"{TableName[0]}".ToLower() + TableName[1..];
65
66
/// <summary>
67
/// 根据指定type自动设置Get Set方法
68
/// </summary>
69
/// <param name="type">继承于XFEProfile的配置文件类型</param>
70
/// <remarks>
71
/// 对于自动设置Get Set方法的Table,请确保配置文件使用XFEProfile创建ProfileDictionary,属性名称为XXXTable
72
/// </remarks>
73
public XFEDataDictionaryTable(Type type)
74
{
75
TableNameInRequest = $"{TableName[0]}".ToLower() + TableName[1..];
76
var property = type.GetProperty($"{typeof(TValue).Name}Table", BindingFlags.Public | BindingFlags.Static);
77
var profileDictionaryType = typeof(ProfileDictionary<string, TValue>);
78
var addMethod = profileDictionaryType.GetMethod("Add", [typeof(string), typeof(TValue)]);
79
var removeMethod = profileDictionaryType.GetMethod("Remove", [typeof(string)]);
80
var saveMethod = type.GetMethod("SaveProfile", BindingFlags.Public | BindingFlags.Static);
81
if (property is null || addMethod is null || removeMethod is null || saveMethod is null) return;
82
GetTableFunction = () => property.GetValue(null) as ProfileDictionary<string, TValue> ?? [];
83
AddToTableFunction = (key, value) => addMethod.Invoke(GetTableFunction(), [key, value]);
84
RemoveFromTableFunction = key => removeMethod.Invoke(GetTableFunction(), [key]);
85
ChangeItemTableFunction = item =>
86
{
87
var table = GetTableFunction();
88
if (!table.ContainsKey(item.Id)) return;
89
table[item.Id] = item;
90
saveMethod.Invoke(null, []);
91
};
92
}
93
94
/// <summary>
95
/// 获取字典中所有值
96
/// </summary>
97
/// <returns></returns>
98
public IEnumerable<TValue> GetValues() => GetTableFunction().Values;
99
100
/// <summary>
101
/// 添加一个元素
102
/// </summary>
103
/// <param name="key"></param>
104
/// <param name="value"></param>
105
public void Add(string key, TValue value) => AddToTableFunction(key, value);
106
107
/// <summary>
108
/// 移除一个元素
109
/// </summary>
110
/// <param name="key"></param>
111
public void Remove(string key) => RemoveFromTableFunction(key);
112
113
/// <summary>
114
/// 更改一个元素
115
/// </summary>
116
/// <param name="value"></param>
117
public void Change(TValue value) => ChangeItemTableFunction(value);
118
119
/// <inheritdoc/>
120
public async Task<HttpStatusCode> Execute(string execute, QueryableJsonNode requestJsonNode, ServerCoreReturnArgs r)
121
{
122
var statusCode = HttpStatusCode.OK;
123
try
124
{
125
switch (execute)
126
{
127
case "get":
128
Console.Write($"获取{TableShowName}列表请求");
129
UserHelper.ValidatePermission(requestJsonNode["session"], requestJsonNode["deviceInfo"], r.Args.ClientIP, GetPermissionLevel, GetEncryptedUserLoginModelFunction(), GetUsersFunction(), r);
130
List<TValue> valueList = [.. GetTableFunction().Values];
131
var pageCount = requestJsonNode["pageCount"]?.GetValue<int>() ?? -1;
132
if (pageCount == -1)
133
{
134
await r.Args.ReplyAndClose(JsonSerializer.Serialize(new
135
{
136
totalCount = valueList.Count,
137
lastPage = -1,
138
dataList = valueList
139
}, JsonSerializerOptions));
140
}
141
else
142
{
143
var page = requestJsonNode["page"]?.GetValue<int>() ?? -1;
144
await r.Args.ReplyAndClose(JsonSerializer.Serialize(new
145
{
146
totalCount = valueList.Count,
147
lastPage = (int)Math.Ceiling((double)valueList.Count / pageCount),
148
dataList = valueList[(page * pageCount)..((page + 1) * pageCount)]
149
}, JsonSerializerOptions));
150
}
151
break;
152
case "add":
153
Console.Write($"添加{TableShowName}请求");
154
var item = JsonSerializer.Deserialize<TValue>(Convert.FromBase64String(requestJsonNode["data"]?.ToString() ?? string.Empty), JsonSerializerOptions);
155
if (item is null)
156
{
157
statusCode = HttpStatusCode.BadRequest;
158
throw new StopAction(() => { }, $"\n无法使用Json转换目标{TableShowName}信息");
159
}
160
Console.Write($":{item.Id}");
161
UserHelper.ValidatePermission(requestJsonNode["session"], requestJsonNode["deviceInfo"], r.Args.ClientIP, AddPermissionLevel, GetEncryptedUserLoginModelFunction(), GetUsersFunction(), r);
162
if (item.Id.IsNullOrWhiteSpace())
163
item.Id = Guid.NewGuid().ToString();
164
var addTable = GetTableFunction();
165
while (addTable.ContainsKey(item.Id))
166
item.Id = Guid.NewGuid().ToString();
167
Add(item.Id, item);
168
r.Args.Close();
169
break;
170
case "remove":
171
Console.Write($"删除{TableShowName}请求");
172
var id = requestJsonNode["id"]?.ToString();
173
Console.Write($":{id}");
174
UserHelper.ValidatePermission(requestJsonNode["session"], requestJsonNode["deviceInfo"], r.Args.ClientIP, RemovePermissionLevel, GetEncryptedUserLoginModelFunction(), GetUsersFunction(), r);
175
if (id.IsNullOrWhiteSpace())
176
{
177
statusCode = HttpStatusCode.BadRequest;
178
throw new StopAction(() => { }, $"{TableShowName}ID不能为空");
179
}
180
Remove(id);
181
r.Args.Close();
182
break;
183
case "change":
184
Console.Write($"更改{TableShowName}请求");
185
item = JsonSerializer.Deserialize<TValue>(Convert.FromBase64String(requestJsonNode["data"]?.ToString() ?? string.Empty), JsonSerializerOptions);
186
if (item is null)
187
{
188
statusCode = HttpStatusCode.BadRequest;
189
throw new StopAction(() => { }, $"\n无法使用Json转换目标{TableShowName}信息");
190
}
191
Console.Write($":{item.Id}");
192
if (item.Id.IsNullOrWhiteSpace())
193
{
194
statusCode = HttpStatusCode.BadRequest;
195
throw new StopAction(() => { }, $"\n{TableShowName}ID不能为空");
196
}
197
UserHelper.ValidatePermission(requestJsonNode["session"], requestJsonNode["deviceInfo"], r.Args.ClientIP, ChangePermissionLevel, GetEncryptedUserLoginModelFunction(), GetUsersFunction(), r);
198
Change(item);
199
r.Args.Close();
200
break;
201
default:
202
Console.WriteLine($"[ERROR] 意料之外的方法:{execute}");
203
await r.Args.ReplyAndClose($"意料之外的方法:{execute}", HttpStatusCode.BadRequest);
204
break;
205
}
206
}
207
catch (Exception ex)
208
{
209
Console.WriteLine($"[WARN]【{r.Args.ClientIP}】{ex.Message}");
210
Console.WriteLine($"[TRACE]{ex.StackTrace}");
211
await r.Args.ReplyAndClose(ex.Message, statusCode);
212
}
213
return statusCode;
214
}
215
}
@@ -68,6 +68,42 @@ public abstract class XFEDataTableManagerBuilder
68
68
JsonSerializerOptions = jsonSerializerOptions
69
69
});
70
70
71
/// <summary>
72
/// 添加字典数据表
73
/// </summary>
74
/// <typeparam name="TValue">数据类型</typeparam>
75
/// <param name="xFEDataTable">字典数据表</param>
76
/// <returns></returns>
77
public XFEDataTableManagerBuilder AddTable<TValue>(XFEDataDictionaryTable<TValue> xFEDataTable) where TValue : IIdModel
78
{
79
_dataTableList.Add(xFEDataTable);
80
ExecuteList.AddRange([$"get_{xFEDataTable.TableNameInRequest}", $"add_{xFEDataTable.TableNameInRequest}", $"change_{xFEDataTable.TableNameInRequest}", $"remove_{xFEDataTable.TableNameInRequest}"]);
81
return this;
82
}
83
84
/// <summary>
85
/// 添加字典数据表
86
/// </summary>
87
/// <typeparam name="TValue">数据类型</typeparam>
88
/// <typeparam name="TP">配置文件类型</typeparam>
89
/// <param name="tableShowName">表格数据的显示名称(如:订单、用户等)</param>
90
/// <param name="addPermissionLevel">增加数据所需的最小权限</param>
91
/// <param name="removePermissionLevel">删除数据所需的最小权限</param>
92
/// <param name="changePermissionLevel">更改数据所需的最小权限</param>
93
/// <param name="getPermissionLevel">获取数据所需的最小权限</param>
94
/// <param name="jsonSerializerOptions">JSON转换器</param>
95
/// <returns></returns>
96
public XFEDataTableManagerBuilder AddDictionaryTable<TValue, TP>(string tableShowName, int addPermissionLevel, int removePermissionLevel, int changePermissionLevel, int getPermissionLevel, JsonSerializerOptions? jsonSerializerOptions = null) where TValue : IIdModel where TP : XFEProfile => AddTable(new XFEDataDictionaryTable<TValue>(typeof(TP))
97
{
98
TableShowName = tableShowName,
99
AddPermissionLevel = addPermissionLevel,
100
RemovePermissionLevel = removePermissionLevel,
101
ChangePermissionLevel = changePermissionLevel,
102
GetPermissionLevel = getPermissionLevel,
103
UserJsonSerializerOptions = _userJsonSerializerOptions,
104
JsonSerializerOptions = jsonSerializerOptions
105
});
106
71
107
/// <summary>
72
108
/// 构建数据表管理器
73
109
/// </summary>