TestController.cs 110 KB

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