TestController.cs 96 KB

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