TestController.cs 77 KB

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