TestController.cs 69 KB

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