TestController.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. using Azure.Cosmos;
  2. using DingTalk.Api;
  3. using DingTalk.Api.Request;
  4. using DingTalk.Api.Response;
  5. using HTEXLib.COMM.Helpers;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.AspNetCore.Http;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.Azure.Cosmos.Table;
  10. using Microsoft.Extensions.Configuration;
  11. using Microsoft.Extensions.Options;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.ComponentModel.DataAnnotations;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Text.Json;
  18. using System.Threading.Tasks;
  19. using TEAMModelBI.Filter;
  20. using TEAMModelBI.Models;
  21. using TEAMModelBI.Tool;
  22. using TEAMModelOS.Models;
  23. using TEAMModelOS.SDK;//引用创建学校Code
  24. using TEAMModelOS.SDK.Context.Attributes.Azure;
  25. using TEAMModelOS.SDK.DI;
  26. using TEAMModelOS.SDK.Extension;
  27. using TEAMModelOS.SDK.Helper.Common.DateTimeHelper;
  28. using TEAMModelOS.SDK.Models;
  29. using TEAMModelOS.SDK.Models.Cosmos.BI;
  30. using TEAMModelOS.SDK.Models.Cosmos.Common;
  31. using TEAMModelOS.SDK.Models.Service;
  32. using TEAMModelOS.SDK.Models.Table;
  33. //.Net 6新的特性
  34. using System.Threading;
  35. using System.Reflection;
  36. using System.Numerics;
  37. using System.Security.Cryptography;
  38. using System.Runtime.InteropServices;
  39. using System.Runtime.CompilerServices;
  40. using System.IdentityModel.Tokens.Jwt;
  41. using TEAMModelBI.Tool.Extension;
  42. namespace TEAMModelBI.Controllers.BITest
  43. {
  44. [Route("apitest")]
  45. [ApiController]
  46. public class TestController : ControllerBase
  47. {
  48. private readonly AzureCosmosFactory _azureCosmos;
  49. private readonly DingDing _dingDing;
  50. private readonly Option _option;
  51. private readonly AzureStorageFactory _azureStorage;
  52. private readonly IWebHostEnvironment _environment; //读取文件
  53. //读取配置文件
  54. private readonly IConfiguration _configuration;
  55. public readonly string mobel = "测试接口";
  56. public TestController(AzureCosmosFactory azureCosmos, DingDing dingDing, AzureStorageFactory azureStorage, IOptionsSnapshot<Option> option, IWebHostEnvironment hostingEnvironment, IConfiguration configuration)
  57. {
  58. _azureCosmos = azureCosmos;
  59. _dingDing = dingDing;
  60. _azureStorage = azureStorage;
  61. _option = option?.Value;
  62. _environment = hostingEnvironment;
  63. _configuration = configuration;
  64. }
  65. /// <summary>
  66. /// 删除册别,删除章节 创区
  67. /// </summary>
  68. /// <param name="jsonElement"></param>
  69. /// <returns></returns>
  70. [HttpPost("del-standard")]
  71. public async Task<IActionResult> DelStandard(JsonElement jsonElement)
  72. {
  73. if (!jsonElement.TryGetProperty("oldStandard", out JsonElement _oldStandard)) return BadRequest();
  74. var cosmosClient = _azureCosmos.GetCosmosClient();
  75. List<string> abilityIds = new List<string>(); //册别的ID集合
  76. //查询册别信息
  77. await foreach (var tempAbility in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<Ability>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Ability-{_oldStandard}") }))
  78. {
  79. abilityIds.Add(tempAbility.id); //查询出来册别ID添加册别ID集合
  80. }
  81. //删除册别
  82. if (abilityIds.IsNotEmpty())
  83. {
  84. var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityIds, $"Ability-{_oldStandard}");
  85. }
  86. List<string> abilityTaskIds = new List<string>(); //章节ID集合
  87. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").GetItemQueryIterator<AbilityTask>(queryText: $"select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"AbilityTask-{_oldStandard}") }))
  88. {
  89. abilityTaskIds.Add(item.id); //查询出来的章节信息ID添加到战绩集合
  90. }
  91. //删除章节
  92. if (abilityTaskIds.IsNotEmpty())
  93. {
  94. var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityTaskIds, $"AbilityTask-{_oldStandard}");
  95. }
  96. return Ok(new { state = 200 });
  97. }
  98. /// <summary>
  99. /// 测试生产Code
  100. /// </summary>
  101. /// <param name="jsonElement"></param>
  102. /// <returns></returns>
  103. [ProducesDefaultResponseType]
  104. [HttpPost("get-schoolcode")]
  105. public async Task<IActionResult> GetTest(JsonElement jsonElement)
  106. {
  107. //string data = await SchoolCode.GenerateSchoolCode(jsonElement, _dingDing, _environment).ToString();
  108. CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo();
  109. createSchoolInfo.province = "四川省";
  110. createSchoolInfo.id = "tmdplc";
  111. createSchoolInfo.name = "醍摩豆批量创校学校";
  112. createSchoolInfo.city = "成都市";
  113. createSchoolInfo.aname = "";
  114. createSchoolInfo.createCount = 0;
  115. //Random random = new Random();
  116. ////随机小写字母
  117. //int a = random.Next(0, 26);
  118. //char ch = (char)('a' + a);
  119. //string Number = GenerateRandom.Number(1);
  120. //string Number1 = GenerateRandom.Number(1, true);
  121. //string Str = GenerateRandom.Str(1);
  122. //string Str1 = GenerateRandom.Str(1, true);
  123. //string Str_char = GenerateRandom.Str_char(1);
  124. //string Str_char1 = GenerateRandom.Str_char(1, true);
  125. CreateSchoolInfo data = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  126. return Ok(new { state = 200, data, data.id });
  127. }
  128. /// <summary>
  129. /// 查询table数据
  130. /// </summary>
  131. /// <param name="jsonElement"></param>
  132. /// <returns></returns>
  133. [HttpPost("file-table")]
  134. public async Task<IActionResult> SaveTable(JsonElement jsonElement)
  135. {
  136. jsonElement.TryGetProperty("single", out JsonElement single);
  137. jsonElement.TryGetProperty("startDate", out JsonElement startDate);
  138. jsonElement.TryGetProperty("endDate", out JsonElement endDate);
  139. jsonElement.TryGetProperty("platform", out JsonElement platform);
  140. List<string> strlist = new List<string>();
  141. if (!string.IsNullOrEmpty($"{single}"))
  142. strlist.Add($"RowKey {QueryComparisons.Equal} {single}");
  143. if (!string.IsNullOrEmpty($"{startDate}"))
  144. strlist.Add($"RowKey {QueryComparisons.GreaterThanOrEqual} {startDate}");
  145. if (!string.IsNullOrEmpty($"{endDate}"))
  146. strlist.Add($"RowKey {QueryComparisons.LessThanOrEqual} {endDate}");
  147. if (!string.IsNullOrEmpty($"{platform}"))
  148. strlist.Add($"platform {QueryComparisons.Equal} {platform}");
  149. string sql = string.Join(" and ", strlist);
  150. var temp = _azureStorage.QueryWhereString<OptLog>(sql);
  151. return Ok(new { state = 200, temp });
  152. }
  153. /// <summary>
  154. /// 查询BI操作记录
  155. /// </summary>
  156. /// <param name="jsonElement"></param>
  157. /// <returns></returns>
  158. [HttpPost("get-operatelogbydate")]
  159. public async Task<IActionResult> GetOperateLogByDate(JsonElement jsonElement)
  160. {
  161. try
  162. {
  163. jsonElement.TryGetProperty("single", out JsonElement single);
  164. jsonElement.TryGetProperty("startDate", out JsonElement startDate);
  165. jsonElement.TryGetProperty("endDate", out JsonElement endDate);
  166. jsonElement.TryGetProperty("platform", out JsonElement platform);
  167. List<OptLog> operateLogs = null;
  168. StringBuilder tableSql = new StringBuilder();
  169. if (!string.IsNullOrEmpty($"{single}"))
  170. tableSql.Append($"RowKey {QueryComparisons.Equal} '{single}' ");
  171. if (!string.IsNullOrEmpty($"{startDate}"))
  172. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' " : $"RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' ");
  173. if (!string.IsNullOrEmpty($"{endDate}"))
  174. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.LessThanOrEqual} '{endDate}' " : $" RowKey { QueryComparisons.LessThanOrEqual} '{endDate}' ");
  175. if (!string.IsNullOrEmpty($"{platform}"))
  176. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} platform {QueryComparisons.Equal} '{platform}' " : $" platform {QueryComparisons.Equal} '{platform}' ");
  177. operateLogs = await _azureStorage.QueryWhereString<OptLog>(tableSql.ToString());
  178. return Ok(new { state = 200, operateLogs });
  179. }
  180. catch (Exception ex)
  181. {
  182. await _dingDing.SendBotMsg($"BI,{_option.Location} /operatelog/get-operatelogbydate {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  183. return BadRequest();
  184. }
  185. }
  186. /// <summary>
  187. /// 查询离职信息
  188. /// </summary>
  189. /// <returns></returns>
  190. [ProducesDefaultResponseType]
  191. [HttpPost("quitstaff")]
  192. public async Task<IActionResult> QuitStaff()
  193. {
  194. string appKey = _configuration["DingDingAuth:appKey"];
  195. string appSecret = _configuration["DingDingAuth:appSecret"];
  196. string agentld = _configuration["DingDingAuth:Agentld"];
  197. //获取access_token
  198. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  199. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  200. request.SetHttpMethod("Get");
  201. OapiGettokenResponse response = client.Execute(request);
  202. if (response.IsError)
  203. {
  204. return BadRequest();
  205. }
  206. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  207. string access_token = response.AccessToken;
  208. List<string> datalist = new List<string>();
  209. IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
  210. OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new OapiSmartworkHrmEmployeeQuerydimissionRequest() { Offset = 0L, Size = 50L };
  211. OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
  212. if (rspDimission.SubErrCode == "60011")
  213. {
  214. return Ok(new { state = 60011, message = "没有调用该接口的权限!" });
  215. }
  216. else if (rspDimission.Result != null)
  217. {
  218. datalist = rspDimission.Result.DataList;
  219. return Ok(new { state = 200, datalist = datalist });
  220. }
  221. else
  222. {
  223. return Ok(new { state = rspDimission.SubErrCode, message = rspDimission.Errmsg });
  224. }
  225. }
  226. /// <summary>
  227. /// 测试获取待入职人员的userId接口
  228. /// </summary>
  229. /// <returns></returns>
  230. [ProducesDefaultResponseType]
  231. [HttpPost("Induction")]
  232. public async Task<IActionResult> Induction()
  233. {
  234. string appKey = _configuration["DingDingAuth:appKey"];
  235. string appSecret = _configuration["DingDingAuth:appSecret"];
  236. string agentld = _configuration["DingDingAuth:Agentld"];
  237. //获取access_token
  238. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  239. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  240. request.SetHttpMethod("Get");
  241. OapiGettokenResponse response = client.Execute(request);
  242. if (response.IsError)
  243. {
  244. return BadRequest();
  245. }
  246. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  247. string access_token = response.AccessToken;
  248. IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
  249. OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new OapiSmartworkHrmEmployeeQuerypreentryRequest() { Offset = 0L, Size = 50 };
  250. reqInduction.SetHttpMethod("GET");
  251. OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
  252. if (rspInduction.Result.DataList != null)
  253. {
  254. foreach (var itemId in rspInduction.Result.DataList)
  255. {
  256. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  257. OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
  258. {
  259. Userid = itemId,
  260. Language = "zh_CN"
  261. };
  262. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
  263. }
  264. return Ok(new { state = 200, rspInduction.Result.DataList });
  265. }
  266. else
  267. {
  268. return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
  269. }
  270. }
  271. /// <summary>
  272. /// 分页
  273. /// </summary>
  274. /// <returns></returns>
  275. [HttpPost("get-testpage")]
  276. public async Task<IActionResult> GetTestPage()
  277. {
  278. List<string> st = new List<string> { { "1-23" }, { "2-022" }, { "3-ijjis" }, { "4-ssss" }, { "5-02rrr2" }, { "6-00srr22" }, { "7-002sr2" }, { "8-00s2srg2" }, { "9-0022ssgf" }, { "10-0ssa022" }, { "11-002saf2" }, { "12-0022" } };
  279. List<pageTest> pageTests = new List<pageTest>();
  280. List<pageTest1> pageTests1 = new List<pageTest1>();
  281. foreach (var item in st)
  282. {
  283. int i = 0;
  284. pageTest pageTest = new pageTest();
  285. pageTest.keyt = $"分页{i}";
  286. pageTest.listv = item;
  287. pageTests.Add(pageTest);
  288. i += 1;
  289. }
  290. for (int i = 0; i < st.Count; i++)
  291. {
  292. pageTest1 pageTest = new pageTest1();
  293. pageTest.keyt = $"分页{i}";
  294. pageTest.listv = st.Skip(i).Take(1).ToList();
  295. pageTests1.Add(pageTest);
  296. }
  297. return Ok(new { pageTests1 });
  298. }
  299. /// <summary>
  300. /// 赋值默认的顾问角色和BI默认的功能权限
  301. /// </summary>
  302. /// <returns></returns>
  303. [HttpPost("set-rolesorperm")]
  304. public async Task<IActionResult> SetRolesOrPermissions()
  305. {
  306. List<DingDingUserInfo> ddUserId = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", "continent" } });
  307. List<string> read = new List<string>() { "abilitystandard-read", "batcharea-read", "batchschool-read", "orgusers-read" };
  308. List<DingDingUserInfo> tempUserInfo = new List<DingDingUserInfo>();
  309. foreach (var user in ddUserId)
  310. {
  311. if (string.IsNullOrEmpty(user.roles))
  312. {
  313. user.roles = "assist";
  314. }
  315. if (string.IsNullOrEmpty(user.permissions))
  316. {
  317. user.permissions = string.Join(",", read);
  318. }
  319. List<string> tempRead = new List<string>(user.permissions.Split(","));
  320. foreach (var temp in read)
  321. {
  322. if (!tempRead.Contains(temp))
  323. {
  324. tempRead.Add(temp);
  325. }
  326. }
  327. user.permissions = string.Join(",", tempRead);
  328. tempUserInfo.Add(user);
  329. }
  330. var response = await _azureStorage.SaveOrUpdateAll<DingDingUserInfo>(tempUserInfo);
  331. return Ok(new { state = 200, response });
  332. }
  333. /// <summary>
  334. /// 保存日志文件
  335. /// </summary>
  336. /// <returns></returns>
  337. [AuthToken(Roles = "assist")]
  338. [HttpPost("save-tablelog")]
  339. public async Task<IActionResult> SaveTableLogTest()
  340. {
  341. //await OperateLogHelper.SaveTableLog(_azureStorage, "BI", "1636016499", "彭礼", "测试保存方法", "table-save", "save-tablelog");
  342. await _azureStorage.SaveLog(type:"table-save", msg:"测试保存方法01",dingDing: _dingDing,httpContext:HttpContext);
  343. return Ok(123);
  344. }
  345. /// <summary>
  346. /// 课例二维数组统计
  347. /// </summary>
  348. /// <param name="jsonElement"></param>
  349. /// <returns></returns>
  350. [HttpPost("get-test")]
  351. public async Task<IActionResult> test(JsonElement jsonElement)
  352. {
  353. var cosmosClient = _azureCosmos.GetCosmosClient();
  354. List<lessons> lessons = new List<lessons>();
  355. List<LessonCount> lessonCounts = new List<LessonCount>();
  356. List<List<double>> begin = new();
  357. await foreach (var item in cosmosClient.GetContainer(Constant.TEAMModelOS,"School").GetItemQueryIterator<LessonCount>(queryText:$"select value(c) from c where c.pk='LessonCount'",requestOptions:new QueryRequestOptions() { }))
  358. {
  359. lessons le = new lessons() {
  360. countB =item.beginCount.Count,
  361. countP = item.pCount.Count,
  362. countT = item.tCount.Count,
  363. countPT = item.ptCount.Count,
  364. lesson = item
  365. };
  366. lessons.Add(le);
  367. lessonCounts.Add(item);
  368. begin.Add(item.beginCount);
  369. }
  370. return Ok(new { state = 200 , lessonCounts });
  371. }
  372. /// <summary>
  373. /// 测试使用 CosmosDB中的COUNT 函数统计
  374. /// </summary>
  375. /// <param name="jsonElement"></param>
  376. /// <returns></returns>
  377. [HttpPost("get-count")]
  378. public async Task<IActionResult> GetCount(JsonElement jsonElement)
  379. {
  380. var cosmosClient = _azureCosmos.GetCosmosClient();
  381. List<KeyValuePair<int, int>> layerCount = new List<KeyValuePair<int, int>>();
  382. for (int i = 1; i <= 6; i++)
  383. {
  384. int total = 0;
  385. //string sqlText = $"select value(c.id) from c where c.pk='Item' and c.field={i}";
  386. string sqlText = $"select COUNT(c.id) AS totals from c where c.pk='Item' and c.field={i}";
  387. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
  388. {
  389. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  390. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt32() > 0)
  391. {
  392. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  393. {
  394. //total += obj.GetInt64();
  395. total += obj.GetProperty("totals").GetInt32();
  396. }
  397. //total += count.GetInt64();
  398. }
  399. }
  400. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
  401. {
  402. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  403. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt64() > 0)
  404. {
  405. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  406. {
  407. //total += obj.GetInt64();
  408. total += obj.GetProperty("totals").GetInt32();
  409. }
  410. }
  411. }
  412. layerCount.Add(new KeyValuePair<int, int>(i, total));
  413. }
  414. return Ok(new { state = 200, layerCount });
  415. }
  416. /// <summary>
  417. /// 测试算日期
  418. /// </summary>
  419. /// <returns></returns>
  420. [HttpPost("get-date")]
  421. public async Task<IActionResult> GetDate()
  422. {
  423. DateTimeOffset dateTime = DateTimeOffset.UtcNow.AddDays(0);
  424. int year = DateTimeOffset.UtcNow.Year;
  425. int month = DateTimeOffset.UtcNow.Month;
  426. List<string> strList = monthsOfYear("2021-1");
  427. var ere = DateTimeOffset.Parse("2024-02");
  428. var start = GetMonthStart(ere);
  429. var end = GetMonthEnd(ere);
  430. List<MonthStartEnd> endList = DateTimeHeloer.GetYearMonthlyStartEnd10(DateTimeOffset.UtcNow.Year);
  431. List<MonthStartEnd> endList1 = DateTimeHeloer.GetYearMonthlyStartEnd13(DateTimeOffset.UtcNow.Year);
  432. List<MonthStartEnd> endList2 = DateTimeHeloer.monthsOfYear(DateTimeOffset.UtcNow.ToString());
  433. return Ok(new { strList, dateTime, year, start, end, endList, endList1 , endList2 });
  434. }
  435. public static List<string> monthsOfYear(string yearMonth)
  436. {
  437. DateTime dateTime = DateTime.Parse(yearMonth);
  438. int year = dateTime.Year;
  439. int month = dateTime.Month;
  440. List<string> months = new List<string>();
  441. while (year > dateTime.Year - 1 || month > dateTime.Month)
  442. {
  443. months.Add($"{year}-{(month < 10 ? "0" : "") + month}");
  444. month -= 1;
  445. if (month <= 0)
  446. {
  447. year -= 1;
  448. month = 12;
  449. }
  450. }
  451. return months;
  452. }
  453. /// <summary>
  454. /// 统计一年中每月得新增校
  455. /// </summary>
  456. /// <returns></returns>
  457. [HttpPost("get-yearmonth")]
  458. public async Task<IActionResult> GetYearMonth()
  459. {
  460. var cosmosClient = _azureCosmos.GetCosmosClient();
  461. Dictionary<int, long> tempYear = new Dictionary<int, long>();
  462. List<TempSchool> tempSchools = new List<TempSchool>();
  463. for (int i = 1; i < 13; i++)
  464. {
  465. var start = 00022222330;
  466. long tempCount = 0;
  467. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: $"SELECT c._ts,c.name,c.id FROM c WHERE c._ts>={start}L", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  468. {
  469. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  470. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt64() > 0)
  471. {
  472. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  473. {
  474. TempSchool tempSchool = new TempSchool();
  475. tempSchool.id = obj.GetProperty("id").GetString();
  476. tempSchool.ts = obj.GetProperty("_ts").GetInt64();
  477. tempSchool.name = obj.GetProperty("name").GetString();
  478. tempSchools.Add(tempSchool);
  479. }
  480. tempCount += count.GetInt64();
  481. }
  482. }
  483. if (tempCount != 0)
  484. {
  485. tempYear.Add(i, tempCount);
  486. }
  487. }
  488. return Ok(new { state = 200, tempYear, tempSchools });
  489. }
  490. /// <summary>
  491. /// 测试.net 6 的一些特性
  492. /// </summary>
  493. /// <returns></returns>
  494. [HttpPost("get-newnet6")]
  495. public async Task<IActionResult> GetNewNet6()
  496. {
  497. ///PriorityQueue
  498. //.NET 6 新增的数据结构, PriorityQueue, 队列每个元素都有一个关联的优先级,它决定了出队顺序, 编号小的元素优先出列。
  499. PriorityQueue<string, int> priorityQueue = new();
  500. priorityQueue.Enqueue("Second", 2);
  501. priorityQueue.Enqueue("Fourth", 4);
  502. priorityQueue.Enqueue("Third 1", 3);
  503. priorityQueue.Enqueue("Third 2", 5);
  504. priorityQueue.Enqueue("First", 1);
  505. while (priorityQueue.Count > 0)
  506. {
  507. string item = priorityQueue.Dequeue();
  508. Console.WriteLine(item);
  509. }
  510. //PeriodicTimer
  511. //认识一个完全异步的“PeriodicTimer”, 更适合在异步场景中使用, 它有一个方法 WaitForNextTickAsync。
  512. //using PeriodicTimer timer = new(TimeSpan.FromSeconds(2));
  513. //while (await timer.WaitForNextTickAsync())
  514. //{
  515. // Console.WriteLine(DateTime.UtcNow);
  516. //}
  517. //检查元素是否可为空的反射API
  518. var example = new Example();
  519. var nullabilityInfoContext = new NullabilityInfoContext();
  520. foreach (var propertyInfo in example.GetType().GetProperties())
  521. {
  522. var nullabilityInfo = nullabilityInfoContext.Create(propertyInfo);
  523. Console.WriteLine($"{propertyInfo.Name} property is {nullabilityInfo.WriteState}");
  524. }
  525. //直接通过 Environment 获取进程ID和路径。
  526. int processId = Environment.ProcessId;
  527. string path = Environment.ProcessPath;
  528. Console.WriteLine(processId);
  529. Console.WriteLine(path);
  530. //CSPNG 密码安全伪随机数生成器
  531. byte[] bytes = RandomNumberGenerator.GetBytes(300);
  532. Console.WriteLine(string.Join("", bytes.ToArray()));
  533. //Power of 2
  534. //.NET 6 引入了用于处理 2 的幂的新方法。
  535. //‘IsPow2’ 判断指定值是否为 2 的幂。
  536. //‘RoundUpToPowerOf2’ 将指定值四舍五入到 2 的幂
  537. Console.WriteLine(BitOperations.IsPow2(121)); // True
  538. Console.WriteLine(BitOperations.RoundUpToPowerOf2(260)); // 256
  539. //WaitAsync on Task 您可以更轻松地等待异步任务执行, 如果超时会抛出 “TimeoutException”
  540. Task operationTask = DoSomethingLongAsync();
  541. await operationTask.WaitAsync(TimeSpan.FromSeconds(5));
  542. async Task DoSomethingLongAsync()
  543. {
  544. Console.WriteLine("DoSomethingLongAsync started.");
  545. await Task.Delay(TimeSpan.FromSeconds(10));
  546. Console.WriteLine("DoSomethingLongAsync ended.");
  547. }
  548. //新的数学API
  549. // New methods SinCos, ReciprocalEstimate and ReciprocalSqrtEstimate
  550. // Simultaneously computes Sin and Cos
  551. (double sin, double cos) = Math.SinCos(1.57);
  552. Console.WriteLine($"Sin = {sin}\nCos = {cos}");
  553. // Computes an approximate of 1 / x
  554. double recEst = Math.ReciprocalEstimate(5);
  555. Console.WriteLine($"Reciprocal estimate = {recEst}");
  556. // Computes an approximate of 1 / Sqrt(x)
  557. double recSqrtEst = Math.ReciprocalSqrtEstimate(5);
  558. Console.WriteLine($"Reciprocal sqrt estimate = {recSqrtEst}");
  559. // New overloads
  560. // Min, Max, Abs, Clamp and Sign supports nint and nuint
  561. (nint a, nint b) = (5, 10);
  562. nint min = Math.Min(a, b);
  563. nint max = Math.Max(a, b);
  564. nint abs = Math.Abs(a);
  565. nint clamp = Math.Clamp(abs, min, max);
  566. nint sign = Math.Sign(a);
  567. Console.WriteLine($"Min = {min}\nMax = {max}\nAbs = {abs}");
  568. Console.WriteLine($"Clamp = {clamp}\nSign = {sign}");
  569. // DivRem variants return a tuple
  570. (int quotient, int remainder) = Math.DivRem(2, 7);
  571. Console.WriteLine($"Quotient = {quotient}\nRemainder = {remainder}");
  572. //CollectionsMarshal.GetValueRefOrNullRef
  573. //这个是在字典中循环或者修改结可变结构体时用, 可以减少结构的副本复制, 也可以避免字典重复进行哈希计算,这个有点晦涩难懂
  574. Dictionary<int, MyStruct> dictionary = new()
  575. {
  576. { 1, new MyStruct { Count = 100 } }
  577. };
  578. int key = 1;
  579. MyStruct values = CollectionsMarshal.GetValueRefOrNullRef(dictionary, key);
  580. // Returns Unsafe.NullRef<TValue>() if it doesn't exist; check using Unsafe.IsNullRef(ref value)
  581. if (!Unsafe.IsNullRef(ref values))
  582. {
  583. Console.WriteLine(values.Count); // Output: 100
  584. // Mutate in-place
  585. values.Count++;
  586. Console.WriteLine(values.Count); // Output: 101
  587. }
  588. return Ok(new { state = 200 });
  589. }
  590. [HttpPost("get-diptid")]
  591. public async Task<IActionResult> GetDeptIdUser(JsonElement jsonElement)
  592. {
  593. if (!jsonElement.TryGetProperty("deptId", out JsonElement deptId)) return BadRequest();
  594. string divide = _configuration["CustomParam:SiteScope"];
  595. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", $"{divide}" } };
  596. List<DingDingUserInfo> tempUserInfo = await _azureStorage.FindListByDict<DingDingUserInfo>(dic);
  597. List<DingDingUserInfo> userInfo = new();
  598. tempUserInfo.ForEach(x => {
  599. if (x.depts.Contains($"{deptId}"))
  600. {
  601. if (x.depts.Contains($"{x.pid}"))
  602. {
  603. userInfo.Add(x);
  604. }
  605. userInfo.Add(x);
  606. }
  607. });
  608. return Ok(new { state = 200, count = userInfo.Count, userInfo });
  609. }
  610. [HttpPost("get-repeat")]
  611. public async Task<IActionResult> GetRepeat(JsonElement jsonElement)
  612. {
  613. jsonElement.TryGetProperty("datetime", out JsonElement _datetime);
  614. Dictionary<string, string> prodict = new Dictionary<string, string>() { { "YMPCVCIM", "学情分析模组" }, { "IPDYZYLC", "智慧学校管理服务" }, { "3CLYJ6NP", "AClass ONE智慧学伴" }, { "IPALJ6NY", "数据储存服务空间" },{ "VABAJ6NV", "卷卡合一阅卷系统" } };
  615. var ste = prodict["IPDYZYLC"];
  616. List<string> str_str = new List<string>() { "12", "20", "13", "13", "14", "16" };
  617. List<strend> strends = new List<strend> { new strend { id = 1, name = "12", age = 20 }, new strend { id = 1, name = "13", age = 20 }, new strend { id = 2, name = "22", age = 22 }, new strend { id = 3, name = "23", age = 23 } };
  618. //str_str.Distinct().ToList();
  619. strends.Where((x, i) => strends.FindIndex(z => z.id.Equals(x.id)) == i).ToList();
  620. List<strend> str_strend1 = strends.Where((x, i) => strends.FindIndex(z => z.id.Equals(x.id)) == i).ToList();
  621. List<strend> str_strend2 = strends.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
  622. DateTime dt = DateTime.Parse($"{_datetime}");
  623. int year = dt.Year;
  624. DateTime dt0 = new DateTime(year, 1, 1);
  625. int days = (dt.Date - dt0.Date).Days + 1;
  626. //int pydays = ((lastYear + 1) % 4 == 0 && (lastYear + 1) % 100 != 0 || (lastYear + 1) % 400 == 0) ? 366 : 365;
  627. int pydays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  628. //int pydays = DateTimeHelper.getDays(year);
  629. return Ok(new { state = 200, pydays, days, strends , str_strend1, str_strend2 , ste });
  630. }
  631. /// <summary>
  632. /// 计算天数
  633. /// </summary>
  634. /// <param name="jsonElement"></param>
  635. /// <returns></returns>
  636. [HttpPost("get-dateday")]
  637. public async Task<IActionResult> GetDateDay(JsonElement jsonElement)
  638. {
  639. jsonElement.TryGetProperty("year", out JsonElement _year);
  640. jsonElement.TryGetProperty("moth", out JsonElement _moth);
  641. int year = int.Parse($"{_year}");
  642. int day = 0;
  643. List<int> moths = _moth.ToObject<List<int>>();
  644. foreach (var item in moths)
  645. {
  646. int days = 0;
  647. switch (item)
  648. {
  649. case 1:
  650. case 3:
  651. case 5:
  652. case 7:
  653. case 8:
  654. case 10:
  655. case 12:
  656. days = 31;
  657. break;
  658. case 4:
  659. case 6:
  660. case 9:
  661. case 11:
  662. days = 30;
  663. break;
  664. case 2:
  665. int years = 0;
  666. if (item <= 8 && item >= 3)
  667. years = year;
  668. else
  669. years = year+1;
  670. if (years % 4 == 0 && year % 100 != 0 || year % 400 == 0)
  671. days = 29;
  672. else
  673. days = 28;
  674. break;
  675. }
  676. day += days;
  677. }
  678. return Ok(new { state = 200, day });
  679. }
  680. [ProducesDefaultResponseType]
  681. [HttpPost("get-xauth")]
  682. public async Task<IActionResult> GetXAuth(JsonElement jsonElement)
  683. {
  684. string authHeader = this.Request.Headers["Authorization"];//Header中的token
  685. string _auth = HttpContext.GetXAuth("AuthToken");
  686. //var (id, name, pic, did, dname, dpic) = HttpJwtAnalysis.GetAuthTokenInfo(HttpContext);
  687. var (tmdId, tmdName) = HttpJwtAnalysis.JwtXAuth(_auth, _option);
  688. //var (tmdId, tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(_auth, _option);
  689. // var (id, name) = httpXAuth(_auth, _option);
  690. //string id = null;
  691. //string name = null;
  692. //if (!string.IsNullOrWhiteSpace(_auth) && JwtAuthExtension.ValidateApiToken(_auth, _option.JwtSecretKey))
  693. //{
  694. // var jwt = new JwtSecurityTokenHandler().ReadJwtToken(_auth);
  695. // id = jwt.Payload.Sub;
  696. // name = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("name"))?.Value;
  697. //}
  698. return Ok(new { state = 200, tmdId, tmdName });
  699. }
  700. public (string id, string name) httpXAuth(string auth,Option option)
  701. {
  702. string id = null;
  703. string name = null;
  704. if (!string.IsNullOrWhiteSpace(auth) && JwtAuthExtension.ValidateApiToken(auth, option.JwtSecretKey))
  705. {
  706. var jwt = new JwtSecurityTokenHandler().ReadJwtToken(auth);
  707. id = jwt.Payload.Sub;
  708. name = jwt.Claims.FirstOrDefault(claim => claim.Type.Equals("name"))?.Value;
  709. }
  710. return (id, name);
  711. }
  712. public class strend
  713. {
  714. public int id { get; set; }
  715. public string name { get; set; }
  716. public int age { get; set; }
  717. }
  718. struct MyStruct
  719. {
  720. public int Count { get; set; }
  721. }
  722. class Example
  723. {
  724. public string? Name { get; set; }
  725. public string Value { get; set; }
  726. }
  727. public record TempSchool
  728. {
  729. public long ts { get; set; }
  730. public string id { get; set; }
  731. public string name { get; set; }
  732. }
  733. public static long GetMonthEnd(DateTimeOffset dt)
  734. {
  735. DateTime dtNew = new DateTime(dt.Year, dt.Month, 1);
  736. var ste = dtNew.AddMonths(1).AddDays(-1).Day;
  737. long iLastDay = DateTimeOffset.Parse($"{dt.Year}-{dt.Month}-{ste} 23:59:59").ToUnixTimeSeconds();
  738. return iLastDay;
  739. }
  740. public static long GetMonthStart(DateTimeOffset dt)
  741. {
  742. DateTime dtNew = new DateTime(dt.Year, dt.Month, 1);
  743. long iLastDay = DateTimeOffset.Parse($"{dtNew}").ToUnixTimeSeconds();
  744. return iLastDay;
  745. }
  746. public record lessons
  747. {
  748. public long countB { get; set; }
  749. public long countP { get; set; }
  750. public long countT { get; set; }
  751. public long countPT { get; set; }
  752. public LessonCount lesson { get; set; }
  753. }
  754. public record pageTest
  755. {
  756. public string keyt { get; set; }
  757. public string listv { get; set; }
  758. }
  759. public record pageTest1
  760. {
  761. public string keyt { get; set; }
  762. public List<string> listv { get; set; }
  763. }
  764. public class GenerateRandom
  765. {
  766. /// <summary>
  767. /// 生成随机数字
  768. /// </summary>
  769. /// <param name="length">生成长度</param>
  770. /// <returns></returns>
  771. public static string Number(int Length)
  772. {
  773. return Number(Length, false);
  774. }
  775. /// <summary>
  776. /// 生成随机数字
  777. /// </summary>
  778. /// <param name="Length">生成长度</param>
  779. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  780. /// <returns></returns>
  781. public static string Number(int Length, bool Sleep)
  782. {
  783. if (Sleep)
  784. System.Threading.Thread.Sleep(3);
  785. string result = "";
  786. System.Random random = new Random();
  787. for (int i = 0; i < Length; i++)
  788. {
  789. result += random.Next(10).ToString();
  790. }
  791. return result;
  792. }
  793. /// <summary>
  794. /// 生成随机字母与数字
  795. /// </summary>
  796. /// <param name="IntStr">生成长度</param>
  797. /// <returns></returns>
  798. public static string Str(int Length)
  799. {
  800. return Str(Length, false);
  801. }
  802. /// <summary>
  803. /// 生成随机字母与数字
  804. /// </summary>
  805. /// <param name="Length">生成长度</param>
  806. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  807. /// <returns></returns>
  808. public static string Str(int Length, bool Sleep)
  809. {
  810. if (Sleep)
  811. System.Threading.Thread.Sleep(3);
  812. char[] Pattern = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
  813. string result = "";
  814. int n = Pattern.Length;
  815. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  816. for (int i = 0; i < Length; i++)
  817. {
  818. int rnd = random.Next(0, n);
  819. result += Pattern[rnd];
  820. }
  821. return result;
  822. }
  823. /// <summary>
  824. /// 生成随机纯字母随机数
  825. /// </summary>
  826. /// <param name="IntStr">生成长度</param>
  827. /// <returns></returns>
  828. public static string Str_char(int Length)
  829. {
  830. return Str_char(Length, false);
  831. }
  832. /// <summary>
  833. /// 生成随机纯字母随机数
  834. /// </summary>
  835. /// <param name="Length">生成长度</param>
  836. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  837. /// <returns></returns>
  838. public static string Str_char(int Length, bool Sleep)
  839. {
  840. if (Sleep) System.Threading.Thread.Sleep(3);
  841. //char[] Pattern = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
  842. char[] Pattern = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
  843. string result = "";
  844. int n = Pattern.Length;
  845. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  846. for (int i = 0; i < Length; i++)
  847. {
  848. int rnd = random.Next(0, n);
  849. result += Pattern[rnd];
  850. }
  851. return result;
  852. }
  853. }
  854. }
  855. }