TestController.cs 75 KB

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