123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584 |
- using Azure.Cosmos;
- using DingTalk.Api;
- using DingTalk.Api.Request;
- using DingTalk.Api.Response;
- using HTEXLib.COMM.Helpers;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Azure.Cosmos.Table;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelBI.Filter;
- using TEAMModelBI.Models;
- using TEAMModelBI.Tool;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;//引用创建学校Code
- using TEAMModelOS.SDK.Context.Attributes.Azure;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.BI;
- using TEAMModelOS.SDK.Models.Cosmos.Common;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Table;
- //.Net 6新的特性
- using System.Reflection;
- using System.Numerics;
- using System.Security.Cryptography;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.IdentityModel.Tokens.Jwt;
- using TEAMModelBI.Tool.Extension;
- using System.IO;
- using System.Net.Http;
- using System.Net.Http.Json;
- using System.Net;
- using TEAMModelBI.Tool.CosmosBank;
- using System.Diagnostics;
- using StackExchange.Redis;
- using TEAMModelBI.Tool.Context;
- using TEAMModelBI.DI.BIAzureStorage;
- namespace TEAMModelBI.Controllers.BITest
- {
- [Route("apitest")]
- [ApiController]
- public class TestController : ControllerBase
- {
- private readonly AzureCosmosFactory _azureCosmos;
- private readonly AzureStorageFactory _azureStorage;
- private readonly AzureRedisFactory _azureRedis;
- private readonly DingDing _dingDing;
- private readonly Option _option;
- private readonly IWebHostEnvironment _environment; //读取文件
- //读取配置文件
- private readonly IConfiguration _configuration;
- private readonly CoreAPIHttpService _coreAPIHttpService;
- private readonly HttpClient _httpClient;
- public TestController(AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option, IWebHostEnvironment hostingEnvironment, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService, HttpClient httpClient)
- {
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _dingDing = dingDing;
- _option = option?.Value;
- _environment = hostingEnvironment;
- _configuration = configuration;
- _coreAPIHttpService = coreAPIHttpService;
- _httpClient = httpClient;
- }
- /// <summary>
- /// 删除册别,删除章节 创区
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("del-standard")]
- public async Task<IActionResult> DelStandard(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("oldStandard", out JsonElement _oldStandard)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<string> abilityIds = new List<string>(); //册别的ID集合
- //查询册别信息
- 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}") }))
- {
- abilityIds.Add(tempAbility.id); //查询出来册别ID添加册别ID集合
- }
- //删除册别
- if (abilityIds.IsNotEmpty())
- {
- var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityIds, $"Ability-{_oldStandard}");
- }
- List<string> abilityTaskIds = new List<string>(); //章节ID集合
- 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}") }))
- {
- abilityTaskIds.Add(item.id); //查询出来的章节信息ID添加到战绩集合
- }
- //删除章节
- if (abilityTaskIds.IsNotEmpty())
- {
- var sresponse = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Normal").DeleteItemsStreamAsync(abilityTaskIds, $"AbilityTask-{_oldStandard}");
- }
- return Ok(new { state = 200 });
- }
- /// <summary>
- /// 测试生产Code
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schoolcode")]
- public async Task<IActionResult> GetSchoolCode(JsonElement jsonElement)
- {
- //string data = await SchoolCode.GenerateSchoolCode(jsonElement, _dingDing, _environment).ToString();
- CreateSchoolInfo createSchoolInfo = new CreateSchoolInfo();
- createSchoolInfo.province = "四川省";
- createSchoolInfo.id = "tmdplc";
- createSchoolInfo.name = "醍摩豆批量创校学校";
- createSchoolInfo.city = "成都市";
- createSchoolInfo.aname = "";
- createSchoolInfo.createCount = 0;
- //Random random = new Random();
- ////随机小写字母
- //int a = random.Next(0, 26);
- //char ch = (char)('a' + a);
- //string Number = GenerateRandom.Number(1);
- //string Number1 = GenerateRandom.Number(1, true);
- //string Str = GenerateRandom.Str(1);
- //string Str1 = GenerateRandom.Str(1, true);
- //string Str_char = GenerateRandom.Str_char(1);
- //string Str_char1 = GenerateRandom.Str_char(1, true);
- CreateSchoolInfo data = await SchoolCode.GenerateSchoolCode(createSchoolInfo, _dingDing, _environment);
- return Ok(new { state = 200, data, data.id });
- }
- /// <summary>
- /// 保存日志文件
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "assist,admin")]
- [HttpPost("set-savebilog")]
- public async Task<IActionResult> SetTestSaveBIlog(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("site", out JsonElement site);
- jsonElement.TryGetProperty("msg", out JsonElement msg);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- var redisClinet = _azureRedis.GetRedisClient(8);
- if ($"{site}".Equals(BIConst.GlobalSite))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.GlobalSite);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.GlobalSite);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.GlobalSite);
- redisClinet = _azureRedis.GetRedisClient(dbnum: 8, name: BIConst.GlobalSite);
- }
- var (_tmdId, _tmdName, pic, did, dname, dpic) = HttpJwtAnalysis.JwtXAuthBI(HttpContext.GetXAuth("AuthToken"), _option);
- await _azureStorage.SaveLog(type: "table-save", msg: "测试保存方法01", dingDing: _dingDing, httpContext: HttpContext); //IES5 日志记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "Test-test", $"{msg}", _dingDing, httpContext: HttpContext);//BI 日志记录
- return Ok(new { state = 200 });
- }
- /// <summary>
- /// 查询table数据
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("file-table")]
- public async Task<IActionResult> SaveTable(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("single", out JsonElement single);
- jsonElement.TryGetProperty("startDate", out JsonElement startDate);
- jsonElement.TryGetProperty("endDate", out JsonElement endDate);
- jsonElement.TryGetProperty("platform", out JsonElement platform);
- List<string> strlist = new List<string>();
- if (!string.IsNullOrEmpty($"{single}"))
- strlist.Add($"RowKey {QueryComparisons.Equal} {single}");
- if (!string.IsNullOrEmpty($"{startDate}"))
- strlist.Add($"RowKey {QueryComparisons.GreaterThanOrEqual} {startDate}");
- if (!string.IsNullOrEmpty($"{endDate}"))
- strlist.Add($"RowKey {QueryComparisons.LessThanOrEqual} {endDate}");
- if (!string.IsNullOrEmpty($"{platform}"))
- strlist.Add($"platform {QueryComparisons.Equal} {platform}");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
- string sql = string.Join(" and ", strlist);
- var temp = table.QueryWhereString<BIOptLog>(sql);
- return Ok(new { state = 200, temp });
- }
- /// <summary>
- /// 查询BI操作记录
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-operatelogbydate")]
- public async Task<IActionResult> GetOperateLogByDate(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("single", out JsonElement single);
- jsonElement.TryGetProperty("startDate", out JsonElement startDate);
- jsonElement.TryGetProperty("endDate", out JsonElement endDate);
- jsonElement.TryGetProperty("platform", out JsonElement platform);
- List<BIOptLog> operateLogs = new();
- StringBuilder tableSql = new();
- if (!string.IsNullOrEmpty($"{single}"))
- tableSql.Append($"RowKey {QueryComparisons.Equal} '{single}' ");
- if (!string.IsNullOrEmpty($"{startDate}"))
- tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' " : $"RowKey {QueryComparisons.GreaterThanOrEqual} '{startDate}' ");
- if (!string.IsNullOrEmpty($"{endDate}"))
- tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} RowKey {QueryComparisons.LessThanOrEqual} '{endDate}' " : $" RowKey { QueryComparisons.LessThanOrEqual} '{endDate}' ");
- if (!string.IsNullOrEmpty($"{platform}"))
- tableSql.Append(!string.IsNullOrEmpty(tableSql.ToString()) ? $" {TableOperators.And} platform {QueryComparisons.Equal} '{platform}' " : $" platform {QueryComparisons.Equal} '{platform}' ");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
- operateLogs = await table.QueryWhereString<BIOptLog>(tableSql.ToString());
- return Ok(new { state = 200, operateLogs });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /operatelog/get-operatelogbydate \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 查询离职信息
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("quitstaff")]
- public async Task<IActionResult> QuitStaff()
- {
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- string agentld = _configuration["DingDingAuth:Agentld"];
- //获取access_token
- IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
- request.SetHttpMethod("Get");
- OapiGettokenResponse response = client.Execute(request);
- if (response.IsError)
- {
- return BadRequest();
- }
- //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
- string access_token = response.AccessToken;
-
- IDingTalkClient quitStaffClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querydimission");
- OapiSmartworkHrmEmployeeQuerydimissionRequest reqDimission = new OapiSmartworkHrmEmployeeQuerydimissionRequest() { Offset = 0L, Size = 50L };
- OapiSmartworkHrmEmployeeQuerydimissionResponse rspDimission = quitStaffClient.Execute(reqDimission, access_token);
- if (rspDimission.SubErrCode == "60011")
- {
- return Ok(new { state = 60011, message = "没有调用该接口的权限!" });
- }
- else if (rspDimission.Result != null)
- {
- var datalist = rspDimission.Result.DataList;
- return Ok(new { state = 200, datalist });
- }
- else
- {
- return Ok(new { state = rspDimission.SubErrCode, message = rspDimission.Errmsg });
- }
- }
- /// <summary>
- /// 测试获取待入职人员的userId接口
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("Induction")]
- public async Task<IActionResult> Induction()
- {
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- string agentld = _configuration["DingDingAuth:Agentld"];
- //获取access_token
- IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
- request.SetHttpMethod("Get");
- OapiGettokenResponse response = client.Execute(request);
- if (response.IsError)
- {
- return BadRequest();
- }
- //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
- string access_token = response.AccessToken;
- IDingTalkClient InductionClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/querypreentry");
- OapiSmartworkHrmEmployeeQuerypreentryRequest reqInduction = new OapiSmartworkHrmEmployeeQuerypreentryRequest() { Offset = 0L, Size = 50 };
- reqInduction.SetHttpMethod("GET");
- OapiSmartworkHrmEmployeeQuerypreentryResponse rspInduction = InductionClient.Execute(reqInduction, access_token);
- if (rspInduction.Result.DataList != null)
- {
- foreach (var itemId in rspInduction.Result.DataList)
- {
- IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
- OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
- {
- Userid = itemId,
- Language = "zh_CN"
- };
- OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
- }
- return Ok(new { state = 200, rspInduction.Result.DataList });
- }
- else
- {
- return Ok(new { state = 400, rspInduction.SubErrCode, rspInduction.SubErrMsg });
- }
- }
- /// <summary>
- /// 获取在职ID
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-onthejob")]
- public async Task<IActionResult> GetOnTheJob()
- {
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- string agentld = _configuration["DingDingAuth:Agentld"];
- //获取access_token
- IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest request = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
- request.SetHttpMethod("Get");
- OapiGettokenResponse response = client.Execute(request);
- if (response.IsError)
- {
- return BadRequest();
- }
- //access_token的有效期为7200秒(2小时),有效期内重复获取会返回相同结果并自动续期,过期后获取会返回新的access_token
- string access_token = response.AccessToken;
- //bool vars = false;
- //long offst = 1;
- //do
- //{
- // IDingTalkClient jobclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
- // OapiSmartworkHrmEmployeeQueryonjobRequest jobreq = new OapiSmartworkHrmEmployeeQueryonjobRequest { StatusList = "2,3,-1", Offset = offst, Size = 50 }; //2:试用期 3:正式 5:待离职 -1:无状态
- // OapiSmartworkHrmEmployeeQueryonjobResponse jobrsp = jobclient.Execute(jobreq, access_token);
- // if (jobrsp.Result.NextCursor > 0)
- // offst += 1;
- // else vars = true;
- //} while (vars);
- IDingTalkClient jobclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
- OapiSmartworkHrmEmployeeQueryonjobRequest jobreq = new OapiSmartworkHrmEmployeeQueryonjobRequest { StatusList = "2,3,-1", Offset = 1, Size = 50 }; //2:试用期 3:正式 5:待离职 -1:无状态
- OapiSmartworkHrmEmployeeQueryonjobResponse jobrsp = jobclient.Execute(jobreq, access_token);
- if (jobrsp.SubErrCode == "60011")
- {
- return Ok(new { state = 200, msg = jobrsp.SubErrMsg });
- }
- foreach (var item in jobrsp.Result.DataList)
- {
-
- }
- var ser = jobrsp.Result.DataList; // jobrsp.Body.GetEnumerator("result");
- return Ok(new { state = 200, jobrsp.Body, ser });
- }
- /// <summary>
- /// 测试 使用yield 优化
- /// 依据学校编号查询学校信息;若是没有传学校编号,则查询所有学校信息
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-schoolsinfo")]
- public async Task<IActionResult> GetSchoolsInfo(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("schoolCode", out JsonElement _schoolCode);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<AssistSchool> schoolAssists = new();
- //StringBuilder stringBuilder = new StringBuilder("select value(c) from c");
- 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");
- if (!string.IsNullOrEmpty($"{_schoolCode}"))
- {
- stringBuilder.Append($" where c.id='{_schoolCode}'");
- }
- //await foreach (var itemSchool in cosmosClient.GetContainer(Constant.TEAMModelOS, "School").GetItemQueryIterator<School>(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- //{
- // SchoolAssist schoolAssist = new()
- // {
- // id = itemSchool.id,
- // code = itemSchool.code,
- // schoolCode = itemSchool.schoolCode,
- // name = itemSchool.name,
- // region = itemSchool.region,
- // province = itemSchool.province,
- // city = itemSchool.city,
- // dist = itemSchool.dist,
- // size = itemSchool.size,
- // address = itemSchool.address,
- // picture = itemSchool.picture,
- // type = itemSchool.type,
- // scale = itemSchool.scale,
- // areaId = itemSchool.areaId,
- // standard = itemSchool.standard
- // };
- // var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(itemSchool.id, new PartitionKey("ProductSum"));
- // if (response.Status == 200)
- // {
- // using var json = await JsonDocument.ParseAsync(response.ContentStream);
- // if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- // {
- // schoolAssist.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- // }
- // if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- // {
- // schoolAssist.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- // }
- // if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- // {
- // schoolAssist.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
- // }
- // }
- // schoolAssist.assists = await CommonFind.FindSchoolRoles(cosmosClient, itemSchool.id, "assist");
- // schoolAssists.Add(schoolAssist);
- //}
- //return Ok(new { state = 200, schoolAssists });
- await foreach (var itemSchool in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- using var jsonSchool = await JsonDocument.ParseAsync(itemSchool.ContentStream);
- foreach (var objSchool in jsonSchool.RootElement.GetProperty("Documents").EnumerateArray())
- {
- var schoolId = objSchool.GetProperty("id").GetString();
- AssistSchool schoolAssist = new()
- {
- id = schoolId,
- code = objSchool.GetProperty("code").GetString(),
- schoolCode = objSchool.GetProperty("schoolCode").GetString(),
- name = objSchool.GetProperty("name").GetString(),
- region = objSchool.GetProperty("region").GetString(),
- province = objSchool.GetProperty("province").GetString(),
- city = objSchool.GetProperty("city").GetString(),
- dist = objSchool.GetProperty("dist").GetString(),
- size = objSchool.GetProperty("size").GetInt32(),
- address = objSchool.GetProperty("address").GetString(),
- picture = objSchool.GetProperty("picture").GetString(),
- type = objSchool.GetProperty("type").GetInt32(),
- //scale = objSchool.GetProperty("scale").GetInt32(),
- areaId = objSchool.GetProperty("areaId").GetString(),
- standard = objSchool.GetProperty("standard").GetString(),
- };
- try { schoolAssist.scale = objSchool.GetProperty("scale").GetInt32(); }
- catch { schoolAssist.scale = 0; }
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(schoolId, new PartitionKey("ProductSum"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- {
- schoolAssist.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- {
- schoolAssist.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- {
- schoolAssist.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
- }
- }
- //schoolAssist.assists = await CommonFind.FindSchoolRoles(cosmosClient, schoolId, "assist");
- schoolAssists.Add(schoolAssist);
- }
- }
- List<AssistSchool> tempSchoolAssists = new();
- await foreach (var temp in GetSchools(cosmosClient, schoolAssists))
- {
- tempSchoolAssists.AddRange(temp);
- }
- return Ok(new { state = 200, schoolAssists = tempSchoolAssists });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /batchschool/get-schoolsinfo \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 使用yield 优化
- /// </summary>
- /// <param name="cosmosClient"></param>
- /// <param name="schoolAssists"></param>
- /// <returns></returns>
- private async IAsyncEnumerable<List<AssistSchool>> GetSchools(CosmosClient cosmosClient, List<AssistSchool> schoolAssists)
- {
- List<AssistSchool> tempSchoolAssists = new();
- foreach (var temp in schoolAssists)
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync(temp.id, new PartitionKey("ProductSum"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- if (json.RootElement.TryGetProperty("serial", out JsonElement serial) && !serial.ValueKind.Equals(JsonValueKind.Null))
- {
- temp.serial = serial.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("service", out JsonElement service) && !service.ValueKind.Equals(JsonValueKind.Null))
- {
- temp.service = service.ToObject<List<SchoolProductSumData>>().Select(x => x.prodCode).ToList();
- }
- if (json.RootElement.TryGetProperty("hard", out JsonElement hard) && !hard.ValueKind.Equals(JsonValueKind.Null))
- {
- temp.hard = hard.ToObject<List<SchoolProductSumDataHard>>().Select(x => x.prodCode).ToList();
- }
- }
- temp.assists = await CommonFind.FindSchoolRoles(cosmosClient, temp.id, "assist");
- tempSchoolAssists.Add(temp);
- }
- yield return tempSchoolAssists;
- }
- /// <summary>
- /// 赋值默认的顾问角色和BI默认的功能权限
- /// </summary>
- /// <returns></returns>
- [HttpPost("set-rolesorperm")]
- public async Task<IActionResult> SetRolesOrPermissions()
- {
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- List<DingDingUserInfo> ddUserId = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", "continent" } });
- List<string> read = new() { "abilitystandard-read", "batcharea-read", "batchschool-read", "orgusers-read" };
- List<DingDingUserInfo> tempUserInfo = new();
- foreach (var user in ddUserId)
- {
- if (string.IsNullOrEmpty(user.roles))
- {
- user.roles = "assist";
- }
- if (string.IsNullOrEmpty(user.permissions))
- {
- user.permissions = string.Join(",", read);
- }
- List<string> tempRead = new(user.permissions.Split(","));
- foreach (var temp in read)
- {
- if (!tempRead.Contains(temp))
- {
- tempRead.Add(temp);
- }
- }
- user.permissions = string.Join(",", tempRead);
- tempUserInfo.Add(user);
- }
- var response = await table.SaveOrUpdateAll<DingDingUserInfo>(tempUserInfo);
- return Ok(new { state = 200, response });
- }
- /// <summary>
- /// 测试使用 CosmosDB中的COUNT 函数统计
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-count")]
- public async Task<IActionResult> GetCount(JsonElement jsonElement)
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<KeyValuePair<int, int>> layerCount = new List<KeyValuePair<int, int>>();
- for (int i = 1; i <= 6; i++)
- {
- int total = 0;
- //string sqlText = $"select value(c.id) from c where c.pk='Item' and c.field={i}";
- string sqlText = $"select COUNT(c.id) AS totals from c where c.pk='Item' and c.field={i}";
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt32() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- //total += obj.GetInt64();
- total += obj.GetProperty("totals").GetInt32();
- }
- //total += count.GetInt64();
- }
- }
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Teacher").GetItemQueryStreamIterator(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt64() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- //total += obj.GetInt64();
- total += obj.GetProperty("totals").GetInt32();
- }
- }
- }
- layerCount.Add(new KeyValuePair<int, int>(i, total));
- }
- return Ok(new { state = 200, layerCount });
- }
- /// <summary>
- /// 测试算日期
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-date")]
- public async Task<IActionResult> GetDate()
- {
- DateTimeOffset dateTime = DateTimeOffset.UtcNow.AddDays(0);
- int year = DateTimeOffset.UtcNow.Year;
- int month = DateTimeOffset.UtcNow.Month;
- var datetime7 = DateTimeOffset.UtcNow.AddDays(-7); //前七天的时间
- List<string> strList = monthsOfYear("2021-1");
- var ere = DateTimeOffset.Parse("2022-04-25");
- DateTimeOffset ste = new();
- if (ere.Month > 9)
- {
- ste = new DateTime(ere.Year, ere.Month - 4, 1);
- }
- else
- {
- ste = new DateTime(ere.Year - 1, ere.Month, 1);
- }
- var (start1, end1) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow);
- var (start2, end2) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "week");
- var (start3, end3) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastweek");
- var (start4, end4) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "term");
- var (start5, end5) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastterm");
- var (start6, end6) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "month");
- var (start7, end7) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "year");
- var start = GetMonthStart(ere);
- var end = GetMonthEnd(ere);
- List<MonthStartEnd> endList = TimeHelper.GetYearMonthlyStartEnd10(DateTimeOffset.UtcNow.Year);
- List<MonthStartEnd> endList1 = TimeHelper.GetYearMonthlyStartEnd13(DateTimeOffset.UtcNow.Year);
- //return Ok(new { strList, dateTime, year, start, end, endList, endList1, endList2 });
- return Ok(new { datetime7, start1, end1, start2, end2, start3, end3, start4, end4 , start5, end5 , start6, end6 , start7, end7 });
- }
- public static List<string> monthsOfYear(string yearMonth)
- {
- DateTime dateTime = DateTime.Parse(yearMonth);
- int year = dateTime.Year;
- int month = dateTime.Month;
- List<string> months = new List<string>();
- while (year > dateTime.Year - 1 || month > dateTime.Month)
- {
- months.Add($"{year}-{(month < 10 ? "0" : "") + month}");
- month -= 1;
- if (month <= 0)
- {
- year -= 1;
- month = 12;
- }
- }
- return months;
- }
- /// <summary>
- /// 统计一年中每月得新增校
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-yearmonth")]
- public async Task<IActionResult> GetYearMonth()
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- Dictionary<int, long> tempYear = new Dictionary<int, long>();
- List<TempSchool> tempSchools = new List<TempSchool>();
- for (int i = 1; i < 13; i++)
- {
- var start = 00022222330;
- long tempCount = 0;
- 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") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt64() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- TempSchool tempSchool = new TempSchool();
- tempSchool.id = obj.GetProperty("id").GetString();
- tempSchool.ts = obj.GetProperty("_ts").GetInt64();
- tempSchool.name = obj.GetProperty("name").GetString();
- tempSchools.Add(tempSchool);
- }
- tempCount += count.GetInt64();
- }
- }
- if (tempCount != 0)
- {
- tempYear.Add(i, tempCount);
- }
- }
- return Ok(new { state = 200, tempYear, tempSchools });
- }
- /// <summary>
- /// 测试.net 6 的一些特性
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-newnet6")]
- public async Task<IActionResult> GetNewNet6()
- {
- ///PriorityQueue
- //.NET 6 新增的数据结构, PriorityQueue, 队列每个元素都有一个关联的优先级,它决定了出队顺序, 编号小的元素优先出列。
- PriorityQueue<string, int> priorityQueue = new();
- priorityQueue.Enqueue("Second", 2);
- priorityQueue.Enqueue("Fourth", 4);
- priorityQueue.Enqueue("Third 1", 3);
- priorityQueue.Enqueue("Third 2", 5);
- priorityQueue.Enqueue("First", 1);
- while (priorityQueue.Count > 0)
- {
- string item = priorityQueue.Dequeue();
- Console.WriteLine(item);
- }
- //PeriodicTimer
- //认识一个完全异步的“PeriodicTimer”, 更适合在异步场景中使用, 它有一个方法 WaitForNextTickAsync。
- //using PeriodicTimer timer = new(TimeSpan.FromSeconds(2));
- //while (await timer.WaitForNextTickAsync())
- //{
- // Console.WriteLine(DateTime.UtcNow);
- //}
- //检查元素是否可为空的反射API
- var example = new Example();
- var nullabilityInfoContext = new NullabilityInfoContext();
- foreach (var propertyInfo in example.GetType().GetProperties())
- {
- var nullabilityInfo = nullabilityInfoContext.Create(propertyInfo);
- Console.WriteLine($"{propertyInfo.Name} property is {nullabilityInfo.WriteState}");
- }
- //直接通过 Environment 获取进程ID和路径。
- int processId = Environment.ProcessId;
- string path = Environment.ProcessPath;
- Console.WriteLine(processId);
- Console.WriteLine(path);
- //CSPNG 密码安全伪随机数生成器
- byte[] bytes = RandomNumberGenerator.GetBytes(300);
- Console.WriteLine(string.Join("", bytes.ToArray()));
- //Power of 2
- //.NET 6 引入了用于处理 2 的幂的新方法。
- //‘IsPow2’ 判断指定值是否为 2 的幂。
- //‘RoundUpToPowerOf2’ 将指定值四舍五入到 2 的幂
- Console.WriteLine(BitOperations.IsPow2(121)); // True
- Console.WriteLine(BitOperations.RoundUpToPowerOf2(260)); // 256
- //WaitAsync on Task 您可以更轻松地等待异步任务执行, 如果超时会抛出 “TimeoutException”
- Task operationTask = DoSomethingLongAsync();
- await operationTask.WaitAsync(TimeSpan.FromSeconds(5));
- async Task DoSomethingLongAsync()
- {
- Console.WriteLine("DoSomethingLongAsync started.");
- await Task.Delay(TimeSpan.FromSeconds(10));
- Console.WriteLine("DoSomethingLongAsync ended.");
- }
- //新的数学API
- // New methods SinCos, ReciprocalEstimate and ReciprocalSqrtEstimate
- // Simultaneously computes Sin and Cos
- (double sin, double cos) = Math.SinCos(1.57);
- Console.WriteLine($"Sin = {sin}\nCos = {cos}");
- // Computes an approximate of 1 / x
- double recEst = Math.ReciprocalEstimate(5);
- Console.WriteLine($"Reciprocal estimate = {recEst}");
- // Computes an approximate of 1 / Sqrt(x)
- double recSqrtEst = Math.ReciprocalSqrtEstimate(5);
- Console.WriteLine($"Reciprocal sqrt estimate = {recSqrtEst}");
- // New overloads
- // Min, Max, Abs, Clamp and Sign supports nint and nuint
- (nint a, nint b) = (5, 10);
- nint min = Math.Min(a, b);
- nint max = Math.Max(a, b);
- nint abs = Math.Abs(a);
- nint clamp = Math.Clamp(abs, min, max);
- nint sign = Math.Sign(a);
- Console.WriteLine($"Min = {min}\nMax = {max}\nAbs = {abs}");
- Console.WriteLine($"Clamp = {clamp}\nSign = {sign}");
- // DivRem variants return a tuple
- (int quotient, int remainder) = Math.DivRem(2, 7);
- Console.WriteLine($"Quotient = {quotient}\nRemainder = {remainder}");
- //CollectionsMarshal.GetValueRefOrNullRef
- //这个是在字典中循环或者修改结可变结构体时用, 可以减少结构的副本复制, 也可以避免字典重复进行哈希计算,这个有点晦涩难懂
- Dictionary<int, MyStruct> dictionary = new()
- {
- { 1, new MyStruct { Count = 100 } }
- };
- int key = 1;
- MyStruct values = CollectionsMarshal.GetValueRefOrNullRef(dictionary, key);
- // Returns Unsafe.NullRef<TValue>() if it doesn't exist; check using Unsafe.IsNullRef(ref value)
- if (!Unsafe.IsNullRef(ref values))
- {
- Console.WriteLine(values.Count); // Output: 100
- // Mutate in-place
- values.Count++;
- Console.WriteLine(values.Count); // Output: 101
- }
- return Ok(new { state = 200 });
- }
- /// <summary>
- /// 去重、判断
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-repeat")]
- public async Task<IActionResult> GetRepeat(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("datetime", out JsonElement _datetime);
- Dictionary<string, string> prodict = new Dictionary<string, string>() { { "YMPCVCIM", "学情分析模组" }, { "IPDYZYLC", "智慧学校管理服务" }, { "3CLYJ6NP", "AClass ONE智慧学伴" }, { "IPALJ6NY", "数据储存服务空间" },{ "VABAJ6NV", "卷卡合一阅卷系统" } };
- var ste = prodict["IPDYZYLC"];
- List<string> str_str = new List<string>() { "12", "20", "13", "13", "14", "16" };
- 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 } };
- //str_str.Distinct().ToList();
- strends.Where((x, i) => strends.FindIndex(z => z.id.Equals(x.id)) == i).ToList();
- List<strend> str_strend1 = strends.Where((x, i) => strends.FindIndex(z => z.id.Equals(x.id)) == i).ToList();
- List<strend> str_strend2 = strends.GroupBy(p => p).Select(p => p.Key).ToList();//去重复
- DateTime dt = DateTime.Parse($"{_datetime}");
- int year = dt.Year;
- DateTime dt0 = new DateTime(year, 1, 1);
- int days = (dt.Date - dt0.Date).Days + 1;
- //int pydays = ((lastYear + 1) % 4 == 0 && (lastYear + 1) % 100 != 0 || (lastYear + 1) % 400 == 0) ? 366 : 365;
- int pydays = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 366 : 365;
- //int pydays = DateTimeHelper.getDays(year);
- return Ok(new { state = 200, pydays, days, strends , str_strend1, str_strend2 , ste });
- }
- /// <summary>
- /// 计算天数
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-dateday")]
- public async Task<IActionResult> GetDateDay(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("year", out JsonElement _year);
- jsonElement.TryGetProperty("moth", out JsonElement _moth);
- int year = int.Parse($"{_year}");
- int day = 0;
- List<int> moths = _moth.ToObject<List<int>>();
- foreach (var item in moths)
- {
- int days = 0;
- switch (item)
- {
- case 1:
- case 3:
- case 5:
- case 7:
- case 8:
- case 10:
- case 12:
- days = 31;
- break;
- case 4:
- case 6:
- case 9:
- case 11:
- days = 30;
- break;
- case 2:
- int years = 0;
- if (item <= 8 && item >= 3)
- years = year;
- else
- years = year+1;
- if (years % 4 == 0 && year % 100 != 0 || year % 400 == 0)
- days = 29;
- else
- days = 28;
- break;
- }
- day += days;
- }
- return Ok(new { state = 200, day });
-
- }
-
- /// <summary>
- /// 测试CosmosDB分页查询 SQL语句分页
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-page")]
- public async Task<IActionResult> cosmosDBPage(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("pageSize", out JsonElement pageSize)) return BadRequest();
- if (!jsonElement.TryGetProperty("endPosition", out JsonElement endPosition)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<School> schools = new List<School>();
- //string sqlTxt = $"SELECT * FROM c where c.code='Base' order by c.id offset {endPosition} limit {pageSize}";
- string sqlTxt = $"SELECT * FROM c order by c.id offset {pageSize} limit {endPosition}";
- await foreach (var tempPage in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryStreamIterator(queryText: sqlTxt, requestOptions:new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(tempPage.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- schools.Add(obj.ToObject<School>());
- }
- }
- }
- IAsyncResult iAsyncResult = null;
- return Ok(new { state = 200, schools });
- }
- /// <summary>
- /// 分页案例
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-cosmodbtokenpage")]
- public async Task<IActionResult> GetCancellationTokenPage(JsonElement jsonElement)
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- //默认不指定返回大小
- int? pageSize = null;
- string continuationToken = string.Empty;
- string pageToken = default;
- if (jsonElement.TryGetProperty("pageSize", out JsonElement jsonPageSize))
- {
- if (!jsonPageSize.ValueKind.Equals(JsonValueKind.Undefined) && !jsonPageSize.ValueKind.Equals(JsonValueKind.Null) && jsonPageSize.TryGetInt32(out int tempPageSize))
- {
- pageSize = tempPageSize;
- }
- }
- //是否需要进行分页查询,默认不分页
- bool iscontinuation = false;
- if (pageSize != null && pageSize.Value > 0)
- {
- iscontinuation = true;
- }
- if (jsonElement.TryGetProperty("contToken", out JsonElement ContToken))
- {
- pageToken = ContToken.GetString();
- }
- List<School> schools = new();
- 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") }))
- {
- using var json = await JsonDocument.ParseAsync(item.ContentStream);
- if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
- {
- foreach (var obj in json.RootElement.GetProperty("Documents").EnumerateArray())
- {
- schools.Add(obj.ToObject<School>());
- }
- if (iscontinuation)
- {
- continuationToken = item.GetContinuationToken();
- break;
- }
- }
- }
- return Ok(new { state = 200, continuationToken, count = schools.Count, schools });
- }
- /// <summary>
- /// 测试隐式登录
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-implicit")]
- public async Task<IActionResult> GetImplicit()
- {
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var location = _option.Location;
- if (location.Contains("China"))
- {
- location = "China";
- }
- else if (location.Contains("Global"))
- {
- location = "Global";
- }
- var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, location);
- if (_httpClient.DefaultRequestHeaders.Contains("Authorization"))
- {
- _httpClient.DefaultRequestHeaders.Remove("Authorization");
- }
- _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
- var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- url = $"{url}/oauth2/implicit";
- Dictionary<string, string> data = new()
- {
- { "grant_type", "implicit" },
- { "client_id", clientID },
- { "account", "1636016499" },
- { "nonce", Guid.NewGuid().ToString() }
- };
- HttpResponseMessage responseMessage = await _httpClient.PostAsJsonAsync(url, data);
- if (responseMessage.StatusCode == HttpStatusCode.OK) //BI连接字符
- {
- string content = await responseMessage.Content.ReadAsStringAsync();
- }
- return Ok(new { state = 200, token, responseMessage });
- }
- /// <summary>
- /// 测试
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-test")]
- public async Task<IActionResult> GetTest(JsonElement jsonElement)
- {
- List<Test> list1 = new();
- list1.Add(new Test { score = 10, name = "001" });
- list1.Add(new Test { score = 20, name = "002" });
- list1.Add(new Test { score = 30, name = "003" });
- list1.Add(new Test { score = 40, name = "004" });
- list1.Add(new Test { score = 50, name = "005" });
- list1.Add(new Test { score = 60, name = "006" });
- List<Test> list2 = new();
- list2.Add(new Test { score = 40, name = "004" });
- list2.Add(new Test { score = 50, name = "005" });
- list2.Add(new Test { score = 60, name = "006" });
- list2.Add(new Test { score = 70, name = "007" });
- list2.Add(new Test { score = 80, name = "008" });
- list2.Add(new Test { score = 90, name = "009" });
- list2.Add(new Test { score = 100, name = "010" });
- //list3 return 2
- List<Test> list3 = list1.Where(x => !list2.Any(x2 => x.score == x2.score && x.name==x2.name)).ToList();
- //list4 return 2
- List<Test> list4 = list1.Where(x => list2.All(x2 => x.score != x2.score)).ToList();
- List<Test> temp = list1.Where(p => !list2.Select(b => b.score).Contains(p.score)).ToList();
- //List<Test> mergedList = new List<Test>(list1);
- //mergedList.AddRange(list2.Except(list1));
- // var mergedList = list1.Union(list2);
- var en2 = list1.Concat(list2).Except(list1.Intersect(list2));// 容斥原理
- var bingji = list1.Union(list2).ToList();//并(全)集
- var cha = bingji.GroupBy(x => x.score).Select(c => c.First()).ToList();
- var jiaoji = list1.Intersect(list2).ToList();//交集
- var chaji = list1.Except(list2).ToList();//差集
- List<Test> have = list1.Where(a => !list2.Exists(t => a.score == t.score)).ToList();
- have.AddRange(list2.Where(a => !list1.Exists(t => a.score == t.score)).ToList());
- var ss = DateTime.Now.AddDays(0 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7).ToString("yyyy-MM-dd");//上周日
- var sss = DateTime.Now.AddDays(6 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7).ToString("yyyy-MM-dd");//上周六
- var ssss = DateTime.Now.AddDays(1 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7+1).ToString("yyyy-MM-dd");//上周一
- var sssss = DateTime.Now.AddDays(7 - Convert.ToInt16(DateTime.Now.DayOfWeek) - 7+1).ToString("yyyy-MM-dd");//上周日
- //计算上周
- var date = DateTime.Now;
- var m = (date.DayOfWeek == DayOfWeek.Sunday ? (DayOfWeek)7 : date.DayOfWeek) - DayOfWeek.Monday;
- var s = (date.DayOfWeek == DayOfWeek.Sunday ? (DayOfWeek)7 : date.DayOfWeek) - (DayOfWeek)7;
- var Mon = date.AddDays((-7 - m)).ToString("yyyy-MM-dd");
- var Sun = date.AddDays((-7 - s)).ToString("yyyy-MM-dd");
- var (lastWeekStart, lastWeekEnd) = TimeHelper.GetStartOrEnd(DateTimeOffset.UtcNow, "lastweek");
- return Ok(new { state = 200, Mon,Sun, ss, sss, ssss, sssss, lastWeekStart, lastWeekEnd, have, en2, bingji, cha, jiaoji, chaji, list3, list4, temp, list1 });
- }
- /// <summary>
- /// token 分页
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-parallelforeach")]
- public async Task<IActionResult> GetParallelForEach()
- {
- //string ser= $"SELECT Id,name,ownership,modifiedDate FROM {5('TableName')}WHERE ORDER BY Id fetch_size": { variables('Rows')}, "cursor": "";
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, $"1636016499");
- List<School> schools = new List<School>();
- Parallel.ForEach(schoolIds, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, async item =>
- {
- School school = new();
- var response = await cosmosClient.GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(item, new PartitionKey("Base"));
- if (response.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(response.ContentStream);
- school = json.ToObject<School>();
- }
- schools.Add(school);
- });
- return Ok(new { state = 200 , schools });
- }
- /// <summary>
- /// table 表分页查询
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-tablepage")]
- public async Task<IActionResult> GetTablePage(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("page", out JsonElement jpage);
- jsonElement.TryGetProperty("size", out JsonElement jsize);
- int page = string.IsNullOrEmpty($"{jsize}") ?1: int.Parse($"{jpage}");
- int size = string.IsNullOrEmpty($"{jsize}") ? 2 : int.Parse($"{jsize}");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
- List<BIOptLog> operateLogs = new();
- //lambda 表达式排序
- operateLogs = await table.QueryWhereString<BIOptLog>();
- //lambda 排序 降序
- operateLogs.Sort((x, y) => y.time.CompareTo(x.time));
- List<BIOptLog> bIOptLogs = operateLogs.Skip((page - 1) * size).Take(size).ToList();
- return Ok(new { state = 200, allcount = operateLogs.Count, bIOptLogs });
- }
- /// <summary>
- /// 流式传输响应
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-stream")]
- public async Task<IActionResult> GetStream()
- {
- var sw = Stopwatch.StartNew();
- //while (true)
- //{
- // var q = new Queue<int>();
- // for (int i = 0; i < 100_000_000; i++)
- // {
- // q.Enqueue(i);
- // q.Dequeue();
- // }
- // Console.WriteLine(sw.Elapsed);
- //}
- var ss = new SortedSet<int>(Enumerable.Repeat(42, 400_000));
- Console.WriteLine(sw.Elapsed);
- HttpContext.Response.ContentType = "text/plain";
-
- StreamWriter writer;
- //using (writer = new StreamWriter(HttpContext.Response.Body))
- // for (int i = 0; i < 100; i++)
- // {
- // await writer.WriteAsync($"S-{i} \n");
- // }
- // //await writer.FlushAsync("Hello World");
- return Ok(new { state = 200});
- }
- [HttpPost("get-linqcount")]
- public async Task<IActionResult> GetLinqCount()
- {
- List<linqTest> linqTests = new();
- for (int i = 0; i < 10; i++)
- {
- 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() } } };
- linqTests.Add(linqt);
- }
- //var set = linqTests.Select((x, y) => x.linq1s.Find(l => l.id.Equals($"abc0"))).ToList();
- var set = linqTests.Where(x=> !string.IsNullOrEmpty(x.linq1s.Find(l => l.id.Equals($"abc0")).ToString()) );
- //var tem220p = linqTests.ForEach(x => {
- // var coreUser = linqTests.Find(c => c.id.Equals("abc0"));
- // }); //.Except(linqTests.Select(y => y.linq1s.Find(n => n.times.Equals("abc0"))));
- return Ok(new { state = 200, linqTests, set });
- }
- /// <summary>
- /// 多个连接字符串方式
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-manydb")]
- public async Task<IActionResult> GetMany(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("site", out JsonElement site);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- var redisClinet = _azureRedis.GetRedisClient(8);
- if ($"{site}".Equals(BIConst.GlobalSite))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.GlobalSite);
- table = _azureStorage.GetCloudTableClient(BIConst.GlobalSite).GetTableReference("");
- redisClinet = _azureRedis.GetRedisClient(dbnum: 8, name: BIConst.GlobalSite);
- }
- #region 依赖注入的方式
- DateTimeOffset dateTime = DateTimeOffset.UtcNow;
- var dateDay = dateTime.ToString("yyyyMMdd"); //获取当天的日期
- Dictionary<long, int> allDays = new(); //所有在线人数
- Dictionary<long, int> tchDays = new(); //教师在线人数
- SortedSetEntry[] tchDay = _azureRedis.GetRedisClient(8).SortedSetRangeByScoreWithScores($"Login:IES:teacher:{dateDay}");
- if (tchDay.Length > 0)
- {
- foreach (var item in tchDay)
- {
- int val = ((int)item.Score);
- int key = ((int)item.Element);
- var utcTo = new DateTimeOffset(new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, key, 0, 0)).Hour;
- //var hour = int.Parse(DateTime.SpecifyKind(Convert.ToDateTime($"{dateTime.Year}/{dateTime.Month}/{ dateTime.Day} {key}:00:00"), DateTimeKind.Utc).ToLocalTime().ToString("HH"));
- tchDays.Add(utcTo, val);
- if (allDays.ContainsKey(utcTo))
- allDays[utcTo] = (allDays[utcTo] + val);
- else
- allDays.Add(utcTo, val);
- }
- }
- var redisGl = _azureRedis.GetRedisClient(dbnum: 0, name: "Global");
- var temps= await _azureRedis.GetRedisClient(dbnum: 0, name: "Global").SortedSetIncrementAsync($"Login:IES:Test", $"1", 1);//一天24小时 小时为单位
- var cosmosDefaulat = _azureCosmos.GetCosmosClient(); //默认数据库
- List<School> schools = new();
- await foreach (var item in cosmosDefaulat.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<School>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- schools.Add(item);
- }
- var cosmosGlobal = _azureCosmos.GetCosmosClient(name: "Global"); //默认数据库
- List<School> schoolGlobals = new();
- await foreach (var item in cosmosGlobal.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<School>(queryText: "select value(c) from c", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- schoolGlobals.Add(item);
- }
- return Ok(new { state = 200, dcnt = schools.Count, schools, dgcnt = schoolGlobals.Count, schoolGlobals });
- ////table多库连接
- //var tableDefulat = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin"); //Table默认表
- //List<DayLogin> hourLoginsDefualt = await tableDefulat.FindListByDict<DayLogin>(new Dictionary<string, object> { { "PartitionKey", $"DayLogin" } });
- //var table = _azureStorage.GetCloudTableClient("Global").GetTableReference("IESLogin"); //Table国际站
- //List<DayLogin> hourLogins= await table.FindListByDict<DayLogin>(new Dictionary<string, object> { { "PartitionKey", $"DayLogin" } });
- //return Ok(new { state = 200, hourLogins, hourLoginsDefualt });
- #endregion
- #region 原始方式
- //cosmosDB连接字符串
- //var clientUrl = _configuration.GetValue<string>("Azure:CosmosUrl:ConnectionString");
- //var clientKey = _configuration.GetValue<string>("Azure:CosmosKey:ConnectionString");
- //CosmosClient cosmosClient = new(clientUrl, clientKey);
- //var response = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync("hbcn", new PartitionKey("Base"));
- //School school = new();
- //if (response.Status == 200)
- //{
- // using var json = await JsonDocument.ParseAsync(response.ContentStream);
- // school = json.ToObject<School>();
- //}
- //Table连接字符串
- //var tableUrl = _configuration.GetValue<string>("Azure:StorageUrl:ConnectionString");
- //Uri url = new(tableUrl, UriKind.Absolute);
- //var tableKey = _configuration.GetValue<string>("Azure:StorageKey:ConnectionString");
- //StorageCredentials sta = new StorageCredentials("teammodeltest", tableKey);
- //CloudTableClient cloudTableClient = new CloudTableClient(url, sta);
- //var table1 = cloudTableClient.GetTableReference("IESLogin");
- //var tableGlobal = _configuration.GetValue<string>("AzureGlobal");
- //Dictionary<string, object> dic = new() { { "PartitionKey", $"HourLogin" } };
- //List<HourLogin> hourLogin = await table1.FindListByDict<HourLogin>(dic);
- //List<HourLogin> hourLogin1= await table.FindListByDict<HourLogin>(dic);
- //var table = _azureStorage.GetCloudTableClient().GetTableReference("IESLogin");
- //return Ok(new { state = 200 });
- #endregion
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="linqTestm"></param>
- /// <param name="site"></param>
- /// <returns></returns>
- [HttpPost("parameter")]
- public async Task<IActionResult> parameter(linqTest linqTestm, [FromHeader]string site)
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if ($"{site}".Equals(BIConst.GlobalSite))
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.GlobalSite);
- linqTest linqTest = new linqTest();
- linqTest.id = linqTestm.id; linqTest.name = linqTestm.name;
- var resp = await cosmosClient.GetContainer("TEAMModelOS", "School").ReadItemStreamAsync($"{linqTestm.id}", new PartitionKey("Base"));
- return Ok(new { state = 200, linqTest,cosmosClient,site });
- }
- [HttpPost("get-bizschool")]
- public async Task<IActionResult> GetTable(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey);
- jsonElement.TryGetProperty("rowKey", out JsonElement rowKey);
- var tableClient = _azureStorage.GetCloudTableClient();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
- BusinessSchool tempUser = table.Get<BusinessSchool>(partitionKey: $"{partitionKey}", rowKey: $"{rowKey}");
- return Ok(new { state = 200, table = tempUser });
- }
- public class linqTest
- {
- public string id{ get; set; }
- public string name { get; set; }
- public List<linq1> linq1s { get; set; }
- }
- public class linq1
- {
- public string id { get; set; }
- public long times { get; set; }
- }
- public class Test
- {
- public int age { get; set; }
- public string name { get; set; }
- public int score { get; set; }
- }
- public class strend
- {
- public int id { get; set; }
- public string name { get; set; }
- public int age { get; set; }
- }
- struct MyStruct
- {
- public int Count { get; set; }
- }
- class Example
- {
- public string? Name { get; set; }
- public string Value { get; set; }
- }
- public record TempSchool
- {
- public long ts { get; set; }
- public string id { get; set; }
- public string name { get; set; }
- }
- public static long GetMonthEnd(DateTimeOffset dt)
- {
- DateTime dtNew = new DateTime(dt.Year, dt.Month, 1);
- var ste = dtNew.AddMonths(1).AddDays(-1).Day;
- long iLastDay = DateTimeOffset.Parse($"{dt.Year}-{dt.Month}-{ste} 23:59:59").ToUnixTimeSeconds();
- return iLastDay;
- }
- public static long GetMonthStart(DateTimeOffset dt)
- {
- DateTime dtNew = new DateTime(dt.Year, dt.Month, 1);
- long iLastDay = DateTimeOffset.Parse($"{dtNew}").ToUnixTimeSeconds();
- return iLastDay;
- }
- public class GenerateRandom1
- {
- /// <summary>
- /// 生成随机数字
- /// </summary>
- /// <param name="length">生成长度</param>
- /// <returns></returns>
- public static string Number(int Length)
- {
- return Number(Length, false);
- }
- /// <summary>
- /// 生成随机数字
- /// </summary>
- /// <param name="Length">生成长度</param>
- /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
- /// <returns></returns>
- public static string Number(int Length, bool Sleep)
- {
- if (Sleep)
- System.Threading.Thread.Sleep(3);
- string result = "";
- System.Random random = new Random();
- for (int i = 0; i < Length; i++)
- {
- result += random.Next(10).ToString();
- }
- return result;
- }
- /// <summary>
- /// 生成随机字母与数字
- /// </summary>
- /// <param name="IntStr">生成长度</param>
- /// <returns></returns>
- public static string Str(int Length)
- {
- return Str(Length, false);
- }
- /// <summary>
- /// 生成随机字母与数字
- /// </summary>
- /// <param name="Length">生成长度</param>
- /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
- /// <returns></returns>
- public static string Str(int Length, bool Sleep)
- {
- if (Sleep)
- System.Threading.Thread.Sleep(3);
- 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' };
- string result = "";
- int n = Pattern.Length;
- System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
- for (int i = 0; i < Length; i++)
- {
- int rnd = random.Next(0, n);
- result += Pattern[rnd];
- }
- return result;
- }
- /// <summary>
- /// 生成随机纯字母随机数
- /// </summary>
- /// <param name="IntStr">生成长度</param>
- /// <returns></returns>
- public static string Str_char(int Length)
- {
- return Str_char(Length, false);
- }
- /// <summary>
- /// 生成随机纯字母随机数
- /// </summary>
- /// <param name="Length">生成长度</param>
- /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
- /// <returns></returns>
- public static string Str_char(int Length, bool Sleep)
- {
- if (Sleep) System.Threading.Thread.Sleep(3);
- //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' };
- 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' };
- string result = "";
- int n = Pattern.Length;
- System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
- for (int i = 0; i < Length; i++)
- {
- int rnd = random.Next(0, n);
- result += Pattern[rnd];
- }
- return result;
- }
- }
- }
- }
|