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