TestController.cs 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667
  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.Tool.Context;
  48. using TEAMModelBI.DI.BIAzureStorage;
  49. using TEAMModelOS.SDK.Models.Service.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> endList = TimeHelper.GetYearMonthlyStartEnd10(DateTimeOffset.UtcNow.Year);
  624. List<MonthStartEnd> endList1 = TimeHelper.GetYearMonthlyStartEnd13(DateTimeOffset.UtcNow.Year);
  625. //return Ok(new { strList, dateTime, year, start, end, endList, endList1, endList2 });
  626. return Ok(new { datetime7, start1, end1, start2, end2, start3, end3, start4, end4 , start5, end5 , start6, end6 , start7, end7 });
  627. }
  628. public static List<string> monthsOfYear(string yearMonth)
  629. {
  630. DateTime dateTime = DateTime.Parse(yearMonth);
  631. int year = dateTime.Year;
  632. int month = dateTime.Month;
  633. List<string> months = new List<string>();
  634. while (year > dateTime.Year - 1 || month > dateTime.Month)
  635. {
  636. months.Add($"{year}-{(month < 10 ? "0" : "") + month}");
  637. month -= 1;
  638. if (month <= 0)
  639. {
  640. year -= 1;
  641. month = 12;
  642. }
  643. }
  644. return months;
  645. }
  646. /// <summary>
  647. /// 统计一年中每月得新增校
  648. /// </summary>
  649. /// <returns></returns>
  650. [HttpPost("get-yearmonth")]
  651. public async Task<IActionResult> GetYearMonth()
  652. {
  653. var cosmosClient = _azureCosmos.GetCosmosClient();
  654. Dictionary<int, long> tempYear = new Dictionary<int, long>();
  655. List<TempSchool> tempSchools = new List<TempSchool>();
  656. for (int i = 1; i < 13; i++)
  657. {
  658. var start = 00022222330;
  659. long tempCount = 0;
  660. 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") }))
  661. {
  662. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  663. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt64() > 0)
  664. {
  665. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  666. {
  667. TempSchool tempSchool = new TempSchool();
  668. tempSchool.id = obj.GetProperty("id").GetString();
  669. tempSchool.ts = obj.GetProperty("_ts").GetInt64();
  670. tempSchool.name = obj.GetProperty("name").GetString();
  671. tempSchools.Add(tempSchool);
  672. }
  673. tempCount += count.GetInt64();
  674. }
  675. }
  676. if (tempCount != 0)
  677. {
  678. tempYear.Add(i, tempCount);
  679. }
  680. }
  681. return Ok(new { state = 200, tempYear, tempSchools });
  682. }
  683. /// <summary>
  684. /// 测试.net 6 的一些特性
  685. /// </summary>
  686. /// <returns></returns>
  687. [HttpPost("get-newnet6")]
  688. public async Task<IActionResult> GetNewNet6()
  689. {
  690. ///PriorityQueue
  691. //.NET 6 新增的数据结构, PriorityQueue, 队列每个元素都有一个关联的优先级,它决定了出队顺序, 编号小的元素优先出列。
  692. PriorityQueue<string, int> priorityQueue = new();
  693. priorityQueue.Enqueue("Second", 2);
  694. priorityQueue.Enqueue("Fourth", 4);
  695. priorityQueue.Enqueue("Third 1", 3);
  696. priorityQueue.Enqueue("Third 2", 5);
  697. priorityQueue.Enqueue("First", 1);
  698. while (priorityQueue.Count > 0)
  699. {
  700. string item = priorityQueue.Dequeue();
  701. Console.WriteLine(item);
  702. }
  703. //PeriodicTimer
  704. //认识一个完全异步的“PeriodicTimer”, 更适合在异步场景中使用, 它有一个方法 WaitForNextTickAsync。
  705. //using PeriodicTimer timer = new(TimeSpan.FromSeconds(2));
  706. //while (await timer.WaitForNextTickAsync())
  707. //{
  708. // Console.WriteLine(DateTime.UtcNow);
  709. //}
  710. //检查元素是否可为空的反射API
  711. var example = new Example();
  712. var nullabilityInfoContext = new NullabilityInfoContext();
  713. foreach (var propertyInfo in example.GetType().GetProperties())
  714. {
  715. var nullabilityInfo = nullabilityInfoContext.Create(propertyInfo);
  716. Console.WriteLine($"{propertyInfo.Name} property is {nullabilityInfo.WriteState}");
  717. }
  718. //直接通过 Environment 获取进程ID和路径。
  719. int processId = Environment.ProcessId;
  720. string path = Environment.ProcessPath;
  721. Console.WriteLine(processId);
  722. Console.WriteLine(path);
  723. //CSPNG 密码安全伪随机数生成器
  724. byte[] bytes = RandomNumberGenerator.GetBytes(300);
  725. Console.WriteLine(string.Join("", bytes.ToArray()));
  726. //Power of 2
  727. //.NET 6 引入了用于处理 2 的幂的新方法。
  728. //‘IsPow2’ 判断指定值是否为 2 的幂。
  729. //‘RoundUpToPowerOf2’ 将指定值四舍五入到 2 的幂
  730. Console.WriteLine(BitOperations.IsPow2(121)); // True
  731. Console.WriteLine(BitOperations.RoundUpToPowerOf2(260)); // 256
  732. //WaitAsync on Task 您可以更轻松地等待异步任务执行, 如果超时会抛出 “TimeoutException”
  733. Task operationTask = DoSomethingLongAsync();
  734. await operationTask.WaitAsync(TimeSpan.FromSeconds(5));
  735. async Task DoSomethingLongAsync()
  736. {
  737. Console.WriteLine("DoSomethingLongAsync started.");
  738. await Task.Delay(TimeSpan.FromSeconds(10));
  739. Console.WriteLine("DoSomethingLongAsync ended.");
  740. }
  741. //新的数学API
  742. // New methods SinCos, ReciprocalEstimate and ReciprocalSqrtEstimate
  743. // Simultaneously computes Sin and Cos
  744. (double sin, double cos) = Math.SinCos(1.57);
  745. Console.WriteLine($"Sin = {sin}\nCos = {cos}");
  746. // Computes an approximate of 1 / x
  747. double recEst = Math.ReciprocalEstimate(5);
  748. Console.WriteLine($"Reciprocal estimate = {recEst}");
  749. // Computes an approximate of 1 / Sqrt(x)
  750. double recSqrtEst = Math.ReciprocalSqrtEstimate(5);
  751. Console.WriteLine($"Reciprocal sqrt estimate = {recSqrtEst}");
  752. // New overloads
  753. // Min, Max, Abs, Clamp and Sign supports nint and nuint
  754. (nint a, nint b) = (5, 10);
  755. nint min = Math.Min(a, b);
  756. nint max = Math.Max(a, b);
  757. nint abs = Math.Abs(a);
  758. nint clamp = Math.Clamp(abs, min, max);
  759. nint sign = Math.Sign(a);
  760. Console.WriteLine($"Min = {min}\nMax = {max}\nAbs = {abs}");
  761. Console.WriteLine($"Clamp = {clamp}\nSign = {sign}");
  762. // DivRem variants return a tuple
  763. (int quotient, int remainder) = Math.DivRem(2, 7);
  764. Console.WriteLine($"Quotient = {quotient}\nRemainder = {remainder}");
  765. //CollectionsMarshal.GetValueRefOrNullRef
  766. //这个是在字典中循环或者修改结可变结构体时用, 可以减少结构的副本复制, 也可以避免字典重复进行哈希计算,这个有点晦涩难懂
  767. Dictionary<int, MyStruct> dictionary = new()
  768. {
  769. { 1, new MyStruct { Count = 100 } }
  770. };
  771. int key = 1;
  772. MyStruct values = CollectionsMarshal.GetValueRefOrNullRef(dictionary, key);
  773. // Returns Unsafe.NullRef<TValue>() if it doesn't exist; check using Unsafe.IsNullRef(ref value)
  774. if (!Unsafe.IsNullRef(ref values))
  775. {
  776. Console.WriteLine(values.Count); // Output: 100
  777. // Mutate in-place
  778. values.Count++;
  779. Console.WriteLine(values.Count); // Output: 101
  780. }
  781. return Ok(new { state = 200 });
  782. }
  783. /// <summary>
  784. /// 去重、判断
  785. /// </summary>
  786. /// <param name="jsonElement"></param>
  787. /// <returns></returns>
  788. [HttpPost("get-repeat")]
  789. public async Task<IActionResult> GetRepeat(JsonElement jsonElement)
  790. {
  791. jsonElement.TryGetProperty("datetime", out JsonElement _datetime);
  792. Dictionary<string, string> prodict = new Dictionary<string, string>() { { "YMPCVCIM", "学情分析模组" }, { "IPDYZYLC", "智慧学校管理服务" }, { "3CLYJ6NP", "AClass ONE智慧学伴" }, { "IPALJ6NY", "数据储存服务空间" },{ "VABAJ6NV", "卷卡合一阅卷系统" } };
  793. var ste = prodict["IPDYZYLC"];
  794. List<string> str_str = new List<string>() { "12", "20", "13", "13", "14", "16" };
  795. 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 } };
  796. //str_str.Distinct().ToList();
  797. strends.Where((x, i) => strends.FindIndex(z => z.id.Equals(x.id)) == i).ToList();
  798. List<strend> str_strend1 = strends.Where((x, i) => strends.FindIndex(z => z.id.Equals(x.id)) == i).ToList();
  799. List<strend> str_strend2 = strends.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
  800. DateTime dt = DateTime.Parse($"{_datetime}");
  801. int year = dt.Year;
  802. DateTime dt0 = new DateTime(year, 1, 1);
  803. int days = (dt.Date - dt0.Date).Days + 1;
  804. //int pydays = ((lastYear + 1) % 4 == 0 && (lastYear + 1) % 100 != 0 || (lastYear + 1) % 400 == 0) ? 366 : 365;
  805. int pydays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
  806. //int pydays = DateTimeHelper.getDays(year);
  807. return Ok(new { state = 200, pydays, days, strends , str_strend1, str_strend2 , ste });
  808. }
  809. /// <summary>
  810. /// 计算天数
  811. /// </summary>
  812. /// <param name="jsonElement"></param>
  813. /// <returns></returns>
  814. [HttpPost("get-dateday")]
  815. public async Task<IActionResult> GetDateDay(JsonElement jsonElement)
  816. {
  817. jsonElement.TryGetProperty("year", out JsonElement _year);
  818. jsonElement.TryGetProperty("moth", out JsonElement _moth);
  819. int year = int.Parse($"{_year}");
  820. int day = 0;
  821. List<int> moths = _moth.ToObject<List<int>>();
  822. foreach (var item in moths)
  823. {
  824. int days = 0;
  825. switch (item)
  826. {
  827. case 1:
  828. case 3:
  829. case 5:
  830. case 7:
  831. case 8:
  832. case 10:
  833. case 12:
  834. days = 31;
  835. break;
  836. case 4:
  837. case 6:
  838. case 9:
  839. case 11:
  840. days = 30;
  841. break;
  842. case 2:
  843. int years = 0;
  844. if (item <= 8 && item >= 3)
  845. years = year;
  846. else
  847. years = year+1;
  848. if (years % 4 == 0 && year % 100 != 0 || year % 400 == 0)
  849. days = 29;
  850. else
  851. days = 28;
  852. break;
  853. }
  854. day += days;
  855. }
  856. return Ok(new { state = 200, day });
  857. }
  858. /// <summary>
  859. /// 测试CosmosDB分页查询 SQL语句分页
  860. /// </summary>
  861. /// <param name="jsonElement"></param>
  862. /// <returns></returns>
  863. [HttpPost("get-page")]
  864. public async Task<IActionResult> cosmosDBPage(JsonElement jsonElement)
  865. {
  866. if (!jsonElement.TryGetProperty("pageSize", out JsonElement pageSize)) return BadRequest();
  867. if (!jsonElement.TryGetProperty("endPosition", out JsonElement endPosition)) return BadRequest();
  868. var cosmosClient = _azureCosmos.GetCosmosClient();
  869. List<School> schools = new List<School>();
  870. //string sqlTxt = $"SELECT * FROM c where c.code='Base' order by c.id offset {endPosition} limit {pageSize}";
  871. string sqlTxt = $"SELECT * FROM c order by c.id offset {pageSize} limit {endPosition}";
  872. await foreach (var tempPage in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlTxt, requestOptions:new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
  873. {
  874. using var json = await JsonDocument.ParseAsync(tempPage.ContentStream);
  875. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt16() > 0)
  876. {
  877. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  878. {
  879. schools.Add(obj.ToObject<School>());
  880. }
  881. }
  882. }
  883. IAsyncResult iAsyncResult = null;
  884. return Ok(new { state = 200, schools });
  885. }
  886. /// <summary>
  887. /// 分页案例
  888. /// </summary>
  889. /// <param name="jsonElement"></param>
  890. /// <returns></returns>
  891. [HttpPost("get-cosmodbtokenpage")]
  892. public async Task<IActionResult> GetCancellationTokenPage(JsonElement jsonElement)
  893. {
  894. var cosmosClient = _azureCosmos.GetCosmosClient();
  895. //默认不指定返回大小
  896. int? pageSize = null;
  897. string continuationToken = string.Empty;
  898. string pageToken = default;
  899. if (jsonElement.TryGetProperty("pageSize", out JsonElement jsonPageSize))
  900. {
  901. if (!jsonPageSize.ValueKind.Equals(JsonValueKind.Undefined) && !jsonPageSize.ValueKind.Equals(JsonValueKind.Null) && jsonPageSize.TryGetInt32(out int tempPageSize))
  902. {
  903. pageSize = tempPageSize;
  904. }
  905. }
  906. //是否需要进行分页查询,默认不分页
  907. bool iscontinuation = false;
  908. if (pageSize != null && pageSize.Value > 0)
  909. {
  910. iscontinuation = true;
  911. }
  912. if (jsonElement.TryGetProperty("contToken", out JsonElement ContToken))
  913. {
  914. pageToken = ContToken.GetString();
  915. }
  916. List<School> schools = new();
  917. 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") }))
  918. {
  919. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  920. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  921. {
  922. foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
  923. {
  924. schools.Add(obj.ToObject<School>());
  925. }
  926. if (iscontinuation)
  927. {
  928. continuationToken = item.GetContinuationToken();
  929. break;
  930. }
  931. }
  932. }
  933. return Ok(new { state = 200, continuationToken, count = schools.Count, schools });
  934. }
  935. /// <summary>
  936. /// 测试隐式登录
  937. /// </summary>
  938. /// <returns></returns>
  939. [HttpPost("get-implicit")]
  940. public async Task<IActionResult> GetImplicit()
  941. {
  942. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  943. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  944. var location = _option.Location;
  945. if (location.Contains("China"))
  946. {
  947. location = "China";
  948. }
  949. else if (location.Contains("Global"))
  950. {
  951. location = "Global";
  952. }
  953. var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
  954. if (_httpClient.DefaultRequestHeaders.Contains("Authorization"))
  955. {
  956. _httpClient.DefaultRequestHeaders.Remove("Authorization");
  957. }
  958. _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
  959. var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  960. url = $"{url}/oauth2/implicit";
  961. Dictionary<string, string> data = new()
  962. {
  963. { "grant_type", "implicit" },
  964. { "client_id", clientID },
  965. { "account", "1636016499" },
  966. { "nonce", Guid.NewGuid().ToString() }
  967. };
  968. HttpResponseMessage responseMessage = await _httpClient.PostAsJsonAsync(url, data);
  969. if (responseMessage.StatusCode == HttpStatusCode.OK) //BI连接字符
  970. {
  971. string content = await responseMessage.Content.ReadAsStringAsync();
  972. }
  973. return Ok(new { state = 200, token, responseMessage });
  974. }
  975. /// <summary>
  976. /// 测试
  977. /// </summary>
  978. /// <param name="jsonElement"></param>
  979. /// <returns></returns>
  980. [HttpPost("get-test")]
  981. public async Task<IActionResult> GetTest(JsonElement jsonElement)
  982. {
  983. List<Test> list1 = new();
  984. list1.Add(new Test { score = 10, name = "001" });
  985. list1.Add(new Test { score = 20, name = "002" });
  986. list1.Add(new Test { score = 30, name = "003" });
  987. list1.Add(new Test { score = 40, name = "004" });
  988. list1.Add(new Test { score = 50, name = "005" });
  989. list1.Add(new Test { score = 60, name = "006" });
  990. List<Test> list2 = new();
  991. list2.Add(new Test { score = 40, name = "004" });
  992. list2.Add(new Test { score = 50, name = "005" });
  993. list2.Add(new Test { score = 60, name = "006" });
  994. list2.Add(new Test { score = 70, name = "007" });
  995. list2.Add(new Test { score = 80, name = "008" });
  996. list2.Add(new Test { score = 90, name = "009" });
  997. list2.Add(new Test { score = 100, name = "010" });
  998. //list3 return 2
  999. List<Test> list3 = list1.Where(x => !list2.Any(x2 => x.score == x2.score && x.name==x2.name)).ToList();
  1000. //list4 return 2
  1001. List<Test> list4 = list1.Where(x => list2.All(x2 => x.score != x2.score)).ToList();
  1002. List<Test> temp = list1.Where(p => !list2.Select(b => b.score).Contains(p.score)).ToList();
  1003. //List<Test> mergedList = new List<Test>(list1);
  1004. //mergedList.AddRange(list2.Except(list1));
  1005. // var mergedList = list1.Union(list2);
  1006. var en2 = list1.Concat(list2).Except(list1.Intersect(list2));// 容斥原理
  1007. var bingji = list1.Union(list2).ToList();//并(全)集
  1008. var cha = bingji.GroupBy(x => x.score).Select(c => c.First()).ToList();
  1009. var jiaoji = list1.Intersect(list2).ToList();//交集
  1010. var chaji = list1.Except(list2).ToList();//差集
  1011. List<Test> have = list1.Where(a => !list2.Exists(t => a.score == t.score)).ToList();
  1012. have.AddRange(list2.Where(a => !list1.Exists(t => a.score == t.score)).ToList());
  1013. var ss = DateTime.Now.AddDays(0 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7).ToString("yyyy-MM-dd");//上周日
  1014. var sss = DateTime.Now.AddDays(6 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7).ToString("yyyy-MM-dd");//上周六
  1015. var ssss = DateTime.Now.AddDays(1 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7+1).ToString("yyyy-MM-dd");//上周一
  1016. var sssss = DateTime.Now.AddDays(7 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7+1).ToString("yyyy-MM-dd");//上周日
  1017. //计算上周
  1018. var date = DateTime.Now;
  1019. var m = (date.DayOfWeek == DayOfWeek.Sunday ? (DayOfWeek)7 : date.DayOfWeek) - DayOfWeek.Monday;
  1020. var s = (date.DayOfWeek == DayOfWeek.Sunday ? (DayOfWeek)7 : date.DayOfWeek) - (DayOfWeek)7;
  1021. var Mon = date.AddDays((-7 - m)).ToString("yyyy-MM-dd");
  1022. var Sun = date.AddDays((-7 - s)).ToString("yyyy-MM-dd");
  1023. var (lastWeekStart, lastWeekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastweek");
  1024. return Ok(new { state = 200, Mon,Sun, ss, sss, ssss, sssss, lastWeekStart, lastWeekEnd, have, en2, bingji, cha, jiaoji, chaji, list3, list4, temp, list1 });
  1025. }
  1026. /// <summary>
  1027. /// token 分页
  1028. /// </summary>
  1029. /// <returns></returns>
  1030. [HttpPost("get-parallelforeach")]
  1031. public async Task<IActionResult> GetParallelForEach()
  1032. {
  1033. //string ser= $"SELECT Id,name,ownership,modifiedDate FROM {5('TableName')}WHERE ORDER BY Id fetch_size": { variables('Rows')}, "cursor": "";
  1034. var cosmosClient = _azureCosmos.GetCosmosClient();
  1035. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"1636016499");
  1036. List<School> schools = new List<School>();
  1037. Parallel.ForEach(schoolIds, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, async item =>
  1038. {
  1039. School school = new();
  1040. var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(item, new PartitionKey("Base"));
  1041. if (response.Status == 200)
  1042. {
  1043. using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1044. school = json.ToObject<School>();
  1045. }
  1046. schools.Add(school);
  1047. });
  1048. return Ok(new { state = 200 , schools });
  1049. }
  1050. /// <summary>
  1051. /// table 表分页查询
  1052. /// </summary>
  1053. /// <param name="jsonElement"></param>
  1054. /// <returns></returns>
  1055. [HttpPost("get-tablepage")]
  1056. public async Task<IActionResult> GetTablePage(JsonElement jsonElement)
  1057. {
  1058. jsonElement.TryGetProperty("page", out JsonElement jpage);
  1059. jsonElement.TryGetProperty("size", out JsonElement jsize);
  1060. int page = string.IsNullOrEmpty($"{jsize}") ?1: int.Parse($"{jpage}");
  1061. int size = string.IsNullOrEmpty($"{jsize}") ? 2 : int.Parse($"{jsize}");
  1062. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
  1063. List<BIOptLog> operateLogs = new();
  1064. //lambda 表达式排序
  1065. operateLogs = await table.QueryWhereString<BIOptLog>();
  1066. //lambda 排序 降序
  1067. operateLogs.Sort((x, y) => y.time.CompareTo(x.time));
  1068. List<BIOptLog> bIOptLogs = operateLogs.Skip((page - 1) * size).Take(size).ToList();
  1069. return Ok(new { state = 200, allcount = operateLogs.Count, bIOptLogs });
  1070. }
  1071. /// <summary>
  1072. /// 流式传输响应
  1073. /// </summary>
  1074. /// <returns></returns>
  1075. [HttpPost("get-stream")]
  1076. public async Task<IActionResult> GetStream()
  1077. {
  1078. var sw = Stopwatch.StartNew();
  1079. //while (true)
  1080. //{
  1081. // var q = new Queue<int>();
  1082. // for (int i = 0; i < 100_000_000; i++)
  1083. // {
  1084. // q.Enqueue(i);
  1085. // q.Dequeue();
  1086. // }
  1087. // Console.WriteLine(sw.Elapsed);
  1088. //}
  1089. var ss = new SortedSet<int>(Enumerable.Repeat(42, 400_000));
  1090. Console.WriteLine(sw.Elapsed);
  1091. HttpContext.Response.ContentType = "text/plain";
  1092. StreamWriter writer;
  1093. //using (writer = new StreamWriter(HttpContext.Response.Body))
  1094. // for (int i = 0; i < 100; i++)
  1095. // {
  1096. // await writer.WriteAsync($"S-{i} \n");
  1097. // }
  1098. // //await writer.FlushAsync("Hello World");
  1099. return Ok(new { state = 200});
  1100. }
  1101. [HttpPost("get-linqcount")]
  1102. public async Task<IActionResult> GetLinqCount()
  1103. {
  1104. List<linqTest> linqTests = new();
  1105. for (int i = 0; i < 10; i++)
  1106. {
  1107. 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() } } };
  1108. linqTests.Add(linqt);
  1109. }
  1110. //var set = linqTests.Select((x, y) => x.linq1s.Find(l => l.id.Equals($"abc0"))).ToList();
  1111. var set = linqTests.Where(x=> !string.IsNullOrEmpty(x.linq1s.Find(l => l.id.Equals($"abc0")).ToString()) );
  1112. //var tem220p = linqTests.ForEach(x => {
  1113. // var coreUser = linqTests.Find(c => c.id.Equals("abc0"));
  1114. // }); //.Except(linqTests.Select(y => y.linq1s.Find(n => n.times.Equals("abc0"))));
  1115. return Ok(new { state = 200, linqTests, set });
  1116. }
  1117. /// <summary>
  1118. /// 多个连接字符串方式
  1119. /// </summary>
  1120. /// <returns></returns>
  1121. [HttpPost("get-manydb")]
  1122. public async Task<IActionResult> GetMany(JsonElement jsonElement)
  1123. {
  1124. jsonElement.TryGetProperty("site", out JsonElement site);
  1125. var cosmosClient = _azureCosmos.GetCosmosClient();
  1126. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  1127. var redisClinet = _azureRedis.GetRedisClient(8);
  1128. if ($"{site}".Equals(BIConst.Global))
  1129. {
  1130. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1131. table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("");
  1132. redisClinet = _azureRedis.GetRedisClient(dbnum: 8, name: BIConst.Global);
  1133. }
  1134. #region 依赖注入的方式
  1135. DateTimeOffset dateTime = DateTimeOffset.UtcNow;
  1136. var dateDay = dateTime.ToString("yyyyMMdd"); //获取当天的日期
  1137. Dictionary<long, int> allDays = new(); //所有在线人数
  1138. Dictionary<long, int> tchDays = new(); //教师在线人数
  1139. SortedSetEntry[] tchDay = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:teacher:{dateDay}");
  1140. if (tchDay.Length > 0)
  1141. {
  1142. foreach (var item in tchDay)
  1143. {
  1144. int val = ((int)item.Score);
  1145. int key = ((int)item.Element);
  1146. var utcTo = new DateTimeOffset(new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, key, 0, 0)).Hour;
  1147. //var hour = int.Parse(DateTime.SpecifyKind(Convert.ToDateTime($"{dateTime.Year}/{dateTime.Month}/{ dateTime.Day} {key}:00:00"), DateTimeKind.Utc).ToLocalTime().ToString("HH"));
  1148. tchDays.Add(utcTo, val);
  1149. if (allDays.ContainsKey(utcTo))
  1150. allDays[utcTo] = (allDays[utcTo] + val);
  1151. else
  1152. allDays.Add(utcTo, val);
  1153. }
  1154. }
  1155. var redisGl = _azureRedis.GetRedisClient(dbnum: 0, name: "Global");
  1156. var temps= await _azureRedis.GetRedisClient(dbnum: 0, name: "Global").SortedSetIncrementAsync($"Login:IES:Test", $"1", 1);//一天24小时 小时为单位
  1157. var cosmosDefaulat = _azureCosmos.GetCosmosClient(); //默认数据库
  1158. List<School> schools = new();
  1159. await foreach (var item in cosmosDefaulat.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<School>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1160. {
  1161. schools.Add(item);
  1162. }
  1163. var cosmosGlobal = _azureCosmos.GetCosmosClient(name: "Global"); //默认数据库
  1164. List<School> schoolGlobals = new();
  1165. await foreach (var item in cosmosGlobal.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<School>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
  1166. {
  1167. schoolGlobals.Add(item);
  1168. }
  1169. return Ok(new { state = 200, dcnt = schools.Count, schools, dgcnt = schoolGlobals.Count, schoolGlobals });
  1170. ////table多库连接
  1171. //var tableDefulat = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin"); //Table默认表
  1172. //List<DayLogin> hourLoginsDefualt = await tableDefulat.FindListByDict<DayLogin>(new Dictionary<string, object> { { "PartitionKey", $"DayLogin" } });
  1173. //var table = _azureStorage.GetCloudTableClient("Global").GetTableReference("IESLogin"); //Table国际站
  1174. //List<DayLogin> hourLogins= await table.FindListByDict<DayLogin>(new Dictionary<string, object> { { "PartitionKey", $"DayLogin" } });
  1175. //return Ok(new { state = 200, hourLogins, hourLoginsDefualt });
  1176. #endregion
  1177. #region 原始方式
  1178. //cosmosDB连接字符串
  1179. //var clientUrl = _configuration.GetValue<string>("Azure:CosmosUrl:ConnectionString");
  1180. //var clientKey = _configuration.GetValue<string>("Azure:CosmosKey:ConnectionString");
  1181. //CosmosClient cosmosClient = new(clientUrl, clientKey);
  1182. //var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync("hbcn", new PartitionKey("Base"));
  1183. //School school = new();
  1184. //if (response.Status == 200)
  1185. //{
  1186. // using var json = await JsonDocument.ParseAsync(response.ContentStream);
  1187. // school = json.ToObject<School>();
  1188. //}
  1189. //Table连接字符串
  1190. //var tableUrl = _configuration.GetValue<string>("Azure:StorageUrl:ConnectionString");
  1191. //Uri url = new(tableUrl, UriKind.Absolute);
  1192. //var tableKey = _configuration.GetValue<string>("Azure:StorageKey:ConnectionString");
  1193. //StorageCredentials sta = new StorageCredentials("teammodeltest", tableKey);
  1194. //CloudTableClient cloudTableClient = new CloudTableClient(url, sta);
  1195. //var table1 = cloudTableClient.GetTableReference("IESLogin");
  1196. //var tableGlobal = _configuration.GetValue<string>("AzureGlobal");
  1197. //Dictionary<string, object> dic = new() { { "PartitionKey", $"HourLogin" } };
  1198. //List<HourLogin> hourLogin = await table1.FindListByDict<HourLogin>(dic);
  1199. //List<HourLogin> hourLogin1= await table.FindListByDict<HourLogin>(dic);
  1200. //var table = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin");
  1201. //return Ok(new { state = 200 });
  1202. #endregion
  1203. }
  1204. /// <summary>
  1205. ///
  1206. /// </summary>
  1207. /// <param name="linqTestm"></param>
  1208. /// <param name="site"></param>
  1209. /// <returns></returns>
  1210. [HttpPost("parameter")]
  1211. public async Task<IActionResult> parameter(linqTest linqTestm, [FromHeader]string site)
  1212. {
  1213. var cosmosClient = _azureCosmos.GetCosmosClient();
  1214. if ($"{site}".Equals(BIConst.Global))
  1215. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  1216. linqTest linqTest = new linqTest();
  1217. linqTest.id = linqTestm.id; linqTest.name = linqTestm.name;
  1218. var resp = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{linqTestm.id}", new PartitionKey("Base"));
  1219. return Ok(new { state = 200, linqTest,cosmosClient,site });
  1220. }
  1221. /// <summary>
  1222. /// 查询一个实体信息
  1223. /// </summary>
  1224. /// <param name="jsonElement"></param>
  1225. /// <returns></returns>
  1226. [HttpPost("get-bizschool")]
  1227. public async Task<IActionResult> GetTable(JsonElement jsonElement)
  1228. {
  1229. jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey);
  1230. jsonElement.TryGetProperty("rowKey", out JsonElement rowKey);
  1231. var tableClient = _azureStorage.GetCloudTableClient();
  1232. var table = _azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
  1233. BusinessSchool tempUser = table.Get<BusinessSchool>(partitionKey: $"{partitionKey}", rowKey: $"{rowKey}");
  1234. return Ok(new { state = 200, table = tempUser });
  1235. }
  1236. [HttpPost("get-testway")]
  1237. public async Task<IActionResult> TestWay (JsonElement jsonElement)
  1238. {
  1239. jsonElement.TryGetProperty("source", out JsonElement source);
  1240. jsonElement.TryGetProperty("splitChar", out JsonElement splitChar);
  1241. jsonElement.TryGetProperty("indexes", out JsonElement indexes);
  1242. jsonElement.TryGetProperty("num", out JsonElement num);
  1243. var upS= BICommonWay.SplitStr(source.GetString(), ',', indexes.GetInt32(), num.GetInt32());
  1244. return Ok(new { state = 200, source, upS });
  1245. }
  1246. List<string> schools = new()
  1247. {
  1248. "dghznx",
  1249. "cxhhlx",
  1250. "xjaxx",
  1251. "zjqxx",
  1252. "xnygxx",
  1253. "lxxcfx",
  1254. "gxjrxx",
  1255. "cdgxsx",
  1256. "yzxx",
  1257. "kjyxx",
  1258. "wjylxx",
  1259. "dsgjxx",
  1260. "ydzt",
  1261. "xndbxx",
  1262. "sqtszx",
  1263. "cdxczx",
  1264. "ghsyzx",
  1265. "lqsx",
  1266. "cdxxps",
  1267. "xcfx",
  1268. "xyqxx",
  1269. "xncbyy",
  1270. "cdlqjk",
  1271. "lqdmxx",
  1272. "lqyx",
  1273. "pclxxx",
  1274. "cdfzx",
  1275. "xnblxx",
  1276. "ghsx",
  1277. "khdycz",
  1278. "khbmxx",
  1279. "khdecz",
  1280. "khzx",
  1281. "khhbzx",
  1282. "gxxcxx",
  1283. "khhtxx",
  1284. "khdxxx",
  1285. "khsyxx"
  1286. };
  1287. public async Task SetTeacherSchool(AzureCosmosFactory _azureCosmos)
  1288. {
  1289. var cosmosClient = _azureCosmos.GetCosmosClient();
  1290. foreach (var item in schools)
  1291. {
  1292. School school = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemAsync<School>($"{item}", new PartitionKey("Base"));
  1293. List<Teacher> teachers = new();
  1294. 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") }))
  1295. {
  1296. teachers.Add(tch);
  1297. }
  1298. if (teachers.Count > 0)
  1299. {
  1300. foreach (var teacher in teachers)
  1301. {
  1302. teacher.schools.ForEach(tch => { if (tch.schoolId.Equals(item)) { tch.areaId = school.areaId; } });
  1303. await cosmosClient.GetContainer("TEAMModelOS", "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey("Base"));
  1304. }
  1305. }
  1306. }
  1307. }
  1308. public class linqTest
  1309. {
  1310. public string id{ get; set; }
  1311. public string name { get; set; }
  1312. public List<linq1> linq1s { get; set; }
  1313. }
  1314. public class linq1
  1315. {
  1316. public string id { get; set; }
  1317. public long times { get; set; }
  1318. }
  1319. public class Test
  1320. {
  1321. public int age { get; set; }
  1322. public string name { get; set; }
  1323. public int score { get; set; }
  1324. }
  1325. public class strend
  1326. {
  1327. public int id { get; set; }
  1328. public string name { get; set; }
  1329. public int age { get; set; }
  1330. }
  1331. struct MyStruct
  1332. {
  1333. public int Count { get; set; }
  1334. }
  1335. class Example
  1336. {
  1337. public string? Name { get; set; }
  1338. public string Value { get; set; }
  1339. }
  1340. public record TempSchool
  1341. {
  1342. public long ts { get; set; }
  1343. public string id { get; set; }
  1344. public string name { get; set; }
  1345. }
  1346. public static long GetMonthEnd(DateTimeOffset dt)
  1347. {
  1348. DateTime dtNew = new DateTime(dt.Year, dt.Month, 1);
  1349. var ste = dtNew.AddMonths(1).AddDays(-1).Day;
  1350. long iLastDay = DateTimeOffset.Parse($"{dt.Year}-{dt.Month}-{ste} 23:59:59").ToUnixTimeSeconds();
  1351. return iLastDay;
  1352. }
  1353. public static long GetMonthStart(DateTimeOffset dt)
  1354. {
  1355. DateTime dtNew = new DateTime(dt.Year, dt.Month, 1);
  1356. long iLastDay = DateTimeOffset.Parse($"{dtNew}").ToUnixTimeSeconds();
  1357. return iLastDay;
  1358. }
  1359. public class GenerateRandom1
  1360. {
  1361. /// <summary>
  1362. /// 生成随机数字
  1363. /// </summary>
  1364. /// <param name="length">生成长度</param>
  1365. /// <returns></returns>
  1366. public static string Number(int Length)
  1367. {
  1368. return Number(Length, false);
  1369. }
  1370. /// <summary>
  1371. /// 生成随机数字
  1372. /// </summary>
  1373. /// <param name="Length">生成长度</param>
  1374. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  1375. /// <returns></returns>
  1376. public static string Number(int Length, bool Sleep)
  1377. {
  1378. if (Sleep)
  1379. System.Threading.Thread.Sleep(3);
  1380. string result = "";
  1381. System.Random random = new Random();
  1382. for (int i = 0; i < Length; i++)
  1383. {
  1384. result += random.Next(10).ToString();
  1385. }
  1386. return result;
  1387. }
  1388. /// <summary>
  1389. /// 生成随机字母与数字
  1390. /// </summary>
  1391. /// <param name="IntStr">生成长度</param>
  1392. /// <returns></returns>
  1393. public static string Str(int Length)
  1394. {
  1395. return Str(Length, false);
  1396. }
  1397. /// <summary>
  1398. /// 生成随机字母与数字
  1399. /// </summary>
  1400. /// <param name="Length">生成长度</param>
  1401. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  1402. /// <returns></returns>
  1403. public static string Str(int Length, bool Sleep)
  1404. {
  1405. if (Sleep)
  1406. System.Threading.Thread.Sleep(3);
  1407. 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' };
  1408. string result = "";
  1409. int n = Pattern.Length;
  1410. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  1411. for (int i = 0; i < Length; i++)
  1412. {
  1413. int rnd = random.Next(0, n);
  1414. result += Pattern[rnd];
  1415. }
  1416. return result;
  1417. }
  1418. /// <summary>
  1419. /// 生成随机纯字母随机数
  1420. /// </summary>
  1421. /// <param name="IntStr">生成长度</param>
  1422. /// <returns></returns>
  1423. public static string Str_char(int Length)
  1424. {
  1425. return Str_char(Length, false);
  1426. }
  1427. /// <summary>
  1428. /// 生成随机纯字母随机数
  1429. /// </summary>
  1430. /// <param name="Length">生成长度</param>
  1431. /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
  1432. /// <returns></returns>
  1433. public static string Str_char(int Length, bool Sleep)
  1434. {
  1435. if (Sleep) System.Threading.Thread.Sleep(3);
  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. 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' };
  1438. string result = "";
  1439. int n = Pattern.Length;
  1440. System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
  1441. for (int i = 0; i < Length; i++)
  1442. {
  1443. int rnd = random.Next(0, n);
  1444. result += Pattern[rnd];
  1445. }
  1446. return result;
  1447. }
  1448. }
  1449. }
  1450. }