A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
[DevToys 2.0] Added URL, HTML and GZip Encoder / Decoder (#910)
Etienne BAUDOUX6fc2d40094df
diff --git a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.csindex 26d181c6f..58ba99452 100644--- a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs+++ b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs@@ -7,4 +7,5 @@ public static class PredefinedCommonDataTypeNamespublic const string Base64Text = "base64Text";public const string Image = "image";public const string File = "file";+ public const string GZip = "gzip";}diff --git a/src/app/dev/DevToys.Blazor/Components/UIElements/UIElementPresenter.razor.cs b/src/app/dev/DevToys.Blazor/Components/UIElements/UIElementPresenter.razor.csindex 82b31e50e..ebb0007ef 100644--- a/src/app/dev/DevToys.Blazor/Components/UIElements/UIElementPresenter.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/UIElements/UIElementPresenter.razor.cs@@ -20,7 +20,10 @@ public partial class UIElementPresenter : ComponentBase, IDisposable// of the current Button being clicked, but due to optimization, it doesn't re-evaluate other elements that may have changed.// As a workaround, we here listen to UIElement.PropertyChanged to be notified when a property of the IUIElement has changed so// we can let Blazor know that we should re-render this element.- StateHasChanged();+ InvokeAsync(() =>+ {+ StateHasChanged();+ });}public void Dispose()diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csprojindex ddbe8acf2..56be91027 100644--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj@@ -29,6 +29,16 @@--></ItemGroup><ItemGroup>+ <Compile Update="Tools\EncodersDecoders\GZip\GZipEncoderDecoder.Designer.cs">+ <DependentUpon>GZipEncoderDecoder.resx</DependentUpon>+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ </Compile>+ <Compile Update="Tools\EncodersDecoders\Url\UrlEncoderDecoder.Designer.cs">+ <DependentUpon>UrlEncoderDecoder.resx</DependentUpon>+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ </Compile><Compile Update="Tools\EncodersDecoders\Html\HtmlEncoderDecoder.Designer.cs"><DependentUpon>HtmlEncoderDecoder.resx</DependentUpon><DesignTime>True</DesignTime>@@ -51,6 +61,14 @@</Compile></ItemGroup><ItemGroup>+ <EmbeddedResource Update="Tools\EncodersDecoders\GZip\GZipEncoderDecoder.resx">+ <LastGenOutput>GZipEncoderDecoder.Designer.cs</LastGenOutput>+ <Generator>ResXFileCodeGenerator</Generator>+ </EmbeddedResource>+ <EmbeddedResource Update="Tools\EncodersDecoders\Url\UrlEncoderDecoder.resx">+ <LastGenOutput>UrlEncoderDecoder.Designer.cs</LastGenOutput>+ <Generator>ResXFileCodeGenerator</Generator>+ </EmbeddedResource><EmbeddedResource Update="Tools\EncodersDecoders\Html\HtmlEncoderDecoder.resx"><LastGenOutput>HtmlEncoderDecoder.Designer.cs</LastGenOutput><Generator>ResXFileCodeGenerator</Generator>diff --git a/src/app/dev/DevToys.Tools/Helpers/GZipHelper.cs b/src/app/dev/DevToys.Tools/Helpers/GZipHelper.csnew file mode 100644index 000000000..eb466eede--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/GZipHelper.cs@@ -0,0 +1,159 @@+using System.IO.Compression;+using System.Text;+using DevToys.Tools.Tools.EncodersDecoders.GZip;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Helpers;++internal static partial class GZipHelper+{+ internal static bool IsGZip(string input)+ {+ if (string.IsNullOrWhiteSpace(input))+ {+ return false;+ }++ int index = -1;+ for (int i = 0; i < input.Length; i++)+ {+ if (!char.IsWhiteSpace(input[i]))+ {+ index = i;+ break;+ }+ }++ if (index > -1 && input.Length > index + 3)+ {+ bool isGZip+ = input[index] == 'H'+ && input[index + 1] == '4'+ && input[index + 2] == 's'+ && input[index + 3] == 'I';++ return isGZip;+ }++ return false;+ }++ internal static async Task<(string compressedData, double compressionPercentage)> CompressOrDecompressAsync(+ string? input,+ CompressionMode compressionMode,+ ILogger logger,+ CancellationToken cancellationToken)+ {+ (string data, double differencePercentage) conversionResult;++ switch (compressionMode)+ {+ case CompressionMode.Compress:+ conversionResult+ = await CompressGZipDataAsync(+ input,+ logger,+ cancellationToken);+ break;++ case CompressionMode.Decompress:+ conversionResult+ = await DecompressGZipDataAsync(+ input,+ logger,+ cancellationToken);+ break;++ default:+ throw new NotSupportedException();+ }++ cancellationToken.ThrowIfCancellationRequested();++ return conversionResult;+ }++ internal static async Task<(string compressedData, double compressionPercentage)> CompressGZipDataAsync(string? data, ILogger logger, CancellationToken cancellationToken)+ {+ if (string.IsNullOrWhiteSpace(data))+ {+ return (string.Empty, 0);+ }++ string compressed = string.Empty;+ try+ {+ byte[] inputBytes = Encoding.UTF8.GetBytes(data);+ using var outputStream = new MemoryStream();+ using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))+ {+ await gZipStream.WriteAsync(inputBytes, cancellationToken);+ }++ compressed = Convert.ToBase64String(outputStream.ToArray());+ cancellationToken.ThrowIfCancellationRequested();+ }+ catch (OperationCanceledException)+ {+ // ignore;+ }+ catch (Exception ex)+ {+ LogFailCompressGZip(logger, ex);+ return (ex.Message, 0);+ }++ int difference = data.Length - compressed.Length;+ double percentageDifference = (double)difference / data.Length * 100;++ return (compressed, percentageDifference);+ }++ internal static async Task<(string decompressedData, double compressionPercentage)> DecompressGZipDataAsync(string? compressedData, ILogger logger, CancellationToken cancellationToken)+ {+ if (string.IsNullOrWhiteSpace(compressedData))+ {+ return (string.Empty, 0);+ }++ string? decompressed = string.Empty;++ try+ {+ byte[] inputBytes = Convert.FromBase64String(compressedData);+ using var inputStream = new MemoryStream(inputBytes);+ using var gZipStream = new GZipStream(inputStream, CompressionMode.Decompress);+ using var streamReader = new StreamReader(gZipStream);+ decompressed = await streamReader.ReadToEndAsync(cancellationToken);+ cancellationToken.ThrowIfCancellationRequested();+ }+ catch (OperationCanceledException)+ {+ // ignore;+ }+ catch (FormatException)+ {+ return (GZipEncoderDecoder.InvalidGZipData, 0);+ }+ catch (Exception ex)+ {+ LogFailDecompressGZip(logger, ex);+ return (GZipEncoderDecoder.InvalidGZipData, 0);+ }++ int difference = decompressed.Length - compressedData.Length;+ double percentageDifference = (double)difference / decompressed.Length * 100;++ return (decompressed, percentageDifference);+ }++ private static void LogFailCompressGZip(ILogger logger, Exception exception)+ {+ logger.LogError(0, exception, $"Failed to compress text to GZip.");+ }++ private static void LogFailDecompressGZip(ILogger logger, Exception exception)+ {+ logger.LogError(1, exception, $"Failed to decompress GZip.");+ }+}diff --git a/src/app/dev/DevToys.Tools/Helpers/HtmlHelper.cs b/src/app/dev/DevToys.Tools/Helpers/HtmlHelper.csnew file mode 100644index 000000000..4affa1cb7--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/HtmlHelper.cs@@ -0,0 +1,96 @@+using System.Web;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Helpers;++internal static partial class HtmlHelper+{+ internal static string EncodeOrDecode(string? input, EncodingConversion conversionMode, ILogger logger, CancellationToken cancellationToken)+ {+ string conversionResult+ = conversionMode switch+ {+ EncodingConversion.Encode+ => EncodeHtmlData(+ input,+ logger,+ cancellationToken),++ EncodingConversion.Decode+ => DecodeHtmlData(+ input,+ logger,+ cancellationToken),++ _ => throw new NotSupportedException(),+ };++ cancellationToken.ThrowIfCancellationRequested();++ return conversionResult;+ }++ internal static string EncodeHtmlData(string? data, ILogger logger, CancellationToken cancellationToken)+ {+ if (string.IsNullOrWhiteSpace(data))+ {+ return string.Empty;+ }++ string encoded = string.Empty;+ try+ {+ encoded = HttpUtility.HtmlEncode(data);+ cancellationToken.ThrowIfCancellationRequested();+ }+ catch (OperationCanceledException)+ {+ // ignore;+ }+ catch (Exception ex)+ {+ LogFailEncodeHtml(logger, ex);+ return ex.Message;+ }++ return encoded;+ }++ internal static string DecodeHtmlData(string? data, ILogger logger, CancellationToken cancellationToken)+ {+ if (string.IsNullOrWhiteSpace(data))+ {+ return string.Empty;+ }++ string? decoded = string.Empty;++ try+ {+ decoded = HttpUtility.HtmlDecode(data);+ cancellationToken.ThrowIfCancellationRequested();+ }+ catch (Exception ex) when (ex is OperationCanceledException || ex is FormatException)+ {+ // ignore;+ }+ catch (Exception ex)+ {+ LogFailDecodeHtml(logger, ex);+ return ex.Message;+ }++ return decoded;+ }++ private static void LogFailEncodeHtml(ILogger logger, Exception exception)+ {+ logger.LogError(0, exception, $"Failed to encode text to Html.");+ }++ private static void LogFailDecodeHtml(ILogger logger, Exception exception)+ {+ logger.LogError(1, exception, $"Failed to decode Html.");+ }+}diff --git a/src/app/dev/DevToys.Tools/Helpers/UrlHelper.cs b/src/app/dev/DevToys.Tools/Helpers/UrlHelper.csnew file mode 100644index 000000000..6cf9b0541--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/UrlHelper.cs@@ -0,0 +1,95 @@+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Helpers;++internal static partial class UrlHelper+{+ internal static string EncodeOrDecode(string? input, EncodingConversion conversionMode, ILogger logger, CancellationToken cancellationToken)+ {+ string conversionResult+ = conversionMode switch+ {+ EncodingConversion.Encode+ => EncodeUrlData(+ input,+ logger,+ cancellationToken),++ EncodingConversion.Decode+ => DecodeUrlData(+ input,+ logger,+ cancellationToken),++ _ => throw new NotSupportedException(),+ };++ cancellationToken.ThrowIfCancellationRequested();++ return conversionResult;+ }++ internal static string EncodeUrlData(string? data, ILogger logger, CancellationToken cancellationToken)+ {+ if (string.IsNullOrWhiteSpace(data))+ {+ return string.Empty;+ }++ string encoded = string.Empty;+ try+ {+ encoded = Uri.EscapeDataString(data);+ cancellationToken.ThrowIfCancellationRequested();+ }+ catch (OperationCanceledException)+ {+ // ignore;+ }+ catch (Exception ex)+ {+ LogFailEncodeUrl(logger, ex);+ return ex.Message;+ }++ return encoded;+ }++ internal static string DecodeUrlData(string? data, ILogger logger, CancellationToken cancellationToken)+ {+ if (string.IsNullOrWhiteSpace(data))+ {+ return string.Empty;+ }++ string? decoded = string.Empty;++ try+ {+ decoded = Uri.UnescapeDataString(data);+ cancellationToken.ThrowIfCancellationRequested();+ }+ catch (Exception ex) when (ex is OperationCanceledException || ex is FormatException)+ {+ // ignore;+ }+ catch (Exception ex)+ {+ LogFailDecodeUrl(logger, ex);+ return ex.Message;+ }++ return decoded;+ }++ private static void LogFailEncodeUrl(ILogger logger, Exception exception)+ {+ logger.LogError(0, exception, $"Failed to encode text to Url.");+ }++ private static void LogFailDecodeUrl(ILogger logger, Exception exception)+ {+ logger.LogError(1, exception, $"Failed to decode Url.");+ }+}diff --git a/src/app/dev/DevToys.Tools/SmartDetection/GZipTextDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/GZipTextDataTypeDetector.csnew file mode 100644index 000000000..09d06221d--- /dev/null+++ b/src/app/dev/DevToys.Tools/SmartDetection/GZipTextDataTypeDetector.cs@@ -0,0 +1,24 @@+using DevToys.Tools.Helpers;++namespace DevToys.Tools.SmartDetection;++[Export(typeof(IDataTypeDetector))]+[DataTypeName(PredefinedCommonDataTypeNames.GZip, baseName: PredefinedCommonDataTypeNames.Text)]+internal sealed partial class GZipTextDataTypeDetector : IDataTypeDetector+{+ public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)+ {+ if (resultFromBaseDetector is not null+ && resultFromBaseDetector.Data is string dataString+ && !long.TryParse(dataString, out _)+ && !string.IsNullOrWhiteSpace(dataString))+ {+ if (GZipHelper.IsGZip(dataString))+ {+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataString));+ }+ }++ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoder.Designer.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoder.Designer.csnew file mode 100644index 000000000..ea2317b77--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoder.Designer.cs@@ -0,0 +1,207 @@+//------------------------------------------------------------------------------+// <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.EncodersDecoders.GZip {+ 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 GZipEncoderDecoder {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal GZipEncoderDecoder() {+ }++ /// <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.EncodersDecoders.GZip.GZipEncoderDecoder", typeof(GZipEncoderDecoder).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 GZip Compressor and Decompressor tool.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Compress.+ /// </summary>+ internal static string CompressionModeCompress {+ get {+ return ResourceManager.GetString("CompressionModeCompress", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Decompress.+ /// </summary>+ internal static string CompressionModeDecompress {+ get {+ return ResourceManager.GetString("CompressionModeDecompress", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Select whether the input should be compressed or decompressed.+ /// </summary>+ internal static string CompressionModeDescription {+ get {+ return ResourceManager.GetString("CompressionModeDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether to compress or decompress a GZip string.+ /// </summary>+ internal static string CompressionModeOptionDescription {+ get {+ return ResourceManager.GetString("CompressionModeOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Compression mode.+ /// </summary>+ internal static string CompressionModeTitle {+ get {+ return ResourceManager.GetString("CompressionModeTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Compression ratio.+ /// </summary>+ internal static string CompressionRatio {+ get {+ return ResourceManager.GetString("CompressionRatio", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to {0:0.#} %.+ /// </summary>+ internal static string CompressionRatioValue {+ get {+ return ResourceManager.GetString("CompressionRatioValue", 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 Compress or decompress a text in GZip.+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Text to compress or GZip to decompress.+ /// </summary>+ internal static string InputOptionDescription {+ get {+ return ResourceManager.GetString("InputOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Input.+ /// </summary>+ internal static string InputTitle {+ get {+ return ResourceManager.GetString("InputTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to <Invalid GZip data>.+ /// </summary>+ internal static string InvalidGZipData {+ get {+ return ResourceManager.GetString("InvalidGZipData", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to GZip Compress / Decompress.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", 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 GZip.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoder.resx b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoder.resxnew file mode 100644index 000000000..273de6e1b--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoder.resx@@ -0,0 +1,168 @@+<?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>GZip Compressor and Decompressor tool</value>+ </data>+ <data name="CompressionModeCompress" xml:space="preserve">+ <value>Compress</value>+ </data>+ <data name="CompressionModeDecompress" xml:space="preserve">+ <value>Decompress</value>+ </data>+ <data name="CompressionModeDescription" xml:space="preserve">+ <value>Select whether the input should be compressed or decompressed</value>+ </data>+ <data name="CompressionModeOptionDescription" xml:space="preserve">+ <value>Whether to compress or decompress a GZip string</value>+ </data>+ <data name="CompressionModeTitle" xml:space="preserve">+ <value>Compression mode</value>+ </data>+ <data name="CompressionRatio" xml:space="preserve">+ <value>Compression ratio</value>+ </data>+ <data name="CompressionRatioValue" xml:space="preserve">+ <value>{0:0.#} %</value>+ </data>+ <data name="ConfigurationTitle" xml:space="preserve">+ <value>Configuration</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Compress or decompress a text in GZip</value>+ </data>+ <data name="InputOptionDescription" xml:space="preserve">+ <value>Text to compress or GZip to decompress</value>+ </data>+ <data name="InputTitle" xml:space="preserve">+ <value>Input</value>+ </data>+ <data name="InvalidGZipData" xml:space="preserve">+ <value><Invalid GZip data></value>+ </data>+ <data name="LongDisplayTitle" xml:space="preserve">+ <value>GZip Compress / Decompress</value>+ </data>+ <data name="OutputTitle" xml:space="preserve">+ <value>Output</value>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>GZip</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderCommandLineTool.csnew file mode 100644index 000000000..168f27e99--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderCommandLineTool.cs@@ -0,0 +1,41 @@+using System.IO.Compression;+using DevToys.Tools.Helpers;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.EncodersDecoders.GZip;++[Export(typeof(ICommandLineTool))]+[Name("GZipEncoderDecoder")]+[CommandName(+ Name = "gzip",+ ResourceManagerBaseName = "DevToys.Tools.Tools.EncodersDecoders.GZip.GZipEncoderDecoder",+ DescriptionResourceName = nameof(GZipEncoderDecoder.Description))]+internal sealed class GZipEncoderDecoderCommandLineTool : ICommandLineTool+{+ [CommandLineOption(+ Name = "input",+ Alias = "i",+ IsRequired = true,+ DescriptionResourceName = nameof(GZipEncoderDecoder.InputOptionDescription))]+ private string? Input { get; set; }++ [CommandLineOption(+ Name = "mode",+ Alias = "m",+ DescriptionResourceName = nameof(GZipEncoderDecoder.CompressionModeOptionDescription))]+ private CompressionMode CompressionMode { get; set; } = CompressionMode.Compress;++ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ (string data, double differencePercentage) conversionResult+ = await GZipHelper.CompressOrDecompressAsync(+ Input,+ CompressionMode,+ logger,+ cancellationToken);++ Console.WriteLine(conversionResult.data);++ return 0;+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.csnew file mode 100644index 000000000..a4b527300--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.cs@@ -0,0 +1,212 @@+using System.IO.Compression;+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using DevToys.Tools.Tools.EncodersDecoders.Base64Text;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.EncodersDecoders.GZip;++[Export(typeof(IGuiTool))]+[Name("GZipEncoderDecoder")]+[ToolDisplayInformation(+ IconFontName = "DevToys-Tools-Icons",+ IconGlyph = '\u0120',+ GroupName = PredefinedCommonToolGroupNames.EncodersDecoders,+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.EncodersDecoders.GZip.GZipEncoderDecoder",+ ShortDisplayTitleResourceName = nameof(GZipEncoderDecoder.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(GZipEncoderDecoder.LongDisplayTitle),+ DescriptionResourceName = nameof(GZipEncoderDecoder.Description),+ AccessibleNameResourceName = nameof(GZipEncoderDecoder.AccessibleName))]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.GZip)]+internal sealed partial class GZipEncoderDecoderGuiTool : IGuiTool, IDisposable+{+ /// <summary>+ /// Whether the tool should compress or decompress GZip.+ /// </summary>+ private static readonly SettingDefinition<CompressionMode> compressionMode+ = new(+ name: $"{nameof(GZipEncoderDecoderGuiTool)}.{nameof(compressionMode)}",+ defaultValue: CompressionMode.Compress);++ private enum GridRows+ {+ Settings,+ Input,+ Output,+ CompressionRatio+ }++ private enum GridColumns+ {+ Stretch+ }++ private readonly ILogger _logger;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IUISwitch _compressionModeSwitch = Switch("gzip-compression-mode-switch");+ private readonly IUIMultiLineTextInput _inputText = MultilineTextInput("gzip-input-box");+ private readonly IUIMultiLineTextInput _outputText = MultilineTextInput("gzip-output-box");+ private readonly IUIInfoBar _compressionRatioInfoBar = InfoBar("gzip-compression-ratio-info-bar");++ private CancellationTokenSource? _cancellationTokenSource;++ [ImportingConstructor]+ public GZipEncoderDecoderGuiTool(ISettingsProvider settingsProvider)+ {+ _logger = this.Log();+ _settingsProvider = settingsProvider;++ switch (_settingsProvider.GetSetting(compressionMode))+ {+ case CompressionMode.Compress:+ _compressionModeSwitch.On();+ _inputText.AutoWrap();+ _outputText.AlwaysWrap();+ break;++ case CompressionMode.Decompress:+ _inputText.AlwaysWrap();+ _outputText.AutoWrap();+ break;++ default:+ throw new NotSupportedException();+ }+ }++ // For unit tests.+ internal Task? WorkTask { get; private set; }++ public UIToolView View+ => new(+ isScrollable: true,+ Grid()+ .RowLargeSpacing()++ .Rows(+ (GridRows.Settings, Auto),+ (GridRows.Input, new UIGridLength(1, UIGridUnitType.Fraction)),+ (GridRows.Output, new UIGridLength(1, UIGridUnitType.Fraction)),+ (GridRows.CompressionRatio, Auto))++ .Columns(+ (GridColumns.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Cells(+ Cell(+ GridRows.Settings,+ GridColumns.Stretch,++ Stack()+ .Vertical()+ .SmallSpacing()++ .WithChildren(+ Label()+ .Text(GZipEncoderDecoder.ConfigurationTitle),++ Setting("gzip-conversion-mode-setting")+ .Icon("FluentSystemIcons", '\uF18D')+ .Title(GZipEncoderDecoder.CompressionModeTitle)+ .Description(GZipEncoderDecoder.CompressionModeDescription)++ .InteractiveElement(+ _compressionModeSwitch+ .OnText(GZipEncoderDecoder.CompressionModeCompress)+ .OffText(GZipEncoderDecoder.CompressionModeDecompress)+ .OnToggle(OnCompressionModeChanged)))),++ Cell(+ GridRows.Input,+ GridColumns.Stretch,++ _inputText+ .Title(GZipEncoderDecoder.InputTitle)+ .OnTextChanged(OnInputTextChanged)),++ Cell(+ GridRows.Output,+ GridColumns.Stretch,++ _outputText+ .Title(GZipEncoderDecoder.OutputTitle)+ .ReadOnly()+ .Extendable()),++ Cell(+ GridRows.CompressionRatio,+ GridColumns.Stretch,++ _compressionRatioInfoBar+ .Informational()+ .NonClosable()+ .HideIcon()+ .Open()+ .Title(GZipEncoderDecoder.CompressionRatio))));++ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ if (dataTypeName == PredefinedCommonDataTypeNames.GZip && parsedData is string text)+ {+ _compressionModeSwitch.Off(); // Switch to Decompress mode+ _inputText.Text(text); // This will trigger a conversion.+ }+ }++ public void Dispose()+ {+ _cancellationTokenSource?.Dispose();+ }++ private void OnCompressionModeChanged(bool conversionMode)+ {+ _settingsProvider.SetSetting(compressionMode, conversionMode ? CompressionMode.Compress : CompressionMode.Decompress);+ _inputText.Text(_outputText.Text); // This will trigger a conversion.++ switch (_settingsProvider.GetSetting(compressionMode))+ {+ case CompressionMode.Compress:+ _inputText.AutoWrap();+ _outputText.AlwaysWrap();+ break;++ case CompressionMode.Decompress:+ _inputText.AlwaysWrap();+ _outputText.AutoWrap();+ break;++ default:+ throw new NotSupportedException();+ }+ }++ private void OnInputTextChanged(string text)+ {+ StartConvert(text);+ }++ private void StartConvert(string text)+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _cancellationTokenSource = new CancellationTokenSource();++ WorkTask = ConvertAsync(text, _cancellationTokenSource.Token);+ }++ private async Task ConvertAsync(string input, CancellationToken cancellationToken)+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ (string data, double differencePercentage) conversionResult+ = await GZipHelper.CompressOrDecompressAsync(+ input,+ _settingsProvider.GetSetting(compressionMode),+ _logger,+ cancellationToken);++ _compressionRatioInfoBar.Description(string.Format(GZipEncoderDecoder.CompressionRatioValue, conversionResult.differencePercentage));+ _outputText.Text(conversionResult.data);+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoder.Designer.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoder.Designer.csnew file mode 100644index 000000000..0185e2593--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoder.Designer.cs@@ -0,0 +1,180 @@+//------------------------------------------------------------------------------+// <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.EncodersDecoders.Html {+ 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 HtmlEncoderDecoder {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal HtmlEncoderDecoder() {+ }++ /// <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.EncodersDecoders.Html.HtmlEncoderDecoder", typeof(HtmlEncoderDecoder).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 HTML Encoder and Decoder tool.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", 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 Decode.+ /// </summary>+ internal static string ConversionDecode {+ get {+ return ResourceManager.GetString("ConversionDecode", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Select which conversion mode you want to use.+ /// </summary>+ internal static string ConversionDescription {+ get {+ return ResourceManager.GetString("ConversionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Encode.+ /// </summary>+ internal static string ConversionEncode {+ get {+ return ResourceManager.GetString("ConversionEncode", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether to encode or decode HTML.+ /// </summary>+ internal static string ConversionOptionDescription {+ get {+ return ResourceManager.GetString("ConversionOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Conversion.+ /// </summary>+ internal static string ConversionTitle {+ get {+ return ResourceManager.GetString("ConversionTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Encode and decode HTML text data.+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Text to encode or HTML to decode.+ /// </summary>+ internal static string InputOptionDescription {+ get {+ return ResourceManager.GetString("InputOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Input.+ /// </summary>+ internal static string InputTitle {+ get {+ return ResourceManager.GetString("InputTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to HTML Text Encoder / Decoder.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", 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 HTML.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoder.resx b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoder.resxnew file mode 100644index 000000000..5f217ad12--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoder.resx@@ -0,0 +1,159 @@+<?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>HTML Encoder and Decoder tool</value>+ </data>+ <data name="ConfigurationTitle" xml:space="preserve">+ <value>Configuration</value>+ </data>+ <data name="ConversionDecode" xml:space="preserve">+ <value>Decode</value>+ </data>+ <data name="ConversionDescription" xml:space="preserve">+ <value>Select which conversion mode you want to use</value>+ </data>+ <data name="ConversionEncode" xml:space="preserve">+ <value>Encode</value>+ </data>+ <data name="ConversionOptionDescription" xml:space="preserve">+ <value>Whether to encode or decode HTML</value>+ </data>+ <data name="ConversionTitle" xml:space="preserve">+ <value>Conversion</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Encode and decode HTML text data</value>+ </data>+ <data name="InputOptionDescription" xml:space="preserve">+ <value>Text to encode or HTML to decode</value>+ </data>+ <data name="InputTitle" xml:space="preserve">+ <value>Input</value>+ </data>+ <data name="LongDisplayTitle" xml:space="preserve">+ <value>HTML Text Encoder / Decoder</value>+ </data>+ <data name="OutputTitle" xml:space="preserve">+ <value>Output</value>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>HTML</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderCommandLineTool.csnew file mode 100644index 000000000..085f9f6e0--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderCommandLineTool.cs@@ -0,0 +1,39 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.EncodersDecoders.Html;++[Export(typeof(ICommandLineTool))]+[Name("HtmlEncoderDecoder")]+[CommandName(+ Name = "html",+ ResourceManagerBaseName = "DevToys.Tools.Tools.EncodersDecoders.Html.HtmlEncoderDecoder",+ DescriptionResourceName = nameof(HtmlEncoderDecoder.Description))]+internal sealed class HtmlEncoderDecoderCommandLineTool : ICommandLineTool+{+ [CommandLineOption(+ Name = "input",+ Alias = "i",+ IsRequired = true,+ DescriptionResourceName = nameof(HtmlEncoderDecoder.InputOptionDescription))]+ private string? Input { get; set; }++ [CommandLineOption(+ Name = "conversion",+ Alias = "c",+ DescriptionResourceName = nameof(HtmlEncoderDecoder.ConversionOptionDescription))]+ private EncodingConversion EncodingConversionMode { get; set; } = EncodingConversion.Encode;++ public ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ Console.WriteLine(+ HtmlHelper.EncodeOrDecode(+ Input,+ EncodingConversionMode,+ logger,+ cancellationToken));++ return new ValueTask<int>(0);+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.csnew file mode 100644index 000000000..09f4fabc1--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.cs@@ -0,0 +1,172 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.EncodersDecoders.Html;++[Export(typeof(IGuiTool))]+[Name("HtmlEncoderDecoder")]+[ToolDisplayInformation(+ IconFontName = "DevToys-Tools-Icons",+ IconGlyph = '\u0107',+ GroupName = PredefinedCommonToolGroupNames.EncodersDecoders,+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.EncodersDecoders.Html.HtmlEncoderDecoder",+ ShortDisplayTitleResourceName = nameof(HtmlEncoderDecoder.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(HtmlEncoderDecoder.LongDisplayTitle),+ DescriptionResourceName = nameof(HtmlEncoderDecoder.Description),+ AccessibleNameResourceName = nameof(HtmlEncoderDecoder.AccessibleName))]+internal sealed partial class HtmlEncoderDecoderGuiTool : IGuiTool, IDisposable+{+ /// <summary>+ /// Whether the tool should encode or decode Html.+ /// </summary>+ private static readonly SettingDefinition<EncodingConversion> conversionMode+ = new(+ name: $"{nameof(HtmlEncoderDecoderGuiTool)}.{nameof(conversionMode)}",+ defaultValue: EncodingConversion.Encode);++ private enum GridRows+ {+ Settings,+ Input,+ Output+ }++ private enum GridColumns+ {+ Stretch+ }++ private readonly ILogger _logger;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IUISwitch _conversionModeSwitch = Switch("html-conversion-mode-switch");+ private readonly IUIMultiLineTextInput _inputText = MultilineTextInput("html-input-box");+ private readonly IUIMultiLineTextInput _outputText = MultilineTextInput("html-output-box");++ private CancellationTokenSource? _cancellationTokenSource;++ [ImportingConstructor]+ public HtmlEncoderDecoderGuiTool(ISettingsProvider settingsProvider)+ {+ _logger = this.Log();+ _settingsProvider = settingsProvider;++ switch (_settingsProvider.GetSetting(conversionMode))+ {+ case EncodingConversion.Encode:+ _conversionModeSwitch.On();+ _inputText.AutoWrap();+ _outputText.AlwaysWrap();+ break;++ case EncodingConversion.Decode:+ _inputText.AlwaysWrap();+ _outputText.AutoWrap();+ break;++ default:+ throw new NotSupportedException();+ }+ }++ // For unit tests.+ internal Task? WorkTask { get; private set; }++ public UIToolView View+ => new(+ isScrollable: true,+ Grid()+ .RowLargeSpacing()++ .Rows(+ (GridRows.Settings, Auto),+ (GridRows.Input, new UIGridLength(1, UIGridUnitType.Fraction)),+ (GridRows.Output, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Columns(+ (GridColumns.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Cells(+ Cell(+ GridRows.Settings,+ GridColumns.Stretch,++ Stack()+ .Vertical()+ .SmallSpacing()++ .WithChildren(+ Label()+ .Text(HtmlEncoderDecoder.ConfigurationTitle),++ Setting("html-conversion-mode-setting")+ .Icon("FluentSystemIcons", '\uF18D')+ .Title(HtmlEncoderDecoder.ConversionTitle)+ .Description(HtmlEncoderDecoder.ConversionDescription)++ .InteractiveElement(+ _conversionModeSwitch+ .OnText(HtmlEncoderDecoder.ConversionEncode)+ .OffText(HtmlEncoderDecoder.ConversionDecode)+ .OnToggle(OnConversionModeChanged)))),++ Cell(+ GridRows.Input,+ GridColumns.Stretch,++ _inputText+ .Title(HtmlEncoderDecoder.InputTitle)+ .OnTextChanged(OnInputTextChanged)),++ Cell(+ GridRows.Output,+ GridColumns.Stretch,++ _outputText+ .Title(HtmlEncoderDecoder.OutputTitle)+ .ReadOnly()+ .Extendable())));++ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ throw new NotImplementedException();+ }++ public void Dispose()+ {+ _cancellationTokenSource?.Dispose();+ }++ private void OnConversionModeChanged(bool conversionMode)+ {+ _settingsProvider.SetSetting(HtmlEncoderDecoderGuiTool.conversionMode, conversionMode ? EncodingConversion.Encode : EncodingConversion.Decode);+ _inputText.Text(_outputText.Text); // This will trigger a conversion.+ }++ private void OnInputTextChanged(string text)+ {+ StartConvert(text);+ }++ private void StartConvert(string text)+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _cancellationTokenSource = new CancellationTokenSource();++ WorkTask = ConvertAsync(text, _cancellationTokenSource.Token);+ }++ private async Task ConvertAsync(string input, CancellationToken cancellationToken)+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ _outputText.Text(+ HtmlHelper.EncodeOrDecode(+ input,+ _settingsProvider.GetSetting(conversionMode),+ _logger,+ cancellationToken));+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoder.Designer.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoder.Designer.csnew file mode 100644index 000000000..ffd6b3fd1--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoder.Designer.cs@@ -0,0 +1,180 @@+//------------------------------------------------------------------------------+// <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.EncodersDecoders.Url {+ 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 UrlEncoderDecoder {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal UrlEncoderDecoder() {+ }++ /// <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.EncodersDecoders.Url.UrlEncoderDecoder", typeof(UrlEncoderDecoder).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 URL Encoder and Decoder tool.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", 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 Decode.+ /// </summary>+ internal static string ConversionDecode {+ get {+ return ResourceManager.GetString("ConversionDecode", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Select which conversion mode you want to use.+ /// </summary>+ internal static string ConversionDescription {+ get {+ return ResourceManager.GetString("ConversionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Encode.+ /// </summary>+ internal static string ConversionEncode {+ get {+ return ResourceManager.GetString("ConversionEncode", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether to encode or decode text in a URL parameter.+ /// </summary>+ internal static string ConversionOptionDescription {+ get {+ return ResourceManager.GetString("ConversionOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Conversion.+ /// </summary>+ internal static string ConversionTitle {+ get {+ return ResourceManager.GetString("ConversionTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Encode or decode all the applicable characters to their corresponding URL entities.+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Text to encode or URL to decode.+ /// </summary>+ internal static string InputOptionDescription {+ get {+ return ResourceManager.GetString("InputOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Input.+ /// </summary>+ internal static string InputTitle {+ get {+ return ResourceManager.GetString("InputTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to URL Encoder / Decoder.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", 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 URL.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoder.resx b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoder.resxnew file mode 100644index 000000000..3b9eb07e6--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoder.resx@@ -0,0 +1,159 @@+<?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>URL Encoder and Decoder tool</value>+ </data>+ <data name="ConfigurationTitle" xml:space="preserve">+ <value>Configuration</value>+ </data>+ <data name="ConversionDecode" xml:space="preserve">+ <value>Decode</value>+ </data>+ <data name="ConversionDescription" xml:space="preserve">+ <value>Select which conversion mode you want to use</value>+ </data>+ <data name="ConversionEncode" xml:space="preserve">+ <value>Encode</value>+ </data>+ <data name="ConversionOptionDescription" xml:space="preserve">+ <value>Whether to encode or decode text in a URL parameter</value>+ </data>+ <data name="ConversionTitle" xml:space="preserve">+ <value>Conversion</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Encode or decode all the applicable characters to their corresponding URL entities</value>+ </data>+ <data name="InputOptionDescription" xml:space="preserve">+ <value>Text to encode or URL to decode</value>+ </data>+ <data name="InputTitle" xml:space="preserve">+ <value>Input</value>+ </data>+ <data name="LongDisplayTitle" xml:space="preserve">+ <value>URL Encoder / Decoder</value>+ </data>+ <data name="OutputTitle" xml:space="preserve">+ <value>Output</value>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>URL</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderCommandLineTool.csnew file mode 100644index 000000000..55e07b030--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderCommandLineTool.cs@@ -0,0 +1,39 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.EncodersDecoders.Url;++[Export(typeof(ICommandLineTool))]+[Name("UrlEncoderDecoder")]+[CommandName(+ Name = "url",+ ResourceManagerBaseName = "DevToys.Tools.Tools.EncodersDecoders.Url.UrlEncoderDecoder",+ DescriptionResourceName = nameof(UrlEncoderDecoder.Description))]+internal sealed class UrlEncoderDecoderCommandLineTool : ICommandLineTool+{+ [CommandLineOption(+ Name = "input",+ Alias = "i",+ IsRequired = true,+ DescriptionResourceName = nameof(UrlEncoderDecoder.InputOptionDescription))]+ private string? Input { get; set; }++ [CommandLineOption(+ Name = "conversion",+ Alias = "c",+ DescriptionResourceName = nameof(UrlEncoderDecoder.ConversionOptionDescription))]+ private EncodingConversion EncodingConversionMode { get; set; } = EncodingConversion.Encode;++ public ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ Console.WriteLine(+ UrlHelper.EncodeOrDecode(+ Input,+ EncodingConversionMode,+ logger,+ cancellationToken));++ return new ValueTask<int>(0);+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.csnew file mode 100644index 000000000..02c419a30--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.cs@@ -0,0 +1,173 @@+using DevToys.Api;+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.EncodersDecoders.Url;++[Export(typeof(IGuiTool))]+[Name("UrlEncoderDecoder")]+[ToolDisplayInformation(+ IconFontName = "DevToys-Tools-Icons",+ IconGlyph = '\u0121',+ GroupName = PredefinedCommonToolGroupNames.EncodersDecoders,+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.EncodersDecoders.Url.UrlEncoderDecoder",+ ShortDisplayTitleResourceName = nameof(UrlEncoderDecoder.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(UrlEncoderDecoder.LongDisplayTitle),+ DescriptionResourceName = nameof(UrlEncoderDecoder.Description),+ AccessibleNameResourceName = nameof(UrlEncoderDecoder.AccessibleName))]+internal sealed partial class UrlEncoderDecoderGuiTool : IGuiTool, IDisposable+{+ /// <summary>+ /// Whether the tool should encode or decode Url.+ /// </summary>+ private static readonly SettingDefinition<EncodingConversion> conversionMode+ = new(+ name: $"{nameof(UrlEncoderDecoderGuiTool)}.{nameof(conversionMode)}",+ defaultValue: EncodingConversion.Encode);++ private enum GridRows+ {+ Settings,+ Input,+ Output+ }++ private enum GridColumns+ {+ Stretch+ }++ private readonly ILogger _logger;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IUISwitch _conversionModeSwitch = Switch("url-conversion-mode-switch");+ private readonly IUIMultiLineTextInput _inputText = MultilineTextInput("url-input-box");+ private readonly IUIMultiLineTextInput _outputText = MultilineTextInput("url-output-box");++ private CancellationTokenSource? _cancellationTokenSource;++ [ImportingConstructor]+ public UrlEncoderDecoderGuiTool(ISettingsProvider settingsProvider)+ {+ _logger = this.Log();+ _settingsProvider = settingsProvider;++ switch (_settingsProvider.GetSetting(conversionMode))+ {+ case EncodingConversion.Encode:+ _conversionModeSwitch.On();+ _inputText.AutoWrap();+ _outputText.AlwaysWrap();+ break;++ case EncodingConversion.Decode:+ _inputText.AlwaysWrap();+ _outputText.AutoWrap();+ break;++ default:+ throw new NotSupportedException();+ }+ }++ // For unit tests.+ internal Task? WorkTask { get; private set; }++ public UIToolView View+ => new(+ isScrollable: true,+ Grid()+ .RowLargeSpacing()++ .Rows(+ (GridRows.Settings, Auto),+ (GridRows.Input, new UIGridLength(1, UIGridUnitType.Fraction)),+ (GridRows.Output, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Columns(+ (GridColumns.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Cells(+ Cell(+ GridRows.Settings,+ GridColumns.Stretch,++ Stack()+ .Vertical()+ .SmallSpacing()++ .WithChildren(+ Label()+ .Text(UrlEncoderDecoder.ConfigurationTitle),++ Setting("url-conversion-mode-setting")+ .Icon("FluentSystemIcons", '\uF18D')+ .Title(UrlEncoderDecoder.ConversionTitle)+ .Description(UrlEncoderDecoder.ConversionDescription)++ .InteractiveElement(+ _conversionModeSwitch+ .OnText(UrlEncoderDecoder.ConversionEncode)+ .OffText(UrlEncoderDecoder.ConversionDecode)+ .OnToggle(OnConversionModeChanged)))),++ Cell(+ GridRows.Input,+ GridColumns.Stretch,++ _inputText+ .Title(UrlEncoderDecoder.InputTitle)+ .OnTextChanged(OnInputTextChanged)),++ Cell(+ GridRows.Output,+ GridColumns.Stretch,++ _outputText+ .Title(UrlEncoderDecoder.OutputTitle)+ .ReadOnly()+ .Extendable())));++ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ throw new NotImplementedException();+ }++ public void Dispose()+ {+ _cancellationTokenSource?.Dispose();+ }++ private void OnConversionModeChanged(bool conversionMode)+ {+ _settingsProvider.SetSetting(UrlEncoderDecoderGuiTool.conversionMode, conversionMode ? EncodingConversion.Encode : EncodingConversion.Decode);+ _inputText.Text(_outputText.Text); // This will trigger a conversion.+ }++ private void OnInputTextChanged(string text)+ {+ StartConvert(text);+ }++ private void StartConvert(string text)+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _cancellationTokenSource = new CancellationTokenSource();++ WorkTask = ConvertAsync(text, _cancellationTokenSource.Token);+ }++ private async Task ConvertAsync(string input, CancellationToken cancellationToken)+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ _outputText.Text(+ UrlHelper.EncodeOrDecode(+ input,+ _settingsProvider.GetSetting(conversionMode),+ _logger,+ cancellationToken));+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiToolTests.csnew file mode 100644index 000000000..a4507dabd--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiToolTests.cs@@ -0,0 +1,64 @@+using System.Threading.Tasks;+using DevToys.Core.Tools.Metadata;+using DevToys.Tools.Tools.EncodersDecoders.Base64Text;++namespace DevToys.UnitTests.Tools.EncodersDecoders.Base64Text;++public sealed class Base64TextEncoderDecoderGuiToolTests : MefBasedTest+{+ private readonly Base64TextEncoderDecoderGuiTool _tool;+ private readonly UIToolView _toolView;+ private readonly IUIMultiLineTextInput _inputBox;+ private readonly IUIMultiLineTextInput _outputBox;++ public Base64TextEncoderDecoderGuiToolTests()+ : base(typeof(Base64TextEncoderDecoderGuiTool).Assembly)+ {+ _tool = (Base64TextEncoderDecoderGuiTool)MefProvider.ImportMany<IGuiTool, GuiToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "Base64TextEncoderDecoder")+ .Value;++ _toolView = _tool.View;++ _inputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("base64-text-input-box");+ _outputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("base64-text-output-box");+ }++ [Fact]+ public async Task EncodeUtf8()+ {+ _inputBox.Text("Hello world &é'(-è_çèà)");+ await _tool.WorkTask;+ _outputBox.Text.Should().Be("SGVsbG8gd29ybGQgJsOpJygtw6hfw6fDqMOgKQ==");+ }++ [Fact]+ public async Task EncodeAscii()+ {+ var encodingOption = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("base64-text-encoding-setting")).InteractiveElement;+ encodingOption.Select(1); // Select ASCII++ _inputBox.Text("Hello world &é'(-è_çèà)");+ await _tool.WorkTask;+ _outputBox.Text.Should().Be("SGVsbG8gd29ybGQgJj8nKC0/Xz8/Pyk=");+ }++ [Fact]+ public async Task SwitchConversionMode()+ {+ var conversionMode = (IUISwitch)_toolView.GetChildElementById("base64-text-conversion-mode-switch");++ await EncodeUtf8();++ conversionMode.Off(); // Switch to Decode++ await _tool.WorkTask;+ _inputBox.Text.Should().Be("SGVsbG8gd29ybGQgJsOpJygtw6hfw6fDqMOgKQ==");+ await _tool.WorkTask;+ _outputBox.Text("Hello world &é'(-è_çèà)");++ conversionMode.On(); // Switch to Encode+ await _tool.WorkTask;+ await EncodeUtf8();+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiToolTests.csnew file mode 100644index 000000000..1a2e28fe4--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiToolTests.cs@@ -0,0 +1,50 @@+using System.Threading.Tasks;+using DevToys.Core.Tools.Metadata;+using DevToys.Tools.Tools.EncodersDecoders.GZip;++namespace DevToys.UnitTests.Tools.EncodersDecoders.GZip;++public sealed class GZipEncoderDecoderGuiToolTests : MefBasedTest+{+ private readonly GZipEncoderDecoderGuiTool _tool;+ private readonly UIToolView _toolView;+ private readonly IUIMultiLineTextInput _inputBox;+ private readonly IUIMultiLineTextInput _outputBox;++ public GZipEncoderDecoderGuiToolTests()+ : base(typeof(GZipEncoderDecoderGuiTool).Assembly)+ {+ _tool = (GZipEncoderDecoderGuiTool)MefProvider.ImportMany<IGuiTool, GuiToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "GZipEncoderDecoder")+ .Value;++ _toolView = _tool.View;++ _inputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("gzip-input-box");+ _outputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("gzip-output-box");+ }++ [Fact]+ public async Task SwitchConversionMode()+ {+ var conversionMode = (IUISwitch)_toolView.GetChildElementById("gzip-compression-mode-switch");++ _inputBox.Text("<hello world>");+ await _tool.WorkTask;+ _outputBox.Text.Should().Be("H4sIAAAAAAAACrPJSM3JyVcozy/KSbEDAKEb3mcNAAAA");++ conversionMode.Off(); // Switch to Decompress++ await _tool.WorkTask;+ _inputBox.Text.Should().Be("H4sIAAAAAAAACrPJSM3JyVcozy/KSbEDAKEb3mcNAAAA");+ await _tool.WorkTask;+ _outputBox.Text("<hello world>");++ conversionMode.On(); // Switch to Compress++ await _tool.WorkTask;+ _inputBox.Text("<hello world>");+ await _tool.WorkTask;+ _outputBox.Text.Should().Be("H4sIAAAAAAAACrPJSM3JyVcozy/KSbEDAKEb3mcNAAAA");+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiToolTests.csnew file mode 100644index 000000000..0b58e5946--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiToolTests.cs@@ -0,0 +1,50 @@+using System.Threading.Tasks;+using DevToys.Core.Tools.Metadata;+using DevToys.Tools.Tools.EncodersDecoders.Html;++namespace DevToys.UnitTests.Tools.EncodersDecoders.Html;++public sealed class HtmlEncoderDecoderGuiToolTests : MefBasedTest+{+ private readonly HtmlEncoderDecoderGuiTool _tool;+ private readonly UIToolView _toolView;+ private readonly IUIMultiLineTextInput _inputBox;+ private readonly IUIMultiLineTextInput _outputBox;++ public HtmlEncoderDecoderGuiToolTests()+ : base(typeof(HtmlEncoderDecoderGuiTool).Assembly)+ {+ _tool = (HtmlEncoderDecoderGuiTool)MefProvider.ImportMany<IGuiTool, GuiToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "HtmlEncoderDecoder")+ .Value;++ _toolView = _tool.View;++ _inputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("html-input-box");+ _outputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("html-output-box");+ }++ [Fact]+ public async Task SwitchConversionMode()+ {+ var conversionMode = (IUISwitch)_toolView.GetChildElementById("html-conversion-mode-switch");++ _inputBox.Text("<hello>");+ await _tool.WorkTask;+ _outputBox.Text.Should().Be("<hello>");++ conversionMode.Off(); // Switch to Decode++ await _tool.WorkTask;+ _inputBox.Text.Should().Be("<hello>");+ await _tool.WorkTask;+ _outputBox.Text("<hello>");++ conversionMode.On(); // Switch to Encode++ await _tool.WorkTask;+ _inputBox.Text("<hello>");+ await _tool.WorkTask;+ _outputBox.Text.Should().Be("<hello>");+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiToolTests.csnew file mode 100644index 000000000..16a994b8b--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiToolTests.cs@@ -0,0 +1,50 @@+using System.Threading.Tasks;+using DevToys.Core.Tools.Metadata;+using DevToys.Tools.Tools.EncodersDecoders.Url;++namespace DevToys.UnitTests.Tools.EncodersDecoders.Url;++public sealed class UrlEncoderDecoderGuiToolTests : MefBasedTest+{+ private readonly UrlEncoderDecoderGuiTool _tool;+ private readonly UIToolView _toolView;+ private readonly IUIMultiLineTextInput _inputBox;+ private readonly IUIMultiLineTextInput _outputBox;++ public UrlEncoderDecoderGuiToolTests()+ : base(typeof(UrlEncoderDecoderGuiTool).Assembly)+ {+ _tool = (UrlEncoderDecoderGuiTool)MefProvider.ImportMany<IGuiTool, GuiToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "UrlEncoderDecoder")+ .Value;++ _toolView = _tool.View;++ _inputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("url-input-box");+ _outputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("url-output-box");+ }++ [Fact]+ public async Task SwitchConversionMode()+ {+ var conversionMode = (IUISwitch)_toolView.GetChildElementById("url-conversion-mode-switch");++ _inputBox.Text("<hello world>");+ await _tool.WorkTask;+ _outputBox.Text.Should().Be("%3Chello%20world%3E");++ conversionMode.Off(); // Switch to Decode++ await _tool.WorkTask;+ _inputBox.Text.Should().Be("%3Chello%20world%3E");+ await _tool.WorkTask;+ _outputBox.Text("<hello world>");++ conversionMode.On(); // Switch to Encode++ await _tool.WorkTask;+ _inputBox.Text("<hello world>");+ await _tool.WorkTask;+ _outputBox.Text.Should().Be("%3Chello%20world%3E");+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/GZipHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/GZipHelperTests.csnew file mode 100644index 000000000..b7bba7417--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/GZipHelperTests.cs@@ -0,0 +1,58 @@+using System.Threading;+using System.Threading.Tasks;+using DevToys.Tools.Helpers;+using DevToys.UnitTests.Mocks;++namespace DevToys.UnitTests.Tools.Helpers;++public class GZipHelperTests+{+ [Theory]+ [InlineData(null, false)]+ [InlineData("", false)]+ [InlineData(" ", false)]+ [InlineData(" ", false)]+ [InlineData("H4sIAAAAAAAAC/NIzcnJBwCCidH3BQAAAA==", true)]+ [InlineData(" H4sIAAAAAAAAC/NIzcnJBwCCidH3BQAAAA==", true)]+ [InlineData(" H4sIAAAAAAAAC/NIzcnJBwCCidH3BQAAAA==", true)]+ [InlineData("H4sI", true)]+ [InlineData("H4sIA", true)]+ [InlineData("H4s", false)]+ public void IsValid(string input, bool expectedResult)+ {+ GZipHelper.IsGZip(input).Should().Be(expectedResult);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("Hello World!", "H4sIAAAAAAAACvNIzcnJVwjPL8pJUQQAoxwpHAwAAAA=")]+ [InlineData("Hello World! é)à", "H4sIAAAAAAAACvNIzcnJVwjPL8pJUVQ4vFLz8AIAeJm72xIAAAA=")]+ [InlineData("H4sIAAAAAAAACvNIzcnJVwjPL8pJUVQ4vFLz8AIAeJm72xIAAAA=", "H4sIAAAAAAAACvMwKfZ0hALnMj/PquQ8r7DyrAAfiwKv0LBAkzI3nyoLR0/HVK9cc6MKsFJbAI7LDrY0AAAA")]+ internal async Task CompressToGZip(string input, string expectedResult)+ {+ (await GZipHelper.CompressGZipDataAsync(+ input,+ new MockILogger(),+ CancellationToken.None))+ .compressedData+ .Should()+ .Be(expectedResult);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("H4sIAAAAAAAACvNIzcnJVwjPL8pJUQQAoxwpHAwAAAA=", "Hello World!")]+ [InlineData("H4sIAAAAAAAACvNIzcnJVwjPL8pJUVQ4vFLz8AIAeJm72xIAAAA=", "Hello World! é)à")]+ [InlineData("H4sIAAAAAAAACvMwKfZ0hALnMj/PquQ8r7DyrAAfiwKv0LBAkzI3nyoLR0/HVK9cc6MKsFJbAI7LDrY0AAAA", "H4sIAAAAAAAACvNIzcnJVwjPL8pJUVQ4vFLz8AIAeJm72xIAAAA=")]+ [InlineData("Hello", "<Invalid GZip data>")]+ internal async Task DecompressGZip(string input, string expectedResult)+ {+ (await GZipHelper.DecompressGZipDataAsync(+ input,+ new MockILogger(),+ CancellationToken.None))+ .decompressedData+ .Should()+ .Be(expectedResult);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/HtmlHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/HtmlHelperTests.csnew file mode 100644index 000000000..bf8b141e3--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/HtmlHelperTests.cs@@ -0,0 +1,36 @@+using System.Threading;+using DevToys.Tools.Helpers;+using DevToys.UnitTests.Mocks;++namespace DevToys.UnitTests.Tools.Helpers;++public class HtmlHelperTests+{+ [Theory]+ [InlineData(null, "")]+ [InlineData("<hello world>", "<hello world>")]+ [InlineData("<hello>", "&lt;hello&gt;")]+ internal void EncodeHtml(string input, string expectedResult)+ {+ HtmlHelper.EncodeHtmlData(+ input,+ new MockILogger(),+ CancellationToken.None)+ .Should()+ .Be(expectedResult);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("<hello world>", "<hello world>")]+ [InlineData("&lt;hello&gt;", "<hello>")]+ internal void DecodeHtml(string input, string expectedResult)+ {+ HtmlHelper.DecodeHtmlData(+ input,+ new MockILogger(),+ CancellationToken.None)+ .Should()+ .Be(expectedResult);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/UrlHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/UrlHelperTests.csnew file mode 100644index 000000000..af0c57f7a--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/UrlHelperTests.cs@@ -0,0 +1,36 @@+using System.Threading;+using DevToys.Tools.Helpers;+using DevToys.UnitTests.Mocks;++namespace DevToys.UnitTests.Tools.Helpers;++public class UrlHelperTests+{+ [Theory]+ [InlineData(null, "")]+ [InlineData("<hello world>", "%3Chello%20world%3E")]+ [InlineData("%3Chello%20world%3E", "%253Chello%2520world%253E")]+ internal void EncodeUrl(string input, string expectedResult)+ {+ UrlHelper.EncodeUrlData(+ input,+ new MockILogger(),+ CancellationToken.None)+ .Should()+ .Be(expectedResult);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("%3Chello%20world%3E", "<hello world>")]+ [InlineData("%253Chello%2520world%253E", "%3Chello%20world%3E")]+ internal void DecodeUrl(string input, string expectedResult)+ {+ UrlHelper.DecodeUrlData(+ input,+ new MockILogger(),+ CancellationToken.None)+ .Should()+ .Be(expectedResult);+ }+}