TestController.cs 108 KB

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