This commit is contained in:
tk
2023-06-06 16:53:37 +08:00
parent ab0af253a4
commit c6facb89df
57 changed files with 534 additions and 414 deletions

View File

@ -10,22 +10,33 @@ indent_style = space
insert_final_newline = false
trim_trailing_whitespace = true
[{*.json,*.yml}]
indent_size = 2
[*.cs]
dotnet_analyzer_diagnostic.severity = warning
dotnet_diagnostic.CA1200.severity = none
dotnet_diagnostic.CA1707.severity = none
dotnet_diagnostic.CA1716.severity = none
dotnet_diagnostic.CA1848.severity = none
dotnet_diagnostic.CA2254.severity = none
dotnet_diagnostic.CA5350.severity = none
dotnet_diagnostic.CA5351.severity = none
dotnet_diagnostic.IDE0005.severity = none
dotnet_diagnostic.IDE0008.severity = none
dotnet_diagnostic.IDE0010.severity = none
dotnet_diagnostic.IDE0017.severity = none
dotnet_diagnostic.IDE0048.severity = none
dotnet_diagnostic.IDE0055.severity = none
dotnet_diagnostic.IDE0058.severity = none
dotnet_diagnostic.IDE0160.severity = none
dotnet_diagnostic.IDE0270.severity = none
dotnet_diagnostic.RCS1123.severity = none
dotnet_diagnostic.RCS1141.severity = none
dotnet_diagnostic.RCS1142.severity = none
dotnet_diagnostic.RCS1181.severity = none
dotnet_diagnostic.RCS1186.severity = none
dotnet_diagnostic.S101.severity = none
dotnet_diagnostic.S1075.severity = none
dotnet_diagnostic.S1199.severity = none
dotnet_diagnostic.S125.severity = none
dotnet_diagnostic.S2094.severity = none
dotnet_diagnostic.S3925.severity = none
dotnet_diagnostic.S4663.severity = none
dotnet_diagnostic.SYSLIB1045.severity = none

4
.gitignore vendored
View File

@ -400,5 +400,5 @@ FodyWeavers.xsd
# User Define
dist/
nuget.config
*.[Dd]esigner.cs
*.[Dd]esigner.cs
*.db

View File

@ -1,4 +1,4 @@
[hook "startcommit"]
cmdline = code-format.cmd
cmdline = dot-clean.cmd
wait = true
show = true

View File

@ -1,27 +0,0 @@
#r "nuget: Newtonsoft.Json, 13.0.0"
using System.Xml;
using System.IO;
using Newtonsoft.Json.Linq;
var path = Directory.GetFiles(@".idea", "workspace.xml", SearchOption.AllDirectories).First();
XmlDocument xdoc = new XmlDocument();
using(var fs = File.Open(path, FileMode.Open)){
xdoc.Load(fs);
fs.Seek(0, SeekOrigin.Begin);
var propertiesComponent = xdoc.SelectSingleNode("""//component[@name="PropertiesComponent"]""");
var jsonStr = propertiesComponent.InnerText;
var jsonObj = JObject.Parse(jsonStr);
var keyToStringObj = jsonObj["keyToString"] as JObject;
if (keyToStringObj.ContainsKey("rider.code.cleanup.on.save")) return;
keyToStringObj.Add(new JProperty("rider.code.cleanup.on.save", "true"));
var newNode = xdoc.CreateCDataSection(jsonObj.ToString());
propertiesComponent.InnerText=string.Empty;
propertiesComponent.AppendChild(newNode);
var settings = new XmlWriterSettings { Indent = true };
using(var writer = XmlWriter.Create(fs, settings)){
xdoc.WriteTo(writer);
}
}

View File

@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<CodeAnalysisRuleSet>../StyleCopAnalyzers.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSet>$(SolutionDir)/StyleCopAnalyzers.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<MSBuildTreatWarningsAsErrors>true</MSBuildTreatWarningsAsErrors>
@ -13,6 +13,26 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Roslynator.Analyzers" Version="4.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="SonarAnalyzer.CSharp" Version="9.2.0.71021">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="AsyncSuffixAnalyzer" Version="1.0.6285.32977">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="AsyncFixer" Version="1.6.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="ProductiveRage.SealedClassVerification.Net" Version="1.7.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<!-- <PackageReference Include="NSCodeAnalysis" Version="1.0.1-alpha.0.2">-->
<!-- <PrivateAssets>all</PrivateAssets>-->
<!-- <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>-->

View File

@ -0,0 +1,10 @@
<Project>
<Target Name="AfterTargetsBuild" AfterTargets="Build">
<ItemGroup>
<PackageReferenceFiles
Condition="%(PackageReference.CopyToOutputDirectory) != ''"
Include="$(NugetPackageRoot)\%(PackageReference.Identity)\%(PackageReference.Version)\%(PackageReference.CopyToOutputDirectory)" />
</ItemGroup>
<Copy SourceFiles="@(PackageReferenceFiles)" DestinationFolder="$(OutDir)" />
</Target>
</Project>

View File

@ -1,16 +1,16 @@
<Project>
<PropertyGroup>
<!-- $(XXX) 定义有顺序 排序请注意-->
<SolutionDir>$(MSBuildThisFileDirectory)</SolutionDir>
<Authors>nsnail</Authors>
<BaseIntermediateOutputPath>../dist</BaseIntermediateOutputPath>
<BaseOutputPath>../dist</BaseOutputPath>
<BaseIntermediateOutputPath>$(SolutionDir)/dist</BaseIntermediateOutputPath>
<BaseOutputPath>$(SolutionDir)/dist</BaseOutputPath>
<Copyright>© 2006-2023 nsnail</Copyright>
<Description>功能全面的实用工具 - 程序员的瑞士军刀</Description>
<EnableBaseIntermediateOutputPathMismatchWarning>false</EnableBaseIntermediateOutputPathMismatchWarning>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<ImplicitUsings>enable</ImplicitUsings>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)/$(MSBuildProjectName)/obj</IntermediateOutputPath>
<MSBuildProjectExtensionsPath>$(BaseIntermediateOutputPath)/$(MSBuildProjectName)/obj</MSBuildProjectExtensionsPath>
<OutputPath>$(BaseOutputPath)/$(MSBuildProjectName)/bin</OutputPath>
<MinVerDefaultPreReleaseIdentifiers>beta</MinVerDefaultPreReleaseIdentifiers>
<Product>dot</Product>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/nsnail/dot.git</RepositoryUrl>

View File

@ -4,42 +4,62 @@
*
*/
var files = Directory.EnumerateFiles(".", "*.png"
, new EnumerationOptions {
RecurseSubdirectories = true
, AttributesToSkip = FileAttributes.ReparsePoint
, IgnoreInaccessible = true
})
.ToArray();
var files = Directory
.EnumerateFiles(
".",
"*.png",
new EnumerationOptions
{
RecurseSubdirectories = true,
AttributesToSkip = FileAttributes.ReparsePoint,
IgnoreInaccessible = true
}
)
.ToArray();
Parallel.ForEach(files, file => {
var startInfo = new ProcessStartInfo {
FileName = "pngquant"
, Arguments
= $"\"{file}\" --force --output \"{file}\" --skip-if-larger"
};
using var p = Process.Start(startInfo);
p.WaitForExit();
Console.WriteLine($"{file}: {p.ExitCode}");
});
Parallel.ForEach(
files,
file =>
{
var startInfo = new ProcessStartInfo
{
FileName = "pngquant",
Arguments = $"\"{file}\" --force --output \"{file}\" --skip-if-larger"
};
using var p = Process.Start(startInfo);
p.WaitForExit();
Console.WriteLine($"{file}: {p.ExitCode}");
}
);
files = new[] { "*.jpg", "*.jpeg" }
.SelectMany(x => Directory.EnumerateFiles(
".", x
, new EnumerationOptions {
RecurseSubdirectories = true
, AttributesToSkip = FileAttributes.ReparsePoint
, IgnoreInaccessible = true
}))
.ToArray();
files = new[] { "*.jpg", "*.jpeg" }
.SelectMany(
x =>
Directory.EnumerateFiles(
".",
x,
new EnumerationOptions
{
RecurseSubdirectories = true,
AttributesToSkip = FileAttributes.ReparsePoint,
IgnoreInaccessible = true
}
)
)
.ToArray();
Parallel.ForEach(files, file => {
var startInfo = new ProcessStartInfo {
FileName = "jpegtran"
, Arguments = $"-copy none -optimize -perfect \"{file}\" \"{file}\""
};
using var p = Process.Start(startInfo);
p.WaitForExit();
Console.WriteLine($"{file}: {p.ExitCode}");
});
Parallel.ForEach(
files,
file =>
{
var startInfo = new ProcessStartInfo
{
FileName = "jpegtran",
Arguments = $"-copy none -optimize -perfect \"{file}\" \"{file}\""
};
using var p = Process.Start(startInfo);
p.WaitForExit();
Console.WriteLine($"{file}: {p.ExitCode}");
}
);

9
NuGet.Config Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="nuget.cdn.azure.cn" value="https://nuget.cdn.azure.cn/v3/index.json" />
<add key="cnblogs" value="https://nuget.cnblogs.com/v3/index.json" />
</packageSources>
</configuration>

44
ResharperCodeClean.csx Normal file
View File

@ -0,0 +1,44 @@
using System.Text.RegularExpressions;
using System.Net.Http;
using System.Net.Http.Json;
{
var files = string.Join(
';',
Args[0]
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Replace('\\', '/').Trim())
);
Console.WriteLine(files);
using var p = Process.Start(
new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "dotnet",
Arguments = $"jb cleanupcode --include=\"{files}\" --no-build ./ShopCore.sln",
UseShellExecute = false,
RedirectStandardOutput = true
}
);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd());
using var p2 = Process.Start(
new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "git",
Arguments = $"status",
UseShellExecute = false,
RedirectStandardOutput = true
}
);
p2.WaitForExit();
var content = p2.StandardOutput.ReadToEnd();
Console.WriteLine(content);
return content.Contains("working tree clean") ? 0 : 1;
}

View File

@ -1,17 +0,0 @@
Hotkey,^d,start
return
start:
loop,100{
send,{AppsKey}
Sleep,100
send,{Up}
Sleep,100
send,{Up}
Sleep,100
Send,{Enter}
Sleep,500
Send,{Esc},
Sleep,100
Send,{Down}
Sleep,100
}

View File

@ -56,7 +56,7 @@
<Rule Id="SA1115" Action="Warning" /> <!-- Parameter should follow comma -->
<Rule Id="SA1116" Action="Warning" /> <!-- Split parameters should start on line after declaration -->
<Rule Id="SA1117" Action="None" /> <!-- Parameters should be on same line or separate lines -->
<Rule Id="SA1118" Action="Warning" /> <!-- Parameter should not span multiple lines -->
<Rule Id="SA1118" Action="None"/> <!-- Parameter should not span multiple lines -->
<Rule Id="SA1120" Action="None" /> <!-- Comments should contain text -->
<Rule Id="SA1121" Action="Warning" /> <!-- Use built-in type alias -->
<Rule Id="SA1122" Action="Warning" /> <!-- Use string.Empty for empty strings -->
@ -111,7 +111,7 @@
<Rule Id="SA1310" Action="None" /> <!-- Field names should not contain underscore -->
<Rule Id="SA1311" Action="Warning" /> <!-- Static readonly fields should begin with upper-case letter -->
<Rule Id="SA1312" Action="Warning" /> <!-- Variable names should begin with lower-case letter -->
<Rule Id="SA1313" Action="Warning" /> <!-- Parameter names should begin with lower-case letter -->
<Rule Id="SA1313" Action="None"/> <!-- Parameter names should begin with lower-case letter -->
<Rule Id="SA1314" Action="Warning" /> <!-- Type parameter names should begin with T -->
<Rule Id="SX1309" Action="Warning" /> <!-- Field names should begin with underscore -->
<Rule Id="SX1309S" Action="Warning" /> <!-- Static field names should begin with underscore -->

View File

@ -1,14 +1,17 @@
using System.Text.RegularExpressions;
var slnFile = Directory.GetFiles(@".", "*.sln").First();
var content = File.ReadAllText(slnFile);
content = Regex.Replace(content,@"ProjectSection\(SolutionItems\) = preProject(?:.|\n)*?EndProjectSection",
$"""
var content = File.ReadAllText(slnFile);
content = Regex.Replace(
content,
@"ProjectSection\(SolutionItems\) = preProject(?:.|\n)*?EndProjectSection",
$"""
ProjectSection(SolutionItems) = preProject
{string.Join('\n',
Directory.GetFiles(@".", "*").Where(x => !x.EndsWith(".sln") && !x.EndsWith(".user"))
.Select(x=>$"\t\t{Path.GetFileName(x)} = {Path.GetFileName(x)}"))}
{'\t'}EndProjectSection
""");
Console.WriteLine(content);
File.WriteAllText(slnFile, content);
"""
);
Console.WriteLine(content);
File.WriteAllText(slnFile, content);

13
dot.sln
View File

@ -12,10 +12,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "meta", "meta", "{AD79881E-7
.gitignore = .gitignore
.tgitconfig = .tgitconfig
build.cake = build.cake
code-format.cmd = code-format.cmd
CodeCleanupOnSave.csx = CodeCleanupOnSave.csx
CodeQuality.props = CodeQuality.props
CopyPackageXmlCommentFiles.targets = CopyPackageXmlCommentFiles.targets
Directory.Build.props = Directory.Build.props
dot-clean.cmd = dot-clean.cmd
dot.sln.DotSettings = dot.sln.DotSettings
dotnet-tools.json = dotnet-tools.json
GenerateResx.targets = GenerateResx.targets
@ -23,14 +23,15 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "meta", "meta", "{AD79881E-7
global.json = global.json
ImageOptimize.csx = ImageOptimize.csx
LICENSE = LICENSE
NuGet.Config = NuGet.Config
package.json = package.json
README.md = README.md
README.zh-CN.md = README.zh-CN.md
SafetyDelUnusedResx.ahk = SafetyDelUnusedResx.ahk
resharper-clean-full.cmd = resharper-clean-full.cmd
resharper-clean.ps1 = resharper-clean.ps1
ResharperCodeClean.csx = ResharperCodeClean.csx
stylecop.json = stylecop.json
StyleCopAnalyzers.ruleset = StyleCopAnalyzers.ruleset
switch-nuget.cmd = switch-nuget.cmd
switch-project.cmd = switch-project.cmd
switcher.nsext.json = switcher.nsext.json
SyncMetaFiles.csx = SyncMetaFiles.csx
EndProjectSection
EndProject

View File

@ -5,7 +5,8 @@
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ACCESSORHOLDER_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_FIELD_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_RECORD_FIELD_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:Boolean x:Key="/Default/ReSpeller/ReSpellerEnabled/@EntryValue">False</s:Boolean>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=UI/@EntryIndexedValue">UI</s:String>
<s:Boolean x:Key="/Default/ReSpeller/ReSpellerEnabled/@EntryValue">True</s:Boolean>
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_CODE/@EntryValue">1</s:Int64>
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_DECLARATIONS/@EntryValue">1</s:Int64>
<s:String x:Key="/Default/CodeInspection/Highlighting/AnalysisEnabled/@EntryValue">OFF</s:String>
@ -58,4 +59,15 @@
&lt;/Entry&gt;
&lt;/TypePattern&gt;
&lt;/Patterns&gt;</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=CHANGECBCHAIN/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=DRAWCLIPBOARD/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=fract/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=fsrw/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=hwnd/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Kbdllhooks/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=KEYEVENTF/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=LBUTTONDOWN/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=lpfn/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Pbox/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Rbom/@EntryIndexedValue">True</s:Boolean>
</wpf:ResourceDictionary>

View File

@ -1,12 +1,30 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-t4": {
"version": "2.3.1",
"commands": [
"t4"
]
}
"version": 1,
"isRoot": true,
"tools": {
"dotnet-t4": {
"version": "2.3.1",
"commands": [
"t4"
]
},
"cake.tool": {
"version": "3.0.0",
"commands": [
"dotnet-cake"
]
},
"dotnet-script": {
"version": "1.4.0",
"commands": [
"dotnet-script"
]
},
"jetbrains.resharper.globaltools": {
"version": "2022.3.2",
"commands": [
"jb"
]
}
}
}

View File

@ -1,10 +1,10 @@
{
"sdk": {
"version": "7.0.100",
"allowPrerelease": true,
"rollForward": "major"
},
"tools": {
"dotnet": "7.0.100"
}
"sdk": {
"version": "7.0.100",
"allowPrerelease": true,
"rollForward": "major"
},
"tools": {
"dotnet": "7.0.100"
}
}

12
package.json Normal file
View File

@ -0,0 +1,12 @@
{
"devDependencies": {
"cz-conventional-changelog": "^3.3.0",
"prettier": "2.8.1",
"prettier-plugin-csharp": "0.6.0-development"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
}

1
resharper-clean-full.cmd Normal file
View File

@ -0,0 +1 @@
dotnet jb cleanupcode --no-build ./dot.sln

4
resharper-clean.ps1 Normal file
View File

@ -0,0 +1,4 @@
$files=$(foreach ($line in $(git diff head origin/dev --stat-width 200) | findstr '\|'){$line.split('\|')[0].trim()}) -join ';'
echo $files
dotnet jb cleanupcode --no-build --include="$files" ./ShopCore.sln
dotnet script ./PushSign.csx

View File

@ -11,7 +11,7 @@ namespace Dot.Color;
// ReSharper disable once ClassNeverInstantiated.Global
internal sealed class Main : ToolBase<Option>
{
protected override Task Core()
protected override Task CoreAsync()
{
Application.Run(new WinMain());
return Task.CompletedTask;

View File

@ -10,30 +10,32 @@ namespace Dot.Color;
internal sealed class WinInfo : Form
{
private const int _WINDOW_SIZE = 480; // 窗口大小
private const int _ZOOM_RATE = 16; // 缩放倍率
private const int _ZOOM_RATE = 16; // 缩放倍率
private readonly Graphics _graphics;
private readonly PictureBox _pbox;
private bool _disposed;
public WinInfo()
{
FormBorderStyle = FormBorderStyle.None;
TopMost = true;
MinimizeBox = false;
MaximizeBox = false;
Size = new Size(_WINDOW_SIZE, _WINDOW_SIZE);
StartPosition = FormStartPosition.Manual;
Location = new Point(0, 0);
_pbox = new PictureBox();
_pbox.Location = new Point(0, 0);
_pbox.Size = Size;
_pbox.Image = new Bitmap(_WINDOW_SIZE, _WINDOW_SIZE);
_graphics = Graphics.FromImage(_pbox.Image);
_graphics.InterpolationMode = InterpolationMode.NearestNeighbor; // 指定最临近插值法,禁止平滑缩放(模糊)
_graphics.CompositingQuality = CompositingQuality.HighQuality;
_graphics.SmoothingMode = SmoothingMode.None;
_pbox.MouseEnter += PboxOnMouseEnter;
#pragma warning disable IDE0017
FormBorderStyle = FormBorderStyle.None;
TopMost = true;
MinimizeBox = false;
MaximizeBox = false;
Size = new Size(_WINDOW_SIZE, _WINDOW_SIZE);
StartPosition = FormStartPosition.Manual;
Location = new Point(0, 0);
_pbox = new PictureBox();
_pbox.Location = new Point(0, 0);
_pbox.Size = Size;
_pbox.Image = new Bitmap(_WINDOW_SIZE, _WINDOW_SIZE);
_graphics = Graphics.FromImage(_pbox.Image);
_graphics.InterpolationMode = InterpolationMode.NearestNeighbor; // 指定最临近插值法,禁止平滑缩放(模糊)
_graphics.CompositingQuality = CompositingQuality.HighQuality;
_graphics.SmoothingMode = SmoothingMode.None;
_pbox.MouseEnter += PboxOnMouseEnter;
Controls.Add(_pbox);
#pragma warning restore IDE0017
}
~WinInfo()
@ -46,13 +48,13 @@ internal sealed class WinInfo : Form
// 计算复制小图的区域
var copySize = new Size(_WINDOW_SIZE / _ZOOM_RATE, _WINDOW_SIZE / _ZOOM_RATE);
_graphics.DrawImage(img, new Rectangle(0, 0, _WINDOW_SIZE, _WINDOW_SIZE) //
, x - copySize.Width / 2 // 左移x使光标位置居中
, y - copySize.Height / 2 // 上移y使光标位置居中
, copySize.Width, copySize.Height, GraphicsUnit.Pixel);
, x - copySize.Width / 2 // 左移x使光标位置居中
, y - copySize.Height / 2 // 上移y使光标位置居中
, copySize.Width, copySize.Height, GraphicsUnit.Pixel);
using var pen = new Pen(System.Drawing.Color.Aqua); // 绘制准星
_graphics.DrawRectangle(pen, _WINDOW_SIZE / 2 - _ZOOM_RATE / 2 //
, _WINDOW_SIZE / 2 - _ZOOM_RATE / 2 //
, _ZOOM_RATE, _ZOOM_RATE);
, _WINDOW_SIZE / 2 - _ZOOM_RATE / 2 //
, _ZOOM_RATE, _ZOOM_RATE);
// 取鼠标位置颜色
var posColor = img.GetPixel(x, y);
@ -61,8 +63,8 @@ internal sealed class WinInfo : Form
_graphics.FillRectangle(Brushes.Black, 0, _WINDOW_SIZE - 30, _WINDOW_SIZE, 30);
_graphics.DrawString( //
$"{Ln.ClickCopyColor} X: {x} Y: {y} RGB({posColor.R},{posColor.G},{posColor.B})"
, new Font(FontFamily.GenericSerif, 10) //
, Brushes.White, 0, _WINDOW_SIZE - 20);
, new Font(FontFamily.GenericSerif, 10) //
, Brushes.White, 0, _WINDOW_SIZE - 20);
// 触发重绘
_pbox.Refresh();

View File

@ -17,14 +17,14 @@ internal sealed class WinMain : Form
public WinMain()
{
// 隐藏控制台窗口,避免捕获到截屏
Win32.ShowWindow(Win32.GetConsoleWindow(), Win32.SW_HIDE);
_ = Win32.ShowWindow(Win32.GetConsoleWindow(), Win32.SW_HIDE);
FormBorderStyle = FormBorderStyle.None;
Size = Screen.PrimaryScreen!.Bounds.Size;
StartPosition = FormStartPosition.Manual;
Location = new Point(0, 0);
Opacity = 0.01d; // 主窗体加载截图过程设置为透明避免闪烁
_bmp = new Bitmap(Size.Width, Size.Height);
Size = Screen.PrimaryScreen!.Bounds.Size;
StartPosition = FormStartPosition.Manual;
Location = new Point(0, 0);
Opacity = 0.01d; // 主窗体加载截图过程设置为透明避免闪烁
_bmp = new Bitmap(Size.Width, Size.Height);
using var g = Graphics.FromImage(_bmp);
g.CopyFromScreen(0, 0, 0, 0, Size);
}

View File

@ -4,12 +4,12 @@ namespace Dot;
// ReSharper disable once UnusedType.Global
// ReSharper disable once UnusedMember.Global
internal sealed class CsxEditor
internal static class CsxEditor
{
// ReSharper disable once UnusedMember.Local
#pragma warning disable IDE0051
#pragma warning disable S1144, RCS1213, IDE0051
private static void Run()
#pragma warning restore IDE0051
#pragma warning restore IDE0051, RCS1213, S1144
{
/*
for %%i in (*.png) do pngquant %%i --force --output %%i --skip-if-larger

View File

@ -2,7 +2,7 @@
namespace Dot;
internal class DirOption : OptionBase
internal abstract class DirOption : OptionBase
{
[CommandOption("-e|--exclude")]
[Description(nameof(Ln.ExcludePathRegexes))]

View File

@ -10,14 +10,14 @@ internal abstract class FilesTool<TOption> : ToolBase<TOption>
where TOption : DirOption
{
// ReSharper disable once StaticMemberInGenericType
private static readonly object _lock = new(); // 线程锁
private readonly ConcurrentDictionary<string, int> _writeStats = new(); // 写入统计:后缀,数量
private int _breakCnt; // 跳过文件数
private ProgressTask _childTask; // 子任务进度
private int _excludeCnt; // 排除文件数
private int _readCnt; // 读取文件数
private int _totalCnt; // 总文件数
private int _writeCnt; // 写入文件数
private readonly object _lock = new(); // 线程锁
private readonly ConcurrentDictionary<string, int> _writeStats = new(); // 写入统计:后缀,数量
private int _breakCnt; // 跳过文件数
private ProgressTask _childTask; // 子任务进度
private int _excludeCnt; // 排除文件数
private int _readCnt; // 读取文件数
private int _totalCnt; // 总文件数
private int _writeCnt; // 写入文件数
protected static FileStream CreateTempFile(out string file)
{
@ -37,7 +37,7 @@ internal abstract class FilesTool<TOption> : ToolBase<TOption>
File.SetAttributes(file, new FileInfo(file).Attributes & ~FileAttributes.ReadOnly);
fsr = new FileStream(file, mode, access, share);
}
catch (Exception) {
catch {
// ignored
}
}
@ -48,15 +48,15 @@ internal abstract class FilesTool<TOption> : ToolBase<TOption>
return fsr;
}
protected override Task Core()
protected override Task CoreAsync()
{
return !Directory.Exists(Opt.Path)
? throw new ArgumentException( //
nameof(Opt.Path), string.Format(CultureInfo.InvariantCulture, Ln.PathNotFound, Opt.Path))
: CoreInternal();
: CoreInternalAsync();
}
protected abstract ValueTask FileHandle(string file, CancellationToken cancelToken);
protected abstract ValueTask FileHandleAsync(string file, CancellationToken cancelToken);
protected void ShowMessage(int readCnt, int writeCnt, int breakCnt)
{
@ -78,7 +78,7 @@ internal abstract class FilesTool<TOption> : ToolBase<TOption>
_ = _writeStats.AddOrUpdate(key, 1, (_, oldValue) => oldValue + 1);
}
private async Task CoreInternal()
private async Task CoreInternalAsync()
{
if (!Opt.WriteMode) {
AnsiConsole.MarkupLine(CultureInfo.InvariantCulture, "[gray]{0}[/]", Ln.ExerciseMode);
@ -93,15 +93,15 @@ internal abstract class FilesTool<TOption> : ToolBase<TOption>
, new SpinnerColumn() //
, new TaskDescriptionColumn { Alignment = Justify.Left }) //
.StartAsync(async ctx => {
var taskSearchfile = ctx.AddTask(Ln.SearchingFile).IsIndeterminate();
var taskSearchFile = ctx.AddTask(Ln.SearchingFile).IsIndeterminate();
_childTask = ctx.AddTask("-/-", false);
fileList = EnumerateFiles(Opt.Path, Opt.Filter, out _excludeCnt);
_totalCnt = fileList.Count();
taskSearchfile.StopTask();
taskSearchFile.StopTask();
_childTask.MaxValue = _totalCnt;
_childTask.StartTask();
await Parallel.ForEachAsync(fileList, FileHandle);
await Parallel.ForEachAsync(fileList, FileHandleAsync);
});
var grid = new Grid().AddColumn(new GridColumn().NoWrap().PadRight(16))

View File

@ -8,11 +8,12 @@ namespace Dot.Get;
[Description(nameof(Ln.DownloadTool))]
[Localization(typeof(Ln))]
internal sealed partial class Main : ToolBase<Option>
internal sealed class Main : ToolBase<Option>
{
private const string _PART = "part";
private const string _PART = "part";
private static readonly Regex _partRegex = new($"(\\d+)\\.{_PART}", RegexOptions.Compiled);
protected override async Task Core()
protected override async Task CoreAsync()
{
using var http = new HttpClient();
string attachment = default;
@ -28,7 +29,9 @@ internal sealed partial class Main : ToolBase<Option>
attachment = content.Headers.ContentDisposition?.FileName ??
Opt.Url[(Opt.Url.LastIndexOf('/') + 1)..];
foreach (var kv in content.Headers) {
#pragma warning disable IDE0058
table.AddRow(kv.Key, string.Join(Environment.NewLine, kv.Value));
#pragma warning restore IDE0058
}
});
AnsiConsole.Write(table);
@ -59,38 +62,41 @@ internal sealed partial class Main : ToolBase<Option>
tParent.Increment(x);
});
tParent.MaxValue = tParent.Value; // 写完了
tParent.IsIndeterminate(false);
_ = tParent.IsIndeterminate(false);
tParent.StopTask();
}
// 已知文件长度,多线程下载:
else {
tParent.IsIndeterminate(false);
_ = tParent.IsIndeterminate(false);
tParent.MaxValue = contentLength;
var chunkSize = contentLength / Opt.ChunkNumbers;
Parallel.For(0, Opt.ChunkNumbers
, new ParallelOptions { MaxDegreeOfParallelism = Opt.MaxParallel } //
, i => {
var tChild = ctx.AddTask(
$"{Ln.Thread}{i} {Ln.RemainingTime}:", maxValue: chunkSize);
using var getReq = new HttpRequestMessage(HttpMethod.Get, Opt.Url);
var startPos = i * chunkSize;
var endPos = startPos + chunkSize - 1;
if (i == Opt.ChunkNumbers - 1) {
endPos += contentLength % chunkSize;
}
async void BodyAction(int i)
{
var tChild = ctx.AddTask( //
$"{Ln.Thread}{i} {Ln.RemainingTime}:", maxValue: chunkSize);
using var getReq = new HttpRequestMessage(HttpMethod.Get, Opt.Url);
var startPos = i * chunkSize;
var endPos = startPos + chunkSize - 1;
if (i == Opt.ChunkNumbers - 1) {
endPos += contentLength % chunkSize;
}
getReq.Headers.Range = new RangeHeaderValue(startPos, endPos);
getReq.Headers.Range = new RangeHeaderValue(startPos, endPos);
// ReSharper disable once AccessToDisposedClosure
using var getRsp
= http.Send(getReq, HttpCompletionOption.ResponseHeadersRead);
WritePart(getRsp, mainFilePath, i, startPos, endPos, x => {
tChild.Increment(x);
tParent.Increment(x);
});
});
// ReSharper disable once AccessToDisposedClosure
using var getRsp
= await http.SendAsync(getReq, HttpCompletionOption.ResponseHeadersRead);
WritePart(getRsp, mainFilePath, i, startPos, endPos, x => {
tChild.Increment(x);
tParent.Increment(x);
});
}
_ = Parallel.For(0, Opt.ChunkNumbers
, new ParallelOptions { MaxDegreeOfParallelism = Opt.MaxParallel } //
, BodyAction);
MergeParts(mainFilePath);
}
@ -109,14 +115,14 @@ internal sealed partial class Main : ToolBase<Option>
private static string BuildFilePath(string path, string file)
{
// path 是一个存在的文件,已追加尾标
if (GetUseablePath(ref path)) {
if (GetUsablePath(ref path)) {
return path;
}
// ReSharper disable once InvertIf
if (Directory.Exists(path)) { // path 是一个存在的目录。
path = Path.Combine(path, file); // 构建文件路径
GetUseablePath(ref path); // 追加序号。
_ = GetUsablePath(ref path); // 追加序号。
return path;
}
@ -124,15 +130,14 @@ internal sealed partial class Main : ToolBase<Option>
return path;
}
private static bool GetUseablePath(ref string path)
private static bool GetUsablePath(ref string path)
{
var dir = Path.GetDirectoryName(path);
var name = Path.GetFileNameWithoutExtension(path);
var ext = Path.GetExtension(path);
var ret = false;
#pragma warning disable SA1002
for (var i = 1;; ++i) {
#pragma warning restore SA1002
for (var i = 1; ; ++i) {
if (File.Exists(path)) {
path = Path.Combine(dir!, $"{name}({i}){ext}");
ret = true;
@ -153,7 +158,7 @@ internal sealed partial class Main : ToolBase<Option>
.OrderBy(x => x)
.ToArray();
using var fs = File.Create(mainFilePath);
fs.SetLength(PartRegex().Match(files.Last()).Groups[1].Value.Int64());
fs.SetLength(_partRegex.Match(files[^1]).Groups[1].Value.Int64());
foreach (var file in files) {
using var fsc = File.OpenRead(file);
fsc.CopyTo(fs);
@ -162,9 +167,6 @@ internal sealed partial class Main : ToolBase<Option>
}
}
[GeneratedRegex($"(\\d+)\\.{_PART}")]
private static partial Regex PartRegex();
private void StreamCopy(Stream source, Stream dest, Action<int> rateHandle)
{
Span<byte> buf = stackalloc byte[Opt.BufferSize];

View File

@ -15,16 +15,16 @@ internal sealed class Main : ToolBase<Option>
private ConcurrentDictionary<string, StringBuilder> _repoRsp; // 仓库信息容器
private ConcurrentDictionary<string, TaskStatusColumn.Statues> _repoStatus;
protected override Task Core()
protected override Task CoreAsync()
{
return !Directory.Exists(Opt.Path)
? throw new ArgumentException( //
nameof(Opt.Path) //
, string.Format(CultureInfo.InvariantCulture, Ln.PathNotFound, Opt.Path))
: CoreInternal();
: CoreInternalAsync();
}
private async Task CoreInternal()
private async Task CoreInternalAsync()
{
_gitOutputEnc = Encoding.GetEncoding(Opt.GitOutputEncoding);
var progressBar = new ProgressBarColumn { Width = 10 };
@ -63,7 +63,7 @@ internal sealed class Main : ToolBase<Option>
taskFinder.StopTask();
taskFinder.State.Status(TaskStatusColumn.Statues.Succeed);
await Parallel.ForEachAsync(tasks, DirHandle);
await Parallel.ForEachAsync(tasks, DirHandleAsync);
});
var table = new Table().AddColumn(new TableColumn(Ln.Repository) { Width = 50 })
@ -74,17 +74,16 @@ internal sealed class Main : ToolBase<Option>
.Succeed)}[/]/{_repoStatus.Count}");
foreach (var repo in _repoRsp) {
var status = _repoStatus[repo.Key].Desc();
table.AddRow(status.Replace(_repoStatus[repo.Key].ToString(), new DirectoryInfo(repo.Key).Name), Opt.Args
, status.Replace(_repoStatus[repo.Key].ToString(), repo.Value.ToString()));
var status = _repoStatus[repo.Key].ResDesc<Ln>();
_ = table.AddRow( //
status.Replace(_repoStatus[repo.Key].ToString(), new DirectoryInfo(repo.Key).Name), Opt.Args
, status.Replace(_repoStatus[repo.Key].ToString(), repo.Value.ToString()));
}
AnsiConsole.Write(table);
}
#pragma warning disable SA1313
private async ValueTask DirHandle(KeyValuePair<string, ProgressTask> payload, CancellationToken _)
#pragma warning restore SA1313
private async ValueTask DirHandleAsync(KeyValuePair<string, ProgressTask> payload, CancellationToken ct)
{
payload.Value.StartTask();
payload.Value.State.Status(TaskStatusColumn.Statues.Executing);
@ -97,7 +96,7 @@ internal sealed class Main : ToolBase<Option>
}
var msg = Encoding.UTF8.GetString(_gitOutputEnc.GetBytes(e.Data));
_repoRsp[payload.Key].Append(msg.EscapeMarkup());
_ = _repoRsp[payload.Key].Append(msg.EscapeMarkup());
}
// 启动git进程
@ -119,14 +118,14 @@ internal sealed class Main : ToolBase<Option>
if (p.ExitCode == 0) {
payload.Value.State.Status(TaskStatusColumn.Statues.Succeed);
_repoStatus.AddOrUpdate(payload.Key, _ => TaskStatusColumn.Statues.Succeed
, (_, _) => TaskStatusColumn.Statues.Succeed);
_ = _repoStatus.AddOrUpdate(payload.Key, _ => TaskStatusColumn.Statues.Succeed
, (_, _) => TaskStatusColumn.Statues.Succeed);
payload.Value.StopTask();
}
else {
payload.Value.State.Status(TaskStatusColumn.Statues.Failed);
_repoStatus.AddOrUpdate(payload.Key, _ => TaskStatusColumn.Statues.Failed
, (_, _) => TaskStatusColumn.Statues.Failed);
_ = _repoStatus.AddOrUpdate(payload.Key, _ => TaskStatusColumn.Statues.Failed
, (_, _) => TaskStatusColumn.Statues.Failed);
}
payload.Value.StopTask();

View File

@ -14,7 +14,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Ready
/// </summary>
[Description($"[gray]{nameof(Ready)}[/]")]
Ready
Ready = 0
,
@ -22,7 +22,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Executing
/// </summary>
[Description($"[yellow]{nameof(Executing)}[/]")]
Executing
Executing = 1
,
@ -30,7 +30,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Succeed
/// </summary>
[Description($"[green]{nameof(Succeed)}[/]")]
Succeed
Succeed = 2
,
@ -38,7 +38,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Failed
/// </summary>
[Description($"[red]{nameof(Failed)}[/]")]
Failed
Failed = 3
}
/// <summary>
@ -53,6 +53,6 @@ internal sealed class TaskStatusColumn : ProgressColumn
public override IRenderable Render(RenderOptions options, ProgressTask task, TimeSpan deltaTime)
{
var text = task.State.Get<Statues>(nameof(TaskStatusColumn));
return new Markup(text.Desc()).Overflow(Overflow.Ellipsis).Justify(Alignment);
return new Markup(text.ResDesc<Ln>()).Overflow(Overflow.Ellipsis).Justify(Alignment);
}
}

View File

@ -10,7 +10,7 @@ namespace Dot.Guid;
[Localization(typeof(Ln))]
internal sealed class Main : ToolBase<Option>
{
protected override Task Core()
protected override Task CoreAsync()
{
var guid = System.Guid.NewGuid().ToString();
if (Opt.Upper) {

View File

@ -9,7 +9,9 @@ namespace Dot.IP;
[Localization(typeof(Ln))]
internal sealed class Main : ToolBase<Option>
{
protected override async Task Core()
private const string _HTTP_BIN_ORG_IP = "http://httpbin.org/ip";
protected override async Task CoreAsync()
{
foreach (var item in NetworkInterface.GetAllNetworkInterfaces()) {
if (item.NetworkInterfaceType != NetworkInterfaceType.Ethernet ||
@ -21,13 +23,13 @@ internal sealed class Main : ToolBase<Option>
Environment.NewLine
, item.GetIPProperties()
.UnicastAddresses.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
.Select(x => @$"{item.Name}: {x.Address}"));
.Select(x => $"{item.Name}: {x.Address}"));
Console.WriteLine(output);
}
using var http = new HttpClient();
Console.Write(Ln.PublicIP);
var str = await http.GetStringAsync("http://httpbin.org/ip");
var str = await http.GetStringAsync(_HTTP_BIN_ORG_IP);
Console.WriteLine(str);
}
}

View File

@ -14,7 +14,7 @@ internal sealed class Main : ToolBase<Option>
{
private object _inputObj;
protected override Task Core()
protected override Task CoreAsync()
{
var inputText = Opt.InputText;
@ -43,7 +43,7 @@ internal sealed class Main : ToolBase<Option>
throw new ArgumentException(Ln.InvalidJsonString);
}
return CoreInternal();
return CoreInternalAsync();
}
private static string UnescapeString(string text)
@ -51,24 +51,23 @@ internal sealed class Main : ToolBase<Option>
return text.Replace("\\\"", "\"");
}
private async Task<string> ConvertToString()
private async Task<string> ConvertToStringAsync()
{
var ret = await JsonCompress();
ret = ret.Replace("\"", "\\\"");
return ret;
var ret = await JsonCompressAsync();
return ret.Replace("\"", "\\\"");
}
private async Task CoreInternal()
private async Task CoreInternalAsync()
{
string result = null;
if (Opt.Compress) {
result = await JsonCompress();
result = await JsonCompressAsync();
}
else if (Opt.ConvertToString) {
result = await ConvertToString();
result = await ConvertToStringAsync();
}
else if (Opt.Format) {
result = await JsonFormat();
result = await JsonFormatAsync();
}
if (!result.NullOrWhiteSpace()) {
@ -78,15 +77,15 @@ internal sealed class Main : ToolBase<Option>
}
}
private Task<string> JsonCompress()
private Task<string> JsonCompressAsync()
{
var ret = _inputObj.Json();
return Task.FromResult(ret);
}
private Task<string> JsonFormat()
private Task<string> JsonFormatAsync()
{
var ret = _inputObj.Json(true);
var ret = _inputObj.Json(new JsonSerializerOptions { WriteIndented = true });
return Task.FromResult(ret);
}
}

View File

@ -50,7 +50,7 @@
<value>Screen coordinate color selection tool</value>
</data>
<data name="DownloadTool" xml:space="preserve">
<value>Multithreaded download tool</value>
<value>Multi-Threaded download tool</value>
</data>
<data name="TextTool" xml:space="preserve">
<value>Text encoding tool</value>

View File

@ -34,7 +34,7 @@ internal sealed class KeyboardHook : IDisposable
private static nint SetHook(Win32.HookProc lpfn)
{
using var process = Process.GetCurrentProcess();
using var module = process.MainModule;
using var module = process.MainModule;
return Win32.SetWindowsHookExA(Win32.WH_KEYBOARD_LL, lpfn, module!.BaseAddress, 0);
}
@ -49,7 +49,7 @@ internal sealed class KeyboardHook : IDisposable
}
if (_hookId != default) {
Win32.UnhookWindowsHookExA(_hookId);
_ = Win32.UnhookWindowsHookExA(_hookId);
}
_disposed = true;

View File

@ -21,7 +21,7 @@ internal sealed class MouseHook : IDisposable
Dispose(false);
}
public event MouseEventHandler MouseMoveEvent;
public event EventHandler<MouseEventArgs> MouseMoveEvent;
public void Dispose()
{
@ -32,7 +32,7 @@ internal sealed class MouseHook : IDisposable
private static nint SetHook(Win32.HookProc lpfn)
{
using var process = Process.GetCurrentProcess();
using var module = process.MainModule;
using var module = process.MainModule;
return Win32.SetWindowsHookExA(Win32.WH_MOUSE_LL, lpfn, module!.BaseAddress, 0);
}
@ -47,7 +47,7 @@ internal sealed class MouseHook : IDisposable
}
if (_hookId != default) {
Win32.UnhookWindowsHookExA(_hookId);
_ = Win32.UnhookWindowsHookExA(_hookId);
}
_disposed = true;
@ -58,7 +58,7 @@ internal sealed class MouseHook : IDisposable
// ReSharper disable once InvertIf
if (wParam == Win32.WM_MOUSEMOVE) {
var hookStruct = (Msllhookstruct)Marshal.PtrToStructure(lParam, typeof(Msllhookstruct))!;
MouseMoveEvent?.Invoke(null, new MouseEventArgs(MouseButtons.None, 0, hookStruct.X, hookStruct.Y, 0));
MouseMoveEvent?.Invoke(this, new MouseEventArgs(MouseButtons.None, 0, hookStruct.X, hookStruct.Y, 0));
}
return Win32.CallNextHookEx(_hookId, nCode, wParam, lParam);

View File

@ -1,6 +1,6 @@
// ReSharper disable UnusedMember.Global
#pragma warning disable CS1591
// ReSharper disable IdentifierTypo
// ReSharper disable CommentTypo
namespace Dot.Native;

View File

@ -1,7 +1,7 @@
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMethodReturnValue.Global
#pragma warning disable SA1307, SX1309
#pragma warning disable SA1307,SX1309
using System.Runtime.InteropServices;
@ -71,7 +71,7 @@ internal static partial class Win32
public static partial int SetClipboardViewer(nint hWnd);
[LibraryImport(_KERNEL32_DLL)]
public static partial void SetLocalTime(Systemtime st);
public static partial void SetLocalTime(SystemTime st);
[LibraryImport(_USER32_DLL)]
public static partial nint SetWindowsHookExA(int idHook, HookProc lpfn, nint hMod, uint dwThreadId);
@ -136,7 +136,7 @@ internal static partial class Win32
}
[StructLayout(LayoutKind.Explicit)]
public ref struct Systemtime
public ref struct SystemTime
{
[FieldOffset(6)]
public ushort wDay;

View File

@ -18,7 +18,7 @@ internal sealed class Main : ToolBase<Option>
, "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".ToCharArray()
};
protected override Task Core()
protected override Task CoreAsync()
{
unsafe {
var pSource = stackalloc char[_charTable.Sum(x => x.Length)];

View File

@ -8,10 +8,11 @@ internal sealed class Option : OptionBase
[Flags]
public enum GenerateTypes
{
Number = 0b0001
, LowerCaseLetter = 0b0010
, UpperCaseLetter = 0b0100
, SpecialCharacter = 0b1000
None = 0
, Number = 1
, LowerCaseLetter = 1 << 1
, UpperCaseLetter = 1 << 2
, SpecialCharacter = 1 << 3
}
[CommandArgument(1, "<password length>")]

View File

@ -8,7 +8,7 @@ internal sealed class Main : FilesTool<Option>
{
private readonly byte[] _utf8Bom = { 0xef, 0xbb, 0xbf };
protected override async ValueTask FileHandle(string file, CancellationToken cancelToken)
protected override async ValueTask FileHandleAsync(string file, CancellationToken cancelToken)
{
ShowMessage(1, 0, 0);

View File

@ -15,9 +15,9 @@ namespace Dot.Text;
internal sealed class Main : ToolBase<Option>
{
#if NET7_0_WINDOWS
protected override async Task Core()
#else
protected override Task Core()
protected override async Task CoreAsync()
#else
protected override Task CoreAsync()
#endif
{
#if NET7_0_WINDOWS
@ -39,15 +39,18 @@ internal sealed class Main : ToolBase<Option>
{
Output ret;
var inputHex = text.Hex(enc);
ret.Base64DeCodeHex = ReadOnlySpan<char>.Empty;
ret.Base64DeCode = ReadOnlySpan<char>.Empty;
ret.EncodingName = enc.EncodingName;
ret.Hex = inputHex.String();
ret.Base64 = text.Base64(enc);
ret.Md5 = MD5.HashData(inputHex).String();
ret.Sha1 = SHA1.HashData(inputHex).String();
ret.Sha256 = SHA256.HashData(inputHex).String();
ret.Sha512 = SHA512.HashData(inputHex).String();
ret.Base64DeCodeHex = ReadOnlySpan<char>.Empty;
ret.Base64DeCode = ReadOnlySpan<char>.Empty;
ret.EncodingName = enc.EncodingName;
ret.Hex = inputHex.Str();
ret.Base64 = text.Base64(enc);
#pragma warning disable CA5351, CA5350
ret.Md5 = MD5.HashData(inputHex).Str();
ret.Sha1 = SHA1.HashData(inputHex).Str();
#pragma warning restore CA5350, CA5351
ret.Sha256 = SHA256.HashData(inputHex).Str();
ret.Sha512 = SHA512.HashData(inputHex).Str();
ret.UrlEncode = text.Url();
ret.UrlDecode = text.UrlDe();
ret.HtmlDecode = text.HtmlDe();
@ -58,9 +61,9 @@ internal sealed class Main : ToolBase<Option>
ret.UnicodeDecode = text.UnicodeDe();
if (Equals(enc, Encoding.BigEndianUnicode)) {
ret.PercentUnicode = inputHex.String(false, "%u", 2);
ret.AndUnicode = inputHex.String(false, @";&#x", 2)[1..] + ";";
ret.BacksLantUnicode = inputHex.String(false, @"\u", 2);
ret.PercentUnicode = inputHex.Str(false, "%u", 2);
ret.AndUnicode = inputHex.Str(false, ";&#x", 2)[1..] + ";";
ret.BacksLantUnicode = inputHex.Str(false, @"\u", 2);
}
if (!text.IsBase64String()) {
@ -71,7 +74,7 @@ internal sealed class Main : ToolBase<Option>
try {
base64DeHex = text.Base64De();
}
catch (Exception) {
catch {
// ignored
}
@ -79,7 +82,7 @@ internal sealed class Main : ToolBase<Option>
return ret;
}
ret.Base64DeCodeHex = base64DeHex.String();
ret.Base64DeCodeHex = base64DeHex.Str();
ret.Base64DeCode = enc.GetString(base64DeHex);
return ret;
@ -89,29 +92,29 @@ internal sealed class Main : ToolBase<Option>
{
var sb = new StringBuilder();
sb.AppendLine( //
_ = sb.AppendLine( //
CultureInfo.InvariantCulture
, $"{new string('-', 20)} {o.EncodingName} {new string('-', 30 - o.EncodingName.Length)}");
sb.AppendLine(CultureInfo.InvariantCulture, $"hex: {o.Hex}");
sb.AppendLine(CultureInfo.InvariantCulture, $"base64: {o.Base64}");
sb.AppendLine(CultureInfo.InvariantCulture, $"base64-decode-hex: {o.Base64DeCodeHex}");
sb.AppendLine(CultureInfo.InvariantCulture, $"base64-decode: {o.Base64DeCode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"md5: {o.Md5}");
sb.AppendLine(CultureInfo.InvariantCulture, $"sha1: {o.Sha1}");
sb.AppendLine(CultureInfo.InvariantCulture, $"sha256: {o.Sha256}");
sb.AppendLine(CultureInfo.InvariantCulture, $"sha512: {o.Sha512}");
sb.AppendLine(CultureInfo.InvariantCulture, $"url-encode: {o.UrlEncode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"url-decode: {o.UrlDecode}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"hex: {o.Hex}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"base64: {o.Base64}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"base64-decode-hex: {o.Base64DeCodeHex}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"base64-decode: {o.Base64DeCode}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"md5: {o.Md5}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"sha1: {o.Sha1}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"sha256: {o.Sha256}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"sha512: {o.Sha512}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"url-encode: {o.UrlEncode}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"url-decode: {o.UrlDecode}");
if (o.EncodingName.Equals(Encoding.BigEndianUnicode.EncodingName, StringComparison.OrdinalIgnoreCase)) {
sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-percent: {o.PercentUnicode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-and: {o.AndUnicode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-backslant: {o.BacksLantUnicode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-decode: {o.UnicodeDecode}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-percent: {o.PercentUnicode}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-and: {o.AndUnicode}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-back-slant: {o.BacksLantUnicode}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-decode: {o.UnicodeDecode}");
}
sb.AppendLine(CultureInfo.InvariantCulture, $"html-encode: {o.HtmlEncode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"html-decode: {o.HtmlDecode}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"html-encode: {o.HtmlEncode}");
_ = sb.AppendLine(CultureInfo.InvariantCulture, $"html-decode: {o.HtmlDecode}");
return sb.ToString();
}
@ -124,10 +127,10 @@ internal sealed class Main : ToolBase<Option>
var unicodeBigEndian = BuildOutput(text, Encoding.BigEndianUnicode);
var sb = new StringBuilder();
sb.AppendLine(BuildTemplate(ansi));
sb.AppendLine(BuildTemplate(utf8));
sb.AppendLine(BuildTemplate(unicodeLittleEndian));
sb.AppendLine(BuildTemplate(unicodeBigEndian));
sb.AppendLine(BuildTemplate(ansi))
.AppendLine(BuildTemplate(utf8))
.AppendLine(BuildTemplate(unicodeLittleEndian))
.AppendLine(BuildTemplate(unicodeBigEndian));
var str = sb.ToString();
Console.WriteLine(str);

View File

@ -12,6 +12,7 @@ internal sealed class Main : ToolBase<Option>
private const int _MAX_DEGREE_OF_PARALLELISM = 10;
private const int _NTP_PORT = 123;
// ReSharper disable StringLiteralTypo
private readonly string[] _ntpServers = {
"ntp.ntsc.ac.cn", "cn.ntp.org.cn", "edu.ntp.org.cn", "cn.pool.ntp.org"
, "time.pool.aliyun.com", "time1.aliyun.com", "time2.aliyun.com"
@ -30,11 +31,12 @@ internal sealed class Main : ToolBase<Option>
, "stdtime.gov.hk"
};
// ReSharper restore StringLiteralTypo
private double _offsetAvg;
private int _successCnt;
protected override async Task Core()
protected override async Task CoreAsync()
{
await AnsiConsole.Progress()
.Columns( //
@ -50,7 +52,7 @@ internal sealed class Main : ToolBase<Option>
await Parallel.ForEachAsync(
tasks, new ParallelOptions { MaxDegreeOfParallelism = _MAX_DEGREE_OF_PARALLELISM }
, ServerHandle);
, ServerHandleAsync);
_offsetAvg = tasks.Where(x => x.Value.State.Status() == TaskStatusColumn.Statues.Succeed)
.Average(x => x.Value.State.Result().TotalMilliseconds);
@ -60,14 +62,14 @@ internal sealed class Main : ToolBase<Option>
, _ntpServers.Length, $"[yellow]{_offsetAvg:f2}[/]");
if (Opt.Sync) {
SetSysteTime(DateTime.Now.AddMilliseconds(-_offsetAvg));
SetSystemTime(DateTime.Now.AddMilliseconds(-_offsetAvg));
AnsiConsole.MarkupLine($"[green]{Ln.LocalTimeSyncDone}[/]");
}
}
protected override async Task Run()
protected override async Task RunAsync()
{
await Core();
await CoreAsync();
if (Opt.KeepSession) {
var table = new Table().HideHeaders()
.AddColumn(new TableColumn(string.Empty))
@ -94,9 +96,9 @@ internal sealed class Main : ToolBase<Option>
}
}
private static void SetSysteTime(DateTime time)
private static void SetSystemTime(DateTime time)
{
var timeToSet = new Win32.Systemtime {
var timeToSet = new Win32.SystemTime {
wDay = (ushort)time.Day
, wDayOfWeek = (ushort)time.DayOfWeek
, wHour = (ushort)time.Hour
@ -145,9 +147,7 @@ internal sealed class Main : ToolBase<Option>
}
}
#pragma warning disable SA1313
private ValueTask ServerHandle(KeyValuePair<string, ProgressTask> payload, CancellationToken _)
#pragma warning restore SA1313
private ValueTask ServerHandleAsync(KeyValuePair<string, ProgressTask> payload, CancellationToken ct)
{
payload.Value.StartTask();
payload.Value.State.Status(TaskStatusColumn.Statues.Connecting);
@ -158,7 +158,7 @@ internal sealed class Main : ToolBase<Option>
else {
payload.Value.State.Status(TaskStatusColumn.Statues.Succeed);
payload.Value.State.Result(offset);
Interlocked.Increment(ref _successCnt);
_ = Interlocked.Increment(ref _successCnt);
}
payload.Value.StopTask();

View File

@ -14,7 +14,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Ready
/// </summary>
[Description($"[gray]{nameof(Ready)}[/]")]
Ready
Ready = 0
,
@ -22,7 +22,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Connecting
/// </summary>
[Description($"[yellow]{nameof(Connecting)}[/]")]
Connecting
Connecting = 1
,
@ -30,7 +30,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Succeed
/// </summary>
[Description($"[green]{nameof(Succeed)}[/]")]
Succeed
Succeed = 2
,
@ -38,7 +38,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Failed
/// </summary>
[Description($"[red]{nameof(Failed)}[/]")]
Failed
Failed = 3
}
/// <summary>
@ -53,6 +53,6 @@ internal sealed class TaskStatusColumn : ProgressColumn
public override IRenderable Render(RenderOptions options, ProgressTask task, TimeSpan deltaTime)
{
var text = task.State.Get<Statues>(nameof(TaskStatusColumn));
return new Markup(text.Desc()).Overflow(Overflow.Ellipsis).Justify(Alignment);
return new Markup(text.ResDesc<Ln>()).Overflow(Overflow.Ellipsis).Justify(Alignment);
}
}

View File

@ -6,7 +6,7 @@ namespace Dot.ToLf;
[Localization(typeof(Ln))]
internal sealed class Main : FilesTool<Option>
{
protected override async ValueTask FileHandle(string file, CancellationToken cancelToken)
protected override async ValueTask FileHandleAsync(string file, CancellationToken cancelToken)
{
ShowMessage(1, 0, 0);
@ -48,7 +48,9 @@ internal sealed class Main : FilesTool<Option>
}
}
#pragma warning disable S2583
if (hasWrote && !isBin) {
#pragma warning restore S2583
if (Opt.WriteMode) {
File.Copy(tmpFile, file, true);
}

View File

@ -8,15 +8,15 @@ internal abstract class ToolBase<TOption> : Command<TOption>
public override int Execute(CommandContext context, TOption settings)
{
Opt = settings;
Run().Wait();
RunAsync().Wait();
return 0;
}
protected abstract Task Core();
protected abstract Task CoreAsync();
protected virtual async Task Run()
protected virtual async Task RunAsync()
{
await Core();
await CoreAsync();
if (Opt.KeepSession) {
AnsiConsole.MarkupLine(Ln.PressAnyKey);
_ = AnsiConsole.Console.Input.ReadKey(true);

View File

@ -23,7 +23,7 @@ internal static class BaiduSignCracker
case < 2048:
e.Add((k >> 6) | 192);
break;
default: {
default:
if ((k & 64512) == 55296 && i + 1 < hash.Length && (hash[i + 1] & 64512) == 56320) {
k = 65536 + ((k & 1023) << 10) + (hash[++i] & 1023);
e.Add((k >> 18) | 240);
@ -36,7 +36,6 @@ internal static class BaiduSignCracker
}
break;
}
}
}
@ -55,7 +54,7 @@ internal static class BaiduSignCracker
var c = password[i + 2];
var moveBit = c >= 'a' ? c - 87 : c.ToString().Int32();
var d = password[i + 1] == '+' ? number >>> moveBit : number << moveBit;
number = password[i] == '+' ? (number + d) & (int)uint.MaxValue : number ^ d;
number = password[i] == '+' ? number + d : number ^ d;
}
}

View File

@ -2,8 +2,10 @@
// ReSharper disable ClassNeverInstantiated.Global
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IdentifierTypo
#pragma warning disable IDE1006,SA1300
namespace Dot.Tran.Dto;
internal sealed record BaiduTranslateResultDto
@ -26,7 +28,9 @@ internal sealed record BaiduTranslateResultDto
public string trg_str { get; set; }
}
#pragma warning disable S1144
public sealed record Root
#pragma warning restore S1144
{
public string errmsg { get; set; }

View File

@ -12,14 +12,14 @@ namespace Dot.Tran;
internal sealed class Main : ToolBase<Option>
{
[SupportedOSPlatform(nameof(OSPlatform.Windows))]
protected override Task Core()
protected override Task CoreAsync()
{
AnsiConsole.MarkupLine(Ln.StartTranslate);
AnsiConsole.MarkupLine(Ln.HideTranslate);
var th = new Thread(() => {
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += UnhandledException;
Application.ThreadException += UIThreadException;
Application.ThreadException += UIThreadException;
using var frm = new WinMain();
try {
Application.Run();
@ -37,7 +37,7 @@ internal sealed class Main : ToolBase<Option>
private static void Log(string msg)
{
var file = Path.Combine(Path.GetTempPath(), $"{DateTime.Now.yyyyMMdd()}.dotlog");
File.AppendAllText(file, $"{Environment.NewLine}{msg}");
File.AppendAllText(file, Environment.NewLine + msg);
}
private static void UIThreadException(object sender, ThreadExceptionEventArgs e)

View File

@ -12,22 +12,22 @@ using Size = System.Drawing.Size;
namespace Dot.Tran;
[SupportedOSPlatform(nameof(OSPlatform.Windows))]
internal sealed partial class WinMain : Form
internal sealed class WinMain : Form
{
private const int _RETRY_WAIT_MIL_SEC = 1000;
private const string _TRANSLATE_API_URL = $"{_TRANSLATE_HOME_URL}/v2transapi";
private const string _TRANSLATE_HOME_URL = "https://fanyi.baidu.com";
private readonly HttpClient _httpClient = new(new HttpClientHandler { UseProxy = false });
private readonly KeyboardHook _keyboardHook = new();
private readonly Label _labelDest = new();
private readonly MouseHook _mouseHook = new();
private readonly Size _mouseMargin = new(10, 10);
private readonly string _stateFile = Path.Combine(Path.GetTempPath(), "dot-tran-state.tmp");
private bool _capsLockPressed;
private volatile string _cookie;
private bool _disposed;
private nint _nextClipMonitor;
private volatile string _token;
private const int _RETRY_WAIT_MIL_SEC = 1000;
private const string _TRANSLATE_API_URL = $"{_TRANSLATE_HOME_URL}/v2transapi";
private const string _TRANSLATE_HOME_URL = "https://fanyi.baidu.com";
private static readonly Regex _tokenRegex = new("token: '(\\w+)'", RegexOptions.Compiled);
private readonly HttpClient _httpClient = new(new HttpClientHandler { UseProxy = false });
private readonly KeyboardHook _keyboardHook = new();
private readonly Label _labelDest = new();
private readonly MouseHook _mouseHook = new();
private readonly Size _mouseMargin = new(10, 10);
private readonly string _stateFile = Path.Combine(Path.GetTempPath(), "dot-tran-state.tmp");
private bool _capsLockPressed;
private bool _disposed;
private nint _nextClipMonitor;
private volatile string _token;
public WinMain()
{
@ -59,7 +59,7 @@ internal sealed partial class WinMain : Form
_keyboardHook?.Dispose();
}
Win32.ChangeClipboardChain(Handle, _nextClipMonitor); // 从剪贴板监视链移除本窗体
_ = Win32.ChangeClipboardChain(Handle, _nextClipMonitor); // 从剪贴板监视链移除本窗体
_disposed = true;
}
@ -94,9 +94,6 @@ internal sealed partial class WinMain : Form
}
}
[GeneratedRegex("token: '(\\w+)'")]
private static partial Regex TokenRegex();
private void InitClipMonitor()
{
_nextClipMonitor = Win32.SetClipboardViewer(Handle);
@ -104,12 +101,12 @@ internal sealed partial class WinMain : Form
private void InitForm()
{
AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink;
MaximumSize = Screen.FromHandle(Handle).Bounds.Size / 2;
AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink;
MaximumSize = Screen.FromHandle(Handle).Bounds.Size / 2;
FormBorderStyle = FormBorderStyle.None;
TopMost = true;
Visible = false;
TopMost = true;
Visible = false;
}
private unsafe void InitHook()
@ -121,27 +118,29 @@ internal sealed partial class WinMain : Form
};
_keyboardHook.KeyUpEvent += (_, e) => {
switch (e.vkCode) {
case VkCode.VK_CAPITAL: {
case VkCode.VK_CAPITAL:
var keyInputs = new Win32.InputStruct[4];
keyInputs[0].type = Win32.INPUT_KEYBOARD;
keyInputs[0].type = Win32.INPUT_KEYBOARD;
keyInputs[0].ki.wVk = VkCode.VK_CONTROL;
keyInputs[1].type = Win32.INPUT_KEYBOARD;
keyInputs[1].type = Win32.INPUT_KEYBOARD;
keyInputs[1].ki.wVk = VkCode.VK_C;
keyInputs[2].type = Win32.INPUT_KEYBOARD;
keyInputs[2].ki.wVk = VkCode.VK_C;
keyInputs[2].type = Win32.INPUT_KEYBOARD;
keyInputs[2].ki.wVk = VkCode.VK_C;
keyInputs[2].ki.dwFlags = Win32.KEYEVENTF_KEYUP;
keyInputs[3].type = Win32.INPUT_KEYBOARD;
keyInputs[3].ki.wVk = VkCode.VK_CONTROL;
keyInputs[3].type = Win32.INPUT_KEYBOARD;
keyInputs[3].ki.wVk = VkCode.VK_CONTROL;
keyInputs[3].ki.dwFlags = Win32.KEYEVENTF_KEYUP;
#pragma warning disable IDE0058
Win32.SendInput((uint)keyInputs.Length, keyInputs, sizeof(Win32.InputStruct));
#pragma warning restore IDE0058
_capsLockPressed = true;
return true;
}
case VkCode.VK_ESCAPE:
Hide();
@ -158,15 +157,15 @@ internal sealed partial class WinMain : Form
{
_httpClient.DefaultRequestHeaders.Add( //
"User-Agent"
, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
}
private void InitLabelDest()
{
_labelDest.Font = new Font(_labelDest.Font.FontFamily, 16);
_labelDest.Font = new Font(_labelDest.Font.FontFamily, 16);
_labelDest.BorderStyle = BorderStyle.None;
_labelDest.Dock = DockStyle.Fill;
_labelDest.AutoSize = true;
_labelDest.Dock = DockStyle.Fill;
_labelDest.AutoSize = true;
Controls.Add(_labelDest);
}
@ -175,11 +174,10 @@ internal sealed partial class WinMain : Form
if (File.Exists(_stateFile)) {
var lines = File.ReadLines(_stateFile).ToArray();
_token = lines[0];
_cookie = lines[1];
_httpClient.DefaultRequestHeaders.Add(nameof(Cookie), _cookie);
_httpClient.DefaultRequestHeaders.Add(nameof(Cookie), lines[1]);
}
else {
Task.Run(UpdateStateFile);
_ = Task.Run(UpdateStateFile);
}
}
@ -191,10 +189,10 @@ internal sealed partial class WinMain : Form
}
_labelDest.Text = Ln.Translating;
Task.Run(() => {
_ = Task.Run(() => {
var translateText = TranslateText(clipText);
ClipboardService.SetText(translateText);
Invoke(() => { _labelDest.Text = translateText; });
_ = Invoke(() => _labelDest.Text = translateText);
});
var point = Cursor.Position;
@ -209,17 +207,17 @@ internal sealed partial class WinMain : Form
var sign = BaiduSignCracker.Sign(sourceText);
var content = new FormUrlEncodedContent(new List<KeyValuePair<string, string>> {
new("from", "auto")
, new( //
, new( //
"to"
, CultureInfo.CurrentCulture.TwoLetterISOLanguageName)
, new("query", sourceText)
, new("simple_means_flag", "3")
, new("sign", sign)
, new("token", _token)
, new("domain", "common")
, CultureInfo.CurrentCulture.TwoLetterISOLanguageName)
, new("query", sourceText)
, new("simple_means_flag", "3")
, new("sign", sign)
, new("token", _token)
, new("domain", "common")
});
var rsp = _httpClient.PostAsync(_TRANSLATE_API_URL, content).Result;
var rsp = _httpClient.PostAsync(_TRANSLATE_API_URL, content).Result;
var rspObj = rsp.Content.ReadAsStringAsync().Result.Object<BaiduTranslateResultDto.Root>();
if (rspObj.error == 0) {
return string.Join(Environment.NewLine, rspObj.trans_result.data.Select(x => x.dst));
@ -236,15 +234,14 @@ internal sealed partial class WinMain : Form
private void UpdateStateFile()
{
var rsp = _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, _TRANSLATE_HOME_URL)).Result;
_cookie = string.Join(
';', rsp.Headers.First(x => x.Key == "Set-Cookie").Value.Select(x => x.Split(';').First()));
_httpClient.DefaultRequestHeaders.Remove(nameof(Cookie));
_httpClient.DefaultRequestHeaders.Add(nameof(Cookie), _cookie);
var rsp = _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, _TRANSLATE_HOME_URL)).Result;
var cookie = string.Join(';', rsp.Headers.First(x => x.Key == "Set-Cookie").Value.Select(x => x.Split(';')[0]));
_ = _httpClient.DefaultRequestHeaders.Remove(nameof(Cookie));
_httpClient.DefaultRequestHeaders.Add(nameof(Cookie), cookie);
var html = _httpClient.GetStringAsync(_TRANSLATE_HOME_URL).Result;
_token = TokenRegex().Match(html).Groups[1].Value;
_token = _tokenRegex.Match(html).Groups[1].Value;
File.WriteAllLines(_stateFile, new[] { _token, _cookie });
File.WriteAllLines(_stateFile, new[] { _token, cookie });
}
}
#endif

View File

@ -8,7 +8,7 @@ namespace Dot.Trim;
[Localization(typeof(Ln))]
internal sealed class Main : FilesTool<Option>
{
protected override async ValueTask FileHandle(string file, CancellationToken cancelToken)
protected override async ValueTask FileHandleAsync(string file, CancellationToken cancelToken)
{
ShowMessage(1, 0, 0);
int spacesCnt;

View File

@ -11,9 +11,9 @@
<DefineConstants>$(DefineConstants);NET7_0_WINDOWS</DefineConstants>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NSExt" Version="1.0.11-alpha.0.1" />
<PackageReference Include="Spectre.Console.Cli.NS" Version="0.45.1-preview.0.48" />
<PackageReference Include="Spectre.Console.NS" Version="0.45.1-preview.0.48" />
<PackageReference Include="NSExt" Version="1.0.15-alpha.0.1" />
<PackageReference Include="Spectre.Console.Cli.NS" Version="0.45.1-preview.0.74" />
<PackageReference Include="Spectre.Console.NS" Version="0.45.1-preview.0.74" />
<PackageReference Condition="'$(TargetFramework)' == 'net7.0-windows'" Include="TextCopy" Version="6.2.1" />
</ItemGroup>
<ItemGroup>

View File

@ -1,9 +1,10 @@
{
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
"settings": {
"indentation": {
"useTabs": false,
"indentationSize": 4
}
"$schema":
"https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
"settings": {
"indentation": {
"useTabs": false,
"indentationSize": 4
}
}
}

View File

@ -1,2 +0,0 @@
@rem https://github.com/RicoSuter/DNT#switch-to-projects
dnt switch-to-packages

View File

@ -1,2 +0,0 @@
@rem https://github.com/RicoSuter/DNT#switch-to-projects
dnt switch-to-projects

View File

@ -1,8 +0,0 @@
{
"solution": "NetAdmin.sln",
"solutionFolder": null,
"mappings": {
"NSExt": "../../../../ForkedGitReps/ns-ext/src/NSExt.csproj"
},
"removeProjects": true
}

View File

@ -5,14 +5,14 @@
<RootNamespace>Dot.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0-preview-20221003-04" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.1" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.3.1" />
<PackageReference Include="NUnit.Analyzers" Version="3.5.0">
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.6.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.2.0">
<PackageReference Include="coverlet.collector" Version="6.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>