TestController.cs 76 KB

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