1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714 |
- 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 TEAMModelOS.SDK.Models.Service.BI;
- using TEAMModelOS.SDK.Context.BI;
- using TEAMModelOS.SDK.Context.Constant;
- using Azure.Storage.Blobs.Models;
- using Azure.Storage.Blobs;
- using Azure.Storage.Blobs.Specialized;
- using System.Web;
- using Azure.Storage.Sas;
- using DocumentFormat.OpenXml.Drawing.Diagrams;
- 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;
- private IPSearcher _ipSearcher;
- public TestController(IPSearcher ipSearcher, 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; _ipSearcher = ipSearcher;
- }
- /// <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(); //册别的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(); //章节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.Global))
- //{
- // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- // redisClinet = _azureRedis.GetRedisClient(dbnum: 8, name: BIConst.Global);
- //}
- 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();
- 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() { 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() { 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() { 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() { 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()
- {
- 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() { 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() { 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("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 value(COUNT(c.id)) from c where c.pk='Item' and c.field={i}";
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "School").GetItemQueryIterator<int>(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
- {
- total += item;
- //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").GetItemQueryIterator<int>(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
- {
- total += item;
- //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()
- {
- List<string> day7 = TimeHelper.GetNearDay(DateTimeOffset.UtcNow, 7);
- List<string> day30 = TimeHelper.GetNearDay(DateTimeOffset.UtcNow, 30);
- 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> endList1 = TimeHelper.GetYearMonthlyStartEnd(DateTimeOffset.UtcNow.Year);
- //return Ok(new { strList, dateTime, year, start, end, endList, endList1, endList2 });
- return Ok(new { day7, day30, 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();
- List<TempSchool> tempSchools = new();
- 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.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() { { "YMPCVCIM", "学情分析模组" }, { "IPDYZYLC", "智慧学校管理服务" }, { "3CLYJ6NP", "AClass ONE智慧学伴" }, { "IPALJ6NY", "数据储存服务空间" }, { "VABAJ6NV", "卷卡合一阅卷系统" } };
- var ste = prodict["IPDYZYLC"];
- List<string> str_str = new() { "12", "20", "13", "13", "14", "16" };
- List<strend> strends = new() { new strend { id = 1, name = "12", age = 20 }, new strend { id = 1, name = "13", age = 20 }, new strend { id = 2, name = "22", age = 22 }, new strend { id = 3, name = "23", age = 23 } };
- //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>
- /// <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>
- /// 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.Global))
- //{
- // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- // table = _azureStorage.GetCloudTableClient(BIConst.Global).GetTableReference("");
- // redisClinet = _azureRedis.GetRedisClient(dbnum: 8, name: BIConst.Global);
- //}
- #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="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-loganalyse")]
- public async Task<IActionResult> GetLogAnalyse(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("path", out JsonElement path)) return BadRequest();
- if (!jsonElement.TryGetProperty("timeType", out JsonElement jTimeType)) return BadRequest();
- List<string> filename = new();
- ////删除过期Blob 文件
- //var azureClient = _azureStorage.GetBlobContainerClient("0-public");//获取容器连接地址
- //int expireTime = int.Parse(DateTimeOffset.UtcNow.AddDays(-180).ToString("yyyyMMdd"));
- //await foreach (var blobItem in azureClient.GetBlobsAsync(BlobTraits.None, BlobStates.None, prefix: "visitCnt"))
- //{
- // string[] sub_name = blobItem.Name.Split('/');
- // if (sub_name.Length > 2)
- // {
- // if (int.Parse(sub_name[1]) <= expireTime)
- // {
- // await azureClient.GetBlobBaseClient(blobItem.Name).DeleteIfExistsAsync();
- // filename.add(sub_name[1]);
- // }
- // }
- //}
- var (an, saveUrl) = await BILogAnalyseService.GetPathAnalyse(_azureStorage, _ipSearcher, _dingDing, $"{path}", BIConst.LogChina, timeType:$"{jTimeType}");
- return Ok(new { state = RespondCode.Ok, cnt = filename.Count, filename, an, saveUrl });
- }
- /// <summary>
- /// 小时/天读取防火墙文件,分析;
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-savefile")]
- public async Task<IActionResult> GetSaveFile(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("time", out JsonElement time)) return BadRequest();
- long str = time.GetInt64();
- DateTimeOffset dateTimeJ = TimeHelper.GetDateTime(str);
- var datetime = dateTimeJ.AddHours(-1);
- var y = datetime.Year;
- var m = datetime.Month >= 10 ? $"{datetime.Month}" : $"0{datetime.Month}";
- var d = datetime.Day >= 10 ? $"{datetime.Day}" : $"0{datetime.Day}";
- var h = datetime.Hour >= 10 ? $"{datetime.Hour}" : $"0{datetime.Hour}";
-
- string path = $"resourceId=/SUBSCRIPTIONS/73B7F9EF-D8B7-4444-9E8D-D80B43BF3CD4/RESOURCEGROUPS/TEAMMODELCHENGDU/PROVIDERS/MICROSOFT.NETWORK/APPLICATIONGATEWAYS/OSFIREWARE/y={y}/m={m}/d={d}/h={h}/m=00/PT1H.json";
- var retn = await BILogAnalyseService.GetPathAnalyse(_azureStorage, _ipSearcher, _dingDing, path, BIConst.LogChina);
- if (retn.recCnts.IsNotEmpty())
- {
- //https://teammodelos.blob.core.chinacloudapi.cn/0-public/pie-borderRadius.html
- string publishUrl = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={HttpUtility.UrlEncode(retn.saveUrls.First(), Encoding.UTF8)}&time={HttpUtility.UrlEncode(datetime.AddHours(8).ToString("yyyy年MM月dd日 HH时"), Encoding.UTF8)}";
- string ulrs = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={retn.saveUrls.First()}&time={datetime.AddHours(8).ToString("yyyy年MM月dd日 HH时")}";
- string ulr = $"http://cdhabook.teammodel.cn:8805/screen/screenshot-png?width=1920&height=1450&url={HttpUtility.UrlEncode(ulrs, Encoding.UTF8)}&delay=6000";
- string image = "";
- try
- {
- string strs = await _httpClient.GetStringAsync(ulr);
- if (!string.IsNullOrWhiteSpace(strs))
- {
- JsonElement json = strs.ToObject<JsonElement>();
- json.TryGetProperty("url", out JsonElement base64);
- using (MemoryStream ms = new MemoryStream(Convert.FromBase64String($"{base64}")))
- {
- image = await _azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(ms, $"visitCnt/{y}{m}{d}", $"{h}.png", false);
- }
- }
- }
- catch (Exception ex) { }
- //await _dingDing.SendBotMarkdown("防火墙日志记录", $"#### 测试(小时)-防火墙日志记录\n> 记录时间:{datetime.AddHours(8).ToString("yyyy-MM-dd HH")}\n> \n> ###### 发布时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}" +
- // $" [发布地址]({publishUrl}) \n", GroupNames.醍摩豆服務運維群組);
- }
- if (h.Equals("00"))
- {
- var pastTime = datetime.AddHours(-1);
- var ptY = pastTime.Year;
- var ptM = pastTime.Month >= 10 ? $"{pastTime.Month}" : $"0{pastTime.Month}";
- var ptD = pastTime.Day >= 10 ? $"{pastTime.Day}" : $"0{pastTime.Day}";
- string dayPath = $"resourceId=/SUBSCRIPTIONS/73B7F9EF-D8B7-4444-9E8D-D80B43BF3CD4/RESOURCEGROUPS/TEAMMODELCHENGDU/PROVIDERS/MICROSOFT.NETWORK/APPLICATIONGATEWAYS/OSFIREWARE/y={ptY}/m={ptM}/d={ptD}";
- var dayRetn = await BILogAnalyseService.GetPathAnalyse(_azureStorage, _ipSearcher, _dingDing, dayPath, BIConst.LogChina, timeType: "Day");
- if (dayRetn.recCnts.IsNotEmpty())
- {
- //一天的统计
- string dayPublishUrl = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={HttpUtility.UrlEncode(dayRetn.saveUrls.First(), Encoding.UTF8)}&time={HttpUtility.UrlEncode(pastTime.ToString("yyyy年MM月dd日"), Encoding.UTF8)}";
- string dayUrls = $"https://teammodelos.blob.core.chinacloudapi.cn/0-public/api-count.html?url={dayRetn.saveUrls.First()}&time={pastTime.ToString("yyyy年MM月dd日")}";
- string dayUrl = $"http://cdhabook.teammodel.cn:8805/screen/screenshot-png?width=1920&height=1450&url={HttpUtility.UrlEncode(dayUrls, Encoding.UTF8)}&delay=6000";
- string dayImage = "";
- string dayStr = await _httpClient.GetStringAsync(dayUrl);
- if (!string.IsNullOrWhiteSpace(dayStr))
- {
- JsonElement dayJson = dayStr.ToObject<JsonElement>();
- dayJson.TryGetProperty("url", out JsonElement dayBase64);
- using (MemoryStream dayMs = new(Convert.FromBase64String($"{dayBase64}")))
- {
- dayImage = await _azureStorage.GetBlobContainerClient("0-public").UploadFileByContainer(dayMs, $"visitCnt/{ptY}{ptM}{ptD}", "days.png", false);
- }
- }
- await _dingDing.SendBotMarkdown("测试-防火墙日志记录", $"#### 测试(天)-防火墙日志记录\n> 记录时间:{pastTime.AddHours(2).ToString("yyyy-MM-dd")}\n> \n> ###### 发布时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}" +$" [发布地址]({dayPublishUrl}) \n", GroupNames.成都开发測試群組);
- }
- }
- return Ok(new { state = 200});
- }
- /// <summary>
- /// 测试研究table 表分页的问题
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-logrec")]
- public async Task<IActionResult> GetLogRec(JsonElement jsonElement)
- {
- int takeCount = 500;
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIOptLog");
- var table1 = _azureStorage.GetCloudTableClient();
- int pagesize = 10;
- int pageNum = 2;
- var query = (from entity in table.CreateQuery<BIOptLog>()
- select entity).ToList().Skip(pagesize * (pageNum - 1)).Take(pagesize);
- //var query = (from entity in table.CreateQuery<BIOptLog>()
- // orderby entity.time descending
- // select entity).Skip(pagesize * (pageNum - 1)).Take(pagesize);
- //var ster = AzureStorageTableExtensions.GetTablePage<BIOptLog>(table1, "BIOptLog", 10, 1);
- return Ok(new { state = 200, query });
- }
- [HttpPost("get-noticev2")]
- public async Task<IActionResult> SetNoticeV2()
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- //v2通知
- Teacher targetTeacher = await cosmosClient.GetContainer(Constant.TEAMModelOS, Constant.Teacher).ReadItemAsync<Teacher>("1636016499", new PartitionKey("Base"));
- _coreAPIHttpService.PushNotify(new List<IdNameCode> { new IdNameCode { id = targetTeacher.id, name = targetTeacher.name, code = targetTeacher.lang } }, "create-school", Constant.NotifyType_IES5_Management, new Dictionary<string, object> { { "tmdname", $"{targetTeacher.name}" }, { "schooName", "商务智能学校(BI)" }, { "schoolId", "cswznb" }, { "tmdid", $"{targetTeacher.id}" } }, _option.Location, _configuration, _dingDing, _environment.ContentRootPath);
- return Ok(new { state = RespondCode.Ok });
- }
- [HttpPost("set-copyfile")]
- public async Task<IActionResult> SetCopyFile()
- {
- List<Task<CopyFromUriOperation>> filelist = new List<Task<CopyFromUriOperation>>();
- //var azureClient = _azureStorage.GetBlobContainerClient($"0-public");//获取容器连接地址
- ////查询目录下所有容器路径
- //await foreach (BlobItem blobItem in azureClient.GetBlobsAsync(BlobTraits.None, BlobStates.None, $"TestMP4Max/"))
- //{
- // string newurl = $"{blobItem.Name}".Replace($"/SourceFile/", $"/SourceFiles/");//替换成新的容器路径
- // var urlSas = _azureStorage.GetBlobSAS($"0-public", blobItem.Name, BlobSasPermissions.Read | BlobSasPermissions.List); //获取容器sas和有效期
- // //await azureClient.GetBlobClient(newurl).StartCopyFromUriAsync(new Uri(urlSas));
- // filelist.Add(azureClient.GetBlobClient(newurl).StartCopyFromUriAsync(new Uri(urlSas)));
- // //await azureClient.GetBlobClient(newurl).SyncCopyFromUriAsync(new Uri(urlSas)); //添加复制文件到集合执行复制操作
- //}
- //if (filelist.Count <= 256)
- //{
- // await Task.WhenAll(filelist);
- //}
- //else
- //{
- // int pages = (filelist.Count + 255) / 256;
- // for (int i = 0; i < pages; i++)
- // {
- // List<Task<CopyFromUriOperation>> rspBlobCopyInfos = filelist.Skip((i) * 256).Take(256).ToList();
- // await Task.WhenAll(rspBlobCopyInfos);
- // }
- //}
- var azureClient = _azureStorage.GetBlobContainerClient($"1636016499");//获取容器连接地址
- //查询目录下所有容器路径
- await foreach (BlobItem blobItem in azureClient.GetBlobsAsync(BlobTraits.None, BlobStates.None, $"doc"))
- {
- string newurl = $"{blobItem.Name}".Replace($"doc/", $"/SourceFiles/");//替换成新的容器路径
- var urlSas = _azureStorage.GetBlobSAS($"1636016499", blobItem.Name, BlobSasPermissions.Read | BlobSasPermissions.List); //获取容器sas和有效期
- //await azureClient.GetBlobClient(newurl).StartCopyFromUriAsync(new Uri(urlSas));
- await azureClient.GetBlobClient(newurl).StartCopyFromUriAsync(new Uri(urlSas));
- //await azureClient.GetBlobClient(newurl).SyncCopyFromUriAsync(new Uri(urlSas)); //添加复制文件到集合执行复制操作
- }
- return Ok(new { state = 200 , filelist });
- }
- [HttpPost("test-copy-file")]
- public async Task<IActionResult> TestCaopyFile()
- {
- string blobName = "cswznb";
- string oldFile = "https://teammodeltest.blob.core.chinacloudapi.cn/cswznb/survey%2Fd011c05b-c009-0a53-428f-b871a58092c7%2Findex.json";//"https://teammodeltest.blob.core.chinacloudapi.cn/1636016499/yxpt%2Fstandard2%2FTEAMModelOS%E6%95%B0%E6%8D%AE%E5%BA%93.doc";
- string oldId = "survey";
- string newId = "survey1";
- List<Task<CopyFromUriOperation>> filelist = new(); //可复制256M以上文件
- //var set = await BatchCopyFileService.SingleCopyFile(_azureStorage, blobName, oldFile, oldId, newId);
- var set = await SingleCopyFile(_azureStorage, blobName, oldFile, oldId, newId);
- //var azureClient = _azureStorage.GetBlobContainerClient($"{blobName}");//获取容器连接地址
- //string newurl = $"{oldFile}".Replace($"/{oldId}/", $"/{newId}/");//替换成新的容器路径
- //var urlSas = _azureStorage.GetBlobSAS($"{blobName}", $"{newurl}", BlobSasPermissions.Read | BlobSasPermissions.List); //获取容器sas和有效期
- //var setr = azureClient.GetBlobClient(newurl).StartCopyFromUriAsync(new Uri(urlSas)); //可复制256M以上文件
- return Ok(new { state = 200 });
- }
- public static Task<int> SingleCopyFile(AzureStorageFactory _azureStorage, string blobName, string oldFile, string oldId, string newId)
- {
- var azureClient = _azureStorage.GetBlobContainerClient($"{blobName}");//获取容器连接地址
- string newurl = oldFile.Substring(oldFile.IndexOf($"{blobName}/") + $"{blobName}/".Length).Replace($"{oldId}", $"{newId}");//替换成新的容器路径
- string oldFileName = oldFile.Substring(oldFile.IndexOf($"{blobName}/") + $"{blobName}/".Length);
- var urlSas = _azureStorage.GetBlobSAS($"{blobName}", "", BlobSasPermissions.Read | BlobSasPermissions.List); //获取容器sas和有效期
- //var respCopy = azureClient.GetBlobClient(HttpUtility.UrlDecode(newurl)).SyncCopyFromUri(new Uri(urlSas)); //可复制256M以下文件
- var respCopy1 = azureClient.GetBlobClient(HttpUtility.UrlDecode(newurl)).StartCopyFromUriAsync(new Uri(urlSas)); //可复制256M以上文件
- return null;
- }
- 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;
- }
- }
- }
- }
|