TestController.cs 85 KB

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