TestController.cs 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189
  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. using System.Web;
  54. using Azure.Storage.Sas;
  55. using DocumentFormat.OpenXml.Drawing.Diagrams;
  56. using DocumentFormat.OpenXml.Bibliography;
  57. using TEAMModelOS.SDK.Models.Service.BIStatsWay;
  58. using MathNet.Numerics.LinearAlgebra.Double;
  59. using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
  60. using DocumentFormat.OpenXml.Drawing;
  61. using Microsoft.OData.Edm;
  62. using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
  63. namespace TEAMModelBI.Controllers.BITest
  64. {
  65. [Route("apitest")]
  66. [ApiController]
  67. public class TestController : ControllerBase
  68. {
  69. private readonly AzureCosmosFactory _azureCosmos;
  70. private readonly AzureStorageFactory _azureStorage;
  71. private readonly AzureRedisFactory _azureRedis;
  72. private readonly DingDing _dingDing;
  73. private readonly Option _option;
  74. private readonly IWebHostEnvironment _environment; //读取文件
  75. //读取配置文件
  76. private readonly IConfiguration _configuration;
  77. private readonly CoreAPIHttpService _coreAPIHttpService;
  78. private readonly IHttpClientFactory _httpClient;
  79. private IPSearcher _ipSearcher;
  80. public TestController(IPSearcher ipSearcher, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option, IWebHostEnvironment hostingEnvironment, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService, IHttpClientFactory httpClient)
  81. {
  82. _azureCosmos = azureCosmos;
  83. _azureStorage = azureStorage;
  84. _azureRedis = azureRedis;
  85. _dingDing = dingDing;
  86. _option = option?.Value;
  87. _environment = hostingEnvironment;
  88. _configuration = configuration;
  89. _coreAPIHttpService = coreAPIHttpService;
  90. _httpClient = httpClient; _ipSearcher = ipSearcher;
  91. }
  92. /// <summary>
  93. /// 删除册别,删除章节 创区
  94. /// </summary>
  95. /// <param name="jsonElement"></param>
  96. /// <returns></returns>
  97. [HttpPost("del-standard")]
  98. public async Task<IActionResult> DelStandard(JsonElement jsonElement)
  99. {
  100. if (!jsonElement.TryGetProperty("oldStandard", out JsonElement _oldStandard)) return BadRequest();
  101. var cosmosClient = _azureCosmos.GetCosmosClient();
  102. List<string> abilityIds = new(); //册别的ID集合
  103. //查询册别信息
  104. 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}") }))
  105. {
  106. abilityIds.Add(tempAbility.id); //查询出来册别ID添加册别ID集合
  107. }
  108. //删除册别
  109. if (abilityIds.IsNotEmpty())
  110. {
  111. var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityIds, $"Ability-{_oldStandard}");
  112. }
  113. List<string> abilityTaskIds = new(); //章节ID集合
  114. 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}") }))
  115. {
  116. abilityTaskIds.Add(item.id); //查询出来的章节信息ID添加到战绩集合
  117. }
  118. //删除章节
  119. if (abilityTaskIds.IsNotEmpty())
  120. {
  121. var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityTaskIds, $"AbilityTask-{_oldStandard}");
  122. }
  123. return Ok(new { state = 200 });
  124. }
  125. /// <summary>
  126. /// 测试生产Code
  127. /// </summary>
  128. /// <param name="jsonElement"></param>
  129. /// <returns></returns>
  130. [ProducesDefaultResponseType]
  131. [HttpPost("get-schoolcode")]
  132. public async Task<IActionResult> GetSchoolCode(JsonElement jsonElement)
  133. {
  134. //string data = await SchoolCode.GenerateSchoolCode(jsonElement, _dingDing, _environment).ToString();
  135. CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo();
  136. createSchoolInfo.province = "四川省";
  137. createSchoolInfo.id = "tmdplc";
  138. createSchoolInfo.name = "醍摩豆批量创校学校";
  139. createSchoolInfo.city = "成都市";
  140. createSchoolInfo.aname = "";
  141. createSchoolInfo.createCount = 0;
  142. //Random random = new Random();
  143. ////随机小写字母
  144. //int a = random.Next(0, 26);
  145. //char ch = (char)('a' + a);
  146. //string Number = GenerateRandom.Number(1);
  147. //string Number1 = GenerateRandom.Number(1, true);
  148. //string Str = GenerateRandom.Str(1);
  149. //string Str1 = GenerateRandom.Str(1, true);
  150. //string Str_char = GenerateRandom.Str_char(1);
  151. //string Str_char1 = GenerateRandom.Str_char(1, true);
  152. CreateSchoolInfo data = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
  153. return Ok(new { state = 200, data, data.id });
  154. }
  155. /// <summary>
  156. /// 保存日志文件
  157. /// </summary>
  158. /// <param name="jsonElement"></param>
  159. /// <returns></returns>
  160. [ProducesDefaultResponseType]
  161. //[AuthToken(Roles = "assist,admin")]
  162. [HttpPost("set-savebilog")]
  163. public async Task<IActionResult> SetTestSaveBIlog(JsonElement jsonElement)
  164. {
  165. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  166. jsonElement.TryGetProperty("msg", out JsonElement msg);
  167. var cosmosClient = _azureCosmos.GetCosmosClient();
  168. var tableClient = _azureStorage.GetCloudTableClient();
  169. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  170. var redisClinet = _azureRedis.GetRedisClient(8);
  171. ////分开部署,就不需要,一站多用时,取消注释
  172. //if ($"{site}".Equals(BIConst.Global))
  173. //{
  174. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  175. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  176. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  177. // redisClinet = _azureRedis.GetRedisClient(dbnum: 8, name: BIConst.Global);
  178. //}
  179. var blob = _azureStorage.GetBlobContainerClient(containerName: "hbcn");
  180. await foreach (BlobItem blobItem in blob.GetBlobsAsync(BlobTraits.None, BlobStates.None, $"records/{383558646003404800}/IES"))
  181. {
  182. if (blobItem.Name.EndsWith("base.json") || blobItem.Name.EndsWith("TimeLine.json"))
  183. {
  184. BlobClient tempClient = blob.GetBlobClient(blobItem.Name);
  185. if (await tempClient.ExistsAsync())
  186. {
  187. using (var meomoryStream = new MemoryStream())
  188. {
  189. var response = blob.GetBlobClient($"{blobItem.Name}").DownloadTo(meomoryStream);
  190. string setr = Encoding.UTF8.GetString(meomoryStream.ToArray()).ToString();
  191. //LessonBase res = Encoding.UTF8.GetString(meomoryStream.ToArray()).ToString().ToObject<LessonBase>();
  192. //var response = await blob.GetBlobClient($"{blobItem.Name}").DownloadToAsync(meomoryStream);
  193. //RecCnt recCnt = Encoding.UTF8.GetString(meomoryStream.ToArray()).ToString().ToObject<RecCnt>();
  194. //string name = stringSuffix.MidStrEx(blobItem.Name, "/", ".");
  195. }
  196. }
  197. }
  198. }
  199. //var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
  200. //await _azureStorage.SaveLog(type: "table-save", msg: "测试保存方法01", dingDing: _dingDing, httpContext: HttpContext); //IES5 日志记录
  201. //await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "Test-test", $"{msg}", _dingDing, httpContext: HttpContext);//BI 日志记录
  202. return Ok(new { state = 200 });
  203. }
  204. /// <summary>
  205. /// 查询table数据 sql
  206. /// </summary>
  207. /// <param name="jsonElement"></param>
  208. /// <returns></returns>
  209. [HttpPost("file-table")]
  210. public async Task<IActionResult> SaveTable(JsonElement jsonElement)
  211. {
  212. jsonElement.TryGetProperty("single", out JsonElement single);
  213. jsonElement.TryGetProperty("startDate", out JsonElement startDate);
  214. jsonElement.TryGetProperty("endDate", out JsonElement endDate);
  215. jsonElement.TryGetProperty("platform", out JsonElement platform);
  216. List<string> strlist = new();
  217. if (!string.IsNullOrEmpty($"{single}"))
  218. strlist.Add($"RowKey {QueryComparisons.Equal} {single}");
  219. if (!string.IsNullOrEmpty($"{startDate}"))
  220. strlist.Add($"RowKey {QueryComparisons.GreaterThanOrEqual} {startDate}");
  221. if (!string.IsNullOrEmpty($"{endDate}"))
  222. strlist.Add($"RowKey {QueryComparisons.LessThanOrEqual} {endDate}");
  223. if (!string.IsNullOrEmpty($"{platform}"))
  224. strlist.Add($"platform {QueryComparisons.Equal} {platform}");
  225. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
  226. string sql = string.Join(" and ", strlist);
  227. var temp = table.QueryWhereString<BIOptLog>(sql);
  228. return Ok(new { state = 200, temp });
  229. }
  230. /// <summary>
  231. /// 查询BI操作记录
  232. /// </summary>
  233. /// <param name="jsonElement"></param>
  234. /// <returns></returns>
  235. [HttpPost("get-operatelogbydate")]
  236. public async Task<IActionResult> GetOperateLogByDate(JsonElement jsonElement)
  237. {
  238. try
  239. {
  240. jsonElement.TryGetProperty("single", out JsonElement single);
  241. jsonElement.TryGetProperty("startDate", out JsonElement startDate);
  242. jsonElement.TryGetProperty("endDate", out JsonElement endDate);
  243. jsonElement.TryGetProperty("platform", out JsonElement platform);
  244. List<BIOptLog> operateLogs = new();
  245. StringBuilder tableSql = new();
  246. if (!string.IsNullOrEmpty($"{single}"))
  247. tableSql.Append($"RowKey {QueryComparisons.Equal} '{single}' ");
  248. if (!string.IsNullOrEmpty($"{startDate}"))
  249. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' " : $"RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' ");
  250. if (!string.IsNullOrEmpty($"{endDate}"))
  251. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.LessThanOrEqual} '{endDate}' " : $" RowKey {QueryComparisons.LessThanOrEqual} '{endDate}' ");
  252. if (!string.IsNullOrEmpty($"{platform}"))
  253. tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} platform {QueryComparisons.Equal} '{platform}' " : $" platform {QueryComparisons.Equal} '{platform}' ");
  254. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
  255. operateLogs = await table.QueryWhereString<BIOptLog>(tableSql.ToString());
  256. return Ok(new { state = 200, operateLogs });
  257. }
  258. catch (Exception ex)
  259. {
  260. await _dingDing.SendBotMsg($"BI,{_option.Location} /operatelog/get-operatelogbydate \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  261. return BadRequest();
  262. }
  263. }
  264. /// <summary>
  265. /// 查询离职信息
  266. /// </summary>
  267. /// <returns></returns>
  268. [ProducesDefaultResponseType]
  269. [HttpPost("quitstaff")]
  270. public async Task<IActionResult> QuitStaff()
  271. {
  272. string appKey = _configuration["DingDingAuth:appKey"];
  273. string appSecret = _configuration["DingDingAuth:appSecret"];
  274. string agentld = _configuration["DingDingAuth:Agentld"];
  275. //获取access_token
  276. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  277. OapiGettokenRequest request = new() { Appkey = appKey, Appsecret = appSecret };
  278. request.SetHttpMethod("Get");
  279. OapiGettokenResponse response = client.Execute(request);
  280. if (response.IsError)
  281. {
  282. return BadRequest();
  283. }
  284. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  285. string access_token = response.AccessToken;
  286. IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
  287. OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new() { Offset = 0L, Size = 50L };
  288. OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
  289. if (rspDimission.SubErrCode == "60011")
  290. {
  291. return Ok(new { state = 60011, message = "没有调用该接口的权限!" });
  292. }
  293. else if (rspDimission.Result != null)
  294. {
  295. var datalist = rspDimission.Result.DataList;
  296. return Ok(new { state = 200, datalist });
  297. }
  298. else
  299. {
  300. return Ok(new { state = rspDimission.SubErrCode, message = rspDimission.Errmsg });
  301. }
  302. }
  303. /// <summary>
  304. /// 测试获取待入职人员的userId接口
  305. /// </summary>
  306. /// <returns></returns>
  307. [ProducesDefaultResponseType]
  308. [HttpPost("Induction")]
  309. public async Task<IActionResult> Induction()
  310. {
  311. string appKey = _configuration["DingDingAuth:appKey"];
  312. string appSecret = _configuration["DingDingAuth:appSecret"];
  313. string agentld = _configuration["DingDingAuth:Agentld"];
  314. //获取access_token
  315. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  316. OapiGettokenRequest request = new() { Appkey = appKey, Appsecret = appSecret };
  317. request.SetHttpMethod("Get");
  318. OapiGettokenResponse response = client.Execute(request);
  319. if (response.IsError)
  320. {
  321. return BadRequest();
  322. }
  323. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  324. string access_token = response.AccessToken;
  325. IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
  326. OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new() { Offset = 0L, Size = 50 };
  327. reqInduction.SetHttpMethod("GET");
  328. OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
  329. if (rspInduction.Result.DataList != null)
  330. {
  331. foreach (var itemId in rspInduction.Result.DataList)
  332. {
  333. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  334. OapiV2UserGetRequest v2GetRequest = new()
  335. {
  336. Userid = itemId,
  337. Language = "zh_CN"
  338. };
  339. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
  340. }
  341. return Ok(new { state = 200, rspInduction.Result.DataList });
  342. }
  343. else
  344. {
  345. return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
  346. }
  347. }
  348. /// <summary>
  349. /// 获取在职ID
  350. /// </summary>
  351. /// <returns></returns>
  352. [HttpPost("get-onthejob")]
  353. public async Task<IActionResult> GetOnTheJob()
  354. {
  355. string appKey = _configuration["DingDingAuth:appKey"];
  356. string appSecret = _configuration["DingDingAuth:appSecret"];
  357. string agentld = _configuration["DingDingAuth:Agentld"];
  358. //获取access_token
  359. IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  360. OapiGettokenRequest request = new() { Appkey = appKey, Appsecret = appSecret };
  361. request.SetHttpMethod("Get");
  362. OapiGettokenResponse response = client.Execute(request);
  363. if (response.IsError)
  364. {
  365. return BadRequest();
  366. }
  367. //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
  368. string access_token = response.AccessToken;
  369. //bool vars = false;
  370. //long offst = 1;
  371. //do
  372. //{
  373. // IDingTalkClient jobclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
  374. // OapiSmartworkHrmEmployeeQueryonjobRequest jobreq = new OapiSmartworkHrmEmployeeQueryonjobRequest { StatusList = "2,3,-1", Offset = offst, Size = 50 }; //2:试用期 3:正式 5:待离职 -1:无状态
  375. // OapiSmartworkHrmEmployeeQueryonjobResponse jobrsp = jobclient.Execute(jobreq, access_token);
  376. // if (jobrsp.Result.NextCursor > 0)
  377. // offst += 1;
  378. // else vars = true;
  379. //} while (vars);
  380. IDingTalkClient jobclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
  381. OapiSmartworkHrmEmployeeQueryonjobRequest jobreq = new() { StatusList = "2,3,-1", Offset = 1, Size = 50 }; //2:试用期 3:正式 5:待离职 -1:无状态
  382. OapiSmartworkHrmEmployeeQueryonjobResponse jobrsp = jobclient.Execute(jobreq, access_token);
  383. if (jobrsp.SubErrCode == "60011")
  384. {
  385. return Ok(new { state = 200, msg = jobrsp.SubErrMsg });
  386. }
  387. foreach (var item in jobrsp.Result.DataList)
  388. {
  389. }
  390. var ser = jobrsp.Result.DataList; // jobrsp.Body.GetEnumerator("result");
  391. return Ok(new { state = 200, jobrsp.Body, ser });
  392. }
  393. /// <summary>
  394. /// 测试 使用yield 优化
  395. /// 依据学校编号查询学校信息;若是没有传学校编号,则查询所有学校信息
  396. /// </summary>
  397. /// <param name="jsonElement"></param>
  398. /// <returns></returns>
  399. [ProducesDefaultResponseType]
  400. [HttpPost("get-schoolsinfo")]
  401. public async Task<IActionResult> GetSchoolsInfo(JsonElement jsonElement)
  402. {
  403. try
  404. {
  405. jsonElement.TryGetProperty("schoolCode", out JsonElement _schoolCode);
  406. var cosmosClient = _azureCosmos.GetCosmosClient();
  407. List<AssistSchool> schoolAssists = new();
  408. //StringBuilder stringBuilder = new StringBuilder("select value(c) from c");
  409. StringBuilder stringBuilder = new("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");
  410. if (!string.IsNullOrEmpty($"{_schoolCode}"))
  411. {
  412. stringBuilder.Append($" where c.id='{_schoolCode}'");
  413. }
  414. //await foreach (var itemSchool in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  415. //{
  416. // SchoolAssist schoolAssist = new()
  417. // {
  418. // id = itemSchool.id,
  419. // code = itemSchool.code,
  420. // schoolCode = itemSchool.schoolCode,
  421. // name = itemSchool.name,
  422. // region = itemSchool.region,
  423. // province = itemSchool.province,
  424. // city = itemSchool.city,
  425. // dist = itemSchool.dist,
  426. // size = itemSchool.size,
  427. // address = itemSchool.address,
  428. // picture = itemSchool.picture,
  429. // type = itemSchool.type,
  430. // scale = itemSchool.scale,
  431. // areaId = itemSchool.areaId,
  432. // standard = itemSchool.standard
  433. // };
  434. // var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(itemSchool.id, new PartitionKey("ProductSum"));
  435. // if (response.Status == 200)
  436. // {
  437. // using var json = await JsonDocument.ParseAsync(response.ContentStream);
  438. // if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  439. // {
  440. // schoolAssist.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  441. // }
  442. // if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  443. // {
  444. // schoolAssist.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  445. // }
  446. // if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  447. // {
  448. // schoolAssist.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  449. // }
  450. // }
  451. // schoolAssist.assists = await CommonFind.FindSchoolRoles(cosmosClient, itemSchool.id, "assist");
  452. // schoolAssists.Add(schoolAssist);
  453. //}
  454. //return Ok(new { state = 200, schoolAssists });
  455. await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  456. {
  457. using var jsonSchool = await JsonDocument.ParseAsync(itemSchool.ContentStream);
  458. foreach (var objSchool in jsonSchool.RootElement.GetProperty("Documents").EnumerateArray())
  459. {
  460. var schoolId = objSchool.GetProperty("id").GetString();
  461. AssistSchool schoolAssist = new()
  462. {
  463. id = schoolId,
  464. code = objSchool.GetProperty("code").GetString(),
  465. schoolCode = objSchool.GetProperty("schoolCode").GetString(),
  466. name = objSchool.GetProperty("name").GetString(),
  467. region = objSchool.GetProperty("region").GetString(),
  468. province = objSchool.GetProperty("province").GetString(),
  469. city = objSchool.GetProperty("city").GetString(),
  470. dist = objSchool.GetProperty("dist").GetString(),
  471. size = objSchool.GetProperty("size").GetInt32(),
  472. address = objSchool.GetProperty("address").GetString(),
  473. picture = objSchool.GetProperty("picture").GetString(),
  474. type = objSchool.GetProperty("type").GetInt32(),
  475. //scale = objSchool.GetProperty("scale").GetInt32(),
  476. areaId = objSchool.GetProperty("areaId").GetString(),
  477. standard = objSchool.GetProperty("standard").GetString(),
  478. };
  479. try { schoolAssist.scale = objSchool.GetProperty("scale").GetInt32(); }
  480. catch { schoolAssist.scale = 0; }
  481. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(schoolId, new PartitionKey("ProductSum"));
  482. if (response.Status == 200)
  483. {
  484. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  485. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  486. {
  487. schoolAssist.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  488. }
  489. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  490. {
  491. schoolAssist.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  492. }
  493. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  494. {
  495. schoolAssist.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  496. }
  497. }
  498. //schoolAssist.assists = await CommonFind.FindSchoolRoles(cosmosClient, schoolId, "assist");
  499. schoolAssists.Add(schoolAssist);
  500. }
  501. }
  502. List<AssistSchool> tempSchoolAssists = new();
  503. await foreach (var temp in GetSchools(cosmosClient, schoolAssists))
  504. {
  505. tempSchoolAssists.AddRange(temp);
  506. }
  507. return Ok(new { state = 200, schoolAssists = tempSchoolAssists });
  508. }
  509. catch (Exception ex)
  510. {
  511. await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-schoolsinfo \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  512. return BadRequest();
  513. }
  514. }
  515. /// <summary>
  516. /// 使用yield 优化
  517. /// </summary>
  518. /// <param name="cosmosClient"></param>
  519. /// <param name="schoolAssists"></param>
  520. /// <returns></returns>
  521. private async IAsyncEnumerable<List<AssistSchool>> GetSchools(CosmosClient cosmosClient, List<AssistSchool> schoolAssists)
  522. {
  523. List<AssistSchool> tempSchoolAssists = new();
  524. foreach (var temp in schoolAssists)
  525. {
  526. var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(temp.id, new PartitionKey("ProductSum"));
  527. if (response.Status == 200)
  528. {
  529. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  530. if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
  531. {
  532. temp.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  533. }
  534. if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
  535. {
  536. temp.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
  537. }
  538. if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
  539. {
  540. temp.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
  541. }
  542. }
  543. temp.assists = await CommonFind.FindSchoolRoles(cosmosClient, temp.id, "assist");
  544. tempSchoolAssists.Add(temp);
  545. }
  546. yield return tempSchoolAssists;
  547. }
  548. /// <summary>
  549. /// 赋值默认的顾问角色和BI默认的功能权限
  550. /// </summary>
  551. /// <returns></returns>
  552. [HttpPost("set-rolesorperm")]
  553. public async Task<IActionResult> SetRolesOrPermissions()
  554. {
  555. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  556. List<DingDingUserInfo> ddUserId = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", "continent" } });
  557. List<string> read = new() { "abilitystandard-read", "batcharea-read", "batchschool-read", "orgusers-read" };
  558. List<DingDingUserInfo> tempUserInfo = new();
  559. foreach (var user in ddUserId)
  560. {
  561. if (string.IsNullOrEmpty(user.roles))
  562. {
  563. user.roles = "assist";
  564. }
  565. if (string.IsNullOrEmpty(user.permissions))
  566. {
  567. user.permissions = string.Join(",", read);
  568. }
  569. List<string> tempRead = new(user.permissions.Split(","));
  570. foreach (var temp in read)
  571. {
  572. if (!tempRead.Contains(temp))
  573. {
  574. tempRead.Add(temp);
  575. }
  576. }
  577. user.permissions = string.Join(",", tempRead);
  578. tempUserInfo.Add(user);
  579. }
  580. var response = await table.SaveOrUpdateAll<DingDingUserInfo>(tempUserInfo);
  581. return Ok(new { state = 200, response });
  582. }
  583. /// <summary>
  584. /// 测试使用 CosmosDB中的COUNT 函数统计
  585. /// </summary>
  586. /// <param name="jsonElement"></param>
  587. /// <returns></returns>
  588. [HttpPost("get-count")]
  589. public async Task<IActionResult> GetCount(JsonElement jsonElement)
  590. {
  591. var cosmosClient = _azureCosmos.GetCosmosClient();
  592. List<KeyValuePair<int, int>> layerCount = new List<KeyValuePair<int, int>>();
  593. for (int i = 1; i <= 6; i++)
  594. {
  595. int total = 0;
  596. //string sqlText = $"select value(c.id) from c where c.pk='Item' and c.field={i}";
  597. string sqlText = $"select value(COUNT(c.id)) from c where c.pk='Item' and c.field={i}";
  598. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<int>(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
  599. {
  600. total += item;
  601. //using var json = await JsonDocument.ParseAsync(item.ContentStream);
  602. //if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt32() > 0)
  603. //{
  604. // foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  605. // {
  606. // //total += obj.GetInt64();
  607. // total += obj.GetProperty("totals").GetInt32();
  608. // }
  609. // //total += count.GetInt64();
  610. //}
  611. }
  612. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryIterator<int>(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
  613. {
  614. total += item;
  615. //using var json = await JsonDocument.ParseAsync(item.ContentStream);
  616. //if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt64() > 0)
  617. //{
  618. // foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  619. // {
  620. // //total += obj.GetInt64();
  621. // total += obj.GetProperty("totals").GetInt32();
  622. // }
  623. //}
  624. }
  625. layerCount.Add(new KeyValuePair<int, int>(i, total));
  626. }
  627. return Ok(new { state = 200, layerCount });
  628. }
  629. /// <summary>
  630. /// 测试算日期
  631. /// </summary>
  632. /// <returns></returns>
  633. [HttpPost("get-date")]
  634. public async Task<IActionResult> GetDate()
  635. {
  636. ////计算一年每天的开始/结束时间
  637. //List<StartEndTime> everyDay = TimeHelper.GetYearEveryDay(DateTimeOffset.UtcNow, isCurrDay: true);
  638. //return Ok(new { state = RespondCode.Ok, dayCnt = everyDay.Count, everyDay });
  639. List<string> day7 = TimeHelper.GetNearDay(DateTimeOffset.UtcNow, 7);
  640. List<string> day30 = TimeHelper.GetNearDay(DateTimeOffset.UtcNow, 30);
  641. DateTimeOffset dateTime = DateTimeOffset.UtcNow.AddDays(0);
  642. int year = DateTimeOffset.UtcNow.Year;
  643. int month = DateTimeOffset.UtcNow.Month;
  644. var datetime7 = DateTimeOffset.UtcNow.AddDays(-7); //前七天的时间
  645. List<string> strList = monthsOfYear("2021-1");
  646. var ere = DateTimeOffset.Parse("2022-04-25");
  647. DateTimeOffset ste = new();
  648. if (ere.Month > 9)
  649. {
  650. ste = new DateTime(ere.Year, ere.Month - 4, 1);
  651. }
  652. else
  653. {
  654. ste = new DateTime(ere.Year - 1, ere.Month, 1);
  655. }
  656. var (start1, end1) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow);
  657. var (start2, end2) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "week");
  658. var (start3, end3) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastweek");
  659. var (start4, end4) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "term");
  660. var (start5, end5) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastterm");
  661. var (start6, end6) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "month");
  662. var (start7, end7) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "year");
  663. var start = GetMonthStart(ere);
  664. List<StartEndTime> endList1 = TimeHelper.GetYearMonthlyStartEnd(DateTimeOffset.UtcNow.Year);
  665. //return Ok(new { strList, dateTime, year, start, end, endList, endList1, endList2 });
  666. return Ok(new { day7, day30, datetime7, start1, end1, start2, end2, start3, end3, start4, end4, start5, end5, start6, end6, start7, end7 });
  667. }
  668. public static List<string> monthsOfYear(string yearMonth)
  669. {
  670. DateTime dateTime = DateTime.Parse(yearMonth);
  671. int year = dateTime.Year;
  672. int month = dateTime.Month;
  673. List<string> months = new List<string>();
  674. while (year > dateTime.Year - 1 || month > dateTime.Month)
  675. {
  676. months.Add($"{year}-{(month < 10 ? "0" : "") + month}");
  677. month -= 1;
  678. if (month <= 0)
  679. {
  680. year -= 1;
  681. month = 12;
  682. }
  683. }
  684. return months;
  685. }
  686. /// <summary>
  687. /// 统计一年中每月得新增校
  688. /// </summary>
  689. /// <returns></returns>
  690. [HttpPost("get-yearmonth")]
  691. public async Task<IActionResult> GetYearMonth()
  692. {
  693. var cosmosClient = _azureCosmos.GetCosmosClient();
  694. Dictionary<int, long> tempYear = new();
  695. List<TempSchool> tempSchools = new();
  696. for (int i = 1; i < 13; i++)
  697. {
  698. var start = 00022222330;
  699. long tempCount = 0;
  700. 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") }))
  701. {
  702. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  703. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt64() > 0)
  704. {
  705. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  706. {
  707. TempSchool tempSchool = new();
  708. tempSchool.id = obj.GetProperty("id").GetString();
  709. tempSchool.ts = obj.GetProperty("_ts").GetInt64();
  710. tempSchool.name = obj.GetProperty("name").GetString();
  711. tempSchools.Add(tempSchool);
  712. }
  713. tempCount += count.GetInt64();
  714. }
  715. }
  716. if (tempCount != 0)
  717. {
  718. tempYear.Add(i, tempCount);
  719. }
  720. }
  721. return Ok(new { state = 200, tempYear, tempSchools });
  722. }
  723. /// <summary>
  724. /// 测试.net 6 的一些特性
  725. /// </summary>
  726. /// <returns></returns>
  727. [HttpPost("get-newnet6")]
  728. public async Task<IActionResult> GetNewNet6()
  729. {
  730. ///PriorityQueue
  731. //.NET 6 新增的数据结构, PriorityQueue, 队列每个元素都有一个关联的优先级,它决定了出队顺序, 编号小的元素优先出列。
  732. PriorityQueue<string, int> priorityQueue = new();
  733. priorityQueue.Enqueue("Second", 2);
  734. priorityQueue.Enqueue("Fourth", 4);
  735. priorityQueue.Enqueue("Third 1", 3);
  736. priorityQueue.Enqueue("Third 2", 5);
  737. priorityQueue.Enqueue("First", 1);
  738. while (priorityQueue.Count > 0)
  739. {
  740. string item = priorityQueue.Dequeue();
  741. Console.WriteLine(item);
  742. }
  743. //PeriodicTimer
  744. //认识一个完全异步的“PeriodicTimer”, 更适合在异步场景中使用, 它有一个方法 WaitForNextTickAsync。
  745. //using PeriodicTimer timer = new(TimeSpan.FromSeconds(2));
  746. //while (await timer.WaitForNextTickAsync())
  747. //{
  748. // Console.WriteLine(DateTime.UtcNow);
  749. //}
  750. //检查元素是否可为空的反射API
  751. var example = new Example();
  752. var nullabilityInfoContext = new NullabilityInfoContext();
  753. foreach (var propertyInfo in example.GetType().GetProperties())
  754. {
  755. var nullabilityInfo = nullabilityInfoContext.Create(propertyInfo);
  756. Console.WriteLine($"{propertyInfo.Name} property is {nullabilityInfo.WriteState}");
  757. }
  758. //直接通过 Environment 获取进程ID和路径。
  759. int processId = Environment.ProcessId;
  760. string path = Environment.ProcessPath;
  761. Console.WriteLine(processId);
  762. Console.WriteLine(path);
  763. //CSPNG 密码安全伪随机数生成器
  764. byte[] bytes = RandomNumberGenerator.GetBytes(300);
  765. Console.WriteLine(string.Join("", bytes.ToArray()));
  766. //Power of 2
  767. //.NET 6 引入了用于处理 2 的幂的新方法。
  768. //‘IsPow2’ 判断指定值是否为 2 的幂。
  769. //‘RoundUpToPowerOf2’ 将指定值四舍五入到 2 的幂
  770. Console.WriteLine(BitOperations.IsPow2(121)); // True
  771. Console.WriteLine(BitOperations.RoundUpToPowerOf2(260)); // 256
  772. //WaitAsync on Task 您可以更轻松地等待异步任务执行, 如果超时会抛出 “TimeoutException”
  773. Task operationTask = DoSomethingLongAsync();
  774. await operationTask.WaitAsync(TimeSpan.FromSeconds(5));
  775. async Task DoSomethingLongAsync()
  776. {
  777. Console.WriteLine("DoSomethingLongAsync started.");
  778. await Task.Delay(TimeSpan.FromSeconds(10));
  779. Console.WriteLine("DoSomethingLongAsync ended.");
  780. }
  781. //新的数学API
  782. // New methods SinCos, ReciprocalEstimate and ReciprocalSqrtEstimate
  783. // Simultaneously computes Sin and Cos
  784. (double sin, double cos) = Math.SinCos(1.57);
  785. Console.WriteLine($"Sin = {sin}\nCos = {cos}");
  786. // Computes an approximate of 1 / x
  787. double recEst = Math.ReciprocalEstimate(5);
  788. Console.WriteLine($"Reciprocal estimate = {recEst}");
  789. // Computes an approximate of 1 / Sqrt(x)
  790. double recSqrtEst = Math.ReciprocalSqrtEstimate(5);
  791. Console.WriteLine($"Reciprocal sqrt estimate = {recSqrtEst}");
  792. // New overloads
  793. // Min, Max, Abs, Clamp and Sign supports nint and nuint
  794. (nint a, nint b) = (5, 10);
  795. nint min = Math.Min(a, b);
  796. nint max = Math.Max(a, b);
  797. nint abs = Math.Abs(a);
  798. nint clamp = Math.Clamp(abs, min, max);
  799. nint sign = Math.Sign(a);
  800. Console.WriteLine($"Min = {min}\nMax = {max}\nAbs = {abs}");
  801. Console.WriteLine($"Clamp = {clamp}\nSign = {sign}");
  802. // DivRem variants return a tuple
  803. (int quotient, int remainder) = Math.DivRem(2, 7);
  804. Console.WriteLine($"Quotient = {quotient}\nRemainder = {remainder}");
  805. //CollectionsMarshal.GetValueRefOrNullRef
  806. //这个是在字典中循环或者修改结可变结构体时用, 可以减少结构的副本复制, 也可以避免字典重复进行哈希计算,这个有点晦涩难懂
  807. Dictionary<int, MyStruct> dictionary = new()
  808. {
  809. { 1, new MyStruct { Count = 100 } }
  810. };
  811. int key = 1;
  812. MyStruct values = CollectionsMarshal.GetValueRefOrNullRef(dictionary, key);
  813. // Returns Unsafe.NullRef<TValue>() if it doesn't exist; check using Unsafe.IsNullRef(ref value)
  814. if (!Unsafe.IsNullRef(ref values))
  815. {
  816. Console.WriteLine(values.Count); // Output: 100
  817. // Mutate in-place
  818. values.Count++;
  819. Console.WriteLine(values.Count); // Output: 101
  820. }
  821. return Ok(new { state = 200 });
  822. }
  823. /// <summary>
  824. /// 去重、判断
  825. /// </summary>
  826. /// <param name="jsonElement"></param>
  827. /// <returns></returns>
  828. [HttpPost("get-repeat")]
  829. public async Task<IActionResult> GetRepeat(JsonElement jsonElement)
  830. {
  831. jsonElement.TryGetProperty("datetime", out JsonElement _datetime);
  832. Dictionary<string, string> prodict = new() { { "YMPCVCIM", "学情分析模组" }, { "IPDYZYLC", "智慧学校管理服务" }, { "3CLYJ6NP", "AClass ONE智慧学伴" }, { "IPALJ6NY", "数据储存服务空间" }, { "VABAJ6NV", "卷卡合一阅卷系统" } };
  833. var ste = prodict["IPDYZYLC"];
  834. List<string> str_str = new() { "12", "20", "13", "13", "14", "16" };
  835. List<strend> strends = new() { 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 } };
  836. //str_str.Distinct().ToList();
  837. strends.Where((x, i) => strends.FindIndex(z => z.id.Equals(x.id)) == i).ToList();
  838. List<strend> str_strend1 = strends.Where((x, i) => strends.FindIndex(z => z.id.Equals(x.id)) == i).ToList();
  839. List<strend> str_strend2 = strends.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
  840. DateTime dt = DateTime.Parse($"{_datetime}");
  841. int year = dt.Year;
  842. DateTime dt0 = new DateTime(year, 1, 1);
  843. int days = (dt.Date - dt0.Date).Days + 1;
  844. //int pydays = ((lastYear + 1) % 4 == 0 && (lastYear + 1) % 100 != 0 || (lastYear + 1) % 400 == 0) ? 366 : 365;
  845. int pydays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  846. //int pydays = DateTimeHelper.getDays(year);
  847. return Ok(new { state = 200, pydays, days, strends, str_strend1, str_strend2, ste });
  848. }
  849. /// <summary>
  850. /// 计算天数
  851. /// </summary>
  852. /// <param name="jsonElement"></param>
  853. /// <returns></returns>
  854. [HttpPost("get-dateday")]
  855. public async Task<IActionResult> GetDateDay(JsonElement jsonElement)
  856. {
  857. jsonElement.TryGetProperty("year", out JsonElement _year);
  858. jsonElement.TryGetProperty("moth", out JsonElement _moth);
  859. int year = int.Parse($"{_year}");
  860. int day = 0;
  861. List<int> moths = _moth.ToObject<List<int>>();
  862. foreach (var item in moths)
  863. {
  864. int days = 0;
  865. switch (item)
  866. {
  867. case 1:
  868. case 3:
  869. case 5:
  870. case 7:
  871. case 8:
  872. case 10:
  873. case 12:
  874. days = 31;
  875. break;
  876. case 4:
  877. case 6:
  878. case 9:
  879. case 11:
  880. days = 30;
  881. break;
  882. case 2:
  883. int years = 0;
  884. if (item <= 8 && item >= 3)
  885. years = year;
  886. else
  887. years = year + 1;
  888. if (years % 4 == 0 && year % 100 != 0 || year % 400 == 0)
  889. days = 29;
  890. else
  891. days = 28;
  892. break;
  893. }
  894. day += days;
  895. }
  896. return Ok(new { state = 200, day });
  897. }
  898. /// <summary>
  899. /// 测试CosmosDB分页查询 SQL语句分页
  900. /// </summary>
  901. /// <param name="jsonElement"></param>
  902. /// <returns></returns>
  903. [HttpPost("get-page")]
  904. public async Task<IActionResult> cosmosDBPage(JsonElement jsonElement)
  905. {
  906. if (!jsonElement.TryGetProperty("pageSize", out JsonElement pageSize)) return BadRequest();
  907. if (!jsonElement.TryGetProperty("endPosition", out JsonElement endPosition)) return BadRequest();
  908. var cosmosClient = _azureCosmos.GetCosmosClient();
  909. List<School> schools = new List<School>();
  910. //string sqlTxt = $"SELECT * FROM c where c.code='Base' order by c.id offset {endPosition} limit {pageSize}";
  911. string sqlTxt = $"SELECT * FROM c order by c.id offset {pageSize} limit {endPosition}";
  912. await foreach (var tempPage in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlTxt, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  913. {
  914. using var json = await JsonDocument.ParseAsync(tempPage.ContentStream);
  915. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt16() > 0)
  916. {
  917. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  918. {
  919. schools.Add(obj.ToObject<School>());
  920. }
  921. }
  922. }
  923. IAsyncResult iAsyncResult = null;
  924. return Ok(new { state = 200, schools });
  925. }
  926. /// <summary>
  927. /// 分页案例
  928. /// </summary>
  929. /// <param name="jsonElement"></param>
  930. /// <returns></returns>
  931. [HttpPost("get-cosmodbtokenpage")]
  932. public async Task<IActionResult> GetCancellationTokenPage(JsonElement jsonElement)
  933. {
  934. var cosmosClient = _azureCosmos.GetCosmosClient();
  935. //默认不指定返回大小
  936. int? pageSize = null;
  937. string continuationToken = string.Empty;
  938. string pageToken = default;
  939. if (jsonElement.TryGetProperty("pageSize", out JsonElement jsonPageSize))
  940. {
  941. if (!jsonPageSize.ValueKind.Equals(JsonValueKind.Undefined) && !jsonPageSize.ValueKind.Equals(JsonValueKind.Null) && jsonPageSize.TryGetInt32(out int tempPageSize))
  942. {
  943. pageSize = tempPageSize;
  944. }
  945. }
  946. //是否需要进行分页查询,默认不分页
  947. bool iscontinuation = false;
  948. if (pageSize != null && pageSize.Value > 0)
  949. {
  950. iscontinuation = true;
  951. }
  952. if (jsonElement.TryGetProperty("contToken", out JsonElement ContToken))
  953. {
  954. pageToken = ContToken.GetString();
  955. }
  956. List<School> schools = new();
  957. 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") }))
  958. {
  959. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  960. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  961. {
  962. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  963. {
  964. schools.Add(obj.ToObject<School>());
  965. }
  966. if (iscontinuation)
  967. {
  968. continuationToken = item.GetContinuationToken();
  969. break;
  970. }
  971. }
  972. }
  973. return Ok(new { state = 200, continuationToken, count = schools.Count, schools });
  974. }
  975. /// <summary>
  976. /// table 表分页查询
  977. /// </summary>
  978. /// <param name="jsonElement"></param>
  979. /// <returns></returns>
  980. [HttpPost("get-tablepage")]
  981. public async Task<IActionResult> GetTablePage(JsonElement jsonElement)
  982. {
  983. jsonElement.TryGetProperty("page", out JsonElement jpage);
  984. jsonElement.TryGetProperty("size", out JsonElement jsize);
  985. int page = string.IsNullOrEmpty($"{jsize}") ? 1 : int.Parse($"{jpage}");
  986. int size = string.IsNullOrEmpty($"{jsize}") ? 2 : int.Parse($"{jsize}");
  987. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
  988. List<BIOptLog> operateLogs = new();
  989. //lambda 表达式排序
  990. operateLogs = await table.QueryWhereString<BIOptLog>();
  991. //lambda 排序 降序
  992. operateLogs.Sort((x, y) => y.time.CompareTo(x.time));
  993. List<BIOptLog> bIOptLogs = operateLogs.Skip((page - 1) * size).Take(size).ToList();
  994. int takeCount = 500;
  995. var table1 = _azureStorage.GetCloudTableClient();
  996. int pagesize = 10;
  997. int pageNum = 2;
  998. var query = (from entity in table.CreateQuery<BIOptLog>()
  999. select entity).ToList().Skip(pagesize * (pageNum - 1)).Take(pagesize);
  1000. //var query = (from entity in table.CreateQuery<BIOptLog>()
  1001. // orderby entity.time descending
  1002. // select entity).Skip(pagesize * (pageNum - 1)).Take(pagesize);
  1003. //var ster = AzureStorageTableExtensions.GetTablePage<BIOptLog>(table1, "BIOptLog", 10, 1);
  1004. return Ok(new { state = 200, allcount = operateLogs.Count, bIOptLogs });
  1005. }
  1006. /// <summary>
  1007. /// 流式传输响应
  1008. /// </summary>
  1009. /// <returns></returns>
  1010. [HttpPost("get-stream")]
  1011. public async Task<IActionResult> GetStream()
  1012. {
  1013. var sw = Stopwatch.StartNew();
  1014. //while (true)
  1015. //{
  1016. // var q = new Queue<int>();
  1017. // for (int i = 0; i < 100_000_000; i++)
  1018. // {
  1019. // q.Enqueue(i);
  1020. // q.Dequeue();
  1021. // }
  1022. // Console.WriteLine(sw.Elapsed);
  1023. //}
  1024. var ss = new SortedSet<int>(Enumerable.Repeat(42, 400_000));
  1025. Console.WriteLine(sw.Elapsed);
  1026. HttpContext.Response.ContentType = "text/plain";
  1027. StreamWriter writer;
  1028. //using (writer = new StreamWriter(HttpContext.Response.Body))
  1029. // for (int i = 0; i < 100; i++)
  1030. // {
  1031. // await writer.WriteAsync($"S-{i} \n");
  1032. // }
  1033. // //await writer.FlushAsync("Hello World");
  1034. return Ok(new { state = 200 });
  1035. }
  1036. /// <summary>
  1037. /// lingq 查询
  1038. /// </summary>
  1039. /// <returns></returns>
  1040. [HttpPost("get-linqcount")]
  1041. public async Task<IActionResult> GetLinqCount()
  1042. {
  1043. List<linqTest> linqTests = new()
  1044. {
  1045. new linqTest { id = "10110",aresid = "0",name ="明",linq1 = new linq1 { id ="abc0", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } } ,
  1046. new linqTest { id = "10111",aresid = "1",name ="明1",linq1 = new linq1 { id ="abc1", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } } ,
  1047. new linqTest { id = "10112",aresid = "2",name ="明2",linq1 = new linq1 { id ="abc2", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } } ,
  1048. new linqTest { id = "10113",aresid = "3",name ="明3",linq1 = new linq1 { id ="abc3", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } } ,
  1049. new linqTest { id = "10114",aresid = "4",name ="明4",linq1 = new linq1 { id ="abc4", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } },
  1050. new linqTest { id = "10115",aresid = "5",name ="明5",linq1 = new linq1 { id ="abc5", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } } ,
  1051. new linqTest { id = "10116",aresid = "6",name ="明6",linq1 = new linq1 { id ="abc6", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } },
  1052. new linqTest { id = "10117",aresid = "7",name ="明7",linq1 = new linq1 { id ="abc7", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } },
  1053. new linqTest { id = "10118",aresid = "8",name ="明8",linq1 = new linq1 { id ="abc8", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } },
  1054. new linqTest { id = "10119",aresid = "9",name ="明9",linq1 = new linq1 { id ="abc9", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } },
  1055. new linqTest { id = "10120",aresid = "10",name ="明10",linq1 = new linq1 { id ="abc10", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } }
  1056. };
  1057. for (int i = 0; i < 11; i++)
  1058. {
  1059. linqTest linqt = new() { id = $"qwe{i}", aresid = $"{i}", name = $"名字{i}", linq1 = new linq1 { id = $"abc{i}", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), cnt = (11 + i) } };
  1060. linqTests.Add(linqt);
  1061. }
  1062. var grup = linqTests.GroupBy(g => g.aresid).ToList();
  1063. var grup1 = linqTests.GroupBy(g => g.aresid).Select(s=>new { areid= s.Key,linq1Id = s.Select(sn => sn.linq1.id).ToList(), id = s.Select(sn => sn.id).ToList(), name = s.Select(sn => sn.name).ToList(), linq1Cnt = s.Select(sn => sn.linq1.cnt).ToList(), lescnt = s.Select(sf=>sf.linq1.cnt).Sum()}).ToList();
  1064. return Ok(new { state = RespondCode.Ok, grup1, grup });
  1065. List<Test> list1 = new()
  1066. {
  1067. new Test { score = 10, name = "001" },
  1068. new Test { score = 20, name = "002" },
  1069. new Test { score = 30, name = "003" },
  1070. new Test { score = 40, name = "004" },
  1071. new Test { score = 50, name = "005" },
  1072. new Test { score = 60, name = "006" }
  1073. };
  1074. List<Test> list2 = new()
  1075. {
  1076. new Test { score = 40, name = "004" },
  1077. new Test { score = 50, name = "005" },
  1078. new Test { score = 60, name = "006" },
  1079. new Test { score = 70, name = "007" },
  1080. new Test { score = 80, name = "008" },
  1081. new Test { score = 90, name = "009" },
  1082. new Test { score = 100, name = "010" }
  1083. };
  1084. //list3 return 2
  1085. List<Test> list3 = list1.Where(x => !list2.Any(x2 => x.score == x2.score && x.name == x2.name)).ToList();
  1086. //list4 return 2
  1087. List<Test> list4 = list1.Where(x => list2.All(x2 => x.score != x2.score)).ToList();
  1088. List<Test> temp = list1.Where(p => !list2.Select(b => b.score).Contains(p.score)).ToList();
  1089. //List<Test> mergedList = new List<Test>(list1);
  1090. //mergedList.AddRange(list2.Except(list1));
  1091. // var mergedList = list1.Union(list2);
  1092. var en2 = list1.Concat(list2).Except(list1.Intersect(list2));// 容斥原理
  1093. var bingji = list1.Union(list2).ToList();//并(全)集
  1094. var cha = bingji.GroupBy(x => x.score).Select(c => c.First()).ToList();
  1095. var jiaoji = list1.Intersect(list2).ToList();//交集
  1096. var chaji = list1.Except(list2).ToList();//差集
  1097. List<Test> have = list1.Where(a => !list2.Exists(t => a.score == t.score)).ToList();
  1098. have.AddRange(list2.Where(a => !list1.Exists(t => a.score == t.score)).ToList());
  1099. var ss = DateTime.Now.AddDays(0 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7).ToString("yyyy-MM-dd");//上周日
  1100. var sss = DateTime.Now.AddDays(6 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7).ToString("yyyy-MM-dd");//上周六
  1101. var ssss = DateTime.Now.AddDays(1 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7 + 1).ToString("yyyy-MM-dd");//上周一
  1102. var sssss = DateTime.Now.AddDays(7 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7 + 1).ToString("yyyy-MM-dd");//上周日
  1103. //计算上周
  1104. var date = DateTime.Now;
  1105. var m = (date.DayOfWeek == DayOfWeek.Sunday ? (DayOfWeek)7 : date.DayOfWeek) - DayOfWeek.Monday;
  1106. var s = (date.DayOfWeek == DayOfWeek.Sunday ? (DayOfWeek)7 : date.DayOfWeek) - (DayOfWeek)7;
  1107. var Mon = date.AddDays((-7 - m)).ToString("yyyy-MM-dd");
  1108. var Sun = date.AddDays((-7 - s)).ToString("yyyy-MM-dd");
  1109. var (lastWeekStart, lastWeekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastweek");
  1110. //var set = linqTests.Select((x, y) => x.linq1s.Find(l => l.id.Equals($"abc0"))).ToList();
  1111. //var set = linqTests.Where(x => !string.IsNullOrEmpty(x.linq1s.Find(l => l.id.Equals($"abc0")).ToString()));
  1112. //var tem220p = linqTests.ForEach(x => {
  1113. // var coreUser = linqTests.Find(c => c.id.Equals("abc0"));
  1114. // }); //.Except(linqTests.Select(y => y.linq1s.Find(n => n.times.Equals("abc0"))));
  1115. return Ok(new { state = 200, Mon, Sun, ss, sss, ssss, sssss, lastWeekStart, lastWeekEnd, have, en2, bingji, cha, jiaoji, chaji, list3, list4, temp, list1, linqTests });
  1116. }
  1117. /// <summary>
  1118. /// 多个连接字符串方式
  1119. /// </summary>
  1120. /// <returns></returns>
  1121. [HttpPost("get-manydb")]
  1122. public async Task<IActionResult> GetMany(JsonElement jsonElement)
  1123. {
  1124. jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  1125. var cosmosClient = _azureCosmos.GetCosmosClient();
  1126. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  1127. var redisClinet = _azureRedis.GetRedisClient(8);
  1128. ////分开部署,就不需要,一站多用时,取消注释
  1129. //if ($"{site}".Equals(BIConst.Global))
  1130. //{
  1131. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1132. // table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("");
  1133. // redisClinet = _azureRedis.GetRedisClient(dbnum: 8, name: BIConst.Global);
  1134. //}
  1135. #region 依赖注入的方式
  1136. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1137. var dateDay = dateTime.ToString("yyyyMMdd"); //获取当天的日期
  1138. Dictionary<long, int> allDays = new(); //所有在线人数
  1139. Dictionary<long, int> tchDays = new(); //教师在线人数
  1140. SortedSetEntry[] tchDay = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:teacher:{dateDay}");
  1141. if (tchDay.Length > 0)
  1142. {
  1143. foreach (var item in tchDay)
  1144. {
  1145. int val = ((int)item.Score);
  1146. int key = ((int)item.Element);
  1147. var utcTo = new DateTimeOffset(new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, key, 0, 0)).Hour;
  1148. //var hour = int.Parse(DateTime.SpecifyKind(Convert.ToDateTime($"{dateTime.Year}/{dateTime.Month}/{ dateTime.Day} {key}:00:00"), DateTimeKind.Utc).ToLocalTime().ToString("HH"));
  1149. tchDays.Add(utcTo, val);
  1150. if (allDays.ContainsKey(utcTo))
  1151. allDays[utcTo] = (allDays[utcTo] + val);
  1152. else
  1153. allDays.Add(utcTo, val);
  1154. }
  1155. }
  1156. var redisGl = _azureRedis.GetRedisClient(dbnum: 0, name: "Global");
  1157. var temps = await _azureRedis.GetRedisClient(dbnum: 0, name: "Global").SortedSetIncrementAsync($"Login:IES:Test", $"1", 1);//一天24小时 小时为单位
  1158. var cosmosDefaulat = _azureCosmos.GetCosmosClient(); //默认数据库
  1159. List<School> schools = new();
  1160. await foreach (var item in cosmosDefaulat.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<School>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1161. {
  1162. schools.Add(item);
  1163. }
  1164. var cosmosGlobal = _azureCosmos.GetCosmosClient(name: "Global"); //默认数据库
  1165. List<School> schoolGlobals = new();
  1166. await foreach (var item in cosmosGlobal.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<School>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1167. {
  1168. schoolGlobals.Add(item);
  1169. }
  1170. return Ok(new { state = 200, dcnt = schools.Count, schools, dgcnt = schoolGlobals.Count, schoolGlobals });
  1171. ////table多库连接
  1172. //var tableDefulat = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin"); //Table默认表
  1173. //List<DayLogin> hourLoginsDefualt = await tableDefulat.FindListByDict<DayLogin>(new Dictionary<string, object> { { "PartitionKey", $"DayLogin" } });
  1174. //var table = _azureStorage.GetCloudTableClient("Global").GetTableReference("IESLogin"); //Table国际站
  1175. //List<DayLogin> hourLogins= await table.FindListByDict<DayLogin>(new Dictionary<string, object> { { "PartitionKey", $"DayLogin" } });
  1176. //return Ok(new { state = 200, hourLogins, hourLoginsDefualt });
  1177. #endregion
  1178. #region 原始方式
  1179. //cosmosDB连接字符串
  1180. //var clientUrl = _configuration.GetValue<string>("Azure:CosmosUrl:ConnectionString");
  1181. //var clientKey = _configuration.GetValue<string>("Azure:CosmosKey:ConnectionString");
  1182. //CosmosClient cosmosClient = new(clientUrl, clientKey);
  1183. //var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync("hbcn", new PartitionKey("Base"));
  1184. //School school = new();
  1185. //if (response.Status == 200)
  1186. //{
  1187. // using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1188. // school = json.ToObject<School>();
  1189. //}
  1190. //Table连接字符串
  1191. //var tableUrl = _configuration.GetValue<string>("Azure:StorageUrl:ConnectionString");
  1192. //Uri url = new(tableUrl, UriKind.Absolute);
  1193. //var tableKey = _configuration.GetValue<string>("Azure:StorageKey:ConnectionString");
  1194. //StorageCredentials sta = new StorageCredentials("teammodeltest", tableKey);
  1195. //CloudTableClient cloudTableClient = new CloudTableClient(url, sta);
  1196. //var table1 = cloudTableClient.GetTableReference("IESLogin");
  1197. //var tableGlobal = _configuration.GetValue<string>("AzureGlobal");
  1198. //Dictionary<string, object> dic = new() { { "PartitionKey", $"HourLogin" } };
  1199. //List<HourLogin> hourLogin = await table1.FindListByDict<HourLogin>(dic);
  1200. //List<HourLogin> hourLogin1= await table.FindListByDict<HourLogin>(dic);
  1201. //var table = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin");
  1202. //return Ok(new { state = 200 });
  1203. #endregion
  1204. }
  1205. /// <summary>
  1206. /// 测试删除过期Blob 文件
  1207. /// </summary>
  1208. /// <param name="jsonElement"></param>
  1209. /// <returns></returns>
  1210. [HttpPost("get-loganalyse")]
  1211. public async Task<IActionResult> GetLogAnalyse(JsonElement jsonElement)
  1212. {
  1213. if (!jsonElement.TryGetProperty("path", out JsonElement path)) return BadRequest();
  1214. if (!jsonElement.TryGetProperty("timeType", out JsonElement jTimeType)) return BadRequest();
  1215. List<string> filename = new();
  1216. ////删除过期Blob 文件
  1217. //var azureClient = _azureStorage.GetBlobContainerClient("0-public");//获取容器连接地址
  1218. //int expireTime = int.Parse(DateTimeOffset.UtcNow.AddDays(-180).ToString("yyyyMMdd"));
  1219. //await foreach (var blobItem in azureClient.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix: "visitCnt"))
  1220. //{
  1221. // string[] sub_name = blobItem.Name.Split('/');
  1222. // if (sub_name.Length > 2)
  1223. // {
  1224. // if (int.Parse(sub_name[1]) <= expireTime)
  1225. // {
  1226. // await azureClient.GetBlobBaseClient(blobItem.Name).DeleteIfExistsAsync();
  1227. // filename.add(sub_name[1]);
  1228. // }
  1229. // }
  1230. //}
  1231. var (an, saveUrl) = await BILogAnalyseService.GetPathAnalyse(_azureStorage, _ipSearcher, _dingDing, $"{path}", BIConst.LogChina, timeType: $"{jTimeType}");
  1232. return Ok(new { state = RespondCode.Ok, cnt = filename.Count, filename, an, saveUrl });
  1233. }
  1234. /// <summary>
  1235. /// 小时/天读取防火墙文件,分析;
  1236. /// </summary>
  1237. /// <param name="jsonElement"></param>
  1238. /// <returns></returns>
  1239. [HttpPost("get-savefile")]
  1240. public async Task<IActionResult> GetSaveFile(JsonElement jsonElement)
  1241. {
  1242. if (!jsonElement.TryGetProperty("time", out JsonElement time)) return BadRequest();
  1243. long str = time.GetInt64();
  1244. DateTimeOffset dateTimeJ = TimeHelper.GetDateTime(str);
  1245. var datetime = dateTimeJ.AddHours(-1);
  1246. var y = datetime.Year;
  1247. var m = datetime.Month >= 10 ? $"{datetime.Month}" : $"0{datetime.Month}";
  1248. var d = datetime.Day >= 10 ? $"{datetime.Day}" : $"0{datetime.Day}";
  1249. var h = datetime.Hour >= 10 ? $"{datetime.Hour}" : $"0{datetime.Hour}";
  1250. string path = $"resourceId=/SUBSCRIPTIONS/73B7F9EF-D8B7-4444-9E8D-D80B43BF3CD4/RESOURCEGROUPS/TEAMMODELCHENGDU/PROVIDERS/MICROSOFT.NETWORK/APPLICATIONGATEWAYS/OSFIREWARE/y={y}/m={m}/d={d}/h={h}/m=00/PT1H.json";
  1251. var retn = await BILogAnalyseService.GetPathAnalyse(_azureStorage, _ipSearcher, _dingDing, path, BIConst.LogChina);
  1252. if (retn.recCnts.IsNotEmpty())
  1253. {
  1254. //https://teammodelos.blob.core.chinacloudapi.cn/0-public/pie-borderRadius.html
  1255. string publishUrl = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={HttpUtility.UrlEncode(retn.saveUrls.First(), Encoding.UTF8)}&time={HttpUtility.UrlEncode(datetime.AddHours(8).ToString("yyyy年MM月dd日 HH时"), Encoding.UTF8)}";
  1256. string ulrs = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={retn.saveUrls.First()}&time={datetime.AddHours(8).ToString("yyyy年MM月dd日 HH时")}";
  1257. string ulr = $"http://cdhabook.teammodel.cn:8805/screen/screenshot-png?width=1920&height=1450&url={HttpUtility.UrlEncode(ulrs, Encoding.UTF8)}&delay=6000";
  1258. string image = "";
  1259. try
  1260. {
  1261. string strs = await _httpClient.CreateClient().GetStringAsync(ulr);
  1262. if (!string.IsNullOrWhiteSpace(strs))
  1263. {
  1264. JsonElement json = strs.ToObject<JsonElement>();
  1265. json.TryGetProperty("url", out JsonElement base64);
  1266. using (MemoryStream ms = new MemoryStream(Convert.FromBase64String($"{base64}")))
  1267. {
  1268. image = await _azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(ms, $"visitCnt/{y}{m}{d}", $"{h}.png", false);
  1269. }
  1270. }
  1271. }
  1272. catch (Exception ex) { }
  1273. //await _dingDing.SendBotMarkdown("防火墙日志记录", $"#### 测试(小时)-防火墙日志记录\n> 记录时间:{datetime.AddHours(8).ToString("yyyy-MM-dd HH")}\n> ![screenshot]({image})\n> ###### 发布时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}" +
  1274. // $" [发布地址]({publishUrl}) \n", GroupNames.醍摩豆服務運維群組);
  1275. }
  1276. if (h.Equals("00"))
  1277. {
  1278. var pastTime = datetime.AddHours(-1);
  1279. var ptY = pastTime.Year;
  1280. var ptM = pastTime.Month >= 10 ? $"{pastTime.Month}" : $"0{pastTime.Month}";
  1281. var ptD = pastTime.Day >= 10 ? $"{pastTime.Day}" : $"0{pastTime.Day}";
  1282. string dayPath = $"resourceId=/SUBSCRIPTIONS/73B7F9EF-D8B7-4444-9E8D-D80B43BF3CD4/RESOURCEGROUPS/TEAMMODELCHENGDU/PROVIDERS/MICROSOFT.NETWORK/APPLICATIONGATEWAYS/OSFIREWARE/y={ptY}/m={ptM}/d={ptD}";
  1283. var dayRetn = await BILogAnalyseService.GetPathAnalyse(_azureStorage, _ipSearcher, _dingDing, dayPath, BIConst.LogChina, timeType: "Day");
  1284. if (dayRetn.recCnts.IsNotEmpty())
  1285. {
  1286. //一天的统计
  1287. string dayPublishUrl = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={HttpUtility.UrlEncode(dayRetn.saveUrls.First(), Encoding.UTF8)}&time={HttpUtility.UrlEncode(pastTime.ToString("yyyy年MM月dd日"), Encoding.UTF8)}";
  1288. string dayUrls = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={dayRetn.saveUrls.First()}&time={pastTime.ToString("yyyy年MM月dd日")}";
  1289. string dayUrl = $"http://cdhabook.teammodel.cn:8805/screen/screenshot-png?width=1920&height=1450&url={HttpUtility.UrlEncode(dayUrls, Encoding.UTF8)}&delay=6000";
  1290. string dayImage = "";
  1291. string dayStr = await _httpClient.CreateClient().GetStringAsync(dayUrl);
  1292. if (!string.IsNullOrWhiteSpace(dayStr))
  1293. {
  1294. JsonElement dayJson = dayStr.ToObject<JsonElement>();
  1295. dayJson.TryGetProperty("url", out JsonElement dayBase64);
  1296. using (MemoryStream dayMs = new(Convert.FromBase64String($"{dayBase64}")))
  1297. {
  1298. dayImage = await _azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(dayMs, $"visitCnt/{ptY}{ptM}{ptD}", "days.png", false);
  1299. }
  1300. }
  1301. await _dingDing.SendBotMarkdown("测试-防火墙日志记录", $"#### 测试(天)-防火墙日志记录\n> 记录时间:{pastTime.AddHours(2).ToString("yyyy-MM-dd")}\n> ![screenshot]({dayImage})\n> ###### 发布时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}" + $" [发布地址]({dayPublishUrl}) \n", GroupNames.成都开发測試群組);
  1302. }
  1303. }
  1304. return Ok(new { state = 200 });
  1305. }
  1306. /// <summary>
  1307. /// 端外通知
  1308. /// </summary>
  1309. /// <returns></returns>
  1310. [HttpPost("get-noticev2")]
  1311. public async Task<IActionResult> SetNoticeV2()
  1312. {
  1313. var cosmosClient = _azureCosmos.GetCosmosClient();
  1314. //v2通知
  1315. Teacher targetTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>("1636016499", new PartitionKey("Base"));
  1316. _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "create-school", Constant.NotifyType_IES5_Management, new Dictionary<string, object> { { "tmdname", $"{targetTeacher.name}" }, { "schooName", "商务智能学校(BI)" }, { "schoolId", "cswznb" }, { "tmdid", $"{targetTeacher.id}" } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
  1317. return Ok(new { state = RespondCode.Ok });
  1318. }
  1319. /// <summary>
  1320. /// 复制文件
  1321. /// </summary>
  1322. /// <returns></returns>
  1323. [HttpPost("set-copyfile")]
  1324. public async Task<IActionResult> SetCopyFile()
  1325. {
  1326. ///单个复制文件
  1327. string blobName = "cswznb";
  1328. string oldFile = "https://teammodeltest.blob.core.chinacloudapi.cn/cswznb/survey%2Fd011c05b-c009-0a53-428f-b871a58092c7%2Findex.json";//"https://teammodeltest.blob.core.chinacloudapi.cn/1636016499/yxpt%2Fstandard2%2FTEAMModelOS%E6%95%B0%E6%8D%AE%E5%BA%93.doc";
  1329. string oldId = "survey";
  1330. string newId = "survey1";
  1331. List<Task<CopyFromUriOperation>> filelist = new(); //可复制256M以上文件
  1332. var set = await BatchCopyFileService.SingleCopyFile(_azureStorage, blobName, oldFile, oldId, newId);
  1333. //var azureClient = _azureStorage.GetBlobContainerClient($"{blobName}");//获取容器连接地址
  1334. //string newurl = oldFile.Substring(oldFile.IndexOf($"{blobName}/") + $"{blobName}/".Length).Replace($"{oldId}", $"{newId}");//替换成新的容器路径
  1335. //string oldFileName = oldFile.Substring(oldFile.IndexOf($"{blobName}/") + $"{blobName}/".Length);
  1336. //var urlSas = _azureStorage.GetBlobSAS($"{blobName}", $"{HttpUtility.UrlDecode(oldFileName)}", BlobSasPermissions.Read | BlobSasPermissions.List); //获取容器sas和有效期
  1337. ////var respCopy = azureClient.GetBlobClient(HttpUtility.UrlDecode(newurl)).SyncCopyFromUri(new Uri(urlSas)); //可复制256M以下文件
  1338. //var respCopy1 = await azureClient.GetBlobClient(HttpUtility.UrlDecode(newurl)).StartCopyFromUriAsync(new Uri(urlSas)); //可复制256M以上文件
  1339. //var azureClient = _azureStorage.GetBlobContainerClient($"0-public");//获取容器连接地址
  1340. ////查询目录下所有容器路径
  1341. //await foreach (BlobItem blobItem in azureClient.GetBlobsAsync(BlobTraits.None, BlobStates.None, $"TestMP4Max/"))
  1342. //{
  1343. // string newurl = $"{blobItem.Name}".Replace($"/SourceFile/", $"/SourceFiles/");//替换成新的容器路径
  1344. // var urlSas = _azureStorage.GetBlobSAS($"0-public", blobItem.Name, BlobSasPermissions.Read | BlobSasPermissions.List); //获取容器sas和有效期
  1345. // //await azureClient.GetBlobClient(newurl).StartCopyFromUriAsync(new Uri(urlSas));
  1346. // filelist.Add(azureClient.GetBlobClient(newurl).StartCopyFromUriAsync(new Uri(urlSas)));
  1347. // //await azureClient.GetBlobClient(newurl).SyncCopyFromUriAsync(new Uri(urlSas)); //添加复制文件到集合执行复制操作
  1348. //}
  1349. //if (filelist.Count <= 256)
  1350. //{
  1351. // await Task.WhenAll(filelist);
  1352. //}
  1353. //else
  1354. //{
  1355. // int pages = (filelist.Count + 255) / 256;
  1356. // for (int i = 0; i < pages; i++)
  1357. // {
  1358. // List<Task<CopyFromUriOperation>> rspBlobCopyInfos = filelist.Skip((i) * 256).Take(256).ToList();
  1359. // await Task.WhenAll(rspBlobCopyInfos);
  1360. // }
  1361. //}
  1362. var azureClient = _azureStorage.GetBlobContainerClient($"1636016499");//获取容器连接地址
  1363. //查询目录下所有容器路径
  1364. await foreach (BlobItem blobItem in azureClient.GetBlobsAsync(BlobTraits.None, BlobStates.None, $"doc"))
  1365. {
  1366. string newurl = $"{blobItem.Name}".Replace($"doc/", $"/SourceFiles/");//替换成新的容器路径
  1367. var urlSas = _azureStorage.GetBlobSAS($"1636016499", blobItem.Name, BlobSasPermissions.Read | BlobSasPermissions.List); //获取容器sas和有效期
  1368. //await azureClient.GetBlobClient(newurl).StartCopyFromUriAsync(new Uri(urlSas));
  1369. await azureClient.GetBlobClient(newurl).StartCopyFromUriAsync(new Uri(urlSas));
  1370. //await azureClient.GetBlobClient(newurl).SyncCopyFromUriAsync(new Uri(urlSas)); //添加复制文件到集合执行复制操作
  1371. }
  1372. return Ok(new { state = 200, filelist });
  1373. }
  1374. /// <summary>
  1375. /// 计算一年每月的数据
  1376. /// </summary>
  1377. /// <param name="jsonElement"></param>
  1378. /// <returns></returns>
  1379. [HttpPost("get-yearmonsum")]
  1380. public async Task<IActionResult> GetYearMonthSum(JsonElement jsonElement)
  1381. {
  1382. var cosmosClient = _azureCosmos.GetCosmosClient();
  1383. //LessonStats lessonStats =await StatsWay.GetLessStats(cosmosClient, "hbcn");
  1384. //ActivityStats artStats = await StatsWay.GetActStats(cosmosClient, "hbcn");
  1385. //var tempSc = SchoolStatsWay.GetSingleSc(cosmosClient, "hbcn");
  1386. //return Ok(new { state = 200, ld= artStats.LastYear.Count, d = artStats.year.Count, artStats });
  1387. //示例矩阵
  1388. List<List<double>> matrixDou = new() {
  1389. new List<double>() { 6, 5, 4, 3, 2, 1},
  1390. new List<double>() { 2, 3, 4, 5, 6, 7 },
  1391. new List<double>() { 3, 4, 5, 6, 7, 8 },
  1392. new List<double>() { 4, 5, 6, 7, 8, 9 }
  1393. };
  1394. var artYear = DenseMatrix.OfColumns(matrixDou);
  1395. var rc = artYear.RowCount;
  1396. var cc = artYear.ColumnCount;
  1397. List<double> dous1 = new(); ;
  1398. List<double> dous = new(); ;
  1399. for (int i = 0; i < artYear.RowCount; i++)
  1400. {
  1401. Console.WriteLine($"次数:{i} ; 行数:{rc};列数:{cc}");
  1402. var cl = matrixDou.SelectMany(o => o.Skip(i).Take(1)).ToList();
  1403. var cl1 = matrixDou.SelectMany(o => o.Skip(i).Take(1)).ToList().Sum();
  1404. dous1.Add(cl1);
  1405. var stet = artYear.SubMatrix(i, 1, 0, cc);
  1406. var stet1 = artYear.SubMatrix(i, 1, 0, cc).ColumnSums().Sum();
  1407. dous.Add(stet1);
  1408. //var set = artYear.SubMatrix(0, 4, i, i+1).ColumnSums().Sum();
  1409. //dous.Add(set);
  1410. }
  1411. var s = DateTimeOffset.UtcNow.Year - 1;
  1412. DateTimeOffset date = new(DateTimeOffset.UtcNow.Year - 1, DateTimeOffset.UtcNow.Month, DateTimeOffset.UtcNow.Day, DateTimeOffset.UtcNow.Hour, DateTimeOffset.UtcNow.Minute, DateTimeOffset.UtcNow.Second, TimeSpan.Zero);
  1413. //计算一年每天的开始/结束时间
  1414. List<StartEndTime> leveryDay = TimeHelper.GetYearEveryDay(date);
  1415. List<StartEndTime> everyDay = TimeHelper.GetYearEveryDay(DateTimeOffset.UtcNow, isCurrDay: true);
  1416. List<double> doubles = new() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 6, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 16, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 98, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366 };
  1417. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1418. List<YearMonth> monthty = TimeHelper.GetYearMonth(doubles, dateTime.Year);
  1419. return Ok(new { state = RespondCode.Ok, leverycnt = leveryDay.Count, leveryDay, dayCnt = everyDay.Count, everyDay, monthty });
  1420. }
  1421. /// <summary>
  1422. /// 测试矩阵
  1423. /// </summary>
  1424. /// <param name="jsonElement"></param>
  1425. /// <returns></returns>
  1426. [HttpPost("set-matrix")]
  1427. public async Task<IActionResult> SetMatrix(JsonElement jsonElement)
  1428. {
  1429. var cosmosClient = _azureCosmos.GetCosmosClient();
  1430. //LessonStats lessonStats =await StatsWay.GetLessStats(cosmosClient, "hbcn");
  1431. //ActivityStats artStats = await StatsWay.GetActStats(cosmosClient, "hbcn");
  1432. //var tempSc = SchoolStatsWay.GetSingleSc(cosmosClient, "hbcn");
  1433. //return Ok(new { state = 200, ld= artStats.LastYear.Count, d = artStats.year.Count, artStats });
  1434. //示例矩阵
  1435. DateTimeOffset dt = DateTimeOffset.UtcNow;
  1436. int dayCnt = dt.DayOfYear;
  1437. List<double> set = new double[366].ToList();
  1438. List<List<double>> doubs = new() {
  1439. new List<double>() { 6, 5, 4, 3, 2, 1},
  1440. new List<double>() { 2, 3, 4, 5, 6, 7 }
  1441. };
  1442. var artTerm = DenseMatrix.OfColumns(doubs);
  1443. //var temp1 = artTerm.SetRow(1, 5);
  1444. var temp = artTerm.SubMatrix(1, 5, 0, artTerm.ColumnCount);
  1445. List<List<double>> doubles = new() {
  1446. new List<double>() { 6, 5, 4, 3, 2, 1},
  1447. new List<double>() { 2, 3, 4, 5, 6, 7 },
  1448. new List<double>() { 3, 4, 5, 6, 7, 8 },
  1449. new List<double>() { 4, 5, 6, 7, 8, 9 }
  1450. };
  1451. var artYear = DenseMatrix.OfColumns(doubles);
  1452. var rc = artYear.RowCount;
  1453. var cc = artYear.ColumnCount;
  1454. List<double> dous1 = new(); ;
  1455. List<double> dous = new(); ;
  1456. for (int i = 0; i < artYear.RowCount; i++)
  1457. {
  1458. Console.WriteLine($"次数:{i} ; 行数:{rc};列数:{cc}");
  1459. var cl = doubles.SelectMany(o => o.Skip(i).Take(1)).ToList();
  1460. var cl1 = doubles.SelectMany(o => o.Skip(i).Take(1)).ToList().Sum();
  1461. dous1.Add(cl1);
  1462. var stet = artYear.SubMatrix(i, 1, 0, cc);
  1463. var stet1 = artYear.SubMatrix(i, 1, 0, cc).ColumnSums().Sum();
  1464. dous.Add(stet1);
  1465. //var set = artYear.SubMatrix(0, 4, i, i+1).ColumnSums().Sum();
  1466. //dous.Add(set);
  1467. }
  1468. // double[][] matrix1 = new double[][]
  1469. // {
  1470. //new double[] { 1, 2, 3 },
  1471. //new double[] { 4, 5, 6 },
  1472. //new double[] { 7, 8, 9 }
  1473. // };
  1474. // double[][] matrix2 = new double[][]
  1475. // {
  1476. //new double[] { 2, 3, 4 },
  1477. //new double[] { 5, 6, 7 },
  1478. //new double[] { 8, 9, 10 }
  1479. // };
  1480. // //矩阵加法
  1481. // PrintMatrix(MatrixAdd(matrix1, matrix2));
  1482. // Console.WriteLine();
  1483. return Ok(new { state = 200, set ,dous1, dous /*tempSc*/ });
  1484. }
  1485. /// <summary>
  1486. /// 测试版本
  1487. /// </summary>
  1488. /// <param name="jsonElement"></param>
  1489. /// <returns></returns>
  1490. [HttpPost("set-sc-edittion")]
  1491. public async Task<IActionResult> SetSchoolEdition(JsonElement jsonElement)
  1492. {
  1493. var cosmosClient = _azureCosmos.GetCosmosClient();
  1494. if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
  1495. List<string> server = new();
  1496. _ = BISchoolService.UpSchoolEdition(cosmosClient, _dingDing, server, "hbcn");
  1497. return Ok(new { state = 200 });
  1498. }
  1499. /// <summary>
  1500. /// 每天执行一次
  1501. /// </summary>
  1502. /// <returns></returns>
  1503. public async Task<IActionResult> SetStatsZero()
  1504. {
  1505. await BIStats.SetStatsZeroPoint(_azureCosmos, _dingDing);
  1506. return Ok(new { });
  1507. }
  1508. /// <summary>
  1509. /// 测试依据类型增/减量统计方法
  1510. /// </summary>
  1511. /// <param name="json"></param>
  1512. /// <returns></returns>
  1513. [HttpPost("set-stats")]
  1514. public async Task<IActionResult> SetStats(JsonElement json)
  1515. {
  1516. var cosmosClient = _azureCosmos.GetCosmosClient();
  1517. //await BIStats.SetTypeAddStats(cosmosClient, "hbcn", "Less", 0, 1, 6);//BI统计增/减量
  1518. string scId = null, type = null;
  1519. long careDate = 0;
  1520. int count = 0;
  1521. int interaction = 0;
  1522. int lessType = 0;
  1523. DateTimeOffset cuurDateOff = DateTimeOffset.UtcNow;
  1524. DateTimeOffset dateOff = DateTimeOffset.UtcNow;
  1525. if (json.TryGetProperty("scId", out JsonElement _schoolId))
  1526. scId = $"{_schoolId}";
  1527. if (json.TryGetProperty("type", out JsonElement _type))
  1528. type = $"{_type}";
  1529. if (string.IsNullOrEmpty($"{_schoolId}") && string.IsNullOrEmpty($"{_type}"))
  1530. {
  1531. await _dingDing.SendBotMsg($"set-scstats-type, {json}", GroupNames.成都开发測試群組);
  1532. return Ok(new { state = RespondCode.ParamsError, msg = "参数错误!" });
  1533. }
  1534. if (json.TryGetProperty("cnt", out JsonElement _cnt))
  1535. count = _cnt.GetInt32();
  1536. if(json.TryGetProperty("interaction", out JsonElement _interaction))
  1537. interaction = _interaction.GetInt32();
  1538. if (json.TryGetProperty("lessType", out JsonElement _lessType))
  1539. lessType = _lessType.GetInt32();
  1540. if (json.TryGetProperty("date", out JsonElement _date))
  1541. careDate = _date.GetInt64();
  1542. else
  1543. careDate = dateOff.ToUnixTimeMilliseconds();
  1544. if (string.IsNullOrEmpty(scId))
  1545. return Ok(new { state = 400});
  1546. //DateTimeOffset cuurDateOff = DateTimeOffset.UtcNow;
  1547. //DateTimeOffset dateOff = DateTimeOffset.UtcNow;
  1548. if (careDate > 1000000000000)
  1549. dateOff = DateTimeOffset.FromUnixTimeMilliseconds(careDate);
  1550. else
  1551. dateOff = DateTimeOffset.FromUnixTimeSeconds(careDate);
  1552. if (careDate == 0)
  1553. {
  1554. dateOff = DateTimeOffset.UtcNow;
  1555. careDate = dateOff.ToUnixTimeMilliseconds();
  1556. }
  1557. var (lastWeekS, lastWeekE) = TimeHelper.GetStartOrEnd(dateOff, "lastweek"); //计算上周开始/结束时间
  1558. var (weekS, weekE) = TimeHelper.GetStartOrEnd(dateOff, "week"); //计算本周开始/结束时间
  1559. var (lastMonthS, lastMonthE) = TimeHelper.GetStartOrEnd(dateOff, "lastMonth"); //上月开始/结束时间
  1560. var (monthS, monthE) = TimeHelper.GetStartOrEnd(dateOff, "month"); //本月开始/结束时间
  1561. var (lastTermS, lastTermE) = TimeHelper.GetStartOrEnd(dateOff, "lastterm"); //计算上学期开始/结束时间
  1562. var (termS, termE) = TimeHelper.GetStartOrEnd(dateOff, "term"); //计算本学期开始/结束时间
  1563. var (yearS, yearE) = TimeHelper.GetStartOrEnd(cuurDateOff, "year"); //计算本学期开始/结束时间
  1564. var (weekDayS, weekDayE) = TimeHelper.GetLongToTime(weekS, weekE);
  1565. var (lWeekDayS, lWeekDayE) = TimeHelper.GetLongToTime(lastWeekS, lastWeekE);
  1566. var (lTermDayS, lTermDayE) = TimeHelper.GetLongToTime(lastTermS, lastTermE);
  1567. var (termDayS, termDayE) = TimeHelper.GetLongToTime(lastTermS, lastTermE);
  1568. var (lMonthS, lMonthE) = TimeHelper.GetLongToTime(lastMonthS, lastMonthE);
  1569. var (monthDayS, monthDayE) = TimeHelper.GetLongToTime(monthS, monthE);
  1570. var lastDay = dateOff.AddDays(-1);
  1571. int lmthDay = TimeHelper.GetDateDay(lMonthE);
  1572. StatsInfo statsInfo = new();
  1573. var resStsInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync($"{dateOff.Year}-{scId}", new PartitionKey("Statistics"));
  1574. if (resStsInfo.Status == 200)
  1575. {
  1576. using var fileJson = await JsonDocument.ParseAsync(resStsInfo.ContentStream);
  1577. statsInfo = fileJson.ToObject<StatsInfo>();
  1578. }
  1579. else
  1580. {
  1581. var resLastStsInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync($"{dateOff.Year - 1}-{scId}", new PartitionKey("Statistics"));
  1582. if (resLastStsInfo.Status == 200)
  1583. {
  1584. using var fileJson = await JsonDocument.ParseAsync(resStsInfo.ContentStream);
  1585. statsInfo = fileJson.ToObject<StatsInfo>();
  1586. statsInfo.id = $"{dateOff.Year}-{scId}";
  1587. statsInfo.year = dateOff.Year;
  1588. statsInfo.stuYear = new double[366].ToList();
  1589. statsInfo.tchYear = new double[366].ToList();
  1590. statsInfo.lesson.year = new double[366].ToList();
  1591. statsInfo.lesson.yearInters = new double[366].ToList();
  1592. statsInfo.activity.year = new double[366].ToList();
  1593. }
  1594. else
  1595. {
  1596. ScBase scBase = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<ScBase>(scId, new PartitionKey("Base"));
  1597. statsInfo.id = $"{dateOff.Year}-{scBase.id}";
  1598. statsInfo.schoolId = scBase.id;
  1599. statsInfo.name = scBase.name;
  1600. statsInfo.picture = scBase.picture;
  1601. statsInfo.size = scBase.size;
  1602. statsInfo.scCreateTime = scBase.createTime;
  1603. statsInfo.areaId = scBase.areaId;
  1604. statsInfo.upTime = careDate;
  1605. statsInfo.stuYear = new double[366].ToList();
  1606. statsInfo.tchYear = new double[366].ToList();
  1607. statsInfo.lesson.year = new double[366].ToList();
  1608. statsInfo.lesson.yearInters = new double[366].ToList();
  1609. statsInfo.activity.year = new double[366].ToList();
  1610. }
  1611. }
  1612. switch ($"{type}")
  1613. {
  1614. case "Exam":
  1615. statsInfo.activity.exam += count;
  1616. break;
  1617. case "Survey":
  1618. statsInfo.activity.survey += count;
  1619. break;
  1620. case "Vote":
  1621. statsInfo.activity.vote += count;
  1622. break;
  1623. case "Homework":
  1624. statsInfo.activity.homework += count;
  1625. break;
  1626. case "Less":
  1627. //课例
  1628. statsInfo.lesson.year[dateOff.DayOfYear] += count;
  1629. statsInfo.lesson.all += count;
  1630. if (lessType == 0)
  1631. statsInfo.lesson.open += count;
  1632. else
  1633. statsInfo.lesson.less += count;
  1634. statsInfo.lesson.lastDay = ((int)statsInfo.lesson.year[lastDay.DayOfYear]);
  1635. statsInfo.lesson.day = ((int)statsInfo.lesson.year[dateOff.DayOfYear]);
  1636. var lessList = DenseMatrix.OfColumns(new List<List<double>>() { statsInfo.lesson.year });
  1637. statsInfo.lesson.lastWeek = ((int)lessList.SubMatrix(lWeekDayS.DayOfYear, lWeekDayE.DayOfYear - lWeekDayS.DayOfYear, 0, lessList.ColumnCount).ColumnSums().Sum());
  1638. statsInfo.lesson.week = ((int)lessList.SubMatrix(weekDayS.DayOfYear, (dateOff.DayOfYear - weekDayS.DayOfYear), 0, lessList.ColumnCount).ColumnSums().Sum());
  1639. StatsInfo lastStats = null;
  1640. var resLast = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync($"{lTermDayS.Year}-{scId}", new PartitionKey("Statistics"));
  1641. if (resLast.Status == 200)
  1642. {
  1643. using var fileJson = await JsonDocument.ParseAsync(resLast.ContentStream);
  1644. lastStats = fileJson.ToObject<StatsInfo>();
  1645. }
  1646. int lastTerm = 0;
  1647. if (lTermDayS.Year < dateOff.Year)
  1648. {
  1649. if (lastStats != null)
  1650. {
  1651. var actYer = DenseMatrix.OfColumns(new List<List<double>>() { lastStats.lesson.year });
  1652. lastTerm += ((int)actYer.SubMatrix(lTermDayS.DayOfYear, lastStats.lesson.year.Count - lTermDayS.DayOfYear, 0, 1).ColumnSums().Sum());
  1653. }
  1654. lastTerm += ((int)lessList.SubMatrix(0, lTermDayE.DayOfYear, 0, lessList.ColumnCount).ColumnSums().Sum());
  1655. }
  1656. else
  1657. lastTerm += ((int)lessList.SubMatrix(lTermDayS.DayOfYear, lTermDayE.DayOfYear - lTermDayS.DayOfYear, 0, lessList.ColumnCount).ColumnSums().Sum());
  1658. statsInfo.lesson.lastTerm = lastTerm;
  1659. int term = 0;
  1660. if (termDayE.Year > dateOff.Year)
  1661. {
  1662. if (lastStats != null)
  1663. term = ((int)lessList.SubMatrix(termDayS.DayOfYear, (statsInfo.lesson.year.Count - termDayS.DayOfYear), 0, lessList.ColumnCount).ColumnSums().Sum());
  1664. }
  1665. else
  1666. term = ((int)lessList.SubMatrix(termDayS.DayOfYear, termDayE.DayOfYear - termDayS.DayOfYear, 0, lessList.ColumnCount).ColumnSums().Sum());
  1667. statsInfo.lesson.term = term;
  1668. statsInfo.lesson.lastMonth = ((int)lessList.SubMatrix(lMonthS.DayOfYear, lmthDay, 0, lessList.ColumnCount).ColumnSums().Sum());
  1669. statsInfo.lesson.month += ((int)lessList.SubMatrix(monthDayS.DayOfYear, (dateOff.DayOfYear - monthDayS.DayOfYear), 0, lessList.ColumnCount).ColumnSums().Sum());
  1670. //课例互动
  1671. statsInfo.lesson.yearInters[dateOff.DayOfYear] += interaction;
  1672. statsInfo.lesson.allInter += interaction;
  1673. statsInfo.lesson.lastDayInter = ((int)statsInfo.lesson.yearInters[lastDay.DayOfYear]);
  1674. statsInfo.lesson.dayInter = ((int)statsInfo.lesson.yearInters[dateOff.DayOfYear]);
  1675. var interList = DenseMatrix.OfColumns(new List<List<double>>() { statsInfo.lesson.yearInters });
  1676. statsInfo.lesson.lastMonthInter = ((int)interList.SubMatrix(lMonthS.DayOfYear, lmthDay, 0, interList.ColumnCount).ColumnSums().Sum());
  1677. statsInfo.lesson.monthInter += ((int)interList.SubMatrix(monthDayS.DayOfYear, (dateOff.DayOfYear - monthDayS.DayOfYear), 0, interList.ColumnCount).ColumnSums().Sum());
  1678. int lastTermI = 0;
  1679. if (lastStats != null)
  1680. {
  1681. var actYer = DenseMatrix.OfColumns(new List<List<double>>() { lastStats.lesson.year });
  1682. lastTermI += ((int)actYer.SubMatrix(0, lastStats.lesson.year.Count, 0, actYer.ColumnCount).ColumnSums().Sum());
  1683. }
  1684. statsInfo.lesson.lastYearInter = lastTermI;
  1685. statsInfo.lesson.upTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1686. break;
  1687. case "Student":
  1688. statsInfo.stuYear[dateOff.DayOfYear] += count;
  1689. statsInfo.stu += count;
  1690. statsInfo.dayStu = ((int)statsInfo.stuYear[dateOff.DayOfYear]);
  1691. var stuList = DenseMatrix.OfColumns(new List<List<double>>() { statsInfo.stuYear });
  1692. statsInfo.weekStu = ((int)stuList.SubMatrix(weekDayS.DayOfYear, (dateOff.DayOfYear - weekDayS.DayOfYear), 0, stuList.ColumnCount).ColumnSums().Sum());
  1693. statsInfo.monthStu = ((int)stuList.SubMatrix(monthDayS.DayOfYear, (dateOff.DayOfYear - monthDayS.DayOfYear), 0, stuList.ColumnCount).ColumnSums().Sum());
  1694. statsInfo.stuUpTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1695. break;
  1696. case "Teacher":
  1697. statsInfo.tchYear[dateOff.DayOfYear] += count;
  1698. statsInfo.tch += count;
  1699. statsInfo.dayTch = ((int)statsInfo.tchYear[dateOff.DayOfYear]);
  1700. var tchList = DenseMatrix.OfColumns(new List<List<double>>() { statsInfo.tchYear });
  1701. statsInfo.weekTch = ((int)tchList.SubMatrix(weekDayS.DayOfYear, (dateOff.DayOfYear - weekDayS.DayOfYear), 0, tchList.ColumnCount).ColumnSums().Sum());
  1702. statsInfo.monthTch = ((int)tchList.SubMatrix(monthDayS.DayOfYear, (dateOff.DayOfYear - monthDayS.DayOfYear), 0, tchList.ColumnCount).ColumnSums().Sum());
  1703. statsInfo.tchUpTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1704. break;
  1705. }
  1706. if ($"{type}".Equals("Exam") || $"{type}".Equals("Survey") || $"{type}".Equals("Vote") || $"{type}".Equals("Homework"))
  1707. {
  1708. statsInfo.activity.all += count;
  1709. if (careDate >= yearS && careDate <= yearE)
  1710. {
  1711. if (count > 0)
  1712. {
  1713. statsInfo.activity.year[dateOff.DayOfYear] += count;
  1714. DenseMatrix matris = DenseMatrix.OfColumns(new List<List<double>>() { statsInfo.activity.year });
  1715. statsInfo.activity.lastDay = ((int)statsInfo.activity.year[lastDay.DayOfYear]);
  1716. statsInfo.activity.dayCnt = ((int)statsInfo.activity.year[dateOff.DayOfYear]);
  1717. statsInfo.activity.lastWeek = ((int)matris.SubMatrix(lWeekDayS.DayOfYear, lWeekDayE.DayOfYear- lWeekDayS.DayOfYear, 0, matris.ColumnCount).ColumnSums().Sum());
  1718. statsInfo.activity.week = ((int)matris.SubMatrix(weekDayS.DayOfYear, weekDayE.DayOfYear - weekDayS.DayOfYear, 0, matris.ColumnCount).ColumnSums().Sum());
  1719. StatsInfo lastStats = null;
  1720. var resLast = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").ReadItemStreamAsync($"{lTermDayS.Year}-{scId}", new PartitionKey("Statistics"));
  1721. if (resLast.Status == 200)
  1722. {
  1723. using var fileJson = await JsonDocument.ParseAsync(resLast.ContentStream);
  1724. lastStats = fileJson.ToObject<StatsInfo>();
  1725. }
  1726. int lastTerm = 0;
  1727. if (lTermDayS.Year < dateOff.Year)
  1728. {
  1729. if (lastStats != null)
  1730. {
  1731. var actYer = DenseMatrix.OfColumns(new List<List<double>>() { lastStats.lesson.year });
  1732. lastTerm += ((int)actYer.SubMatrix(lTermDayS.DayOfYear, lastStats.lesson.year.Count - lTermDayS.DayOfYear, 0, 1).ColumnSums().Sum());
  1733. }
  1734. lastTerm += ((int)matris.SubMatrix(0, lTermDayE.DayOfYear, 0, matris.ColumnCount).ColumnSums().Sum());
  1735. }
  1736. else
  1737. lastTerm += ((int)matris.SubMatrix(lTermDayS.DayOfYear, lTermDayE.DayOfYear- lTermDayS.DayOfYear, 0, matris.ColumnCount).ColumnSums().Sum());
  1738. statsInfo.activity.lastTerm = lastTerm;
  1739. int term = 0;
  1740. if (termDayS.Year > dateOff.Year)
  1741. {
  1742. if (lastStats != null)
  1743. {
  1744. var actYer = DenseMatrix.OfColumns(new List<List<double>>() { lastStats.lesson.year });
  1745. term += ((int)actYer.SubMatrix(termDayS.DayOfYear, lastStats.lesson.year.Count - termDayS.DayOfYear, 0, 1).ColumnSums().Sum());
  1746. }
  1747. term += ((int)matris.SubMatrix(0, termDayE.DayOfYear, 0, matris.ColumnCount).ColumnSums().Sum());
  1748. }
  1749. else
  1750. term += ((int)matris.SubMatrix(termDayS.DayOfYear, termDayE.DayOfYear - termDayS.DayOfYear, 0, matris.ColumnCount).ColumnSums().Sum());
  1751. statsInfo.activity.term = term;
  1752. statsInfo.activity.lastMonth = ((int)matris.SubMatrix(lMonthS.DayOfYear, lmthDay, 0, matris.ColumnCount).ColumnSums().Sum());
  1753. statsInfo.activity.month += ((int)matris.SubMatrix(monthDayS.DayOfYear, (dateOff.DayOfYear - monthDayS.DayOfYear), 0, matris.ColumnCount).ColumnSums().Sum());
  1754. statsInfo.activity.upTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
  1755. }
  1756. }
  1757. }
  1758. if (resStsInfo.Status == 200)
  1759. statsInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").ReplaceItemAsync<StatsInfo>(statsInfo, statsInfo.id, new PartitionKey("Statistics"));
  1760. else
  1761. statsInfo = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync<StatsInfo>(statsInfo, new PartitionKey("Statistics"));
  1762. return Ok(new { state = 200, statsInfo });
  1763. }
  1764. public class linqTest
  1765. {
  1766. public string id { get; set; }
  1767. public string aresid { get; set; }
  1768. public string name { get; set; }
  1769. public linq1 linq1 { get; set; }
  1770. }
  1771. public class linq1
  1772. {
  1773. public string id { get; set; }
  1774. public long times { get; set; }
  1775. public int cnt { get; set; }
  1776. }
  1777. public class Test
  1778. {
  1779. public int age { get; set; }
  1780. public string name { get; set; }
  1781. public int score { get; set; }
  1782. }
  1783. public class strend
  1784. {
  1785. public int id { get; set; }
  1786. public string name { get; set; }
  1787. public int age { get; set; }
  1788. }
  1789. struct MyStruct
  1790. {
  1791. public int Count { get; set; }
  1792. }
  1793. class Example
  1794. {
  1795. public string? Name { get; set; }
  1796. public string Value { get; set; }
  1797. }
  1798. public record TempSchool
  1799. {
  1800. public long ts { get; set; }
  1801. public string id { get; set; }
  1802. public string name { get; set; }
  1803. }
  1804. public static (long month, long dayEnd) GetMonthStart(DateTimeOffset dt)
  1805. {
  1806. DateTime dtNew = new DateTime(dt.Year, dt.Month, 1);
  1807. long month = DateTimeOffset.Parse($"{dtNew}").ToUnixTimeSeconds();
  1808. var ste = dtNew.AddMonths(1).AddDays(-1).Day;
  1809. long dayTime = DateTimeOffset.Parse($"{dt.Year}-{dt.Month}-{ste} 23:59:59").ToUnixTimeSeconds();
  1810. return (month, dayTime);
  1811. }
  1812. public class GenerateRandom1
  1813. {
  1814. /// <summary>
  1815. /// 生成随机数字
  1816. /// </summary>
  1817. /// <param name="length">生成长度</param>
  1818. /// <returns></returns>
  1819. public static string Number(int Length)
  1820. {
  1821. return Number(Length, false);
  1822. }
  1823. /// <summary>
  1824. /// 生成随机数字
  1825. /// </summary>
  1826. /// <param name="Length">生成长度</param>
  1827. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  1828. /// <returns></returns>
  1829. public static string Number(int Length, bool Sleep)
  1830. {
  1831. if (Sleep)
  1832. System.Threading.Thread.Sleep(3);
  1833. string result = "";
  1834. System.Random random = new Random();
  1835. for (int i = 0; i < Length; i++)
  1836. {
  1837. result += random.Next(10).ToString();
  1838. }
  1839. return result;
  1840. }
  1841. /// <summary>
  1842. /// 生成随机字母与数字
  1843. /// </summary>
  1844. /// <param name="IntStr">生成长度</param>
  1845. /// <returns></returns>
  1846. public static string Str(int Length)
  1847. {
  1848. return Str(Length, false);
  1849. }
  1850. /// <summary>
  1851. /// 生成随机字母与数字
  1852. /// </summary>
  1853. /// <param name="Length">生成长度</param>
  1854. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  1855. /// <returns></returns>
  1856. public static string Str(int Length, bool Sleep)
  1857. {
  1858. if (Sleep)
  1859. System.Threading.Thread.Sleep(3);
  1860. 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' };
  1861. string result = "";
  1862. int n = Pattern.Length;
  1863. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  1864. for (int i = 0; i < Length; i++)
  1865. {
  1866. int rnd = random.Next(0, n);
  1867. result += Pattern[rnd];
  1868. }
  1869. return result;
  1870. }
  1871. /// <summary>
  1872. /// 生成随机纯字母随机数
  1873. /// </summary>
  1874. /// <param name="IntStr">生成长度</param>
  1875. /// <returns></returns>
  1876. public static string Str_char(int Length)
  1877. {
  1878. return Str_char(Length, false);
  1879. }
  1880. /// <summary>
  1881. /// 生成随机纯字母随机数
  1882. /// </summary>
  1883. /// <param name="Length">生成长度</param>
  1884. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  1885. /// <returns></returns>
  1886. public static string Str_char(int Length, bool Sleep)
  1887. {
  1888. if (Sleep) System.Threading.Thread.Sleep(3);
  1889. //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' };
  1890. 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' };
  1891. string result = "";
  1892. int n = Pattern.Length;
  1893. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  1894. for (int i = 0; i < Length; i++)
  1895. {
  1896. int rnd = random.Next(0, n);
  1897. result += Pattern[rnd];
  1898. }
  1899. return result;
  1900. }
  1901. }
  1902. }
  1903. }