TestController.cs 98 KB

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