TestController.cs 71 KB

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