TestController.cs 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  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.Models;
  28. using TEAMModelOS.SDK.Models.Cosmos.BI;
  29. using TEAMModelOS.SDK.Models.Cosmos.Common;
  30. using TEAMModelOS.SDK.Models.Service;
  31. using TEAMModelOS.SDK.Models.Table;
  32. using static TEAMModelBI.DI.BIAzureStorage.BIAzureStorageBlobExtensions;
  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. using System.IO;
  43. using System.Net.Http;
  44. using System.Net.Http.Json;
  45. using System.Net;
  46. using TEAMModelBI.Tool.CosmosBank;
  47. using System.Diagnostics;
  48. using StackExchange.Redis;
  49. using TEAMModelBI.Tool.Context;
  50. using TEAMModelBI.DI.BIAzureStorage;
  51. namespace TEAMModelBI.Controllers.BITest
  52. {
  53. [Route("apitest")]
  54. [ApiController]
  55. public class TestController : ControllerBase
  56. {
  57. private readonly AzureCosmosFactory _azureCosmos;
  58. private readonly AzureStorageFactory _azureStorage;
  59. private readonly AzureRedisFactory _azureRedis;
  60. private readonly DingDing _dingDing;
  61. private readonly Option _option;
  62. private readonly IWebHostEnvironment _environment; //读取文件
  63. //读取配置文件
  64. private readonly IConfiguration _configuration;
  65. private readonly CoreAPIHttpService _coreAPIHttpService;
  66. private readonly HttpClient _httpClient;
  67. public TestController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option, IWebHostEnvironment hostingEnvironment, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService, HttpClient httpClient)
  68. {
  69. _azureCosmos = azureCosmos;
  70. _azureStorage = azureStorage;
  71. _azureRedis = azureRedis;
  72. _dingDing = dingDing;
  73. _option = option?.Value;
  74. _environment = hostingEnvironment;
  75. _configuration = configuration;
  76. _coreAPIHttpService = coreAPIHttpService;
  77. _httpClient = httpClient;
  78. }
  79. /// <summary>
  80. /// 删除册别,删除章节 创区
  81. /// </summary>
  82. /// <param name="jsonElement"></param>
  83. /// <returns></returns>
  84. [HttpPost("del-standard")]
  85. public async Task<IActionResult> DelStandard(JsonElement jsonElement)
  86. {
  87. if (!jsonElement.TryGetProperty("oldStandard", out JsonElement _oldStandard)) return BadRequest();
  88. var cosmosClient = _azureCosmos.GetCosmosClient();
  89. List<string> abilityIds = new List<string>(); //册别的ID集合
  90. //查询册别信息
  91. 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}") }))
  92. {
  93. abilityIds.Add(tempAbility.id); //查询出来册别ID添加册别ID集合
  94. }
  95. //删除册别
  96. if (abilityIds.IsNotEmpty())
  97. {
  98. var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityIds, $"Ability-{_oldStandard}");
  99. }
  100. List<string> abilityTaskIds = new List<string>(); //章节ID集合
  101. 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}") }))
  102. {
  103. abilityTaskIds.Add(item.id); //查询出来的章节信息ID添加到战绩集合
  104. }
  105. //删除章节
  106. if (abilityTaskIds.IsNotEmpty())
  107. {
  108. var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityTaskIds, $"AbilityTask-{_oldStandard}");
  109. }
  110. return Ok(new { state = 200 });
  111. }
  112. /// <summary>
  113. /// 测试生产Code
  114. /// </summary>
  115. /// <param name="jsonElement"></param>
  116. /// <returns></returns>
  117. [ProducesDefaultResponseType]
  118. [HttpPost("get-schoolcode")]
  119. public async Task<IActionResult> GetSchoolCode(JsonElement jsonElement)
  120. {
  121. //string data = await SchoolCode.GenerateSchoolCode(jsonElement, _dingDing, _environment).ToString();
  122. CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo();
  123. createSchoolInfo.province = "四川省";
  124. createSchoolInfo.id = "tmdplc";
  125. createSchoolInfo.name = "醍摩豆批量创校学校";
  126. createSchoolInfo.city = "成都市";
  127. createSchoolInfo.aname = "";
  128. createSchoolInfo.createCount = 0;
  129. //Random random = new Random();
  130. ////随机小写字母
  131. //int a = random.Next(0, 26);
  132. //char ch = (char)('a' + a);
  133. //string Number = GenerateRandom.Number(1);
  134. //string Number1 = GenerateRandom.Number(1, true);
  135. //string Str = GenerateRandom.Str(1);
  136. //string Str1 = GenerateRandom.Str(1, true);
  137. //string Str_char = GenerateRandom.Str_char(1);
  138. //string Str_char1 = GenerateRandom.Str_char(1, true);
  139. CreateSchoolInfo data = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  140. return Ok(new { state = 200, data, data.id });
  141. }
  142. /// <summary>
  143. /// 保存日志文件
  144. /// </summary>
  145. /// <param name="jsonElement"></param>
  146. /// <returns></returns>
  147. [ProducesDefaultResponseType]
  148. [AuthToken(Roles = "assist,admin")]
  149. [HttpPost("set-savebilog")]
  150. public async Task<IActionResult> SetTestSaveBIlog(JsonElement jsonElement)
  151. {
  152. jsonElement.TryGetProperty("site", out JsonElement site);
  153. jsonElement.TryGetProperty("msg", out JsonElement msg);
  154. var cosmosClient = _azureCosmos.GetCosmosClient();
  155. var tableClient = _azureStorage.GetCloudTableClient();
  156. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  157. var redisClinet = _azureRedis.GetRedisClient(8);
  158. if ($"{site}".Equals(BIConst.GlobalSite))
  159. {
  160. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.GlobalSite);
  161. tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
  162. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
  163. redisClinet = _azureRedis.GetRedisClient(dbnum: 8, name: BIConst.GlobalSite);
  164. }
  165. var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  166. await _azureStorage.SaveLog(type: "table-save", msg: "测试保存方法01", dingDing: _dingDing, httpContext: HttpContext); //IES5 日志记录
  167. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "Test-test", $"{msg}", _dingDing, httpContext: HttpContext);//BI 日志记录
  168. return Ok(new { state = 200 });
  169. }
  170. /// <summary>
  171. /// 查询table数据
  172. /// </summary>
  173. /// <param name="jsonElement"></param>
  174. /// <returns></returns>
  175. [HttpPost("file-table")]
  176. public async Task<IActionResult> SaveTable(JsonElement jsonElement)
  177. {
  178. jsonElement.TryGetProperty("single", out JsonElement single);
  179. jsonElement.TryGetProperty("startDate", out JsonElement startDate);
  180. jsonElement.TryGetProperty("endDate", out JsonElement endDate);
  181. jsonElement.TryGetProperty("platform", out JsonElement platform);
  182. List<string> strlist = new List<string>();
  183. if (!string.IsNullOrEmpty($"{single}"))
  184. strlist.Add($"RowKey {QueryComparisons.Equal} {single}");
  185. if (!string.IsNullOrEmpty($"{startDate}"))
  186. strlist.Add($"RowKey {QueryComparisons.GreaterThanOrEqual} {startDate}");
  187. if (!string.IsNullOrEmpty($"{endDate}"))
  188. strlist.Add($"RowKey {QueryComparisons.LessThanOrEqual} {endDate}");
  189. if (!string.IsNullOrEmpty($"{platform}"))
  190. strlist.Add($"platform {QueryComparisons.Equal} {platform}");
  191. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
  192. string sql = string.Join(" and ", strlist);
  193. var temp = table.QueryWhereString<BIOptLog>(sql);
  194. return Ok(new { state = 200, temp });
  195. }
  196. /// <summary>
  197. /// 查询BI操作记录
  198. /// </summary>
  199. /// <param name="jsonElement"></param>
  200. /// <returns></returns>
  201. [HttpPost("get-operatelogbydate")]
  202. public async Task<IActionResult> GetOperateLogByDate(JsonElement jsonElement)
  203. {
  204. try
  205. {
  206. jsonElement.TryGetProperty("single", out JsonElement single);
  207. jsonElement.TryGetProperty("startDate", out JsonElement startDate);
  208. jsonElement.TryGetProperty("endDate", out JsonElement endDate);
  209. jsonElement.TryGetProperty("platform", out JsonElement platform);
  210. List<BIOptLog> operateLogs = new();
  211. StringBuilder tableSql = new();
  212. if (!string.IsNullOrEmpty($"{single}"))
  213. tableSql.Append($"RowKey {QueryComparisons.Equal} '{single}' ");
  214. if (!string.IsNullOrEmpty($"{startDate}"))
  215. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' " : $"RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' ");
  216. if (!string.IsNullOrEmpty($"{endDate}"))
  217. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.LessThanOrEqual} '{endDate}' " : $" RowKey { QueryComparisons.LessThanOrEqual} '{endDate}' ");
  218. if (!string.IsNullOrEmpty($"{platform}"))
  219. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} platform {QueryComparisons.Equal} '{platform}' " : $" platform {QueryComparisons.Equal} '{platform}' ");
  220. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
  221. operateLogs = await table.QueryWhereString<BIOptLog>(tableSql.ToString());
  222. return Ok(new { state = 200, operateLogs });
  223. }
  224. catch (Exception ex)
  225. {
  226. await _dingDing.SendBotMsg($"BI,{_option.Location} /operatelog/get-operatelogbydate \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  227. return BadRequest();
  228. }
  229. }
  230. /// <summary>
  231. /// 查询离职信息
  232. /// </summary>
  233. /// <returns></returns>
  234. [ProducesDefaultResponseType]
  235. [HttpPost("quitstaff")]
  236. public async Task<IActionResult> QuitStaff()
  237. {
  238. string appKey = _configuration["DingDingAuth:appKey"];
  239. string appSecret = _configuration["DingDingAuth:appSecret"];
  240. string agentld = _configuration["DingDingAuth:Agentld"];
  241. //获取access_token
  242. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  243. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  244. request.SetHttpMethod("Get");
  245. OapiGettokenResponse response = client.Execute(request);
  246. if (response.IsError)
  247. {
  248. return BadRequest();
  249. }
  250. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  251. string access_token = response.AccessToken;
  252. IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
  253. OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new OapiSmartworkHrmEmployeeQuerydimissionRequest() { Offset = 0L, Size = 50L };
  254. OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
  255. if (rspDimission.SubErrCode == "60011")
  256. {
  257. return Ok(new { state = 60011, message = "没有调用该接口的权限!" });
  258. }
  259. else if (rspDimission.Result != null)
  260. {
  261. var datalist = rspDimission.Result.DataList;
  262. return Ok(new { state = 200, datalist });
  263. }
  264. else
  265. {
  266. return Ok(new { state = rspDimission.SubErrCode, message = rspDimission.Errmsg });
  267. }
  268. }
  269. /// <summary>
  270. /// 测试获取待入职人员的userId接口
  271. /// </summary>
  272. /// <returns></returns>
  273. [ProducesDefaultResponseType]
  274. [HttpPost("Induction")]
  275. public async Task<IActionResult> Induction()
  276. {
  277. string appKey = _configuration["DingDingAuth:appKey"];
  278. string appSecret = _configuration["DingDingAuth:appSecret"];
  279. string agentld = _configuration["DingDingAuth:Agentld"];
  280. //获取access_token
  281. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  282. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  283. request.SetHttpMethod("Get");
  284. OapiGettokenResponse response = client.Execute(request);
  285. if (response.IsError)
  286. {
  287. return BadRequest();
  288. }
  289. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  290. string access_token = response.AccessToken;
  291. IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
  292. OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new OapiSmartworkHrmEmployeeQuerypreentryRequest() { Offset = 0L, Size = 50 };
  293. reqInduction.SetHttpMethod("GET");
  294. OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
  295. if (rspInduction.Result.DataList != null)
  296. {
  297. foreach (var itemId in rspInduction.Result.DataList)
  298. {
  299. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  300. OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
  301. {
  302. Userid = itemId,
  303. Language = "zh_CN"
  304. };
  305. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
  306. }
  307. return Ok(new { state = 200, rspInduction.Result.DataList });
  308. }
  309. else
  310. {
  311. return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
  312. }
  313. }
  314. /// <summary>
  315. /// 获取在职ID
  316. /// </summary>
  317. /// <returns></returns>
  318. [HttpPost("get-onthejob")]
  319. public async Task<IActionResult> GetOnTheJob()
  320. {
  321. string appKey = _configuration["DingDingAuth:appKey"];
  322. string appSecret = _configuration["DingDingAuth:appSecret"];
  323. string agentld = _configuration["DingDingAuth:Agentld"];
  324. //获取access_token
  325. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  326. OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  327. request.SetHttpMethod("Get");
  328. OapiGettokenResponse response = client.Execute(request);
  329. if (response.IsError)
  330. {
  331. return BadRequest();
  332. }
  333. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  334. string access_token = response.AccessToken;
  335. //bool vars = false;
  336. //long offst = 1;
  337. //do
  338. //{
  339. // IDingTalkClient jobclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
  340. // OapiSmartworkHrmEmployeeQueryonjobRequest jobreq = new OapiSmartworkHrmEmployeeQueryonjobRequest { StatusList = "2,3,-1", Offset = offst, Size = 50 }; //2:试用期 3:正式 5:待离职 -1:无状态
  341. // OapiSmartworkHrmEmployeeQueryonjobResponse jobrsp = jobclient.Execute(jobreq, access_token);
  342. // if (jobrsp.Result.NextCursor > 0)
  343. // offst += 1;
  344. // else vars = true;
  345. //} while (vars);
  346. IDingTalkClient jobclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
  347. OapiSmartworkHrmEmployeeQueryonjobRequest jobreq = new OapiSmartworkHrmEmployeeQueryonjobRequest { StatusList = "2,3,-1", Offset = 1, Size = 50 }; //2:试用期 3:正式 5:待离职 -1:无状态
  348. OapiSmartworkHrmEmployeeQueryonjobResponse jobrsp = jobclient.Execute(jobreq, access_token);
  349. if (jobrsp.SubErrCode == "60011")
  350. {
  351. return Ok(new { state = 200, msg = jobrsp.SubErrMsg });
  352. }
  353. foreach (var item in jobrsp.Result.DataList)
  354. {
  355. }
  356. var ser = jobrsp.Result.DataList; // jobrsp.Body.GetEnumerator("result");
  357. return Ok(new { state = 200, jobrsp.Body, ser });
  358. }
  359. /// <summary>
  360. /// 测试 使用yield 优化
  361. /// 依据学校编号查询学校信息;若是没有传学校编号,则查询所有学校信息
  362. /// </summary>
  363. /// <param name="jsonElement"></param>
  364. /// <returns></returns>
  365. [ProducesDefaultResponseType]
  366. [HttpPost("get-schoolsinfo")]
  367. public async Task<IActionResult> GetSchoolsInfo(JsonElement jsonElement)
  368. {
  369. try
  370. {
  371. jsonElement.TryGetProperty("schoolCode", out JsonElement _schoolCode);
  372. var cosmosClient = _azureCosmos.GetCosmosClient();
  373. List<AssistSchool> schoolAssists = new();
  374. //StringBuilder stringBuilder = new StringBuilder("select value(c) from c");
  375. StringBuilder stringBuilder = new StringBuilder("select c.id,c.code,c.schoolCode,c.name,c.region,c.province,c.city,c.dist,c.size,c.address,c.picture,c.type,c.scale,c.areaId,c.standard from c");
  376. if (!string.IsNullOrEmpty($"{_schoolCode}"))
  377. {
  378. stringBuilder.Append($" where c.id='{_schoolCode}'");
  379. }
  380. //await foreach (var itemSchool in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  381. //{
  382. // SchoolAssist schoolAssist = new()
  383. // {
  384. // id = itemSchool.id,
  385. // code = itemSchool.code,
  386. // schoolCode = itemSchool.schoolCode,
  387. // name = itemSchool.name,
  388. // region = itemSchool.region,
  389. // province = itemSchool.province,
  390. // city = itemSchool.city,
  391. // dist = itemSchool.dist,
  392. // size = itemSchool.size,
  393. // address = itemSchool.address,
  394. // picture = itemSchool.picture,
  395. // type = itemSchool.type,
  396. // scale = itemSchool.scale,
  397. // areaId = itemSchool.areaId,
  398. // standard = itemSchool.standard
  399. // };
  400. // var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(itemSchool.id, new PartitionKey("ProductSum"));
  401. // if (response.Status == 200)
  402. // {
  403. // using var json = await JsonDocument.ParseAsync(response.ContentStream);
  404. // if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  405. // {
  406. // schoolAssist.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  407. // }
  408. // if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  409. // {
  410. // schoolAssist.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  411. // }
  412. // if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  413. // {
  414. // schoolAssist.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  415. // }
  416. // }
  417. // schoolAssist.assists = await CommonFind.FindSchoolRoles(cosmosClient, itemSchool.id, "assist");
  418. // schoolAssists.Add(schoolAssist);
  419. //}
  420. //return Ok(new { state = 200, schoolAssists });
  421. await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  422. {
  423. using var jsonSchool = await JsonDocument.ParseAsync(itemSchool.ContentStream);
  424. foreach (var objSchool in jsonSchool.RootElement.GetProperty("Documents").EnumerateArray())
  425. {
  426. var schoolId = objSchool.GetProperty("id").GetString();
  427. AssistSchool schoolAssist = new()
  428. {
  429. id = schoolId,
  430. code = objSchool.GetProperty("code").GetString(),
  431. schoolCode = objSchool.GetProperty("schoolCode").GetString(),
  432. name = objSchool.GetProperty("name").GetString(),
  433. region = objSchool.GetProperty("region").GetString(),
  434. province = objSchool.GetProperty("province").GetString(),
  435. city = objSchool.GetProperty("city").GetString(),
  436. dist = objSchool.GetProperty("dist").GetString(),
  437. size = objSchool.GetProperty("size").GetInt32(),
  438. address = objSchool.GetProperty("address").GetString(),
  439. picture = objSchool.GetProperty("picture").GetString(),
  440. type = objSchool.GetProperty("type").GetInt32(),
  441. //scale = objSchool.GetProperty("scale").GetInt32(),
  442. areaId = objSchool.GetProperty("areaId").GetString(),
  443. standard = objSchool.GetProperty("standard").GetString(),
  444. };
  445. try { schoolAssist.scale = objSchool.GetProperty("scale").GetInt32(); }
  446. catch { schoolAssist.scale = 0; }
  447. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(schoolId, new PartitionKey("ProductSum"));
  448. if (response.Status == 200)
  449. {
  450. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  451. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  452. {
  453. schoolAssist.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  454. }
  455. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  456. {
  457. schoolAssist.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  458. }
  459. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  460. {
  461. schoolAssist.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  462. }
  463. }
  464. //schoolAssist.assists = await CommonFind.FindSchoolRoles(cosmosClient, schoolId, "assist");
  465. schoolAssists.Add(schoolAssist);
  466. }
  467. }
  468. List<AssistSchool> tempSchoolAssists = new();
  469. await foreach (var temp in GetSchools(cosmosClient, schoolAssists))
  470. {
  471. tempSchoolAssists.AddRange(temp);
  472. }
  473. return Ok(new { state = 200, schoolAssists = tempSchoolAssists });
  474. }
  475. catch (Exception ex)
  476. {
  477. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-schoolsinfo \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  478. return BadRequest();
  479. }
  480. }
  481. /// <summary>
  482. /// 使用yield 优化
  483. /// </summary>
  484. /// <param name="cosmosClient"></param>
  485. /// <param name="schoolAssists"></param>
  486. /// <returns></returns>
  487. private async IAsyncEnumerable<List<AssistSchool>> GetSchools(CosmosClient cosmosClient, List<AssistSchool> schoolAssists)
  488. {
  489. List<AssistSchool> tempSchoolAssists = new();
  490. foreach (var temp in schoolAssists)
  491. {
  492. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(temp.id, new PartitionKey("ProductSum"));
  493. if (response.Status == 200)
  494. {
  495. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  496. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  497. {
  498. temp.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  499. }
  500. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  501. {
  502. temp.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  503. }
  504. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  505. {
  506. temp.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  507. }
  508. }
  509. temp.assists = await CommonFind.FindSchoolRoles(cosmosClient, temp.id, "assist");
  510. tempSchoolAssists.Add(temp);
  511. }
  512. yield return tempSchoolAssists;
  513. }
  514. /// <summary>
  515. /// 赋值默认的顾问角色和BI默认的功能权限
  516. /// </summary>
  517. /// <returns></returns>
  518. [HttpPost("set-rolesorperm")]
  519. public async Task<IActionResult> SetRolesOrPermissions()
  520. {
  521. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  522. List<DingDingUserInfo> ddUserId = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", "continent" } });
  523. List<string> read = new() { "abilitystandard-read", "batcharea-read", "batchschool-read", "orgusers-read" };
  524. List<DingDingUserInfo> tempUserInfo = new();
  525. foreach (var user in ddUserId)
  526. {
  527. if (string.IsNullOrEmpty(user.roles))
  528. {
  529. user.roles = "assist";
  530. }
  531. if (string.IsNullOrEmpty(user.permissions))
  532. {
  533. user.permissions = string.Join(",", read);
  534. }
  535. List<string> tempRead = new(user.permissions.Split(","));
  536. foreach (var temp in read)
  537. {
  538. if (!tempRead.Contains(temp))
  539. {
  540. tempRead.Add(temp);
  541. }
  542. }
  543. user.permissions = string.Join(",", tempRead);
  544. tempUserInfo.Add(user);
  545. }
  546. var response = await table.SaveOrUpdateAll<DingDingUserInfo>(tempUserInfo);
  547. return Ok(new { state = 200, response });
  548. }
  549. /// <summary>
  550. /// 测试使用 CosmosDB中的COUNT 函数统计
  551. /// </summary>
  552. /// <param name="jsonElement"></param>
  553. /// <returns></returns>
  554. [HttpPost("get-count")]
  555. public async Task<IActionResult> GetCount(JsonElement jsonElement)
  556. {
  557. var cosmosClient = _azureCosmos.GetCosmosClient();
  558. List<KeyValuePair<int, int>> layerCount = new List<KeyValuePair<int, int>>();
  559. for (int i = 1; i <= 6; i++)
  560. {
  561. int total = 0;
  562. //string sqlText = $"select value(c.id) from c where c.pk='Item' and c.field={i}";
  563. string sqlText = $"select COUNT(c.id) AS totals from c where c.pk='Item' and c.field={i}";
  564. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
  565. {
  566. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  567. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt32() > 0)
  568. {
  569. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  570. {
  571. //total += obj.GetInt64();
  572. total += obj.GetProperty("totals").GetInt32();
  573. }
  574. //total += count.GetInt64();
  575. }
  576. }
  577. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
  578. {
  579. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  580. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt64() > 0)
  581. {
  582. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  583. {
  584. //total += obj.GetInt64();
  585. total += obj.GetProperty("totals").GetInt32();
  586. }
  587. }
  588. }
  589. layerCount.Add(new KeyValuePair<int, int>(i, total));
  590. }
  591. return Ok(new { state = 200, layerCount });
  592. }
  593. /// <summary>
  594. /// 测试算日期
  595. /// </summary>
  596. /// <returns></returns>
  597. [HttpPost("get-date")]
  598. public async Task<IActionResult> GetDate()
  599. {
  600. DateTimeOffset dateTime = DateTimeOffset.UtcNow.AddDays(0);
  601. int year = DateTimeOffset.UtcNow.Year;
  602. int month = DateTimeOffset.UtcNow.Month;
  603. var datetime7 = DateTimeOffset.UtcNow.AddDays(-7); //前七天的时间
  604. List<string> strList = monthsOfYear("2021-1");
  605. var ere = DateTimeOffset.Parse("2022-04-25");
  606. DateTimeOffset ste = new();
  607. if (ere.Month > 9)
  608. {
  609. ste = new DateTime(ere.Year, ere.Month - 4, 1);
  610. }
  611. else
  612. {
  613. ste = new DateTime(ere.Year - 1, ere.Month, 1);
  614. }
  615. var (start1, end1) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow);
  616. var (start2, end2) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "week");
  617. var (start3, end3) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastweek");
  618. var (start4, end4) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "term");
  619. var (start5, end5) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastterm");
  620. var (start6, end6) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "month");
  621. var (start7, end7) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "year");
  622. var start = GetMonthStart(ere);
  623. var end = GetMonthEnd(ere);
  624. List<MonthStartEnd> endList = TimeHelper.GetYearMonthlyStartEnd10(DateTimeOffset.UtcNow.Year);
  625. List<MonthStartEnd> endList1 = TimeHelper.GetYearMonthlyStartEnd13(DateTimeOffset.UtcNow.Year);
  626. //return Ok(new { strList, dateTime, year, start, end, endList, endList1, endList2 });
  627. return Ok(new { datetime7, start1, end1, start2, end2, start3, end3, start4, end4 , start5, end5 , start6, end6 , start7, end7 });
  628. }
  629. public static List<string> monthsOfYear(string yearMonth)
  630. {
  631. DateTime dateTime = DateTime.Parse(yearMonth);
  632. int year = dateTime.Year;
  633. int month = dateTime.Month;
  634. List<string> months = new List<string>();
  635. while (year > dateTime.Year - 1 || month > dateTime.Month)
  636. {
  637. months.Add($"{year}-{(month < 10 ? "0" : "") + month}");
  638. month -= 1;
  639. if (month <= 0)
  640. {
  641. year -= 1;
  642. month = 12;
  643. }
  644. }
  645. return months;
  646. }
  647. /// <summary>
  648. /// 统计一年中每月得新增校
  649. /// </summary>
  650. /// <returns></returns>
  651. [HttpPost("get-yearmonth")]
  652. public async Task<IActionResult> GetYearMonth()
  653. {
  654. var cosmosClient = _azureCosmos.GetCosmosClient();
  655. Dictionary<int, long> tempYear = new Dictionary<int, long>();
  656. List<TempSchool> tempSchools = new List<TempSchool>();
  657. for (int i = 1; i < 13; i++)
  658. {
  659. var start = 00022222330;
  660. long tempCount = 0;
  661. 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") }))
  662. {
  663. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  664. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt64() > 0)
  665. {
  666. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  667. {
  668. TempSchool tempSchool = new TempSchool();
  669. tempSchool.id = obj.GetProperty("id").GetString();
  670. tempSchool.ts = obj.GetProperty("_ts").GetInt64();
  671. tempSchool.name = obj.GetProperty("name").GetString();
  672. tempSchools.Add(tempSchool);
  673. }
  674. tempCount += count.GetInt64();
  675. }
  676. }
  677. if (tempCount != 0)
  678. {
  679. tempYear.Add(i, tempCount);
  680. }
  681. }
  682. return Ok(new { state = 200, tempYear, tempSchools });
  683. }
  684. /// <summary>
  685. /// 测试.net 6 的一些特性
  686. /// </summary>
  687. /// <returns></returns>
  688. [HttpPost("get-newnet6")]
  689. public async Task<IActionResult> GetNewNet6()
  690. {
  691. ///PriorityQueue
  692. //.NET 6 新增的数据结构, PriorityQueue, 队列每个元素都有一个关联的优先级,它决定了出队顺序, 编号小的元素优先出列。
  693. PriorityQueue<string, int> priorityQueue = new();
  694. priorityQueue.Enqueue("Second", 2);
  695. priorityQueue.Enqueue("Fourth", 4);
  696. priorityQueue.Enqueue("Third 1", 3);
  697. priorityQueue.Enqueue("Third 2", 5);
  698. priorityQueue.Enqueue("First", 1);
  699. while (priorityQueue.Count > 0)
  700. {
  701. string item = priorityQueue.Dequeue();
  702. Console.WriteLine(item);
  703. }
  704. //PeriodicTimer
  705. //认识一个完全异步的“PeriodicTimer”, 更适合在异步场景中使用, 它有一个方法 WaitForNextTickAsync。
  706. //using PeriodicTimer timer = new(TimeSpan.FromSeconds(2));
  707. //while (await timer.WaitForNextTickAsync())
  708. //{
  709. // Console.WriteLine(DateTime.UtcNow);
  710. //}
  711. //检查元素是否可为空的反射API
  712. var example = new Example();
  713. var nullabilityInfoContext = new NullabilityInfoContext();
  714. foreach (var propertyInfo in example.GetType().GetProperties())
  715. {
  716. var nullabilityInfo = nullabilityInfoContext.Create(propertyInfo);
  717. Console.WriteLine($"{propertyInfo.Name} property is {nullabilityInfo.WriteState}");
  718. }
  719. //直接通过 Environment 获取进程ID和路径。
  720. int processId = Environment.ProcessId;
  721. string path = Environment.ProcessPath;
  722. Console.WriteLine(processId);
  723. Console.WriteLine(path);
  724. //CSPNG 密码安全伪随机数生成器
  725. byte[] bytes = RandomNumberGenerator.GetBytes(300);
  726. Console.WriteLine(string.Join("", bytes.ToArray()));
  727. //Power of 2
  728. //.NET 6 引入了用于处理 2 的幂的新方法。
  729. //‘IsPow2’ 判断指定值是否为 2 的幂。
  730. //‘RoundUpToPowerOf2’ 将指定值四舍五入到 2 的幂
  731. Console.WriteLine(BitOperations.IsPow2(121)); // True
  732. Console.WriteLine(BitOperations.RoundUpToPowerOf2(260)); // 256
  733. //WaitAsync on Task 您可以更轻松地等待异步任务执行, 如果超时会抛出 “TimeoutException”
  734. Task operationTask = DoSomethingLongAsync();
  735. await operationTask.WaitAsync(TimeSpan.FromSeconds(5));
  736. async Task DoSomethingLongAsync()
  737. {
  738. Console.WriteLine("DoSomethingLongAsync started.");
  739. await Task.Delay(TimeSpan.FromSeconds(10));
  740. Console.WriteLine("DoSomethingLongAsync ended.");
  741. }
  742. //新的数学API
  743. // New methods SinCos, ReciprocalEstimate and ReciprocalSqrtEstimate
  744. // Simultaneously computes Sin and Cos
  745. (double sin, double cos) = Math.SinCos(1.57);
  746. Console.WriteLine($"Sin = {sin}\nCos = {cos}");
  747. // Computes an approximate of 1 / x
  748. double recEst = Math.ReciprocalEstimate(5);
  749. Console.WriteLine($"Reciprocal estimate = {recEst}");
  750. // Computes an approximate of 1 / Sqrt(x)
  751. double recSqrtEst = Math.ReciprocalSqrtEstimate(5);
  752. Console.WriteLine($"Reciprocal sqrt estimate = {recSqrtEst}");
  753. // New overloads
  754. // Min, Max, Abs, Clamp and Sign supports nint and nuint
  755. (nint a, nint b) = (5, 10);
  756. nint min = Math.Min(a, b);
  757. nint max = Math.Max(a, b);
  758. nint abs = Math.Abs(a);
  759. nint clamp = Math.Clamp(abs, min, max);
  760. nint sign = Math.Sign(a);
  761. Console.WriteLine($"Min = {min}\nMax = {max}\nAbs = {abs}");
  762. Console.WriteLine($"Clamp = {clamp}\nSign = {sign}");
  763. // DivRem variants return a tuple
  764. (int quotient, int remainder) = Math.DivRem(2, 7);
  765. Console.WriteLine($"Quotient = {quotient}\nRemainder = {remainder}");
  766. //CollectionsMarshal.GetValueRefOrNullRef
  767. //这个是在字典中循环或者修改结可变结构体时用, 可以减少结构的副本复制, 也可以避免字典重复进行哈希计算,这个有点晦涩难懂
  768. Dictionary<int, MyStruct> dictionary = new()
  769. {
  770. { 1, new MyStruct { Count = 100 } }
  771. };
  772. int key = 1;
  773. MyStruct values = CollectionsMarshal.GetValueRefOrNullRef(dictionary, key);
  774. // Returns Unsafe.NullRef<TValue>() if it doesn't exist; check using Unsafe.IsNullRef(ref value)
  775. if (!Unsafe.IsNullRef(ref values))
  776. {
  777. Console.WriteLine(values.Count); // Output: 100
  778. // Mutate in-place
  779. values.Count++;
  780. Console.WriteLine(values.Count); // Output: 101
  781. }
  782. return Ok(new { state = 200 });
  783. }
  784. /// <summary>
  785. /// 去重、判断
  786. /// </summary>
  787. /// <param name="jsonElement"></param>
  788. /// <returns></returns>
  789. [HttpPost("get-repeat")]
  790. public async Task<IActionResult> GetRepeat(JsonElement jsonElement)
  791. {
  792. jsonElement.TryGetProperty("datetime", out JsonElement _datetime);
  793. Dictionary<string, string> prodict = new Dictionary<string, string>() { { "YMPCVCIM", "学情分析模组" }, { "IPDYZYLC", "智慧学校管理服务" }, { "3CLYJ6NP", "AClass ONE智慧学伴" }, { "IPALJ6NY", "数据储存服务空间" },{ "VABAJ6NV", "卷卡合一阅卷系统" } };
  794. var ste = prodict["IPDYZYLC"];
  795. List<string> str_str = new List<string>() { "12", "20", "13", "13", "14", "16" };
  796. 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 } };
  797. //str_str.Distinct().ToList();
  798. strends.Where((x, i) => strends.FindIndex(z => z.id.Equals(x.id)) == i).ToList();
  799. List<strend> str_strend1 = strends.Where((x, i) => strends.FindIndex(z => z.id.Equals(x.id)) == i).ToList();
  800. List<strend> str_strend2 = strends.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
  801. DateTime dt = DateTime.Parse($"{_datetime}");
  802. int year = dt.Year;
  803. DateTime dt0 = new DateTime(year, 1, 1);
  804. int days = (dt.Date - dt0.Date).Days + 1;
  805. //int pydays = ((lastYear + 1) % 4 == 0 && (lastYear + 1) % 100 != 0 || (lastYear + 1) % 400 == 0) ? 366 : 365;
  806. int pydays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  807. //int pydays = DateTimeHelper.getDays(year);
  808. return Ok(new { state = 200, pydays, days, strends , str_strend1, str_strend2 , ste });
  809. }
  810. /// <summary>
  811. /// 计算天数
  812. /// </summary>
  813. /// <param name="jsonElement"></param>
  814. /// <returns></returns>
  815. [HttpPost("get-dateday")]
  816. public async Task<IActionResult> GetDateDay(JsonElement jsonElement)
  817. {
  818. jsonElement.TryGetProperty("year", out JsonElement _year);
  819. jsonElement.TryGetProperty("moth", out JsonElement _moth);
  820. int year = int.Parse($"{_year}");
  821. int day = 0;
  822. List<int> moths = _moth.ToObject<List<int>>();
  823. foreach (var item in moths)
  824. {
  825. int days = 0;
  826. switch (item)
  827. {
  828. case 1:
  829. case 3:
  830. case 5:
  831. case 7:
  832. case 8:
  833. case 10:
  834. case 12:
  835. days = 31;
  836. break;
  837. case 4:
  838. case 6:
  839. case 9:
  840. case 11:
  841. days = 30;
  842. break;
  843. case 2:
  844. int years = 0;
  845. if (item <= 8 && item >= 3)
  846. years = year;
  847. else
  848. years = year+1;
  849. if (years % 4 == 0 && year % 100 != 0 || year % 400 == 0)
  850. days = 29;
  851. else
  852. days = 28;
  853. break;
  854. }
  855. day += days;
  856. }
  857. return Ok(new { state = 200, day });
  858. }
  859. /// <summary>
  860. /// 测试CosmosDB分页查询 SQL语句分页
  861. /// </summary>
  862. /// <param name="jsonElement"></param>
  863. /// <returns></returns>
  864. [HttpPost("get-page")]
  865. public async Task<IActionResult> cosmosDBPage(JsonElement jsonElement)
  866. {
  867. if (!jsonElement.TryGetProperty("pageSize", out JsonElement pageSize)) return BadRequest();
  868. if (!jsonElement.TryGetProperty("endPosition", out JsonElement endPosition)) return BadRequest();
  869. var cosmosClient = _azureCosmos.GetCosmosClient();
  870. List<School> schools = new List<School>();
  871. //string sqlTxt = $"SELECT * FROM c where c.code='Base' order by c.id offset {endPosition} limit {pageSize}";
  872. string sqlTxt = $"SELECT * FROM c order by c.id offset {pageSize} limit {endPosition}";
  873. await foreach (var tempPage in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlTxt, requestOptions:new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  874. {
  875. using var json = await JsonDocument.ParseAsync(tempPage.ContentStream);
  876. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt16() > 0)
  877. {
  878. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  879. {
  880. schools.Add(obj.ToObject<School>());
  881. }
  882. }
  883. }
  884. IAsyncResult iAsyncResult = null;
  885. return Ok(new { state = 200, schools });
  886. }
  887. /// <summary>
  888. /// 分页案例
  889. /// </summary>
  890. /// <param name="jsonElement"></param>
  891. /// <returns></returns>
  892. [HttpPost("get-cosmodbtokenpage")]
  893. public async Task<IActionResult> GetCancellationTokenPage(JsonElement jsonElement)
  894. {
  895. var cosmosClient = _azureCosmos.GetCosmosClient();
  896. //默认不指定返回大小
  897. int? pageSize = null;
  898. string continuationToken = string.Empty;
  899. string pageToken = default;
  900. if (jsonElement.TryGetProperty("pageSize", out JsonElement jsonPageSize))
  901. {
  902. if (!jsonPageSize.ValueKind.Equals(JsonValueKind.Undefined) && !jsonPageSize.ValueKind.Equals(JsonValueKind.Null) && jsonPageSize.TryGetInt32(out int tempPageSize))
  903. {
  904. pageSize = tempPageSize;
  905. }
  906. }
  907. //是否需要进行分页查询,默认不分页
  908. bool iscontinuation = false;
  909. if (pageSize != null && pageSize.Value > 0)
  910. {
  911. iscontinuation = true;
  912. }
  913. if (jsonElement.TryGetProperty("contToken", out JsonElement ContToken))
  914. {
  915. pageToken = ContToken.GetString();
  916. }
  917. List<School> schools = new();
  918. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: "select value(c) from c", continuationToken: pageToken, requestOptions: new QueryRequestOptions() { MaxItemCount = pageSize, PartitionKey = new PartitionKey("Base") }))
  919. {
  920. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  921. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  922. {
  923. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  924. {
  925. schools.Add(obj.ToObject<School>());
  926. }
  927. if (iscontinuation)
  928. {
  929. continuationToken = item.GetContinuationToken();
  930. break;
  931. }
  932. }
  933. }
  934. return Ok(new { state = 200, continuationToken, count = schools.Count, schools });
  935. }
  936. /// <summary>
  937. /// 测试隐式登录
  938. /// </summary>
  939. /// <returns></returns>
  940. [HttpPost("get-implicit")]
  941. public async Task<IActionResult> GetImplicit()
  942. {
  943. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  944. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  945. var location = _option.Location;
  946. if (location.Contains("China"))
  947. {
  948. location = "China";
  949. }
  950. else if (location.Contains("Global"))
  951. {
  952. location = "Global";
  953. }
  954. var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
  955. if (_httpClient.DefaultRequestHeaders.Contains("Authorization"))
  956. {
  957. _httpClient.DefaultRequestHeaders.Remove("Authorization");
  958. }
  959. _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  960. var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  961. url = $"{url}/oauth2/implicit";
  962. Dictionary<string, string> data = new()
  963. {
  964. { "grant_type", "implicit" },
  965. { "client_id", clientID },
  966. { "account", "1636016499" },
  967. { "nonce", Guid.NewGuid().ToString() }
  968. };
  969. HttpResponseMessage responseMessage = await _httpClient.PostAsJsonAsync(url, data);
  970. if (responseMessage.StatusCode == HttpStatusCode.OK) //BI连接字符
  971. {
  972. string content = await responseMessage.Content.ReadAsStringAsync();
  973. }
  974. return Ok(new { state = 200, token, responseMessage });
  975. }
  976. /// <summary>
  977. /// 测试
  978. /// </summary>
  979. /// <param name="jsonElement"></param>
  980. /// <returns></returns>
  981. [HttpPost("get-test")]
  982. public async Task<IActionResult> GetTest(JsonElement jsonElement)
  983. {
  984. List<Test> list1 = new();
  985. list1.Add(new Test { score = 10, name = "001" });
  986. list1.Add(new Test { score = 20, name = "002" });
  987. list1.Add(new Test { score = 30, name = "003" });
  988. list1.Add(new Test { score = 40, name = "004" });
  989. list1.Add(new Test { score = 50, name = "005" });
  990. list1.Add(new Test { score = 60, name = "006" });
  991. List<Test> list2 = new();
  992. list2.Add(new Test { score = 40, name = "004" });
  993. list2.Add(new Test { score = 50, name = "005" });
  994. list2.Add(new Test { score = 60, name = "006" });
  995. list2.Add(new Test { score = 70, name = "007" });
  996. list2.Add(new Test { score = 80, name = "008" });
  997. list2.Add(new Test { score = 90, name = "009" });
  998. list2.Add(new Test { score = 100, name = "010" });
  999. //list3 return 2
  1000. List<Test> list3 = list1.Where(x => !list2.Any(x2 => x.score == x2.score && x.name==x2.name)).ToList();
  1001. //list4 return 2
  1002. List<Test> list4 = list1.Where(x => list2.All(x2 => x.score != x2.score)).ToList();
  1003. List<Test> temp = list1.Where(p => !list2.Select(b => b.score).Contains(p.score)).ToList();
  1004. //List<Test> mergedList = new List<Test>(list1);
  1005. //mergedList.AddRange(list2.Except(list1));
  1006. // var mergedList = list1.Union(list2);
  1007. var en2 = list1.Concat(list2).Except(list1.Intersect(list2));// 容斥原理
  1008. var bingji = list1.Union(list2).ToList();//并(全)集
  1009. var cha = bingji.GroupBy(x => x.score).Select(c => c.First()).ToList();
  1010. var jiaoji = list1.Intersect(list2).ToList();//交集
  1011. var chaji = list1.Except(list2).ToList();//差集
  1012. List<Test> have = list1.Where(a => !list2.Exists(t => a.score == t.score)).ToList();
  1013. have.AddRange(list2.Where(a => !list1.Exists(t => a.score == t.score)).ToList());
  1014. var ss = DateTime.Now.AddDays(0 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7).ToString("yyyy-MM-dd");//上周日
  1015. var sss = DateTime.Now.AddDays(6 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7).ToString("yyyy-MM-dd");//上周六
  1016. var ssss = DateTime.Now.AddDays(1 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7+1).ToString("yyyy-MM-dd");//上周一
  1017. var sssss = DateTime.Now.AddDays(7 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7+1).ToString("yyyy-MM-dd");//上周日
  1018. //计算上周
  1019. var date = DateTime.Now;
  1020. var m = (date.DayOfWeek == DayOfWeek.Sunday ? (DayOfWeek)7 : date.DayOfWeek) - DayOfWeek.Monday;
  1021. var s = (date.DayOfWeek == DayOfWeek.Sunday ? (DayOfWeek)7 : date.DayOfWeek) - (DayOfWeek)7;
  1022. var Mon = date.AddDays((-7 - m)).ToString("yyyy-MM-dd");
  1023. var Sun = date.AddDays((-7 - s)).ToString("yyyy-MM-dd");
  1024. var (lastWeekStart, lastWeekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastweek");
  1025. return Ok(new { state = 200, Mon,Sun, ss, sss, ssss, sssss, lastWeekStart, lastWeekEnd, have, en2, bingji, cha, jiaoji, chaji, list3, list4, temp, list1 });
  1026. }
  1027. /// <summary>
  1028. /// token 分页
  1029. /// </summary>
  1030. /// <returns></returns>
  1031. [HttpPost("get-parallelforeach")]
  1032. public async Task<IActionResult> GetParallelForEach()
  1033. {
  1034. //string ser= $"SELECT Id,name,ownership,modifiedDate FROM {5('TableName')}WHERE ORDER BY Id fetch_size": { variables('Rows')}, "cursor": "";
  1035. var cosmosClient = _azureCosmos.GetCosmosClient();
  1036. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"1636016499");
  1037. List<School> schools = new List<School>();
  1038. Parallel.ForEach(schoolIds, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, async item =>
  1039. {
  1040. School school = new();
  1041. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(item, new PartitionKey("Base"));
  1042. if (response.Status == 200)
  1043. {
  1044. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1045. school = json.ToObject<School>();
  1046. }
  1047. schools.Add(school);
  1048. });
  1049. return Ok(new { state = 200 , schools });
  1050. }
  1051. /// <summary>
  1052. /// table 表分页查询
  1053. /// </summary>
  1054. /// <param name="jsonElement"></param>
  1055. /// <returns></returns>
  1056. [HttpPost("get-tablepage")]
  1057. public async Task<IActionResult> GetTablePage(JsonElement jsonElement)
  1058. {
  1059. jsonElement.TryGetProperty("page", out JsonElement jpage);
  1060. jsonElement.TryGetProperty("size", out JsonElement jsize);
  1061. int page = string.IsNullOrEmpty($"{jsize}") ?1: int.Parse($"{jpage}");
  1062. int size = string.IsNullOrEmpty($"{jsize}") ? 2 : int.Parse($"{jsize}");
  1063. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
  1064. List<BIOptLog> operateLogs = new();
  1065. //lambda 表达式排序
  1066. operateLogs = await table.QueryWhereString<BIOptLog>();
  1067. //lambda 排序 降序
  1068. operateLogs.Sort((x, y) => y.time.CompareTo(x.time));
  1069. List<BIOptLog> bIOptLogs = operateLogs.Skip((page - 1) * size).Take(size).ToList();
  1070. return Ok(new { state = 200, allcount = operateLogs.Count, bIOptLogs });
  1071. }
  1072. /// <summary>
  1073. /// 流式传输响应
  1074. /// </summary>
  1075. /// <returns></returns>
  1076. [HttpPost("get-stream")]
  1077. public async Task<IActionResult> GetStream()
  1078. {
  1079. var sw = Stopwatch.StartNew();
  1080. //while (true)
  1081. //{
  1082. // var q = new Queue<int>();
  1083. // for (int i = 0; i < 100_000_000; i++)
  1084. // {
  1085. // q.Enqueue(i);
  1086. // q.Dequeue();
  1087. // }
  1088. // Console.WriteLine(sw.Elapsed);
  1089. //}
  1090. var ss = new SortedSet<int>(Enumerable.Repeat(42, 400_000));
  1091. Console.WriteLine(sw.Elapsed);
  1092. HttpContext.Response.ContentType = "text/plain";
  1093. StreamWriter writer;
  1094. //using (writer = new StreamWriter(HttpContext.Response.Body))
  1095. // for (int i = 0; i < 100; i++)
  1096. // {
  1097. // await writer.WriteAsync($"S-{i} \n");
  1098. // }
  1099. // //await writer.FlushAsync("Hello World");
  1100. return Ok(new { state = 200});
  1101. }
  1102. [HttpPost("get-linqcount")]
  1103. public async Task<IActionResult> GetLinqCount()
  1104. {
  1105. List<linqTest> linqTests = new();
  1106. for (int i = 0; i < 10; i++)
  1107. {
  1108. linqTest linqt = new() { id = $"qwe{i}",name=$"名字{i}" ,linq1s = new List<linq1> { new linq1 { id =$"abc{i}",times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}, new linq1 { id = $"def{i}", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() } } };
  1109. linqTests.Add(linqt);
  1110. }
  1111. //var set = linqTests.Select((x, y) => x.linq1s.Find(l => l.id.Equals($"abc0"))).ToList();
  1112. var set = linqTests.Where(x=> !string.IsNullOrEmpty(x.linq1s.Find(l => l.id.Equals($"abc0")).ToString()) );
  1113. //var tem220p = linqTests.ForEach(x => {
  1114. // var coreUser = linqTests.Find(c => c.id.Equals("abc0"));
  1115. // }); //.Except(linqTests.Select(y => y.linq1s.Find(n => n.times.Equals("abc0"))));
  1116. return Ok(new { state = 200, linqTests, set });
  1117. }
  1118. /// <summary>
  1119. /// 多个连接字符串方式
  1120. /// </summary>
  1121. /// <returns></returns>
  1122. [HttpPost("get-manydb")]
  1123. public async Task<IActionResult> GetMany(JsonElement jsonElement)
  1124. {
  1125. jsonElement.TryGetProperty("site", out JsonElement site);
  1126. var cosmosClient = _azureCosmos.GetCosmosClient();
  1127. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  1128. var redisClinet = _azureRedis.GetRedisClient(8);
  1129. if ($"{site}".Equals(BIConst.GlobalSite))
  1130. {
  1131. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.GlobalSite);
  1132. table = _azureStorage.GetCloudTableClient(BIConst.GlobalSite).GetTableReference("");
  1133. redisClinet = _azureRedis.GetRedisClient(dbnum: 8, name: BIConst.GlobalSite);
  1134. }
  1135. #region 依赖注入的方式
  1136. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1137. var dateDay = dateTime.ToString("yyyyMMdd"); //获取当天的日期
  1138. Dictionary<long, int> allDays = new(); //所有在线人数
  1139. Dictionary<long, int> tchDays = new(); //教师在线人数
  1140. SortedSetEntry[] tchDay = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:teacher:{dateDay}");
  1141. if (tchDay.Length > 0)
  1142. {
  1143. foreach (var item in tchDay)
  1144. {
  1145. int val = ((int)item.Score);
  1146. int key = ((int)item.Element);
  1147. var utcTo = new DateTimeOffset(new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, key, 0, 0)).Hour;
  1148. //var hour = int.Parse(DateTime.SpecifyKind(Convert.ToDateTime($"{dateTime.Year}/{dateTime.Month}/{ dateTime.Day} {key}:00:00"), DateTimeKind.Utc).ToLocalTime().ToString("HH"));
  1149. tchDays.Add(utcTo, val);
  1150. if (allDays.ContainsKey(utcTo))
  1151. allDays[utcTo] = (allDays[utcTo] + val);
  1152. else
  1153. allDays.Add(utcTo, val);
  1154. }
  1155. }
  1156. var redisGl = _azureRedis.GetRedisClient(dbnum: 0, name: "Global");
  1157. var temps= await _azureRedis.GetRedisClient(dbnum: 0, name: "Global").SortedSetIncrementAsync($"Login:IES:Test", $"1", 1);//一天24小时 小时为单位
  1158. var cosmosDefaulat = _azureCosmos.GetCosmosClient(); //默认数据库
  1159. List<School> schools = new();
  1160. await foreach (var item in cosmosDefaulat.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<School>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1161. {
  1162. schools.Add(item);
  1163. }
  1164. var cosmosGlobal = _azureCosmos.GetCosmosClient(name: "Global"); //默认数据库
  1165. List<School> schoolGlobals = new();
  1166. await foreach (var item in cosmosGlobal.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<School>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1167. {
  1168. schoolGlobals.Add(item);
  1169. }
  1170. return Ok(new { state = 200, dcnt = schools.Count, schools, dgcnt = schoolGlobals.Count, schoolGlobals });
  1171. ////table多库连接
  1172. //var tableDefulat = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin"); //Table默认表
  1173. //List<DayLogin> hourLoginsDefualt = await tableDefulat.FindListByDict<DayLogin>(new Dictionary<string, object> { { "PartitionKey", $"DayLogin" } });
  1174. //var table = _azureStorage.GetCloudTableClient("Global").GetTableReference("IESLogin"); //Table国际站
  1175. //List<DayLogin> hourLogins= await table.FindListByDict<DayLogin>(new Dictionary<string, object> { { "PartitionKey", $"DayLogin" } });
  1176. //return Ok(new { state = 200, hourLogins, hourLoginsDefualt });
  1177. #endregion
  1178. #region 原始方式
  1179. //cosmosDB连接字符串
  1180. //var clientUrl = _configuration.GetValue<string>("Azure:CosmosUrl:ConnectionString");
  1181. //var clientKey = _configuration.GetValue<string>("Azure:CosmosKey:ConnectionString");
  1182. //CosmosClient cosmosClient = new(clientUrl, clientKey);
  1183. //var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync("hbcn", new PartitionKey("Base"));
  1184. //School school = new();
  1185. //if (response.Status == 200)
  1186. //{
  1187. // using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1188. // school = json.ToObject<School>();
  1189. //}
  1190. //Table连接字符串
  1191. //var tableUrl = _configuration.GetValue<string>("Azure:StorageUrl:ConnectionString");
  1192. //Uri url = new(tableUrl, UriKind.Absolute);
  1193. //var tableKey = _configuration.GetValue<string>("Azure:StorageKey:ConnectionString");
  1194. //StorageCredentials sta = new StorageCredentials("teammodeltest", tableKey);
  1195. //CloudTableClient cloudTableClient = new CloudTableClient(url, sta);
  1196. //var table1 = cloudTableClient.GetTableReference("IESLogin");
  1197. //var tableGlobal = _configuration.GetValue<string>("AzureGlobal");
  1198. //Dictionary<string, object> dic = new() { { "PartitionKey", $"HourLogin" } };
  1199. //List<HourLogin> hourLogin = await table1.FindListByDict<HourLogin>(dic);
  1200. //List<HourLogin> hourLogin1= await table.FindListByDict<HourLogin>(dic);
  1201. //var table = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin");
  1202. //return Ok(new { state = 200 });
  1203. #endregion
  1204. }
  1205. /// <summary>
  1206. ///
  1207. /// </summary>
  1208. /// <param name="linqTestm"></param>
  1209. /// <param name="site"></param>
  1210. /// <returns></returns>
  1211. [HttpPost("parameter")]
  1212. public async Task<IActionResult> parameter(linqTest linqTestm, [FromHeader]string site)
  1213. {
  1214. var cosmosClient = _azureCosmos.GetCosmosClient();
  1215. if ($"{site}".Equals(BIConst.GlobalSite))
  1216. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.GlobalSite);
  1217. linqTest linqTest = new linqTest();
  1218. linqTest.id = linqTestm.id; linqTest.name = linqTestm.name;
  1219. var resp = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{linqTestm.id}", new PartitionKey("Base"));
  1220. return Ok(new { state = 200, linqTest,cosmosClient,site });
  1221. }
  1222. public class linqTest
  1223. {
  1224. public string id{ get; set; }
  1225. public string name { get; set; }
  1226. public List<linq1> linq1s { get; set; }
  1227. }
  1228. public class linq1
  1229. {
  1230. public string id { get; set; }
  1231. public long times { get; set; }
  1232. }
  1233. public class Test
  1234. {
  1235. public int age { get; set; }
  1236. public string name { get; set; }
  1237. public int score { get; set; }
  1238. }
  1239. public class strend
  1240. {
  1241. public int id { get; set; }
  1242. public string name { get; set; }
  1243. public int age { get; set; }
  1244. }
  1245. struct MyStruct
  1246. {
  1247. public int Count { get; set; }
  1248. }
  1249. class Example
  1250. {
  1251. public string? Name { get; set; }
  1252. public string Value { get; set; }
  1253. }
  1254. public record TempSchool
  1255. {
  1256. public long ts { get; set; }
  1257. public string id { get; set; }
  1258. public string name { get; set; }
  1259. }
  1260. public static long GetMonthEnd(DateTimeOffset dt)
  1261. {
  1262. DateTime dtNew = new DateTime(dt.Year, dt.Month, 1);
  1263. var ste = dtNew.AddMonths(1).AddDays(-1).Day;
  1264. long iLastDay = DateTimeOffset.Parse($"{dt.Year}-{dt.Month}-{ste} 23:59:59").ToUnixTimeSeconds();
  1265. return iLastDay;
  1266. }
  1267. public static long GetMonthStart(DateTimeOffset dt)
  1268. {
  1269. DateTime dtNew = new DateTime(dt.Year, dt.Month, 1);
  1270. long iLastDay = DateTimeOffset.Parse($"{dtNew}").ToUnixTimeSeconds();
  1271. return iLastDay;
  1272. }
  1273. public class GenerateRandom1
  1274. {
  1275. /// <summary>
  1276. /// 生成随机数字
  1277. /// </summary>
  1278. /// <param name="length">生成长度</param>
  1279. /// <returns></returns>
  1280. public static string Number(int Length)
  1281. {
  1282. return Number(Length, false);
  1283. }
  1284. /// <summary>
  1285. /// 生成随机数字
  1286. /// </summary>
  1287. /// <param name="Length">生成长度</param>
  1288. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  1289. /// <returns></returns>
  1290. public static string Number(int Length, bool Sleep)
  1291. {
  1292. if (Sleep)
  1293. System.Threading.Thread.Sleep(3);
  1294. string result = "";
  1295. System.Random random = new Random();
  1296. for (int i = 0; i < Length; i++)
  1297. {
  1298. result += random.Next(10).ToString();
  1299. }
  1300. return result;
  1301. }
  1302. /// <summary>
  1303. /// 生成随机字母与数字
  1304. /// </summary>
  1305. /// <param name="IntStr">生成长度</param>
  1306. /// <returns></returns>
  1307. public static string Str(int Length)
  1308. {
  1309. return Str(Length, false);
  1310. }
  1311. /// <summary>
  1312. /// 生成随机字母与数字
  1313. /// </summary>
  1314. /// <param name="Length">生成长度</param>
  1315. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  1316. /// <returns></returns>
  1317. public static string Str(int Length, bool Sleep)
  1318. {
  1319. if (Sleep)
  1320. System.Threading.Thread.Sleep(3);
  1321. 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' };
  1322. string result = "";
  1323. int n = Pattern.Length;
  1324. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  1325. for (int i = 0; i < Length; i++)
  1326. {
  1327. int rnd = random.Next(0, n);
  1328. result += Pattern[rnd];
  1329. }
  1330. return result;
  1331. }
  1332. /// <summary>
  1333. /// 生成随机纯字母随机数
  1334. /// </summary>
  1335. /// <param name="IntStr">生成长度</param>
  1336. /// <returns></returns>
  1337. public static string Str_char(int Length)
  1338. {
  1339. return Str_char(Length, false);
  1340. }
  1341. /// <summary>
  1342. /// 生成随机纯字母随机数
  1343. /// </summary>
  1344. /// <param name="Length">生成长度</param>
  1345. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  1346. /// <returns></returns>
  1347. public static string Str_char(int Length, bool Sleep)
  1348. {
  1349. if (Sleep) System.Threading.Thread.Sleep(3);
  1350. //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' };
  1351. 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' };
  1352. string result = "";
  1353. int n = Pattern.Length;
  1354. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  1355. for (int i = 0; i < Length; i++)
  1356. {
  1357. int rnd = random.Next(0, n);
  1358. result += Pattern[rnd];
  1359. }
  1360. return result;
  1361. }
  1362. }
  1363. }
  1364. }