A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Added Hash / Checksum tool (#956)
Etienne BAUDOUXcb425488ecc4
diff --git a/src/app/dev/DevToys.Api/Core/OneOfExtensions.cs b/src/app/dev/DevToys.Api/Core/OneOfExtensions.csnew file mode 100644index 000000000..f68a4a6b4--- /dev/null+++ b/src/app/dev/DevToys.Api/Core/OneOfExtensions.cs@@ -0,0 +1,71 @@+using OneOf;++namespace DevToys.Api.Core;++public static class OneOfExtensions+{+ public static Task<Stream> GetStreamAsync(+ this OneOf<string, FileInfo> input,+ IFileStorage fileStorage,+ CancellationToken cancellationToken)+ {+ if (input.IsT1)+ {+ return GetStreamAsync(OneOf<FileInfo, string>.FromT0(input.AsT1), fileStorage, cancellationToken);+ }++ return GetStreamAsync(OneOf<FileInfo, string>.FromT1(input.AsT0), fileStorage, cancellationToken);+ }++ public static Task<Stream> GetStreamAsync(+ this OneOf<FileInfo, string> input,+ IFileStorage fileStorage,+ CancellationToken cancellationToken)+ {+ return+ input.Match(+ inputFile => Task.FromResult(fileStorage.OpenReadFile(inputFile.FullName)),+ async inputString =>+ {+ var stringStream = new MemoryStream();+ var writer = new StreamWriter(stringStream);+ if (inputString is not null)+ {+ await writer.WriteAsync(inputString.AsMemory(), cancellationToken);+ }+ writer.Flush();+ stringStream.Position = 0;+ return (Stream)stringStream;+ });+ }++ public static Task<string> ReadAllTextAsync(+ this OneOf<string, FileInfo> input,+ IFileStorage fileStorage,+ CancellationToken cancellationToken)+ {+ if (input.IsT1)+ {+ return ReadAllTextAsync(OneOf<FileInfo, string>.FromT0(input.AsT1), fileStorage, cancellationToken);+ }++ return ReadAllTextAsync(OneOf<FileInfo, string>.FromT1(input.AsT0), fileStorage, cancellationToken);+ }++ public static Task<string> ReadAllTextAsync(+ this OneOf<FileInfo, string> input,+ IFileStorage fileStorage,+ CancellationToken cancellationToken)+ {+ return+ input.Match(+ async inputFile =>+ {+ using Stream fileStream = fileStorage.OpenReadFile(inputFile.FullName);+ using var reader = new StreamReader(fileStream);+ string content = await reader.ReadToEndAsync(cancellationToken);+ return content;+ },+ inputString => Task.FromResult(inputString));+ }+}diff --git a/src/app/dev/DevToys.Api/Tool/CLI/ConsoleProgressBar.cs b/src/app/dev/DevToys.Api/Tool/CLI/ConsoleProgressBar.csnew file mode 100644index 000000000..4a50cd9fc--- /dev/null+++ b/src/app/dev/DevToys.Api/Tool/CLI/ConsoleProgressBar.cs@@ -0,0 +1,110 @@+using System.Text;++namespace DevToys.Api.Tool.CLI;++// TODO: Credit https://gist.github.com/DanielSWolf/0ab6a96899cc5377bf54++/// <summary>+/// A progress bar for the console.+/// </summary>+public class ConsoleProgressBar : IDisposable, IProgress<double>+{+ private const int BlockCount = 10;+ private readonly TimeSpan _animationInterval = TimeSpan.FromMilliseconds(125);+ private const string Animation = @"|/-\";++ private readonly Timer _timer;++ private double _currentPercent = 0;+ private string _currentText = string.Empty;+ private bool _disposed = false;+ private int _animationIndex = 0;++ public ConsoleProgressBar()+ {+ _timer = new Timer(TimerHandler);++ // A progress bar is only for temporary display in a console window.+ // If the console output is redirected to a file, draw nothing.+ // Otherwise, we'll end up with a lot of garbage in the target file.+ if (!Console.IsOutputRedirected)+ {+ ResetTimer();+ }+ }++ public void Dispose()+ {+ lock (_timer)+ {+ _disposed = true;+ UpdateText(string.Empty);+ }++ GC.SuppressFinalize(this);+ }++ public void Report(double value)+ {+ Guard.IsBetweenOrEqualTo(value, 0, 100);++ Interlocked.Exchange(ref _currentPercent, value);+ }++ private void TimerHandler(object? state)+ {+ lock (_timer)+ {+ if (_disposed)+ {+ return;+ }++ int progressBlockCount = (int)(_currentPercent / 100 * BlockCount);+ string text+ = string.Format("[{0}{1}] {2}% {3}",+ new string('#', progressBlockCount),+ new string('-', BlockCount - progressBlockCount),+ Math.Floor(_currentPercent),+ Animation[_animationIndex++ % Animation.Length]);++ UpdateText(text);++ ResetTimer();+ }+ }++ private void UpdateText(string text)+ {+ // Get length of common portion+ int commonPrefixLength = 0;+ int commonLength = Math.Min(_currentText.Length, text.Length);+ while (commonPrefixLength < commonLength && text[commonPrefixLength] == _currentText[commonPrefixLength])+ {+ commonPrefixLength++;+ }++ // Backtrack to the first differing character+ var outputBuilder = new StringBuilder();+ outputBuilder.Append('\b', _currentText.Length - commonPrefixLength);++ // Output new suffix+ outputBuilder.Append(text.AsSpan(commonPrefixLength));++ // If the new text is shorter than the old one: delete overlapping characters+ int overlapCount = _currentText.Length - text.Length;+ if (overlapCount > 0)+ {+ outputBuilder.Append(' ', overlapCount);+ outputBuilder.Append('\b', overlapCount);+ }++ Console.Write(outputBuilder);+ _currentText = text;+ }++ private void ResetTimer()+ {+ _timer.Change(_animationInterval, TimeSpan.FromMilliseconds(-1));+ }+}diff --git a/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.cs b/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.csindex 885afef53..ed8d5639c 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.cs@@ -4,4 +4,5 @@ public static class PredefinedCommonToolGroupNames{public const string EncodersDecoders = "Encoders / Decoders";public const string Converters = "Converters";+ public const string Generators = "Generators";}diff --git a/src/app/dev/DevToys.Blazor/Components/UIElements/UIFileSelectorPresenter.razor b/src/app/dev/DevToys.Blazor/Components/UIElements/UIFileSelectorPresenter.razorindex ef00ed560..c61618a0d 100644--- a/src/app/dev/DevToys.Blazor/Components/UIElements/UIFileSelectorPresenter.razor+++ b/src/app/dev/DevToys.Blazor/Components/UIElements/UIFileSelectorPresenter.razor@@ -63,7 +63,13 @@IsVisible="@HasInvalidFilesSelected"Appearance="TextBlockAppearance.Caption"HorizontalAlignment="UIHorizontalAlignment.Center"- Style="color: orange"/>+ Style="color: orange" />++ <TextBlock Text="@SelectedFilesDescription"+ IsVisible="@HasFilesSelected"+ Appearance="TextBlockAppearance.Caption"+ HorizontalAlignment="UIHorizontalAlignment.Center"+ Style="color: orange" /></StackPanel>diff --git a/src/app/dev/DevToys.Blazor/Components/UIElements/UIFileSelectorPresenter.razor.cs b/src/app/dev/DevToys.Blazor/Components/UIElements/UIFileSelectorPresenter.razor.csindex eab1a9f88..d37a98b42 100644--- a/src/app/dev/DevToys.Blazor/Components/UIElements/UIFileSelectorPresenter.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/UIElements/UIFileSelectorPresenter.razor.cs@@ -29,6 +29,10 @@ public partial class UIFileSelectorPresenter : MefComponentBaseinternal bool HasInvalidFilesSelected { get; private set; }+ internal bool HasFilesSelected { get; private set; }++ internal string SelectedFilesDescription { get; private set; } = string.Empty;+protected override void OnInitialized(){base.OnInitialized();@@ -102,6 +106,8 @@ public partial class UIFileSelectorPresenter : MefComponentBase{UIFileSelector.WithFiles(pickedFiles);}++ UpdateSelectedFilesDescription();}private async Task OnBrowseFoldersButtonClickAsync()@@ -137,6 +143,8 @@ public partial class UIFileSelectorPresenter : MefComponentBase{UIFileSelector.WithFiles(files.ToArray());}++ UpdateSelectedFilesDescription();}private async Task OnPasteButtonClickAsync()@@ -167,6 +175,8 @@ public partial class UIFileSelectorPresenter : MefComponentBaseUIFileSelector.WithFiles(pickedFile);}}++ UpdateSelectedFilesDescription();}private string[] GetTreatedFileExtensions()@@ -252,6 +262,28 @@ public partial class UIFileSelectorPresenter : MefComponentBase}}+ private void UpdateSelectedFilesDescription()+ {+ if (UIFileSelector.SelectedFiles is null || UIFileSelector.SelectedFiles.Length == 0)+ {+ SelectedFilesDescription = string.Empty;+ HasFilesSelected = false;+ }+ else if (UIFileSelector.SelectedFiles.Length == 1)+ {+ SelectedFilesDescription = UIFileSelector.SelectedFiles[0].FileName;+ HasFilesSelected = true;+ }+ else+ {+ SelectedFilesDescription+ = string.Format(+ DevToys.Localization.Strings.UIFileSelectorPresenter.UIFileSelectorPresenter.FileSelectorMultipleFilesSelected,+ UIFileSelector.SelectedFiles.Length);+ HasFilesSelected = true;+ }+ }+private void UIFileSelector_CanSelectManyFilesChanged(object? sender, EventArgs e){UpdateInstructionStrings();@@ -313,6 +345,8 @@ public partial class UIFileSelectorPresenter : MefComponentBaseHasInvalidFilesSelected = true;return;}++ UpdateSelectedFilesDescription();}private string GetFileName(IBrowserFile browserFile)diff --git a/src/app/dev/DevToys.Localization/Strings/UIFileSelectorPresenter/UIFileSelectorPresenter.Designer.cs b/src/app/dev/DevToys.Localization/Strings/UIFileSelectorPresenter/UIFileSelectorPresenter.Designer.csindex 812f88a0f..604ea99bd 100644--- a/src/app/dev/DevToys.Localization/Strings/UIFileSelectorPresenter/UIFileSelectorPresenter.Designer.cs+++ b/src/app/dev/DevToys.Localization/Strings/UIFileSelectorPresenter/UIFileSelectorPresenter.Designer.cs@@ -123,6 +123,15 @@ namespace DevToys.Localization.Strings.UIFileSelectorPresenter {}}+ /// <summary>+ /// Looks up a localized string similar to {0} files have been selected..+ /// </summary>+ public static string FileSelectorMultipleFilesSelected {+ get {+ return ResourceManager.GetString("FileSelectorMultipleFilesSelected", resourceCulture);+ }+ }+/// <summary>/// Looks up a localized string similar to or./// </summary>diff --git a/src/app/dev/DevToys.Localization/Strings/UIFileSelectorPresenter/UIFileSelectorPresenter.resx b/src/app/dev/DevToys.Localization/Strings/UIFileSelectorPresenter/UIFileSelectorPresenter.resxindex 6aa9b9eee..406dcaea9 100644--- a/src/app/dev/DevToys.Localization/Strings/UIFileSelectorPresenter/UIFileSelectorPresenter.resx+++ b/src/app/dev/DevToys.Localization/Strings/UIFileSelectorPresenter/UIFileSelectorPresenter.resx@@ -138,6 +138,9 @@<data name="FileSelectorInvalidSelectedFiles" xml:space="preserve"><value>Only {0} file(s) can be used.</value></data>+ <data name="FileSelectorMultipleFilesSelected" xml:space="preserve">+ <value>{0} files have been selected.</value>+ </data><data name="Or" xml:space="preserve"><value>or</value></data>diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csprojindex e5aede701..efb3a037f 100644--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj@@ -74,6 +74,16 @@<AutoGen>True</AutoGen><DependentUpon>EncodersDecoders.resx</DependentUpon></Compile>+ <Compile Update="Tools\Generators\Generators.Designer.cs">+ <DependentUpon>Generators.resx</DependentUpon>+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ </Compile>+ <Compile Update="Tools\Generators\HashAndChecksum\HashAndChecksumGenerator.Designer.cs">+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ <DependentUpon>HashAndChecksumGenerator.resx</DependentUpon>+ </Compile><Compile Update="Tools\Test\Test.Designer.cs"><DependentUpon>Test.resx</DependentUpon><DesignTime>True</DesignTime>@@ -117,6 +127,14 @@<Generator>ResXFileCodeGenerator</Generator><LastGenOutput>EncodersDecoders.Designer.cs</LastGenOutput></EmbeddedResource>+ <EmbeddedResource Update="Tools\Generators\Generators.resx">+ <LastGenOutput>Generators.Designer.cs</LastGenOutput>+ <Generator>ResXFileCodeGenerator</Generator>+ </EmbeddedResource>+ <EmbeddedResource Update="Tools\Generators\HashAndChecksum\HashAndChecksumGenerator.resx">+ <Generator>ResXFileCodeGenerator</Generator>+ <LastGenOutput>HashAndChecksumGenerator.Designer.cs</LastGenOutput>+ </EmbeddedResource><EmbeddedResource Update="Tools\Test\Test.resx"><LastGenOutput>Test.Designer.cs</LastGenOutput><Generator>ResXFileCodeGenerator</Generator>diff --git a/src/app/dev/DevToys.Tools/Helpers/HashingHelper.cs b/src/app/dev/DevToys.Tools/Helpers/HashingHelper.csnew file mode 100644index 000000000..96a850d7b--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/HashingHelper.cs@@ -0,0 +1,114 @@+using System.Security.Authentication;+using System.Security.Cryptography;+using System.Text;+using DevToys.Tools.Models;++namespace DevToys.Tools.Helpers;++internal static class HashingHelper+{+ internal static async Task<string> ComputeHashAsync(+ HashAlgorithmType hashAlgorithm,+ Stream inputStream,+ string? hmacSecretKey,+ Action<HashingProgress>? progressCallback,+ CancellationToken cancellationToken)+ {+ Guard.IsNotNull(inputStream);+ Guard.IsNotEqualTo((int)HashAlgorithmType.None, (int)hashAlgorithm);++ using HashAlgorithm? algorithm = CreateHashAlgorithm(hashAlgorithm, hmacSecretKey);++ byte[]? fileHash+ = await ComputeHashAsync(+ algorithm,+ inputStream,+ progressCallback == null ? null : new Progress<HashingProgress>(progressCallback),+ cancellationToken);++ string? fileHashString+ = BitConverter+ .ToString(fileHash)+ .Replace("-", string.Empty);++ return fileHashString;+ }++ internal static async Task<byte[]> ComputeHashAsync(+ HashAlgorithm hashAlgorithm,+ Stream stream,+ IProgress<HashingProgress>? progressCallback,+ CancellationToken cancellationToken,+ int bufferSize = 1024 * 1024)+ {+ Guard.IsNotNull(stream, nameof(stream));+ Guard.IsNotNull(hashAlgorithm, nameof(hashAlgorithm));++ byte[] buffer = new byte[bufferSize];++ if (stream.Length == 0)+ {+ return hashAlgorithm.ComputeHash(Array.Empty<byte>());+ }++ long totalBytesRead = 0;++ int bytesRead;+ while ((bytesRead = await stream.ReadAsync(buffer, cancellationToken)) != 0)+ {+ hashAlgorithm.TransformBlock(buffer, 0, bytesRead, buffer, 0);+ totalBytesRead += bytesRead;+ ProgressAndCancellation();+ }++ hashAlgorithm.TransformFinalBlock(buffer, 0, bytesRead);+ ProgressAndCancellation();++ return hashAlgorithm.Hash ?? hashAlgorithm.ComputeHash(Array.Empty<byte>());++ void ProgressAndCancellation()+ {+ progressCallback?.Report(new HashingProgress(stream.Length, totalBytesRead, cancellationToken));+ cancellationToken.ThrowIfCancellationRequested();+ }+ }++ private static HashAlgorithm CreateHashAlgorithm(HashAlgorithmType hashingAlgorithm, string? hmacSecretKey)+ {+ if (string.IsNullOrEmpty(hmacSecretKey))+ {+ return CreateHashAlgorithm(hashingAlgorithm);+ }+ else+ {+ return CreateHmacAlgorithm(hashingAlgorithm, hmacSecretKey);+ }+ }++ private static HashAlgorithm CreateHashAlgorithm(HashAlgorithmType hashingAlgorithm)+ {+ return hashingAlgorithm switch+ {+ HashAlgorithmType.Md5 => MD5.Create(),+ HashAlgorithmType.Sha1 => SHA1.Create(),+ HashAlgorithmType.Sha256 => SHA256.Create(),+ HashAlgorithmType.Sha384 => SHA384.Create(),+ HashAlgorithmType.Sha512 => SHA512.Create(),+ _ => throw new ArgumentException("Hash Algorithm not supported", nameof(hashingAlgorithm))+ };+ }++ private static HashAlgorithm CreateHmacAlgorithm(HashAlgorithmType hashingAlgorithm, string hmacSecretKey)+ {+ byte[] key = Encoding.UTF8.GetBytes(hmacSecretKey);+ return hashingAlgorithm switch+ {+ HashAlgorithmType.Md5 => new HMACMD5(key),+ HashAlgorithmType.Sha1 => new HMACSHA1(key),+ HashAlgorithmType.Sha256 => new HMACSHA256(key),+ HashAlgorithmType.Sha384 => new HMACSHA384(key),+ HashAlgorithmType.Sha512 => new HMACSHA512(key),+ _ => throw new ArgumentException("Hash Algorithm not supported", nameof(hashingAlgorithm))+ };+ }+}diff --git a/src/app/dev/DevToys.Tools/Models/HashingProgress.cs b/src/app/dev/DevToys.Tools/Models/HashingProgress.csnew file mode 100644index 000000000..289658bab--- /dev/null+++ b/src/app/dev/DevToys.Tools/Models/HashingProgress.cs@@ -0,0 +1,19 @@+namespace DevToys.Tools.Models;++internal sealed record HashingProgress+{+ internal HashingProgress(long totalBytes, long completedBytes, CancellationToken cancellationToken)+ {+ TotalBytes = totalBytes;+ CompletedBytes = completedBytes;+ CancellationToken = cancellationToken;+ }++ internal long TotalBytes { get; init; }++ internal long CompletedBytes { get; init; }++ internal CancellationToken CancellationToken { get; init; }++ internal double GetPercentage() => 100f * CompletedBytes / TotalBytes;+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineTool.csindex 9459488cc..b9c6f7306 100644--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineTool.cs@@ -1,4 +1,5 @@-using DevToys.Tools.Strings.GlobalStrings;+using DevToys.Tools.SmartDetection;+using DevToys.Tools.Strings.GlobalStrings;using Microsoft.Extensions.Logging;using OneOf;@@ -13,19 +14,6 @@ namespace DevToys.Tools.Tools.EncodersDecoders.Base64Image;DescriptionResourceName = nameof(Base64ImageEncoderDecoder.Description))]internal sealed partial class Base64ImageEncoderDecoderCommandLineTool : ICommandLineTool{- private static readonly string[] supportedImageExtensions- = new string[]- {- ".bmp",- ".gif",- ".ico",- ".jpg",- ".jpeg",- ".png",- ".svg",- ".webp"- };-#pragma warning disable IDE0044 // Add readonly modifier[Import]private IFileStorage _fileStorage = null!;@@ -36,13 +24,13 @@ internal sealed partial class Base64ImageEncoderDecoderCommandLineTool : ICommanAlias = "i",IsRequired = true,DescriptionResourceName = nameof(Base64ImageEncoderDecoder.InputOptionDescription))]- private OneOf<FileInfo, string>? Input { get; set; }+ internal OneOf<FileInfo, string>? Input { get; set; }[CommandLineOption(Name = "outputFile",Alias = "o",DescriptionResourceName = nameof(Base64ImageEncoderDecoder.OutputFileOptionDescription))]- private FileInfo? OutputFile { get; set; }+ internal FileInfo? OutputFile { get; set; }public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken){@@ -60,7 +48,8 @@ internal sealed partial class Base64ImageEncoderDecoderCommandLineTool : ICommanreturn -1;}- bool isImageFile = supportedImageExtensions.Any(ext => ext.Equals(file.Extension, StringComparison.OrdinalIgnoreCase));+ string fileExtension = file.Extension.Trim('.');+ bool isImageFile = Base64ImageFileDataTypeDetector.SupportedFileTypes.Any(ext => ext.Equals(fileExtension, StringComparison.OrdinalIgnoreCase));if (isImageFile){await EncodeAsync(file, cancellationToken);@@ -76,7 +65,7 @@ internal sealed partial class Base64ImageEncoderDecoderCommandLineTool : ICommanasync base64 => await DecodeAsync(base64, cancellationToken));}- public async Task EncodeAsync(FileInfo file, CancellationToken cancellationToken)+ private async Task EncodeAsync(FileInfo file, CancellationToken cancellationToken){using Stream fileStream = _fileStorage.OpenReadFile(file.FullName);using var memoryStream = new MemoryStream();@@ -115,7 +104,7 @@ internal sealed partial class Base64ImageEncoderDecoderCommandLineTool : IComman}}- public async ValueTask<int> DecodeAsync(string input, CancellationToken cancellationToken)+ private async ValueTask<int> DecodeAsync(string input, CancellationToken cancellationToken){Stream? fileStream = null;try@@ -132,7 +121,7 @@ internal sealed partial class Base64ImageEncoderDecoderCommandLineTool : ICommanif (OutputFile is null){- fileStream = await _fileStorage.PickSaveFileAsync(supportedImageExtensions);+ fileStream = await _fileStorage.PickSaveFileAsync(Base64ImageFileDataTypeDetector.SupportedFileTypes);if (fileStream is null){return -1;diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.csindex f4b648c6e..8ea39e35d 100644--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.cs@@ -1,4 +1,5 @@-using DevToys.Tools.Helpers;+using DevToys.Api.Core;+using DevToys.Tools.Helpers;using DevToys.Tools.Models;using Microsoft.Extensions.Logging;using OneOf;@@ -14,6 +15,11 @@ namespace DevToys.Tools.Tools.EncodersDecoders.Base64Text;DescriptionResourceName = nameof(Base64TextEncoderDecoder.Description))]internal sealed class Base64TextEncoderDecoderCommandLineTool : ICommandLineTool{+#pragma warning disable IDE0044 // Add readonly modifier+ [Import]+ private IFileStorage _fileStorage = null!;+#pragma warning restore IDE0044 // Add readonly modifier+[CommandLineOption(Name = "input",Alias = "i",@@ -45,10 +51,7 @@ internal sealed class Base64TextEncoderDecoderCommandLineTool : ICommandLineToolif (Input.HasValue){- input- = await Input.Value.Match(- async file => await File.ReadAllTextAsync(file.FullName, cancellationToken),- text => Task.FromResult(text));+ input = await Input.Value.ReadAllTextAsync(_fileStorage, cancellationToken);}Guard.IsNotNull(input);diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.csindex 429bccec8..0ce5fafa5 100644--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs@@ -18,6 +18,7 @@ namespace DevToys.Tools.Tools.EncodersDecoders.Base64Text;AccessibleNameResourceName = nameof(Base64TextEncoderDecoder.AccessibleName),SearchKeywordsResourceName = nameof(Base64TextEncoderDecoder.SearchKeywords))][AcceptedDataTypeName(PredefinedCommonDataTypeNames.Base64Text)]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Text)]internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDisposable{/// <summary>@@ -160,6 +161,11 @@ internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDispo_conversionModeSwitch.Off(); // Switch to Decode mode_inputText.Text(base64Text); // This will trigger a conversion.}+ else if (dataTypeName == PredefinedCommonDataTypeNames.Text && parsedData is string text)+ {+ _conversionModeSwitch.On(); // Switch to Encode mode+ _inputText.Text(text); // This will trigger a conversion.+ }}public void Dispose()@@ -213,43 +219,43 @@ internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDispo{using (await _semaphore.WaitAsync(cancellationToken)){- await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);-- string conversionResult;-- switch (_settingsProvider.GetSetting(conversionMode))- {- case EncodingConversion.Encode:- conversionResult- = Base64Helper.FromTextToBase64(- input,- _settingsProvider.GetSetting(encoder),- _logger,- cancellationToken);- break;-- case EncodingConversion.Decode:- if (!string.IsNullOrEmpty(input) && !Base64Helper.IsBase64DataStrict(input))- {- cancellationToken.ThrowIfCancellationRequested();- _outputText.Text(Base64TextEncoderDecoder.InvalidBase64);- return;- }-- conversionResult- = Base64Helper.FromBase64ToText(- input,- _settingsProvider.GetSetting(encoder),- _logger,- cancellationToken);- break;-- default:- throw new NotSupportedException();+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ string conversionResult;++ switch (_settingsProvider.GetSetting(conversionMode))+ {+ case EncodingConversion.Encode:+ conversionResult+ = Base64Helper.FromTextToBase64(+ input,+ _settingsProvider.GetSetting(encoder),+ _logger,+ cancellationToken);+ break;++ case EncodingConversion.Decode:+ if (!string.IsNullOrEmpty(input) && !Base64Helper.IsBase64DataStrict(input))+ {+ cancellationToken.ThrowIfCancellationRequested();+ _outputText.Text(Base64TextEncoderDecoder.InvalidBase64);+ return;+ }++ conversionResult+ = Base64Helper.FromBase64ToText(+ input,+ _settingsProvider.GetSetting(encoder),+ _logger,+ cancellationToken);+ break;++ default:+ throw new NotSupportedException();+ }++ cancellationToken.ThrowIfCancellationRequested();+ _outputText.Text(conversionResult);}-- cancellationToken.ThrowIfCancellationRequested();- _outputText.Text(conversionResult);}}-}diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/Generators.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Generators/Generators.Designer.csnew file mode 100644index 000000000..d74842cb0--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/Generators.Designer.cs@@ -0,0 +1,81 @@+//------------------------------------------------------------------------------+// <auto-generated>+// This code was generated by a tool.+// Runtime Version:4.0.30319.42000+//+// Changes to this file may cause incorrect behavior and will be lost if+// the code is regenerated.+// </auto-generated>+//------------------------------------------------------------------------------++namespace DevToys.Tools.Tools.Generators {+ using System;+++ /// <summary>+ /// A strongly-typed resource class, for looking up localized strings, etc.+ /// </summary>+ // This class was auto-generated by the StronglyTypedResourceBuilder+ // class via a tool like ResGen or Visual Studio.+ // To add or remove a member, edit your .ResX file then rerun ResGen+ // with the /str option, or rebuild your VS project.+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]+ internal class Generators {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal Generators() {+ }++ /// <summary>+ /// Returns the cached ResourceManager instance used by this class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ internal static global::System.Resources.ResourceManager ResourceManager {+ get {+ if (object.ReferenceEquals(resourceMan, null)) {+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Generators.Generators", typeof(Generators).Assembly);+ resourceMan = temp;+ }+ return resourceMan;+ }+ }++ /// <summary>+ /// Overrides the current thread's CurrentUICulture property for all+ /// resource lookups using this strongly typed resource class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ internal static global::System.Globalization.CultureInfo Culture {+ get {+ return resourceCulture;+ }+ set {+ resourceCulture = value;+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Generators.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Generators.+ /// </summary>+ internal static string DisplayTitle {+ get {+ return ResourceManager.GetString("DisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/Generators.resx b/src/app/dev/DevToys.Tools/Tools/Generators/Generators.resxnew file mode 100644index 000000000..03dfbbd73--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/Generators.resx@@ -0,0 +1,126 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <!--+ Microsoft ResX Schema++ Version 2.0++ The primary goals of this format is to allow a simple XML format+ that is mostly human readable. The generation and parsing of the+ various data types are done through the TypeConverter classes+ associated with the data types.++ Example:++ ... ado.net/XML headers & schema ...+ <resheader name="resmimetype">text/microsoft-resx</resheader>+ <resheader name="version">2.0</resheader>+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">+ <value>[base64 mime encoded serialized .NET Framework object]</value>+ </data>+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>+ <comment>This is a comment</comment>+ </data>++ There are any number of "resheader" rows that contain simple+ name/value pairs.++ Each data row contains a name, and value. The row also contains a+ type or mimetype. Type corresponds to a .NET class that support+ text/value conversion through the TypeConverter architecture.+ Classes that don't support this are serialized and stored with the+ mimetype set.++ The mimetype is used for serialized objects, and tells the+ ResXResourceReader how to depersist the object. This is currently not+ extensible. For a given mimetype the value must be set accordingly:++ Note - application/x-microsoft.net.object.binary.base64 is the format+ that the ResXResourceWriter will generate, however the reader can+ read any of the formats listed below.++ mimetype: application/x-microsoft.net.object.binary.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.soap.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.bytearray.base64+ value : The object must be serialized into a byte array+ : using a System.ComponentModel.TypeConverter+ : and then encoded with base64 encoding.+ -->+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <data name="AccessibleName" xml:space="preserve">+ <value>Generators</value>+ </data>+ <data name="DisplayTitle" xml:space="preserve">+ <value>Generators</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Generators/GeneratorsGroup.cs b/src/app/dev/DevToys.Tools/Tools/Generators/GeneratorsGroup.csnew file mode 100644index 000000000..868985482--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/GeneratorsGroup.cs@@ -0,0 +1,15 @@+namespace DevToys.Tools.Tools.Generators;++[Export(typeof(GuiToolGroup))]+[Name(PredefinedCommonToolGroupNames.Generators)]+internal sealed class GeneratorsGroup : GuiToolGroup+{+ [ImportingConstructor]+ internal GeneratorsGroup()+ {+ IconFontName = "DevToys-Tools-Icons";+ IconGlyph = '\u0126';+ DisplayTitle = Generators.DisplayTitle;+ AccessibleName = Generators.AccessibleName;+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.Designer.csnew file mode 100644index 000000000..f31d9e57a--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.Designer.cs@@ -0,0 +1,270 @@+//------------------------------------------------------------------------------+// <auto-generated>+// This code was generated by a tool.+// Runtime Version:4.0.30319.42000+//+// Changes to this file may cause incorrect behavior and will be lost if+// the code is regenerated.+// </auto-generated>+//------------------------------------------------------------------------------++namespace DevToys.Tools.Tools.Generators.HashAndChecksum {+ using System;+++ /// <summary>+ /// A strongly-typed resource class, for looking up localized strings, etc.+ /// </summary>+ // This class was auto-generated by the StronglyTypedResourceBuilder+ // class via a tool like ResGen or Visual Studio.+ // To add or remove a member, edit your .ResX file then rerun ResGen+ // with the /str option, or rebuild your VS project.+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]+ internal class HashAndChecksumGenerator {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal HashAndChecksumGenerator() {+ }++ /// <summary>+ /// Returns the cached ResourceManager instance used by this class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ internal static global::System.Resources.ResourceManager ResourceManager {+ get {+ if (object.ReferenceEquals(resourceMan, null)) {+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Generators.HashAndChecksum.HashAndChecksumGenerator", typeof(HashAndChecksumGenerator).Assembly);+ resourceMan = temp;+ }+ return resourceMan;+ }+ }++ /// <summary>+ /// Overrides the current thread's CurrentUICulture property for all+ /// resource lookups using this strongly typed resource class.+ /// </summary>+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]+ internal static global::System.Globalization.CultureInfo Culture {+ get {+ return resourceCulture;+ }+ set {+ resourceCulture = value;+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Hash and Checksum Generator tool.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to FAILED.+ /// </summary>+ internal static string ChecksumVerificationFailed {+ get {+ return ResourceManager.GetString("ChecksumVerificationFailed", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to A text or file containing a checksum to verify data integrity.+ /// </summary>+ internal static string ChecksumVerificationOptionDescription {+ get {+ return ResourceManager.GetString("ChecksumVerificationOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to OK.+ /// </summary>+ internal static string ChecksumVerificationSucceeded {+ get {+ return ResourceManager.GetString("ChecksumVerificationSucceeded", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Checksum to verify data integrity.+ /// </summary>+ internal static string ChecksumVerificationTitle {+ get {+ return ResourceManager.GetString("ChecksumVerificationTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Configuration.+ /// </summary>+ internal static string ConfigurationTitle {+ get {+ return ResourceManager.GetString("ConfigurationTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Calculate hash from text or binary data.+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to The type of hash to generate.+ /// </summary>+ internal static string HashAlgorithmOptionDescription {+ get {+ return ResourceManager.GetString("HashAlgorithmOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to The hashes are the same.+ /// </summary>+ internal static string HashesMatch {+ get {+ return ResourceManager.GetString("HashesMatch", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to The hashes are different.+ /// </summary>+ internal static string HashesMismatch {+ get {+ return ResourceManager.GetString("HashesMismatch", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Select which hashing algorithm you want to use.+ /// </summary>+ internal static string HashingAlgorithmDescription {+ get {+ return ResourceManager.GetString("HashingAlgorithmDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Hashing Algorithm.+ /// </summary>+ internal static string HashingAlgorithmTitle {+ get {+ return ResourceManager.GetString("HashingAlgorithmTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Secret key to use to generate a HMAC hash.+ /// </summary>+ internal static string HmacSecret {+ get {+ return ResourceManager.GetString("HmacSecret", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Secret key to use to generate a HMAC hash.+ /// </summary>+ internal static string HmacSecretOptionDescription {+ get {+ return ResourceManager.GetString("HmacSecretOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Text or path to a file to hash.+ /// </summary>+ internal static string InputOptionDescription {+ get {+ return ResourceManager.GetString("InputOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Input text.+ /// </summary>+ internal static string InputTextTitle {+ get {+ return ResourceManager.GetString("InputTextTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Hash / Checksum Generator.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to or.+ /// </summary>+ internal static string Or {+ get {+ return ResourceManager.GetString("Or", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Output.+ /// </summary>+ internal static string OutputTitle {+ get {+ return ResourceManager.GetString("OutputTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Hash / Checksum.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Hides the progress of the hashing operation.+ /// </summary>+ internal static string SilentOptionDescription {+ get {+ return ResourceManager.GetString("SilentOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether the generated hash should be in uppercase or not.+ /// </summary>+ internal static string UppercaseOptionDescription {+ get {+ return ResourceManager.GetString("UppercaseOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Uppercase.+ /// </summary>+ internal static string UppercaseTitle {+ get {+ return ResourceManager.GetString("UppercaseTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.resx b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.resxnew file mode 100644index 000000000..887664378--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGenerator.resx@@ -0,0 +1,189 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <!--+ Microsoft ResX Schema++ Version 2.0++ The primary goals of this format is to allow a simple XML format+ that is mostly human readable. The generation and parsing of the+ various data types are done through the TypeConverter classes+ associated with the data types.++ Example:++ ... ado.net/XML headers & schema ...+ <resheader name="resmimetype">text/microsoft-resx</resheader>+ <resheader name="version">2.0</resheader>+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">+ <value>[base64 mime encoded serialized .NET Framework object]</value>+ </data>+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>+ <comment>This is a comment</comment>+ </data>++ There are any number of "resheader" rows that contain simple+ name/value pairs.++ Each data row contains a name, and value. The row also contains a+ type or mimetype. Type corresponds to a .NET class that support+ text/value conversion through the TypeConverter architecture.+ Classes that don't support this are serialized and stored with the+ mimetype set.++ The mimetype is used for serialized objects, and tells the+ ResXResourceReader how to depersist the object. This is currently not+ extensible. For a given mimetype the value must be set accordingly:++ Note - application/x-microsoft.net.object.binary.base64 is the format+ that the ResXResourceWriter will generate, however the reader can+ read any of the formats listed below.++ mimetype: application/x-microsoft.net.object.binary.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.soap.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.bytearray.base64+ value : The object must be serialized into a byte array+ : using a System.ComponentModel.TypeConverter+ : and then encoded with base64 encoding.+ -->+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <data name="AccessibleName" xml:space="preserve">+ <value>Hash and Checksum Generator tool</value>+ </data>+ <data name="ChecksumVerificationFailed" xml:space="preserve">+ <value>FAILED</value>+ </data>+ <data name="ChecksumVerificationOptionDescription" xml:space="preserve">+ <value>A text or file containing a checksum to verify data integrity</value>+ </data>+ <data name="ChecksumVerificationSucceeded" xml:space="preserve">+ <value>OK</value>+ </data>+ <data name="ChecksumVerificationTitle" xml:space="preserve">+ <value>Checksum to verify data integrity</value>+ </data>+ <data name="ConfigurationTitle" xml:space="preserve">+ <value>Configuration</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Calculate hash from text or binary data</value>+ </data>+ <data name="HashAlgorithmOptionDescription" xml:space="preserve">+ <value>The type of hash to generate</value>+ </data>+ <data name="HashesMatch" xml:space="preserve">+ <value>The hashes are the same</value>+ </data>+ <data name="HashesMismatch" xml:space="preserve">+ <value>The hashes are different</value>+ </data>+ <data name="HashingAlgorithmDescription" xml:space="preserve">+ <value>Select which hashing algorithm you want to use</value>+ </data>+ <data name="HashingAlgorithmTitle" xml:space="preserve">+ <value>Hashing Algorithm</value>+ </data>+ <data name="HmacSecret" xml:space="preserve">+ <value>Secret key to use to generate a HMAC hash</value>+ </data>+ <data name="HmacSecretOptionDescription" xml:space="preserve">+ <value>Secret key to use to generate a HMAC hash</value>+ </data>+ <data name="InputOptionDescription" xml:space="preserve">+ <value>Text or path to a file to hash</value>+ </data>+ <data name="InputTextTitle" xml:space="preserve">+ <value>Input text</value>+ </data>+ <data name="LongDisplayTitle" xml:space="preserve">+ <value>Hash / Checksum Generator</value>+ </data>+ <data name="Or" xml:space="preserve">+ <value>or</value>+ </data>+ <data name="OutputTitle" xml:space="preserve">+ <value>Output</value>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>Hash / Checksum</value>+ </data>+ <data name="SilentOptionDescription" xml:space="preserve">+ <value>Hides the progress of the hashing operation</value>+ </data>+ <data name="UppercaseOptionDescription" xml:space="preserve">+ <value>Whether the generated hash should be in uppercase or not</value>+ </data>+ <data name="UppercaseTitle" xml:space="preserve">+ <value>Uppercase</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorCommandLineTool.csnew file mode 100644index 000000000..40ebbcf23--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorCommandLineTool.cs@@ -0,0 +1,119 @@+using System.Security.Authentication;+using DevToys.Api.Core;+using DevToys.Api.Tool.CLI;+using DevToys.Tools.Helpers;+using Microsoft.Extensions.Logging;+using OneOf;++namespace DevToys.Tools.Tools.Generators.HashAndChecksum;++[Export(typeof(ICommandLineTool))]+[Name("HashAndChecksumGenerator")]+[CommandName(+ Name = "checksum",+ Alias = "hash",+ ResourceManagerBaseName = "DevToys.Tools.Tools.Generators.HashAndChecksum.HashAndChecksumGenerator",+ DescriptionResourceName = nameof(HashAndChecksumGenerator.Description))]+internal sealed class HashAndChecksumGeneratorCommandLineTool : ICommandLineTool+{+#pragma warning disable IDE0044 // Add readonly modifier+ [Import]+ private IFileStorage _fileStorage = null!;+#pragma warning restore IDE0044 // Add readonly modifier++ [CommandLineOption(+ Name = "input",+ Alias = "i",+ IsRequired = true,+ DescriptionResourceName = nameof(HashAndChecksumGenerator.InputOptionDescription))]+ internal OneOf<string, FileInfo>? Input { get; set; }++ [CommandLineOption(+ Name = "algorithm",+ Alias = "a",+ DescriptionResourceName = nameof(HashAndChecksumGenerator.HashAlgorithmOptionDescription))]+ internal HashAlgorithmType HashAlgorithm { get; set; } = HashAlgorithmType.Md5;++ [CommandLineOption(+ Name = "uppercase",+ Alias = "u",+ DescriptionResourceName = nameof(HashAndChecksumGenerator.UppercaseOptionDescription))]+ internal bool Uppercase { get; set; } = false;++ [CommandLineOption(+ Name = "hmac",+ Alias = "m",+ DescriptionResourceName = nameof(HashAndChecksumGenerator.HmacSecretOptionDescription))]+ internal string? HmacSecretKey { get; set; }++ [CommandLineOption(+ Name = "checksum",+ Alias = "c",+ DescriptionResourceName = nameof(HashAndChecksumGenerator.ChecksumVerificationOptionDescription))]+ internal OneOf<FileInfo, string>? ChecksumVerification { get; set; }++ [CommandLineOption(+ Name = "silent",+ Alias = "s",+ DescriptionResourceName = nameof(HashAndChecksumGenerator.SilentOptionDescription))]+ internal bool Silent { get; set; } = false;++ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ if (!Input.HasValue || HashAlgorithm == HashAlgorithmType.None)+ {+ return -1;+ }++ try+ {+ using Stream inputStream = await Input.Value.GetStreamAsync(_fileStorage, cancellationToken);++ string? fileHashString = null;+ ConsoleProgressBar? progressBar = Silent ? null : new ConsoleProgressBar();+ using (progressBar)+ {+ fileHashString+ = await HashingHelper.ComputeHashAsync(+ HashAlgorithm,+ inputStream,+ HmacSecretKey,+ hashProgress =>+ {+ progressBar?.Report(hashProgress.GetPercentage());+ },+ cancellationToken);+ }++ if (ChecksumVerification.HasValue)+ {+ string? checksum = await ChecksumVerification.Value.ReadAllTextAsync(_fileStorage, cancellationToken);+ if (string.Equals(checksum, fileHashString, StringComparison.OrdinalIgnoreCase))+ {+ Console.WriteLine(HashAndChecksumGenerator.ChecksumVerificationSucceeded);+ return 0;+ }+ else+ {+ Console.WriteLine(HashAndChecksumGenerator.ChecksumVerificationFailed);+ return -1;+ }+ }++ if (!Uppercase)+ {+ Console.WriteLine(fileHashString.ToLowerInvariant());+ }+ else+ {+ Console.WriteLine(fileHashString);+ }++ return 0;+ }+ catch+ {+ return -1;+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorGuiTool.csnew file mode 100644index 000000000..fe2900b30--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorGuiTool.cs@@ -0,0 +1,401 @@+using System.Security.Authentication;+using System.Security.Cryptography;+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using DevToys.Tools.Tools.EncodersDecoders.Url;+using Microsoft.Extensions.Logging;+using OneOf;++namespace DevToys.Tools.Tools.Generators.HashAndChecksum;++[Export(typeof(IGuiTool))]+[Name("HashAndChecksumGenerator")]+[ToolDisplayInformation(+ IconFontName = "DevToys-Tools-Icons",+ IconGlyph = '\u0125',+ GroupName = PredefinedCommonToolGroupNames.Generators,+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.Generators.HashAndChecksum.HashAndChecksumGenerator",+ ShortDisplayTitleResourceName = nameof(HashAndChecksumGenerator.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(HashAndChecksumGenerator.LongDisplayTitle),+ DescriptionResourceName = nameof(HashAndChecksumGenerator.Description),+ AccessibleNameResourceName = nameof(HashAndChecksumGenerator.AccessibleName))]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Text)]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.File)]+internal sealed class HashAndChecksumGeneratorGuiTool : IGuiTool, IDisposable+{+ /// <summary>+ /// Whether the generated hash should be uppercase or lowercase.+ /// </summary>+ private static readonly SettingDefinition<bool> uppercase+ = new(+ name: $"{nameof(HashAndChecksumGeneratorGuiTool)}.{nameof(uppercase)}",+ defaultValue: false);++ /// <summary>+ /// The hashing algorithm to use.+ /// </summary>+ private static readonly SettingDefinition<HashAlgorithmType> hashAlgorithm+ = new(+ name: $"{nameof(HashAndChecksumGeneratorGuiTool)}.{nameof(hashAlgorithm)}",+ defaultValue: HashAlgorithmType.Md5);++ private enum GridRows+ {+ Stretch+ }++ private enum GridColumns+ {+ Left,+ Center,+ Right+ }++ private readonly DisposableSemaphore _semaphore = new();+ private readonly ILogger _logger;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IUIStack _progressStack = Stack();+ private readonly IUIProgressBar _progressBar = ProgressBar();+ private readonly IUISingleLineTextInput _hmacSecretKeyInput = SingleLineTextInput("hash-checksum-generator-hmac-secret-key");+ private readonly IUIMultiLineTextInput _inputText = MultilineTextInput("hash-checksum-generator-input-text");+ private readonly IUIFileSelector _fileSelector = FileSelector("hash-checksum-generator-input-file");+ private readonly IUISingleLineTextInput _output = SingleLineTextInput("hash-checksum-generator-output");+ private readonly IUISingleLineTextInput _checksumVerification = SingleLineTextInput("hash-checksum-generator-checksum-verification");+ private readonly IUIInfoBar _infoBar = InfoBar("hash-checksum-generator-output-comparer-result");++ private CancellationTokenSource? _cancellationTokenSource;+ private OneOf<string, SandboxedFileReader>? _input;+ private bool _ignoreInputTextChange;+ private DateTime _lastStartTime;++ [ImportingConstructor]+ public HashAndChecksumGeneratorGuiTool(ISettingsProvider settingsProvider)+ {+ _logger = this.Log();+ _settingsProvider = settingsProvider;+ }++ // For unit tests.+ internal Task? WorkTask { get; private set; }++ public UIToolView View+ => new(+ isScrollable: true,+ Stack()+ .Vertical()+ .LargeSpacing()++ .WithChildren(+ Stack()+ .Vertical()+ .SmallSpacing()++ .WithChildren(+ Label()+ .Text(HashAndChecksumGenerator.ConfigurationTitle),++ SettingGroup("hash-checksum-generator-hash-algorithm-setting")+ .Icon("FluentSystemIcons", '\uF1EE')+ .Title(HashAndChecksumGenerator.HashingAlgorithmTitle)+ .Description(HashAndChecksumGenerator.HashingAlgorithmDescription)++ .Handle(+ _settingsProvider,+ hashAlgorithm,+ onOptionSelected: OnHashingAlgorithmChanged,+ Item(HashAlgorithmName.MD5.Name, HashAlgorithmType.Md5),+ Item(HashAlgorithmName.SHA1.Name, HashAlgorithmType.Sha1),+ Item(HashAlgorithmName.SHA256.Name, HashAlgorithmType.Sha256),+ Item(HashAlgorithmName.SHA384.Name, HashAlgorithmType.Sha384),+ Item(HashAlgorithmName.SHA512.Name, HashAlgorithmType.Sha512))++ .WithChildren(+ Setting("hash-checksum-generator-uppercase-setting")+ .Title(HashAndChecksumGenerator.UppercaseTitle)+ .Handle(_settingsProvider, uppercase, OnUppercaseChanged),++ _hmacSecretKeyInput+ .Title(HashAndChecksumGenerator.HmacSecret)+ .OnTextChanged(OnHmacSecretKeyChanged))),++ Grid()+ .ColumnMediumSpacing()++ .Rows(+ (GridRows.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Columns(+ (GridColumns.Left, new UIGridLength(1, UIGridUnitType.Fraction)),+ (GridColumns.Center, Auto),+ (GridColumns.Right, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Cells(+ Cell(+ GridRows.Stretch,+ GridColumns.Left,++ _inputText+ .Title(HashAndChecksumGenerator.InputTextTitle)+ .OnTextChanged(OnInputTextChanged)),++ Cell(+ GridRows.Stretch,+ GridColumns.Center,++ Label()+ .Text(HashAndChecksumGenerator.Or)+ .AlignVertically(UIVerticalAlignment.Center)),++ Cell(+ GridRows.Stretch,+ GridColumns.Right,++ _fileSelector+ .CanSelectOneFile()+ .OnFilesSelected(OnInputFileChanged))),++ _progressStack+ .AlignHorizontally(UIHorizontalAlignment.Center)+ .Horizontal()+ .SmallSpacing()+ .Hide()++ .WithChildren(+ _progressBar,+ Button()+ .Icon("FluentSystemIcons", '\uF75A')+ .OnClick(OnCancelButtonClicked)),++ _output+ .Title(HashAndChecksumGenerator.OutputTitle)+ .ReadOnly()+ .OnTextChanged(OnOutputOrOutputComparerTextChanged),++ _checksumVerification+ .Title(HashAndChecksumGenerator.ChecksumVerificationTitle)+ .OnTextChanged(OnOutputOrOutputComparerTextChanged),++ _infoBar.NonClosable()));++ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ if (dataTypeName == PredefinedCommonDataTypeNames.Text && parsedData is string text)+ {+ _inputText.Text(text); // This will trigger a hash generation.+ }+ else if (dataTypeName == PredefinedCommonDataTypeNames.File && parsedData is FileInfo fileInfo)+ {+ _fileSelector.WithFiles(SandboxedFileReader.FromFileInfo(fileInfo)); // This will trigger a hash generation.+ }+ }++ public void Dispose()+ {+ _cancellationTokenSource?.Dispose();+ _semaphore.Dispose();+ }++ private void OnOutputOrOutputComparerTextChanged(string text)+ {+ if (!string.IsNullOrEmpty(_output.Text) && !string.IsNullOrEmpty(_checksumVerification.Text))+ {+ if (string.Equals(_output.Text, _checksumVerification.Text, StringComparison.OrdinalIgnoreCase))+ {+ _infoBar.Title(HashAndChecksumGenerator.HashesMatch).Success();+ }+ else+ {+ _infoBar.Title(HashAndChecksumGenerator.HashesMismatch).Error();+ }++ _infoBar.Open();+ }+ else+ {+ _infoBar.Close();+ }+ }++ private void OnUppercaseChanged(bool isUppercase)+ {+ if (isUppercase)+ {+ _output.Text(_output.Text.ToUpperInvariant());+ }+ else+ {+ _output.Text(_output.Text.ToLowerInvariant());+ }+ }++ private void OnHashingAlgorithmChanged(HashAlgorithmType hashAlgorithm)+ {+ StartComputeHash();+ }++ private void OnHmacSecretKeyChanged(string secretKey)+ {+ StartComputeHash();+ }++ private void OnInputTextChanged(string text)+ {+ if (!_ignoreInputTextChange)+ {+ if (_input.HasValue && _input.Value.TryPickT1(out SandboxedFileReader file, out _))+ {+ file.Dispose();+ }++ _input = text;++ StartComputeHash();+ }+ }++ private void OnInputFileChanged(SandboxedFileReader[] sandboxedFileReader)+ {+ if (_input.HasValue && _input.Value.TryPickT1(out SandboxedFileReader file, out _))+ {+ file.Dispose();+ }++ Guard.HasSizeEqualTo(sandboxedFileReader, 1);+ _input = sandboxedFileReader[0];++ _ignoreInputTextChange = true;+ _inputText.Text(string.Empty);+ _ignoreInputTextChange = false;++ StartComputeHash();+ }++ private void OnCancelButtonClicked()+ {+ _cancellationTokenSource?.Cancel();+ _progressStack.Hide();+ }++ private void StartComputeHash()+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _cancellationTokenSource = new CancellationTokenSource();+ _lastStartTime = DateTime.UtcNow;++ if (_input.HasValue)+ {+ WorkTask+ = ComputeHashAsync(+ _input.Value,+ _settingsProvider.GetSetting(hashAlgorithm),+ _hmacSecretKeyInput.Text,+ _cancellationTokenSource.Token);+ }+ else+ {+ WorkTask = Task.CompletedTask;+ }+ }++ private async Task ComputeHashAsync(+ OneOf<string, SandboxedFileReader> input,+ HashAlgorithmType hashAlgorithm,+ string hmacSecretKey,+ CancellationToken cancellationToken)+ {+ try+ {+ using (await _semaphore.WaitAsync(cancellationToken))+ {+ _output.Text(string.Empty);+ _progressBar.Progress(0);++ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ Stream? inputStream+ = await input.Match(+ async inputString =>+ {+ var stringStream = new MemoryStream();+ var writer = new StreamWriter(stringStream);+ if (inputString is not null)+ {+ await writer.WriteAsync(inputString.AsMemory(), cancellationToken);+ }+ writer.Flush();+ stringStream.Position = 0;+ return (Stream)stringStream;+ },+ inputFile => inputFile.GetNewAccessToFileContentAsync(cancellationToken));++ Guard.IsNotNull(inputStream);+ string hash+ = await ComputeHashFromStreamAsync(+ inputStream,+ hashAlgorithm,+ hmacSecretKey,+ UpdateProgress,+ cancellationToken);++ cancellationToken.ThrowIfCancellationRequested();++ _output.Text(hash);+ }+ }+ finally+ {+ _progressStack.Hide();+ }+ }++ private async Task<string> ComputeHashFromStreamAsync(+ Stream inputStream,+ HashAlgorithmType hashAlgorithm,+ string hmacSecretKey,+ Action<HashingProgress> progressCallback,+ CancellationToken cancellationToken)+ {+ try+ {+ string fileHashString+ = await HashingHelper.ComputeHashAsync(+ hashAlgorithm,+ inputStream,+ hmacSecretKey,+ progressCallback,+ cancellationToken);++ if (!_settingsProvider.GetSetting(uppercase))+ {+ return fileHashString.ToLowerInvariant();+ }++ return fileHashString;+ }+ catch (OperationCanceledException)+ {+ return string.Empty;+ }+ catch (Exception ex)+ {+ // Logger.LogFault("Checksum Generator", ex, $"Failed to calculate FileHash, algorithm used: {inputHashingAlgorithm}");+ return ex.Message;+ }+ }++ private void UpdateProgress(HashingProgress hashingProgress)+ {+ if (!hashingProgress.CancellationToken.IsCancellationRequested)+ {+ if (DateTime.UtcNow - _lastStartTime > TimeSpan.FromMilliseconds(250))+ {+ // Show progress bar only if the operation takes more than 250ms.+ // This avoids having the progress bar flickering as the user type the HMAC secret key or type in the text input form.+ _progressStack.Show();+ }+ _progressBar.ProgressAsync(hashingProgress.GetPercentage()).Forget();+ }+ }+}diff --git a/src/app/tests/DevToys.UnitTests/ConsoleOutputMonitor.cs b/src/app/tests/DevToys.UnitTests/ConsoleOutputMonitor.csnew file mode 100644index 000000000..82b4b34b0--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/ConsoleOutputMonitor.cs@@ -0,0 +1,27 @@+using System.IO;++namespace DevToys.UnitTests;++internal sealed class ConsoleOutputMonitor : IDisposable+{+ private readonly StringWriter _stringWriter = new();+ private readonly TextWriter _originalOutput = Console.Out;++ internal ConsoleOutputMonitor()+ {+ Console.SetOut(_stringWriter);+ }++ internal string GetOutput()+ {+ string result = _stringWriter.ToString();+ _stringWriter.GetStringBuilder().Clear();+ return result;+ }++ public void Dispose()+ {+ Console.SetOut(_originalOutput);+ _stringWriter.Dispose();+ }+}diff --git a/src/app/tests/DevToys.UnitTests/TestParallelizationDisabled.cs b/src/app/tests/DevToys.UnitTests/TestParallelizationDisabled.csnew file mode 100644index 000000000..4bd99ae1e--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/TestParallelizationDisabled.cs@@ -0,0 +1,6 @@+namespace DevToys.UnitTests;++[CollectionDefinition(nameof(TestParallelizationDisabled), DisableParallelization = true)]+public class TestParallelizationDisabled+{+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.csindex a77776cd5..8b3619f00 100644--- a/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.cs+++ b/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.cs@@ -7,6 +7,7 @@ using Microsoft.Extensions.Logging;namespace DevToys.UnitTests.Tools.Converters;+[Collection(nameof(TestParallelizationDisabled))]public sealed class JsonYamlConverterCommandLineToolTests : MefBasedTest{private readonly StringWriter _consoleWriter = new();diff --git a/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineToolTests.csnew file mode 100644index 000000000..743047183--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Base64Image/Base64ImageEncoderDecoderCommandLineToolTests.cs@@ -0,0 +1,75 @@+using System.IO;+using System.Threading;+using System.Threading.Tasks;+using DevToys.CLI;+using DevToys.Tools.Tools.EncodersDecoders.Base64Image;+using DevToys.UnitTests.Mocks;++namespace DevToys.UnitTests.Tools.EncodersDecoders.Base64Image;++[Collection(nameof(TestParallelizationDisabled))]+public sealed class Base64ImageEncoderDecoderCommandLineToolTests : MefBasedTest+{+ private readonly Base64ImageEncoderDecoderCommandLineTool _tool;+ private readonly string _baseTestDataDirectory = Path.Combine("Tools", "TestData", nameof(Base64ImageEncoderDecoder));++ public Base64ImageEncoderDecoderCommandLineToolTests()+ : base(typeof(Base64ImageEncoderDecoderCommandLineTool).Assembly)+ {+ _tool = (Base64ImageEncoderDecoderCommandLineTool)MefProvider.ImportMany<ICommandLineTool, CommandLineToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "Base64ImageEncoderDecoder")+ .Value;+ }++ [Fact]+ public async Task EncodeImage()+ {+ string filePath = Path.Combine(_baseTestDataDirectory, "PNG_transparency_demonstration_1.png");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);++ _tool.Input = inputFile;++ using var consoleOutput = new ConsoleOutputMonitor();+ await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);++ string expectedResult = File.ReadAllText(TestDataProvider.GetFile(Path.Combine(_baseTestDataDirectory, "PNG_transparency_demonstration_1_base64.txt")).FullName);+ string result = consoleOutput.GetOutput().Trim();+ result.Should().Be(expectedResult);+ }++ [Fact]+ public async Task DecodeImageFromText()+ {+ byte[] expectedOutput = File.ReadAllBytes(Path.Combine(_baseTestDataDirectory, "PNG_transparency_demonstration_1.png"));+ string filePath = Path.Combine(_baseTestDataDirectory, "PNG_transparency_demonstration_1_base64.txt");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);++ _tool.Input = File.ReadAllText(inputFile.FullName);+ _tool.OutputFile = new FileInfo(Path.Combine(_baseTestDataDirectory, "testResult.png"));++ using var consoleOutput = new ConsoleOutputMonitor();+ await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);++ byte[] result = File.ReadAllBytes(_tool.OutputFile.FullName);+ expectedOutput.Should().BeEquivalentTo(result);+ _tool.OutputFile.Delete();+ }++ [Fact]+ public async Task DecodeImageFromFile()+ {+ byte[] expectedOutput = File.ReadAllBytes(TestDataProvider.GetFile(Path.Combine(_baseTestDataDirectory, "PNG_transparency_demonstration_1.png")).FullName);+ string filePath = Path.Combine(_baseTestDataDirectory, "PNG_transparency_demonstration_1_base64.txt");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);++ _tool.Input = inputFile;+ _tool.OutputFile = new FileInfo(TestDataProvider.GetFile(Path.Combine(_baseTestDataDirectory, "testResult.png")).FullName);++ using var consoleOutput = new ConsoleOutputMonitor();+ await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);++ byte[] result = File.ReadAllBytes(_tool.OutputFile.FullName);+ expectedOutput.Should().BeEquivalentTo(result);+ _tool.OutputFile.Delete();+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Generators/HashAndChecksumGeneratorCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Generators/HashAndChecksumGeneratorCommandLineToolTests.csnew file mode 100644index 000000000..54f5e89b4--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Generators/HashAndChecksumGeneratorCommandLineToolTests.cs@@ -0,0 +1,124 @@+using System.IO;+using System.Threading;+using System.Threading.Tasks;+using DevToys.CLI;+using DevToys.Tools.Tools.Generators.HashAndChecksum;+using DevToys.UnitTests.Mocks;++namespace DevToys.UnitTests.Tools.Generators;++[Collection(nameof(TestParallelizationDisabled))]+public sealed class HashAndChecksumGeneratorCommandLineToolTests : MefBasedTest+{+ private readonly HashAndChecksumGeneratorCommandLineTool _tool;+ private readonly string _baseTestDataDirectory = Path.Combine("Tools", "TestData", nameof(HashAndChecksumGenerator));++ public HashAndChecksumGeneratorCommandLineToolTests()+ : base(typeof(HashAndChecksumGeneratorCommandLineTool).Assembly)+ {+ _tool = (HashAndChecksumGeneratorCommandLineTool)MefProvider.ImportMany<ICommandLineTool, CommandLineToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "HashAndChecksumGenerator")+ .Value;+ _tool.Silent = true;+ }++ [Fact]+ public async Task HashText()+ {+ _tool.Input = "hello";++ using var consoleOutput = new ConsoleOutputMonitor();+ int exitCode = await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);+ exitCode.Should().Be(0);++ string result = consoleOutput.GetOutput().Trim();+ result.Should().Be("5d41402abc4b2a76b9719d911017c592");+ }++ [Fact]+ public async Task HashFile()+ {+ _tool.Input = TestDataProvider.GetFile(Path.Combine(_baseTestDataDirectory, "File.txt"));++ using var consoleOutput = new ConsoleOutputMonitor();+ int exitCode = await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);+ exitCode.Should().Be(0);++ string result = consoleOutput.GetOutput().Trim();+ result.Should().Be("3e25960a79dbc69b674cd4ec67a72c62");+ }++ [Fact]+ public async Task HashNoAlgorithm()+ {+ _tool.Input = "Hello";+ _tool.HashAlgorithm = System.Security.Authentication.HashAlgorithmType.None;++ using var consoleOutput = new ConsoleOutputMonitor();+ int exitCode = await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);+ exitCode.Should().Be(-1);++ string result = consoleOutput.GetOutput().Trim();+ result.Should().BeEmpty();+ }++ [Fact]+ public async Task HashUppercase()+ {+ _tool.Input = "Hello";+ _tool.Uppercase = true;++ using var consoleOutput = new ConsoleOutputMonitor();+ int exitCode = await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);+ exitCode.Should().Be(0);++ string result = consoleOutput.GetOutput().Trim();+ result.Should().Be("8B1A9953C4611296A827ABF8C47804D7");+ }++ [Fact]+ public async Task HashHmac()+ {+ _tool.Input = "Hello";+ _tool.HmacSecretKey = "secret";++ using var consoleOutput = new ConsoleOutputMonitor();+ int exitCode = await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);+ exitCode.Should().Be(0);++ string result = consoleOutput.GetOutput().Trim();+ result.Should().Be("f386803b6309719e8adad577a10d77c3");+ }++ [Fact]+ public async Task HashChecksum()+ {+ _tool.Input = "Hello";+ _tool.ChecksumVerification = "8B1A9953C4611296A827ABF8C47804D7";++ using var consoleOutput = new ConsoleOutputMonitor();+ int exitCode = await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);+ exitCode.Should().Be(0);++ string result = consoleOutput.GetOutput().Trim();+ result.Should().Be(HashAndChecksumGenerator.ChecksumVerificationSucceeded);++ _tool.Input = "Hello";+ _tool.ChecksumVerification = "foo";++ exitCode = await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);+ exitCode.Should().Be(-1);++ result = consoleOutput.GetOutput().Trim();+ result.Should().Be(HashAndChecksumGenerator.ChecksumVerificationFailed);++ _tool.Input = "Hello";+ _tool.ChecksumVerification = TestDataProvider.GetFile(Path.Combine(_baseTestDataDirectory, "Checksum.txt"));++ exitCode = await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);+ exitCode.Should().Be(0);++ result = consoleOutput.GetOutput().Trim();+ result.Should().Be(HashAndChecksumGenerator.ChecksumVerificationSucceeded);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/HashingHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/HashingHelperTests.csnew file mode 100644index 000000000..dc49b1373--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/HashingHelperTests.cs@@ -0,0 +1,187 @@+using System.IO;+using System.Security.Cryptography;+using System.Text;+using System.Threading;+using System.Threading.Tasks;+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;++namespace DevToys.UnitTests.Tools.Helpers;++public class HashingHelperTests+{+ private static readonly byte[] twoMBArray = Enumerable.Repeat<byte>(1, 1024 * 1024 * 2).ToArray();++ [Fact]+ public void ComputeHashShouldThrowIfStreamIsNull()+ {+ Action act+ = () =>+ HashingHelper.ComputeHashAsync(+ MD5.Create(),+ null,+ new Progress<HashingProgress>((_) => { }), CancellationToken.None)+ .CompleteOnCurrentThread();++ act+ .Should()+ .Throw<ArgumentNullException>()+ .Which.ParamName+ .Should()+ .Be("stream");+ }++ [Fact]+ public void ComputeHashShouldThrowIfHashingAlgorithmIsNull()+ {+ using var stream = new MemoryStream();++ Action act+ = () =>+ HashingHelper.ComputeHashAsync(+ null,+ stream,+ new Progress<HashingProgress>((_) => { }),+ CancellationToken.None)+ .CompleteOnCurrentThread();++ act+ .Should()+ .Throw<ArgumentNullException>()+ .Which.ParamName+ .Should()+ .Be("hashAlgorithm");+ }++ [Theory]+ [InlineData("", "D41D8CD98F00B204E9800998ECF8427E")]+ [InlineData(" ", "7215EE9C7D9DC229D2921A40E899EC5F")]+ [InlineData("Hello World", "B10A8DB164E0754105B7A99BE72E3FE5")]+ [InlineData("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam cursus nec metus vel sagittis. Donec auctor nulla tortor. Praesent pretium, nunc vel porttitor tempor, metus eros pharetra orci, vitae lobortis ligula massa eu libero. Maecenas faucibus dolor ante, non ullamcorper urna blandit nec. Maecenas at pulvinar neque, a fermentum sapien. Curabitur mattis massa leo, a hendrerit lectus condimentum eget. Etiam nec scelerisque tellus. Quisque ligula erat, porttitor quis mi id, vehicula feugiat est.", "02868AD2F0787EF5323B221DBD14BAB2")]+ public async Task ComputeHashMD5(string input, string expectedResult)+ {+ using var stream = new MemoryStream(Encoding.UTF8.GetBytes(input));+ byte[] bytesResult = await HashingHelper.ComputeHashAsync(MD5.Create(), stream, new Progress<HashingProgress>((_) => { }), CancellationToken.None);++ string result = FormatResult(BitConverter.ToString(bytesResult));++ result.Should().Be(expectedResult);+ }++ [Fact]+ public async Task ComputeHashMD5ForLargeFile()+ {+ using var stream = new MemoryStream(twoMBArray);+ byte[] bytesResult = await HashingHelper.ComputeHashAsync(MD5.Create(), stream, new Progress<HashingProgress>((_) => { }), CancellationToken.None);++ string result = FormatResult(BitConverter.ToString(bytesResult));++ result.Should().Be("9F05E7ADB91551CA82CF646CA371344A");+ }++ [Theory]+ [InlineData("", "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709")]+ [InlineData(" ", "B858CB282617FB0956D960215C8E84D1CCF909C6")]+ [InlineData("Hello World", "0A4D55A8D778E5022FAB701977C5D840BBC486D0")]+ [InlineData("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam cursus nec metus vel sagittis. Donec auctor nulla tortor. Praesent pretium, nunc vel porttitor tempor, metus eros pharetra orci, vitae lobortis ligula massa eu libero. Maecenas faucibus dolor ante, non ullamcorper urna blandit nec. Maecenas at pulvinar neque, a fermentum sapien. Curabitur mattis massa leo, a hendrerit lectus condimentum eget. Etiam nec scelerisque tellus. Quisque ligula erat, porttitor quis mi id, vehicula feugiat est.", "DBFE62B3C0817383AC870AACC61DD016BC599689")]+ public async Task ComputeHashSHA1(string input, string expectedResult)+ {+ using var stream = new MemoryStream(Encoding.UTF8.GetBytes(input));+ byte[] bytesResult = await HashingHelper.ComputeHashAsync(SHA1.Create(), stream, new Progress<HashingProgress>((_) => { }), CancellationToken.None);++ string result = FormatResult(BitConverter.ToString(bytesResult));++ result.Should().Be(expectedResult);+ }++ [Fact]+ public async Task ComputeHashSHA1ForLargeFile()+ {+ using var stream = new MemoryStream(twoMBArray);+ byte[] bytesResult = await HashingHelper.ComputeHashAsync(SHA1.Create(), stream, new Progress<HashingProgress>((_) => { }), CancellationToken.None);++ string result = FormatResult(BitConverter.ToString(bytesResult));++ result.Should().Be("F613FCBB54EF5E04D50D734FB0457B245833702B");+ }++ [Theory]+ [InlineData("", "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855")]+ [InlineData(" ", "36A9E7F1C95B82FFB99743E0C5C4CE95D83C9A430AAC59F84EF3CBFAB6145068")]+ [InlineData("Hello World", "A591A6D40BF420404A011733CFB7B190D62C65BF0BCDA32B57B277D9AD9F146E")]+ [InlineData("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam cursus nec metus vel sagittis. Donec auctor nulla tortor. Praesent pretium, nunc vel porttitor tempor, metus eros pharetra orci, vitae lobortis ligula massa eu libero. Maecenas faucibus dolor ante, non ullamcorper urna blandit nec. Maecenas at pulvinar neque, a fermentum sapien. Curabitur mattis massa leo, a hendrerit lectus condimentum eget. Etiam nec scelerisque tellus. Quisque ligula erat, porttitor quis mi id, vehicula feugiat est.", "FD5800A6B0C7EE959AFE2CC011DFD9E9A48E9E4FB80828412F7AFC77A3A97782")]+ public async Task ComputeHashSHA256(string input, string expectedResult)+ {+ using var stream = new MemoryStream(Encoding.UTF8.GetBytes(input));+ byte[] bytesResult = await HashingHelper.ComputeHashAsync(SHA256.Create(), stream, new Progress<HashingProgress>((_) => { }), CancellationToken.None);++ string result = FormatResult(BitConverter.ToString(bytesResult));++ result.Should().Be(expectedResult);+ }++ [Fact]+ public async Task ComputeHashSHA256ForLargeFile()+ {+ using var stream = new MemoryStream(twoMBArray);+ byte[] bytesResult = await HashingHelper.ComputeHashAsync(SHA256.Create(), stream, new Progress<HashingProgress>((_) => { }), CancellationToken.None);++ string result = FormatResult(BitConverter.ToString(bytesResult));++ result.Should().Be("6D75695D93DEB1BF5805617CFBA166466CF60DC0A99A8014FA58893F358F33B8");+ }++ [Theory]+ [InlineData("", "38B060A751AC96384CD9327EB1B1E36A21FDB71114BE07434C0CC7BF63F6E1DA274EDEBFE76F65FBD51AD2F14898B95B")]+ [InlineData(" ", "588016EB10045DD85834D67D187D6B97858F38C58C690320C4A64E0C2F92EEBD9F1BD74DE256E8268815905159449566")]+ [InlineData("Hello World", "99514329186B2F6AE4A1329E7EE6C610A729636335174AC6B740F9028396FCC803D0E93863A7C3D90F86BEEE782F4F3F")]+ [InlineData("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam cursus nec metus vel sagittis. Donec auctor nulla tortor. Praesent pretium, nunc vel porttitor tempor, metus eros pharetra orci, vitae lobortis ligula massa eu libero. Maecenas faucibus dolor ante, non ullamcorper urna blandit nec. Maecenas at pulvinar neque, a fermentum sapien. Curabitur mattis massa leo, a hendrerit lectus condimentum eget. Etiam nec scelerisque tellus. Quisque ligula erat, porttitor quis mi id, vehicula feugiat est.", "D775DFC327D966FE31F96B82A618A3F41CBB5FD9A05106CCD60F433D8079B8EA67546E6BA0501E29A6C9D6355A11A00C")]+ public async Task ComputeHashSHA384(string input, string expectedResult)+ {+ using var stream = new MemoryStream(Encoding.UTF8.GetBytes(input));+ byte[] bytesResult = await HashingHelper.ComputeHashAsync(SHA384.Create(), stream, new Progress<HashingProgress>((_) => { }), CancellationToken.None);++ string result = FormatResult(BitConverter.ToString(bytesResult));++ result.Should().Be(expectedResult);+ }++ [Fact]+ public async Task ComputeHashSHA384ForLargeFile()+ {+ using var stream = new MemoryStream(twoMBArray);+ byte[] bytesResult = await HashingHelper.ComputeHashAsync(SHA384.Create(), stream, new Progress<HashingProgress>((_) => { }), CancellationToken.None);++ string result = FormatResult(BitConverter.ToString(bytesResult));++ result.Should().Be("DBC3E43FA05876C686A500F648D815B4CEEE99C1761C58EFB031C8E439884D0C4363C8BC56A9F9AD5343B4E8EFDE6D37");+ }++ [Theory]+ [InlineData("", "CF83E1357EEFB8BDF1542850D66D8007D620E4050B5715DC83F4A921D36CE9CE47D0D13C5D85F2B0FF8318D2877EEC2F63B931BD47417A81A538327AF927DA3E")]+ [InlineData(" ", "F90DDD77E400DFE6A3FCF479B00B1EE29E7015C5BB8CD70F5F15B4886CC339275FF553FC8A053F8DDC7324F45168CFFAF81F8C3AC93996F6536EEF38E5E40768")]+ [InlineData("Hello World", "2C74FD17EDAFD80E8447B0D46741EE243B7EB74DD2149A0AB1B9246FB30382F27E853D8585719E0E67CBDA0DAA8F51671064615D645AE27ACB15BFB1447F459B")]+ [InlineData("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam cursus nec metus vel sagittis. Donec auctor nulla tortor. Praesent pretium, nunc vel porttitor tempor, metus eros pharetra orci, vitae lobortis ligula massa eu libero. Maecenas faucibus dolor ante, non ullamcorper urna blandit nec. Maecenas at pulvinar neque, a fermentum sapien. Curabitur mattis massa leo, a hendrerit lectus condimentum eget. Etiam nec scelerisque tellus. Quisque ligula erat, porttitor quis mi id, vehicula feugiat est.", "9BE8DB4FE9A776337D500BAA2E99A23C41CDEA2E0D0F445EB72DC8C6BEFAADF9FB5FA4C14BA81E93716F24C004477F08ABF684B3E50F0365C63AE602136E56B5")]+ public async Task ComputeHashSHA512(string input, string expectedResult)+ {+ using var stream = new MemoryStream(Encoding.UTF8.GetBytes(input));+ byte[] bytesResult = await HashingHelper.ComputeHashAsync(SHA512.Create(), stream, new Progress<HashingProgress>((_) => { }), CancellationToken.None);++ string result = FormatResult(BitConverter.ToString(bytesResult));++ result.Should().Be(expectedResult);+ }++ [Fact]+ public async Task ComputeHashSHA512ForLargeFile()+ {+ using var stream = new MemoryStream(twoMBArray);+ byte[] bytesResult = await HashingHelper.ComputeHashAsync(SHA512.Create(), stream, new Progress<HashingProgress>((_) => { }), CancellationToken.None);++ string result = FormatResult(BitConverter.ToString(bytesResult));++ result.Should().Be("417E836E280AEF701556B6135CA4B690819F82B4CF82EAD3B493B5BBC41174B9A868A68F13C90FA1A9DCDCA72BFB6268ABC061C702450BD1F838F59E33E9686D");+ }++ private static string FormatResult(string input) => input.Replace("-", string.Empty);+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/HashAndChecksumGenerator/Checksum.txt b/src/app/tests/DevToys.UnitTests/Tools/TestData/HashAndChecksumGenerator/Checksum.txtnew file mode 100644index 000000000..ca7708228--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/HashAndChecksumGenerator/Checksum.txt@@ -0,0 +1 @@+8B1A9953C4611296A827ABF8C47804D7\ No newline at end of filediff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/HashAndChecksumGenerator/File.txt b/src/app/tests/DevToys.UnitTests/Tools/TestData/HashAndChecksumGenerator/File.txtnew file mode 100644index 000000000..70c379b63--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/HashAndChecksumGenerator/File.txt@@ -0,0 +1 @@+Hello world\ No newline at end of file