TestController.cs 84 KB

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