1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239 |
- using Microsoft.Azure.Cosmos;
- using DingTalk.Api;
- using DingTalk.Api.Request;
- using DingTalk.Api.Response;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- 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;
- 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 TEAMModelOS.SDK.Models.Service.BIStatsWay;
- using MathNet.Numerics.LinearAlgebra.Double;
- using TEAMModelOS.SDK.Models.Cosmos.BI.BISchool;
- using Microsoft.OData.Edm;
- using TEAMModelOS.SDK.Models.Cosmos.OpenEntity;
- using TEAMModelOS.SDK.Models.Cosmos.BI.BICommon;
- using Microsoft.Azure.Cosmos.Table;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.Azure.Amqp.Framing;
- using TEAMModelOS.SDK.Models.Dtos;
- using Microsoft.Extensions.Logging;
- using WebSocketSharp;
- using System.Security.Policy;
- using Azure.Messaging.ServiceBus.Administration;
- using static TEAMModelOS.SDK.CoreAPIHttpService;
- using System.Xml;
- using System.Drawing.Printing;
- using TEAMModelOS.SDK.DI.IPIP;
- using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter;
- using static TEAMModelOS.SDK.Extension.GeoRegion;
- 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 IHttpClientFactory _httpClient;
- private IPSearcher _ipSearcher;
- private readonly City _city;
- public TestController(IPSearcher ipSearcher, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, AzureRedisFactory azureRedis, DingDing dingDing, IOptionsSnapshot<Option> option, IWebHostEnvironment hostingEnvironment, IConfiguration configuration, CoreAPIHttpService coreAPIHttpService, IHttpClientFactory httpClient, City city)
- {
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _azureRedis = azureRedis;
- _dingDing = dingDing;
- _option = option?.Value;
- _environment = hostingEnvironment;
- _configuration = configuration;
- _coreAPIHttpService = coreAPIHttpService;
- _httpClient = httpClient; _ipSearcher = ipSearcher;
- _city = city;
- }
- /// <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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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 blob = _azureStorage.GetBlobContainerClient(containerName: "hbcn");
- await foreach (BlobItem blobItem in blob.GetBlobsAsync(BlobTraits.None, BlobStates.None, $"records/{383558646003404800}/IES"))
- {
- if (blobItem.Name.EndsWith("base.json") || blobItem.Name.EndsWith("TimeLine.json"))
- {
- BlobClient tempClient = blob.GetBlobClient(blobItem.Name);
- if (await tempClient.ExistsAsync())
- {
- using (var meomoryStream = new MemoryStream())
- {
- var response = blob.GetBlobClient($"{blobItem.Name}").DownloadTo(meomoryStream);
- string setr = Encoding.UTF8.GetString(meomoryStream.ToArray()).ToString();
- //LessonBase res = Encoding.UTF8.GetString(meomoryStream.ToArray()).ToString().ToObject<LessonBase>();
- //var response = await blob.GetBlobClient($"{blobItem.Name}").DownloadToAsync(meomoryStream);
- //RecCnt recCnt = Encoding.UTF8.GetString(meomoryStream.ToArray()).ToString().ToObject<RecCnt>();
- //string name = stringSuffix.MidStrEx(blobItem.Name, "/", ".");
- }
- }
- }
- }
- //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数据 sql
- /// </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").GetItemQueryIteratorSql<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.Content);
- // 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").GetItemQueryStreamIteratorSql(queryText: stringBuilder.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Base") }))
- {
- using var jsonSchool = await JsonDocument.ParseAsync(itemSchool.Content);
- 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.StatusCode == HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- 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.StatusCode == HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- 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").GetItemQueryIteratorSql<int>(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
- {
- total += item;
- //using var json = await JsonDocument.ParseAsync(item.Content);
- //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").GetItemQueryIteratorSql<int>(queryText: sqlText, requestOptions: new QueryRequestOptions() { }))
- {
- total += item;
- //using var json = await JsonDocument.ParseAsync(item.Content);
- //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<StartEndTime> everyDay = TimeHelper.GetYearEveryDay(DateTimeOffset.UtcNow, isCurrDay: true);
- //return Ok(new { state = RespondCode.Ok, dayCnt = everyDay.Count, everyDay });
- 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);
- }
- DateTimeOffset date = DateTimeOffset.FromUnixTimeMilliseconds(1672884420686);
- var (start5, end5) = TimeHelper.GetStartOrEnd(date, "lastterm");
- var (start4, end4) = TimeHelper.GetStartOrEnd(date, "term");
- var start = GetMonthStart(ere);
- List<StartEndTime> endList1 = TimeHelper.GetYearMonthlyStartEnd(DateTimeOffset.UtcNow.Year);
- //return Ok(new { strList, dateTime, year, start, end, endList, endList1, endList2 });
- return Ok(new { day7, day30, datetime7, start4, end4, start5, end5 });
- }
- 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").GetItemQueryStreamIteratorSql(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.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: sqlTxt, requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(tempPage.Content);
- 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").GetItemQueryStreamIteratorSql(queryText: "select value(c) from c", continuationToken: pageToken, requestOptions: new QueryRequestOptions() { MaxItemCount = pageSize, PartitionKey = new PartitionKey("Base") }))
- {
- using var json = await JsonDocument.ParseAsync(item.Content);
- 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.ContinuationToken;
- break;
- }
- }
- }
- return Ok(new { state = 200, continuationToken, count = schools.Count, 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();
- int takeCount = 500;
- 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, 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 });
- }
- /// <summary>
- /// lingq 查询
- /// </summary>
- /// <returns></returns>
- [HttpPost("get-linqcount")]
- public async Task<IActionResult> GetLinqCount()
- {
- List<linqTest> linqTests = new()
- {
- new linqTest { id = "10110",aresid = "0",name ="明",linq1 = new linq1 { id ="abc0", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } } ,
- new linqTest { id = "10111",aresid = "1",name ="明1",linq1 = new linq1 { id ="abc1", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } } ,
- new linqTest { id = "10112",aresid = "2",name ="明2",linq1 = new linq1 { id ="abc2", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } } ,
- new linqTest { id = "10113",aresid = "3",name ="明3",linq1 = new linq1 { id ="abc3", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } } ,
- new linqTest { id = "10114",aresid = "4",name ="明4",linq1 = new linq1 { id ="abc4", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } },
- new linqTest { id = "10115",aresid = "5",name ="明5",linq1 = new linq1 { id ="abc5", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } } ,
- new linqTest { id = "10116",aresid = "6",name ="明6",linq1 = new linq1 { id ="abc6", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } },
- new linqTest { id = "10117",aresid = "7",name ="明7",linq1 = new linq1 { id ="abc7", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } },
- new linqTest { id = "10118",aresid = "8",name ="明8",linq1 = new linq1 { id ="abc8", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } },
- new linqTest { id = "10119",aresid = "9",name ="明9",linq1 = new linq1 { id ="abc9", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } },
- new linqTest { id = "10120",aresid = "10",name ="明10",linq1 = new linq1 { id ="abc10", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),cnt=10 } }
- };
- for (int i = 0; i < 11; i++)
- {
- linqTest linqt = new() { id = $"qwe{i}", aresid = $"{i}", name = $"名字{i}", linq1 = new linq1 { id = $"abc{i}", times = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), cnt = (11 + i) } };
- linqTests.Add(linqt);
- }
- var grup = linqTests.GroupBy(g => g.aresid).ToList();
- var grup1 = linqTests.GroupBy(g => g.aresid).Select(s=>new { areid= s.Key,linq1Id = s.Select(sn => sn.linq1.id).ToList(), id = s.Select(sn => sn.id).ToList(), name = s.Select(sn => sn.name).ToList(), linq1Cnt = s.Select(sn => sn.linq1.cnt).ToList(), lescnt = s.Select(sf=>sf.linq1.cnt).Sum()}).ToList();
- return Ok(new { state = RespondCode.Ok, grup1, grup });
- List<Test> list1 = new()
- {
- new Test { score = 10, name = "001" },
- new Test { score = 20, name = "002" },
- new Test { score = 30, name = "003" },
- new Test { score = 40, name = "004" },
- new Test { score = 50, name = "005" },
- new Test { score = 60, name = "006" }
- };
- List<Test> list2 = new()
- {
- new Test { score = 40, name = "004" },
- new Test { score = 50, name = "005" },
- new Test { score = 60, name = "006" },
- new Test { score = 70, name = "007" },
- new Test { score = 80, name = "008" },
- new Test { score = 90, name = "009" },
- 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");
- //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, Mon, Sun, ss, sss, ssss, sssss, lastWeekStart, lastWeekEnd, have, en2, bingji, cha, jiaoji, chaji, list3, list4, temp, list1, linqTests });
- }
- /// <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").GetItemQueryIteratorSql<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").GetItemQueryIteratorSql<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.Content);
- // 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>
- /// 测试删除过期Blob 文件
- /// </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, _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, _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://52.130.252.100:8805/screen/screenshot-png?width=1920&height=1450&url={HttpUtility.UrlEncode(ulrs, Encoding.UTF8)}&delay=6000";
- string image = "";
- try
- {
- string strs = await _httpClient.CreateClient().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, _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://52.130.252.100:8805/screen/screenshot-png?width=1920&height=1450&url={HttpUtility.UrlEncode(dayUrls, Encoding.UTF8)}&delay=6000";
- string dayImage = "";
- string dayStr = await _httpClient.CreateClient().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>
- /// 端外通知
- /// </summary>
- /// <returns></returns>
- [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 });
- }
- /// <summary>
- /// 复制文件
- /// </summary>
- /// <returns></returns>
- [HttpPost("set-copyfile")]
- public async Task<IActionResult> SetCopyFile()
- {
- ///单个复制文件
- 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 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}", $"{HttpUtility.UrlDecode(oldFileName)}", BlobSasPermissions.Read | BlobSasPermissions.List); //获取容器sas和有效期
- ////var respCopy = azureClient.GetBlobClient(HttpUtility.UrlDecode(newurl)).SyncCopyFromUri(new Uri(urlSas)); //可复制256M以下文件
- //var respCopy1 = await azureClient.GetBlobClient(HttpUtility.UrlDecode(newurl)).StartCopyFromUriAsync(new Uri(urlSas)); //可复制256M以上文件
- //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.fullUri));
- //await azureClient.GetBlobClient(newurl).SyncCopyFromUriAsync(new Uri(urlSas)); //添加复制文件到集合执行复制操作
- }
- return Ok(new { state = 200, filelist });
- }
- /// <summary>
- /// 计算一年每月的数据
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("get-yearmonsum")]
- public async Task<IActionResult> GetYearMonthSum(JsonElement jsonElement)
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- //LessonStats lessonStats =await StatsWay.GetLessStats(cosmosClient, "hbcn");
- //ActivityStats artStats = await StatsWay.GetActStats(cosmosClient, "hbcn");
- //var tempSc = SchoolStatsWay.GetSingleSc(cosmosClient, "hbcn");
- //return Ok(new { state = 200, ld= artStats.LastYear.Count, d = artStats.year.Count, artStats });
- //示例矩阵
- List<List<double>> matrixDou = new() {
- new List<double>() { 6, 5, 4, 3, 2, 1},
- new List<double>() { 2, 3, 4, 5, 6, 7 },
- new List<double>() { 3, 4, 5, 6, 7, 8 },
- new List<double>() { 4, 5, 6, 7, 8, 9 }
- };
- var artYear = DenseMatrix.OfColumns(matrixDou);
- var rc = artYear.RowCount;
- var cc = artYear.ColumnCount;
- List<double> dous1 = new(); ;
- List<double> dous = new(); ;
- for (int i = 0; i < artYear.RowCount; i++)
- {
- Console.WriteLine($"次数:{i} ; 行数:{rc};列数:{cc}");
- var cl = matrixDou.SelectMany(o => o.Skip(i).Take(1)).ToList();
- var cl1 = matrixDou.SelectMany(o => o.Skip(i).Take(1)).ToList().Sum();
- dous1.Add(cl1);
- var stet = artYear.SubMatrix(i, 1, 0, cc);
- var stet1 = artYear.SubMatrix(i, 1, 0, cc).ColumnSums().Sum();
- dous.Add(stet1);
- //var set = artYear.SubMatrix(0, 4, i, i+1).ColumnSums().Sum();
- //dous.Add(set);
- }
- var s = DateTimeOffset.UtcNow.Year - 1;
- DateTimeOffset date = new(DateTimeOffset.UtcNow.Year - 1, DateTimeOffset.UtcNow.Month, DateTimeOffset.UtcNow.Day, DateTimeOffset.UtcNow.Hour, DateTimeOffset.UtcNow.Minute, DateTimeOffset.UtcNow.Second, TimeSpan.Zero);
- //计算一年每天的开始/结束时间
- List<StartEndTime> leveryDay = TimeHelper.GetYearEveryDay(date);
- List<StartEndTime> everyDay = TimeHelper.GetYearEveryDay(DateTimeOffset.UtcNow, isCurrDay: true);
- List<double> doubles = new() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 6, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 16, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 98, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366 };
- DateTimeOffset dateTime = DateTimeOffset.UtcNow;
- List<YearMonth> monthty = TimeHelper.GetYearMonth(doubles, dateTime.Year);
- return Ok(new { state = RespondCode.Ok, leverycnt = leveryDay.Count, leveryDay, dayCnt = everyDay.Count, everyDay, monthty });
- }
- /// <summary>
- /// 测试矩阵
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("set-matrix")]
- public async Task<IActionResult> SetMatrix(JsonElement jsonElement)
- {
- DateTimeOffset dateOff = DateTimeOffset.UtcNow;
- string df = dateOff.ToString("yyyyMMdd");
- var (weekS, weekE) = TimeHelper.GetStartOrEnd(dateOff, "week"); //计算本周开始/结束时间
- DateTimeOffset dateOff1 = DateTimeOffset.Parse("2023-1-1 01:20:50");
- DateTimeOffset dateOff2 = DateTimeOffset.Parse("2023-1-1 00:20:50");
- var (termS, termE) = TimeHelper.GetStartOrEnd(dateOff, "term"); //计算本学期开始/结束时间
- var (termDayS, termDayE) = TimeHelper.GetLongToTime(termS, termE);
- var day = dateOff1.DayOfYear;
- var hour = dateOff1.Hour;
- var hour1 = dateOff2.Hour;
- var (weekDayS, weekDayE) = TimeHelper.GetLongToTime(weekS, weekE);
- var days = dateOff.DayOfYear - weekDayS.DayOfYear+1;
- List<double> doub = new() { 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7 };
- List<double> doub1 = new() { 0, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7 };
- DenseMatrix matris = DenseMatrix.OfColumns(new List<List<double>>() { doub });
- DenseMatrix lastMatris = DenseMatrix.OfColumns(new List<List<double>>() { doub1 });
- if (termDayS.Year < dateOff.Year)
- {
- int term = ((int)matris.SubMatrix(termDayS.DayOfYear - 1, termDayE.DayOfYear - termDayS.DayOfYear + 1, 0, matris.ColumnCount).ColumnSums().Sum());
- }
- else
- {
- int term = ((int)matris.SubMatrix(termDayS.DayOfYear - 1, termDayE.DayOfYear - termDayS.DayOfYear + 1, 0, matris.ColumnCount).ColumnSums().Sum());
- }
- var weekDays = matris.SubMatrix(weekDayS.DayOfYear-1, 7, 0, matris.ColumnCount);
- int week = ((int)matris.SubMatrix(weekDayS.DayOfYear, dateOff.DayOfYear - weekDayS.DayOfYear+1, 0, matris.ColumnCount).ColumnSums().Sum());
- var cosmosClient = _azureCosmos.GetCosmosClient();
- //LessonStats lessonStats =await StatsWay.GetLessStats(cosmosClient, "hbcn");
- //ActivityStats artStats = await StatsWay.GetActStats(cosmosClient, "hbcn");
- //var tempSc = SchoolStatsWay.GetSingleSc(cosmosClient, "hbcn");
- //return Ok(new { state = 200, ld= artStats.LastYear.Count, d = artStats.year.Count, artStats });
- //示例矩阵
- DateTimeOffset dt = DateTimeOffset.UtcNow;
- int dayCnt = dt.DayOfYear;
- List<double> set = new double[366].ToList();
- List<List<double>> doubs = new() {
- new List<double>() { 6, 5, 4, 3, 2, 1},
- new List<double>() { 2, 3, 4, 5, 6, 7 }
- };
- var artTerm = DenseMatrix.OfColumns(doubs);
- //var temp1 = artTerm.SetRow(1, 5);
- var temp = artTerm.SubMatrix(1, 5, 0, artTerm.ColumnCount);
- List<List<double>> doubles = new() {
- new List<double>() { 6, 5, 4, 3, 2, 1},
- new List<double>() { 2, 3, 4, 5, 6, 7 },
- new List<double>() { 3, 4, 5, 6, 7, 8 },
- new List<double>() { 4, 5, 6, 7, 8, 9 }
- };
- var artYear = DenseMatrix.OfColumns(doubles);
- var rc = artYear.RowCount;
- var cc = artYear.ColumnCount;
- List<double> dous1 = new(); ;
- List<double> dous = new(); ;
- for (int i = 0; i < artYear.RowCount; i++)
- {
- Console.WriteLine($"次数:{i} ; 行数:{rc};列数:{cc}");
- var cl = doubles.SelectMany(o => o.Skip(i).Take(1)).ToList();
- var cl1 = doubles.SelectMany(o => o.Skip(i).Take(1)).ToList().Sum();
- dous1.Add(cl1);
- var stet = artYear.SubMatrix(i, 1, 0, cc);
- var stet1 = artYear.SubMatrix(i, 1, 0, cc).ColumnSums().Sum();
- dous.Add(stet1);
- //var set = artYear.SubMatrix(0, 4, i, i+1).ColumnSums().Sum();
- //dous.Add(set);
- }
- // double[][] matrix1 = new double[][]
- // {
- //new double[] { 1, 2, 3 },
- //new double[] { 4, 5, 6 },
- //new double[] { 7, 8, 9 }
- // };
- // double[][] matrix2 = new double[][]
- // {
- //new double[] { 2, 3, 4 },
- //new double[] { 5, 6, 7 },
- //new double[] { 8, 9, 10 }
- // };
- // //矩阵加法
- // PrintMatrix(MatrixAdd(matrix1, matrix2));
- // Console.WriteLine();
- return Ok(new { state = 200, set ,dous1, dous /*tempSc*/ });
- }
- /// <summary>
- /// 测试版本
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("set-sc-edittion")]
- public async Task<IActionResult> SetSchoolEdition(JsonElement jsonElement)
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- if (!jsonElement.TryGetProperty("scId", out JsonElement scId)) return BadRequest();
- List<string> server = new() { "YMPCVCIM" };
- ////_ = BISchoolService.UpSchoolEdition(cosmosClient, _dingDing, server, "habook");
- return Ok(new { state = 200 });
- }
- /// <summary>
- /// 每天执行一次
- /// </summary>
- /// <returns></returns>
- [HttpPost("set-statszero")]
- public async Task<IActionResult> SetStatsZero()
- {
- double roomCnt= await SchoolStatsWay.GetShoolWisdomRoomCount(_azureCosmos, _azureRedis, _configuration, _httpClient, _dingDing, "hbcn");
- await BIStats.SetStatsZeroPoint(_azureCosmos, _dingDing);
- return Ok(new { });
- }
- /// <summary>
- /// 测试汇总
- /// </summary>
- /// <returns></returns>
- [HttpPost("set-apiorfun")]
- public async Task<IActionResult> SetApiOrFun(JsonElement jsonElement)
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- StatsNotice statsNotice = new() { id = "20230131-1636016499", type = "private", day= "20230131", rangeId = "1636016499", createTime = 1675133709000, sendTime = 1675180799000, stuDayCnt = 1, classroomDayCnt = 2, weighDayCnt = 3, homeworkDayCnt = 4 };
- await BIStatsNotice.SetStatsNotice(cosmosClient, _dingDing, "Student", "School", "1636016499", 2);
- //await BIStatsNotice.MonitorStatsNotice(_coreAPIHttpService, cosmosClient, _dingDing, _configuration, jsonElement);
- //statsNotice = await cosmosClient.GetContainer(Constant.TEAMModelOS, "Common").CreateItemAsync<StatsNotice>(statsNotice, new PartitionKey("StatsNotice"));
- return Ok(new { state = 200, statsNotice });
- }
- /// <summary>
- /// 测试依据类型增/减量统计方法
- /// </summary>
- /// <param name="json"></param>
- /// <returns></returns>
- [HttpPost("set-stats")]
- public async Task<IActionResult> SetStats(JsonElement json)
- {
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var SETR = _option.Location;
- await BIStats.SetTypeAddStats(cosmosClient, _dingDing, "hbcn", "Homework", 1, careDate: 1672967274766);
- return Ok(new { state = 200 });
- }
- /// <summary>
- /// 生成BI新通知資料格式
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- #if !DEBUG
- [Authorize(Roles = "IES")]
- #endif
- [HttpPost("crt-binotice-data")]
- public async Task<IActionResult> CrtBiNoticeData(JsonElement jsonElement)
- {
- var client = _azureCosmos.GetCosmosClient();
- //批次
- BINotice bINoticeM = new BINotice();
- bINoticeM.id = "6ec182ab-ad08-43f4-8cc2-6fdbd985f584";
- bINoticeM.msgType = "email";
- bINoticeM.selType = "mul";
- bINoticeM.accept = new List<PickParam>();
- ///學區
- PickParam area = new PickParam() {
- mode = "area",
- areaId = "02944f32-f534-3397-ea56-e6f1fc6c3714"
- };
- bINoticeM.accept.Add(area);
- ///地理 學校
- PickParam geoSch = new PickParam() {
- mode = "schGeo",
- countryId = "TW",
- cityId = "30"
- };
- bINoticeM.accept.Add(geoSch);
- ///地理 ID
- PickParam geoId = new PickParam()
- {
- mode = "tmidGeo",
- countryId = "TW",
- cityId = "30"
- };
- bINoticeM.accept.Add(geoId);
- ///機構
- PickParam inst = new PickParam()
- {
- mode = "inst",
- unitType = "1"
- };
- bINoticeM.accept.Add(inst);
- ///學校ID
- PickParam sch = new PickParam()
- {
- mode = "sch",
- school = new NoticeSchool() { eduId = "hbgl", shortCode = "hbgl", name = "測試學校" }
- };
- bINoticeM.accept.Add(sch);
- await client.GetContainer(Constant.TEAMModelOS, Constant.Common).UpsertItemAsync(bINoticeM, new PartitionKey($"BINotice"));
- //個別
- BINotice bINoticeS = new BINotice();
- bINoticeS.id = "9760087c-e29c-494d-9a17-3523f6ddbc27";
- bINoticeS.msgType = "email";
- bINoticeS.selType = "sin";
- ///搜尋資料
- bINoticeS.search = new List<PickParam>();
- ///生成時間
- PickParam crtTime = new PickParam()
- {
- mode = "crtTime",
- crtFrom = 1588262400,
- crtTo = 1609430399
- };
- bINoticeS.search.Add(crtTime);
- ///地理資訊
- PickParam tmidGeo = new PickParam()
- {
- mode = "tmidGeo",
- countryId = "TW",
- cityId = "30"
- };
- bINoticeS.search.Add(tmidGeo);
- ///軟體使用
- PickParam softUse = new PickParam()
- {
- mode = "softUse"
- };
- softUse.softUse.Add("HiTeach");
- softUse.softUse.Add("HiTeachCC");
- softUse.softUse.Add("HiTA");
- softUse.softUse.Add("IES5");
- bINoticeS.search.Add(softUse);
- ///積分
- PickParam point = new PickParam()
- {
- mode = "point",
- pointFrom = 10,
- pointTo = 80
- };
- bINoticeS.search.Add(point);
- ///預選學校
- PickParam schPre1 = new PickParam()
- {
- mode = "sch",
- school = new NoticeSchool() { eduId = "hbgl", shortCode = "hbgl", name = "測試學校" }
- };
- bINoticeS.search.Add(schPre1);
- PickParam schPre2 = new PickParam()
- {
- mode = "sch",
- school = new NoticeSchool() { eduId = "habook", shortCode = "habook", name = "玉山學校" }
- };
- bINoticeS.search.Add(schPre2);
- ///接收名單
- PickParam tmidList = new PickParam() {
- mode = "tmid"
- };
- tmidList.tmId.Add("1595321354");
- tmidList.tmId.Add("1522758684");
- bINoticeS.accept.Add(tmidList);
- await client.GetContainer(Constant.TEAMModelOS, Constant.Common).UpsertItemAsync(bINoticeS, new PartitionKey($"BINotice"));
- return Ok(new { state = 200 });
- }
- /// <summary>
- /// BI呼叫端外通知API測試
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("push-notify-test")]
- public async Task<IActionResult> PushNotifyTest(JsonElement jsonElement)
- {
- //var data = new { value = new{ } };
- //var data = new
- //{
- // value = new
- // {
- // tmdid = "1595321354",
- // tmdname = "罗老师"
- // }
- //};
- var data = new
- {
- value = new
- {
- tmdid = "1595321354",
- tmdname = "罗老师"
- },
- action = new[] {
- new {
- type = "click",
- label = "請按我1",
- url = "https://www.youtube.com/watch?v=HGWFKKDBLsI"
- },
- new {
- type = "click",
- label = "請按我2",
- url = "https://www.youtube.com/watch?v=xe5E6PjR9sg"
- }
- }
-
- };
- var notifyData = new
- {
- hubName = "hita5",
- sender = "IES",
- tags = new[] { "1595321354_BI", "1522758684_BI" },
- title = "端外通知發送測試7",
- body = "2024流行語有哪些,你知道嗎?每個時代都有專屬的流行語,除了去(2023)年流行的瑪卡巴卡、超派之外,今年流行的M3、已購買小孩愛吃都相當特別,不認真解釋可能還不知道是什麼意思。一起掌握2024年網路上最夯的流行語!",
- eventId = "test-368329735249465344",
- eventName = "端外通知發送測試",
- data = data.ToJsonString()
- };
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- var client = _httpClient.CreateClient();
- string sendSite = "Global";
- var token = CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, sendSite).Result;
- if (client.DefaultRequestHeaders.Contains("Authorization"))
- {
- client.DefaultRequestHeaders.Remove("Authorization");
- client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
- }
- else
- {
- client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.AccessToken}");
- }
- HttpResponseMessage responseMessage = client.PostAsJsonAsync($"{url}/service/PushNotify", notifyData).Result;
- return Ok(new { state = 200, responseMessage });
- }
- /// <summary>
- /// 比對統購活動產品的TMID名單
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("compare-purchaseSchool")]
- public async Task<IActionResult> ComparePurchaseSchoolData(JsonElement jsonElement)
- {
- var cosmosClientCSV2 = _azureCosmos.GetCosmosClient(name: "CoreServiceV2");
- List<PurchaseSchoolSeats> result = new List<PurchaseSchoolSeats>();
- //STEP1 取得所有purchaseSchool
- List<PurchaseSchoolSeats> data = new List<PurchaseSchoolSeats>();
- string sqlText = "SELECT * FROM c ";
- await foreach (var item in cosmosClientCSV2.GetContainer("Habb", "Auth").GetItemQueryIteratorSql<PurchaseSchoolSeats>(queryText: sqlText, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"purchaseSchool") }))
- {
- data.Add(item);
- }
- //STEP2 比對相同學校 不同產品的 tmids,有差異的列出來
- List<string> resultIds = new List<string>();
- foreach(PurchaseSchoolSeats dataRow in data)
- {
- PurchaseSchoolSeats difData = data.Where(d => d.shortCode.Equals(dataRow.shortCode) && !d.tmids.Count.Equals(dataRow.tmids.Count)).FirstOrDefault();
- if(difData != null)
- {
- if (!resultIds.Contains(dataRow.id))
- {
- result.Add(dataRow);
- resultIds.Add(dataRow.id);
- }
- if (!resultIds.Contains(difData.id))
- {
- result.Add(difData);
- resultIds.Add(difData.id);
- }
- }
- }
- return Ok(new { state = 200, result });
- }
- /// <summary>
- /// IP轉換地理位置
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("getGeoFromIpTest")]
- public async Task<IActionResult> getGeoFromIpTest(JsonElement jsonElement)
- {
- string ip = (jsonElement.TryGetProperty("ip", out JsonElement _ip)) ? _ip.ToString() : string.Empty;
- string lang = (jsonElement.TryGetProperty("lang", out JsonElement _lang)) ? _lang.ToString() : "zh-tw";
- List<regionrow> region_gl = new List<regionrow>();
- using (StreamReader r = new StreamReader("JsonFile/Region/region_gl.json"))
- {
- string json_g = r.ReadToEnd();
- region_gl = JsonSerializer.Deserialize<List<regionrow>>(json_g);
- }
- List<regionrow> region_cn = new List<regionrow>();
- using (StreamReader r = new StreamReader("JsonFile/Region/region_cn.json"))
- {
- string json_c = r.ReadToEnd();
- region_cn = JsonSerializer.Deserialize<List<regionrow>>(json_c);
- }
- List<string> ipToGeoList = new List<string>();
- IotTeachingData.Geo geo = new IotTeachingData.Geo();
- (geo, ipToGeoList) = BIProdAnalysis.getGeoFromIp(_city, ip, region_gl, region_cn);
- return Ok(new { state = 200, geo, geoFromIp = ipToGeoList });
- }
- public class linqTest
- {
- public string id { get; set; }
- public string aresid { get; set; }
- public string name { get; set; }
- public linq1 linq1 { get; set; }
- }
- public class linq1
- {
- public string id { get; set; }
- public long times { get; set; }
- public int cnt { 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 month, long dayEnd) GetMonthStart(DateTimeOffset dt)
- {
- DateTime dtNew = new DateTime(dt.Year, dt.Month, 1);
- long month = DateTimeOffset.Parse($"{dtNew}").ToUnixTimeSeconds();
- var ste = dtNew.AddMonths(1).AddDays(-1).Day;
- long dayTime = DateTimeOffset.Parse($"{dt.Year}-{dt.Month}-{ste} 23:59:59").ToUnixTimeSeconds();
- return (month, dayTime);
- }
- 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;
- }
- }
- }
- }
|