TestController.cs 71 KB

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