TestController.cs 40 KB

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