Skip to content

A Swiss Army knife for developers.

[DevToys 2.0] Added Base64 Text Encoder / Decoder tool (#902)

Etienne BAUDOUX61530a01ea09
diff --git a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
index 73f583310..26d181c6f 100644
--- a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
+++ b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
@@ -4,6 +4,7 @@ public static class PredefinedCommonDataTypeNames
{
public const string Text = "text";
public const string Json = "json";
+ public const string Base64Text = "base64Text";
public const string Image = "image";
public const string File = "file";
}
diff --git a/src/app/dev/DevToys.Tools/Helpers/Base64Helper.cs b/src/app/dev/DevToys.Tools/Helpers/Base64Helper.cs
new file mode 100644
index 000000000..223e78c70
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Helpers/Base64Helper.cs
@@ -0,0 +1,182 @@
+using System.Text;
+using System.Text.RegularExpressions;
+using DevToys.Tools.Models;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.Tools.Helpers;
+
+internal static partial class Base64Helper
+{
+ internal static bool IsBase64DataStrict(string? data)
+ {
+ if (string.IsNullOrWhiteSpace(data))
+ {
+ return false;
+ }
+
+ data = data!.Trim();
+
+ if (data.Length % 4 != 0)
+ {
+ return false;
+ }
+
+ if (Base64Regex().IsMatch(data))
+ {
+ return false;
+ }
+
+ int equalIndex = data.IndexOf('=');
+ int length = data.Length;
+
+ if (!(equalIndex == -1 || equalIndex == length - 1 || equalIndex == length - 2 && data[length - 1] == '='))
+ {
+ return false;
+ }
+
+ string? decoded;
+
+ try
+ {
+ byte[]? decodedData = Convert.FromBase64String(data);
+ decoded = Encoding.UTF8.GetString(decodedData);
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+
+ //check for special chars that you know should not be there
+ char current;
+ for (int i = 0; i < decoded.Length; i++)
+ {
+ current = decoded[i];
+ if (current == 65533)
+ {
+ return false;
+ }
+
+#pragma warning disable IDE0078 // Use pattern matching
+ if (!(current == 0x9
+ || current == 0xA
+ || current == 0xD
+ || current >= 0x20 && current <= 0xD7FF
+ || current >= 0xE000 && current <= 0xFFFD
+ || current >= 0x10000 && current <= 0x10FFFF))
+#pragma warning restore IDE0078 // Use pattern matching
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ internal static string FromTextToBase64(string? data, Base64Encoding encoding, ILogger logger, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrWhiteSpace(data))
+ {
+ return string.Empty;
+ }
+
+ string? encoded;
+ try
+ {
+ Encoding encoder = GetEncoder(encoding);
+ byte[]? dataBytes = encoder.GetBytes(data);
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ encoded = Convert.ToBase64String(dataBytes);
+
+ cancellationToken.ThrowIfCancellationRequested();
+ }
+ catch (OperationCanceledException)
+ {
+ return string.Empty;
+ }
+ catch (Exception ex)
+ {
+ LogFailEncodeBase64(logger, ex, encoding);
+ return ex.Message;
+ }
+
+ return encoded;
+ }
+
+ internal static string FromBase64ToText(string? data, Base64Encoding encoding, ILogger logger, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrWhiteSpace(data))
+ {
+ return string.Empty;
+ }
+
+ int remainder = data!.Length % 4;
+ if (remainder > 0)
+ {
+ int padding = 4 - remainder;
+ data = data.PadRight(data.Length + padding, '=');
+ }
+
+ string? decoded = string.Empty;
+
+ try
+ {
+ byte[]? decodedData = Convert.FromBase64String(data);
+ cancellationToken.ThrowIfCancellationRequested();
+
+ Encoding encoder = GetEncoder(encoding);
+
+ if (encoder is UTF8Encoding && decodedData != null)
+ {
+ byte[] preamble = encoder.GetPreamble();
+ if (decodedData.Take(preamble.Length).SequenceEqual(preamble))
+ {
+ // need to keep it this way to have the dom char
+ decoded += Encoding.Unicode.GetString(preamble, 0, 1);
+ }
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (decodedData is not null)
+ {
+ decoded += encoder.GetString(decodedData);
+ }
+ }
+ catch (Exception ex) when (ex is OperationCanceledException || ex is FormatException)
+ {
+ // ignore;
+ }
+ catch (Exception ex)
+ {
+ LogFailDecodeBase64(logger, ex, encoding);
+ return ex.Message;
+ }
+
+ return decoded;
+ }
+
+ private static Encoding GetEncoder(Base64Encoding encoding)
+ {
+ return encoding switch
+ {
+ Base64Encoding.Utf8 => new UTF8Encoding(true),
+ Base64Encoding.Ascii => Encoding.ASCII,
+ _ => throw new NotSupportedException(),
+ };
+ }
+
+ private static void LogFailEncodeBase64(ILogger logger, Exception exception, Base64Encoding encoding)
+ {
+ logger.LogError(0, exception, $"Failed to encode text to Base64. Encoding mode: {encoding}");
+ }
+
+ private static void LogFailDecodeBase64(ILogger logger, Exception exception, Base64Encoding encoding)
+ {
+ logger.LogError(1, exception, $"Failed to decode Base64t to text. Encoding mode: {encoding}");
+ }
+
+ [GeneratedRegex("[^A-Z0-9+/=]", RegexOptions.IgnoreCase, "en-US")]
+ private static partial Regex Base64Regex();
+}
diff --git a/src/app/dev/DevToys.Tools/Models/Base64Encoding.cs b/src/app/dev/DevToys.Tools/Models/Base64Encoding.cs
new file mode 100644
index 000000000..3f1ec6cb8
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Models/Base64Encoding.cs
@@ -0,0 +1,7 @@
+namespace DevToys.Tools.Models;
+
+internal enum Base64Encoding
+{
+ Utf8,
+ Ascii
+}
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/Base64TextDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/Base64TextDataTypeDetector.cs
new file mode 100644
index 000000000..afcb25219
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/SmartDetection/Base64TextDataTypeDetector.cs
@@ -0,0 +1,27 @@
+using DevToys.Tools.Helpers;
+
+namespace DevToys.Tools.SmartDetection;
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName(PredefinedCommonDataTypeNames.Base64Text, baseName: PredefinedCommonDataTypeNames.Text)]
+internal sealed partial class Base64TextDataTypeDetector : 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))
+ {
+ string? trimmedData = dataString.Trim();
+ bool isBase64 = Base64Helper.IsBase64DataStrict(trimmedData);
+
+ if (isBase64)
+ {
+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataString));
+ }
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.Designer.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.Designer.cs
new file mode 100644
index 000000000..cb1be9ad0
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.Designer.cs
@@ -0,0 +1,243 @@
+//------------------------------------------------------------------------------
+// <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.Base64Text {
+ 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 Base64TextEncoderDecoder {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Base64TextEncoderDecoder() {
+ }
+
+ /// <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.Base64Text.Base64TextEncoderDecoder", typeof(Base64TextEncoderDecoder).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 Base64 Text Encoder and Decoder tool.
+ /// </summary>
+ internal static string AccessibleName {
+ get {
+ return ResourceManager.GetString("AccessibleName", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to ASCII.
+ /// </summary>
+ internal static string Ascii {
+ get {
+ return ResourceManager.GetString("Ascii", 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 Base64 text.
+ /// </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 Base64 text data.
+ /// </summary>
+ internal static string Description {
+ get {
+ return ResourceManager.GetString("Description", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Select which encoding do you want to use.
+ /// </summary>
+ internal static string EncodingDescription {
+ get {
+ return ResourceManager.GetString("EncodingDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Encoding.
+ /// </summary>
+ internal static string EncodingOptionDescription {
+ get {
+ return ResourceManager.GetString("EncodingOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Encoding.
+ /// </summary>
+ internal static string EncodingTitle {
+ get {
+ return ResourceManager.GetString("EncodingTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Text to encode or Base64 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 &lt;Invalid Base64&gt;.
+ /// </summary>
+ internal static string InvalidBase64 {
+ get {
+ return ResourceManager.GetString("InvalidBase64", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Base64 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 RFC 4648.
+ /// </summary>
+ internal static string SearchKeywords {
+ get {
+ return ResourceManager.GetString("SearchKeywords", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Base64 Text.
+ /// </summary>
+ internal static string ShortDisplayTitle {
+ get {
+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to UTF-8.
+ /// </summary>
+ internal static string Utf8 {
+ get {
+ return ResourceManager.GetString("Utf8", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Sample/Sample.resx b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.resx
similarity index 74%
rename from src/app/dev/DevToys.Tools/Tools/Sample/Sample.resx
rename to src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.resx
index 4a456879f..4b2e2abef 100644
--- a/src/app/dev/DevToys.Tools/Tools/Sample/Sample.resx
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoder.resx
@@ -117,19 +117,65 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
- <data name="CommandDescription" xml:space="preserve">
- <value>Just A Basic Tool</value>
+ <data name="AccessibleName" xml:space="preserve">
+ <value>Base64 Text Encoder and Decoder tool</value>
+ </data>
+ <data name="Ascii" xml:space="preserve">
+ <value>ASCII</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 Base64 text</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 HTML entities</value>
+ <value>Encode and decode Base64 text data</value>
+ </data>
+ <data name="EncodingDescription" xml:space="preserve">
+ <value>Select which encoding do you want to use</value>
+ </data>
+ <data name="EncodingOptionDescription" xml:space="preserve">
+ <value>Encoding</value>
+ </data>
+ <data name="EncodingTitle" xml:space="preserve">
+ <value>Encoding</value>
+ </data>
+ <data name="InputOptionDescription" xml:space="preserve">
+ <value>Text to encode or Base64 to decode</value>
+ </data>
+ <data name="InputTitle" xml:space="preserve">
+ <value>Input</value>
+ </data>
+ <data name="InvalidBase64" xml:space="preserve">
+ <value>&lt;Invalid Base64&gt;</value>
+ </data>
+ <data name="LongDisplayTitle" xml:space="preserve">
+ <value>Base64 Text Encoder / Decoder</value>
+ </data>
+ <data name="OutputTitle" xml:space="preserve">
+ <value>Output</value>
</data>
- <data name="FileOptionDescription" xml:space="preserve">
- <value>File to treat</value>
+ <data name="SearchKeywords" xml:space="preserve">
+ <value>RFC 4648</value>
+ <comment>Alternative search keywords.</comment>
</data>
- <data name="LongTitle" xml:space="preserve">
- <value>JSON Formatter</value>
+ <data name="ShortDisplayTitle" xml:space="preserve">
+ <value>Base64 Text</value>
</data>
- <data name="Utf8OptionDescription" xml:space="preserve">
- <value>A dummy UTF8 option description</value>
+ <data name="Utf8" xml:space="preserve">
+ <value>UTF-8</value>
</data>
</root>
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.cs
new file mode 100644
index 000000000..e6a282037
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderCommandLineTool.cs
@@ -0,0 +1,65 @@
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.Tools.Tools.EncodersDecoders.Base64Text;
+
+[Export(typeof(ICommandLineTool))]
+[Name("Base64TextEncoderDecoder")]
+[CommandName(
+ Name = "base64",
+ Alias = "b64",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.EncodersDecoders.Base64Text.Base64TextEncoderDecoder",
+ DescriptionResourceName = nameof(Base64TextEncoderDecoder.Description))]
+internal sealed class Base64TextEncoderDecoderCommandLineTool : ICommandLineTool
+{
+ private enum Conversion
+ {
+ Encode,
+ Decode
+ }
+
+ [CommandLineOption(
+ Name = "input",
+ Alias = "i",
+ IsRequired = true,
+ DescriptionResourceName = nameof(Base64TextEncoderDecoder.InputOptionDescription))]
+ private string? Input { get; set; } // NOTE: Could be a FileInfo instead of string too, if you we want to accept file as input instead.
+
+ [CommandLineOption(
+ Name = "conversion",
+ Alias = "c",
+ DescriptionResourceName = nameof(Base64TextEncoderDecoder.ConversionOptionDescription))]
+ private Conversion ConversionMode { get; set; } = Conversion.Encode;
+
+ [CommandLineOption(
+ Name = "encoding",
+ Alias = "e",
+ DescriptionResourceName = nameof(Base64TextEncoderDecoder.EncodingOptionDescription))]
+ private Base64Encoding EncodingMode { get; set; } = Base64Encoding.Utf8;
+
+ public ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)
+ {
+ string output;
+ if (ConversionMode == Conversion.Encode)
+ {
+ output = Base64Helper.FromTextToBase64(Input, EncodingMode, logger, cancellationToken);
+ }
+ else
+ {
+ if (!Base64Helper.IsBase64DataStrict(Input))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ Console.Error.WriteLine(Base64TextEncoderDecoder.InvalidBase64);
+ return new ValueTask<int>(-1);
+ }
+
+ output = Base64Helper.FromBase64ToText(Input, EncodingMode, logger, cancellationToken);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+ Console.WriteLine(output);
+
+ return new ValueTask<int>(0);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs
new file mode 100644
index 000000000..c088c8c80
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs
@@ -0,0 +1,235 @@
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.Tools.Tools.EncodersDecoders.Base64Text;
+
+[Export(typeof(IGuiTool))]
+[Name("Base64TextEncoderDecoder")]
+[ToolDisplayInformation(
+ IconFontName = "DevToys-Tools-Icons",
+ IconGlyph = '\u0100',
+ GroupName = PredefinedCommonToolGroupNames.EncodersDecoders,
+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
+ ResourceManagerBaseName = "DevToys.Tools.Tools.EncodersDecoders.Base64Text.Base64TextEncoderDecoder",
+ ShortDisplayTitleResourceName = nameof(Base64TextEncoderDecoder.ShortDisplayTitle),
+ LongDisplayTitleResourceName = nameof(Base64TextEncoderDecoder.LongDisplayTitle),
+ DescriptionResourceName = nameof(Base64TextEncoderDecoder.Description),
+ AccessibleNameResourceName = nameof(Base64TextEncoderDecoder.AccessibleName),
+ SearchKeywordsResourceName = nameof(Base64TextEncoderDecoder.SearchKeywords))]
+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Base64Text)]
+internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDisposable
+{
+ /// <summary>
+ /// Whether the tool should encode or decode Base64. True is encode, false is decode.
+ /// </summary>
+ private static readonly SettingDefinition<bool> conversionMode
+ = new(
+ name: $"{nameof(Base64TextEncoderDecoderGuiTool)}.{nameof(conversionMode)}",
+ defaultValue: true);
+
+ /// <summary>
+ /// Whether the tool should encode/decode in Unicode or ASCII.
+ /// </summary>
+ private static readonly SettingDefinition<Base64Encoding> encoder
+ = new(
+ name: $"{nameof(Base64TextEncoderDecoderGuiTool)}.{nameof(encoder)}",
+ defaultValue: DefaultEncoding);
+
+ private enum GridRows
+ {
+ Settings,
+ Input,
+ Output
+ }
+
+ private enum GridColumns
+ {
+ Stretch
+ }
+
+ private const Base64Encoding DefaultEncoding = Base64Encoding.Utf8;
+
+ private readonly ILogger _logger;
+ private readonly ISettingsProvider _settingsProvider;
+ private readonly IUISwitch _conversionModeSwitch = Switch("base64-text-conversion-mode-switch");
+ private readonly IUIMultiLineTextInput _inputText = MultilineTextInput("base64-text-input-box");
+ private readonly IUIMultiLineTextInput _outputText = MultilineTextInput("base64-text-output-box");
+
+ private CancellationTokenSource? _cancellationTokenSource;
+
+ [ImportingConstructor]
+ public Base64TextEncoderDecoderGuiTool(ISettingsProvider settingsProvider)
+ {
+ _logger = this.Log();
+ _settingsProvider = settingsProvider;
+
+ if (_settingsProvider.GetSetting(conversionMode))
+ {
+ // Encode
+ _conversionModeSwitch.On();
+ _inputText.AutoWrap();
+ _outputText.AlwaysWrap();
+ }
+ else
+ {
+ // Decode
+ _inputText.AlwaysWrap();
+ _outputText.AutoWrap();
+ }
+ }
+
+ 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(Base64TextEncoderDecoder.ConfigurationTitle),
+
+ SettingGroup("base64-text-conversion-mode-setting")
+ .Icon("FluentSystemIcons", '\uF18D')
+ .Title(Base64TextEncoderDecoder.ConversionTitle)
+ .Description(Base64TextEncoderDecoder.ConversionDescription)
+
+ .InteractiveElement(
+ _conversionModeSwitch
+ .OnText(Base64TextEncoderDecoder.ConversionEncode)
+ .OffText(Base64TextEncoderDecoder.ConversionDecode)
+ .OnToggle(OnConversionModeChanged))
+
+ .WithSettings(
+ Setting("base64-text-encoding-setting")
+ .Title(Base64TextEncoderDecoder.EncodingTitle)
+ .Description(Base64TextEncoderDecoder.EncodingDescription)
+
+ .Handle(
+ _settingsProvider,
+ encoder,
+ onOptionSelected: OnEncodingModeChanged,
+ Item(Base64TextEncoderDecoder.Utf8, Base64Encoding.Utf8),
+ Item(Base64TextEncoderDecoder.Ascii, Base64Encoding.Ascii))))),
+
+ Cell(
+ GridRows.Input,
+ GridColumns.Stretch,
+
+ _inputText
+ .Title(Base64TextEncoderDecoder.InputTitle)
+ .OnTextChanged(OnInputTextChanged)),
+
+ Cell(
+ GridRows.Output,
+ GridColumns.Stretch,
+
+ _outputText
+ .Title(Base64TextEncoderDecoder.OutputTitle)
+ .ReadOnly()
+ .Extendable())));
+
+ public void OnDataReceived(string dataTypeName, object? parsedData)
+ {
+ if (dataTypeName == PredefinedCommonDataTypeNames.Base64Text && parsedData is string base64Text)
+ {
+ _conversionModeSwitch.Off(); // Switch to Decode mode
+ _inputText.Text(base64Text); // This will trigger a conversion.
+ }
+ }
+
+ public void Dispose()
+ {
+ _cancellationTokenSource?.Dispose();
+ }
+
+ private void OnConversionModeChanged(bool conversionMode)
+ {
+ _settingsProvider.SetSetting(Base64TextEncoderDecoderGuiTool.conversionMode, conversionMode);
+ _inputText.Text(_outputText.Text); // This will trigger a conversion.
+
+ if (conversionMode)
+ {
+ // Encode
+ _inputText.AutoWrap();
+ _outputText.AlwaysWrap();
+ }
+ else
+ {
+ // Decode
+ _inputText.AlwaysWrap();
+ _outputText.AutoWrap();
+ }
+ }
+
+ private void OnEncodingModeChanged(Base64Encoding encodingMode)
+ {
+ StartConvert(_inputText.Text);
+ }
+
+ private void OnInputTextChanged(string text)
+ {
+ StartConvert(text);
+ }
+
+ private void StartConvert(string text)
+ {
+ _cancellationTokenSource?.Cancel();
+ _cancellationTokenSource?.Dispose();
+ _cancellationTokenSource = new CancellationTokenSource();
+
+ ConvertAsync(text, _cancellationTokenSource.Token).ForgetSafely();
+ }
+
+ private async Task ConvertAsync(string input, CancellationToken cancellationToken)
+ {
+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
+
+ string conversionResult;
+ if (_settingsProvider.GetSetting(conversionMode))
+ {
+ conversionResult
+ = Base64Helper.FromTextToBase64(
+ input,
+ _settingsProvider.GetSetting(encoder),
+ _logger,
+ cancellationToken);
+ }
+ else
+ {
+ if (!string.IsNullOrEmpty(input) && !Base64Helper.IsBase64DataStrict(input))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ _outputText.Text(Base64TextEncoderDecoder.InvalidBase64);
+ return;
+ }
+
+ conversionResult
+ = Base64Helper.FromBase64ToText(
+ input,
+ _settingsProvider.GetSetting(encoder),
+ _logger,
+ cancellationToken);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+ _outputText.Text(conversionResult);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Sample/Sample.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Sample/Sample.Designer.cs
deleted file mode 100644
index 41b32efe2..000000000
--- a/src/app/dev/DevToys.Tools/Tools/Sample/Sample.Designer.cs
+++ /dev/null
@@ -1,108 +0,0 @@
-//------------------------------------------------------------------------------
-// <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.Sample {
- 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 Sample {
-
- private static global::System.Resources.ResourceManager resourceMan;
-
- private static global::System.Globalization.CultureInfo resourceCulture;
-
- [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- internal Sample() {
- }
-
- /// <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.Sample.Sample", typeof(Sample).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 Just A Basic Tool.
- /// </summary>
- internal static string CommandDescription {
- get {
- return ResourceManager.GetString("CommandDescription", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to Encode or decode all the applicable characters to their corresponding HTML entities.
- /// </summary>
- internal static string Description {
- get {
- return ResourceManager.GetString("Description", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to File to treat.
- /// </summary>
- internal static string FileOptionDescription {
- get {
- return ResourceManager.GetString("FileOptionDescription", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to JSON Formatter.
- /// </summary>
- internal static string LongTitle {
- get {
- return ResourceManager.GetString("LongTitle", resourceCulture);
- }
- }
-
- /// <summary>
- /// Looks up a localized string similar to A dummy UTF8 option description.
- /// </summary>
- internal static string Utf8OptionDescription {
- get {
- return ResourceManager.GetString("Utf8OptionDescription", resourceCulture);
- }
- }
- }
-}
diff --git a/src/app/dev/DevToys.Tools/Tools/Sample/SampleToolFactory.cs b/src/app/dev/DevToys.Tools/Tools/Sample/SampleToolFactory.cs
deleted file mode 100644
index bfad1945d..000000000
--- a/src/app/dev/DevToys.Tools/Tools/Sample/SampleToolFactory.cs
+++ /dev/null
@@ -1,134 +0,0 @@
-using System.Text.Json;
-using Microsoft.Extensions.Logging;
-
-namespace DevToys.Tools.Tools.Sample;
-
-[Export(typeof(ICommandLineTool))]
-[Name("Sample tool")]
-[CommandName(
- Name = "base64",
- Alias = "b64",
- ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
- DescriptionResourceName = nameof(Sample.CommandDescription))]
-[TargetPlatform(Platform.Windows)] // Optional. Not putting any attribute means every platforms are supported.
-[TargetPlatform(Platform.Linux)]
-[TargetPlatform(Platform.MacCatalyst)]
-[TargetPlatform(Platform.WASM)]
-internal sealed class SampleCommandLineTool : ICommandLineTool
-{
- [CommandLineOption(
- Name = "file",
- Alias = "f",
- IsRequired = true,
- DescriptionResourceName = nameof(Sample.FileOptionDescription))]
- private FileInfo? File { get; set; }
-
- [CommandLineOption(
- Name = "utf8",
- DescriptionResourceName = nameof(Sample.Utf8OptionDescription))]
- private bool Utf8 { get; set; } = true; // Default value is true.
-
- public ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)
- {
- Console.WriteLine("Dummy output.");
- return new ValueTask<int>(0);
- }
-}
-
-[Export(typeof(IGuiTool))]
-[Name("Sample tool")]
-[ToolDisplayInformation(
- IconFontName = "FluentSystemIcons",
- IconGlyph = '\uE670',
- GroupName = "Encoders / Decoders",
- ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
- ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
- LongDisplayTitleResourceName = nameof(Sample.LongTitle),
- DescriptionResourceName = nameof(Sample.Description),
- AccessibleNameResourceName = nameof(Sample.CommandDescription),
- SearchKeywordsResourceName = nameof(Sample.CommandDescription))]
-[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Json)]
-internal sealed class SampleGuiTool : IGuiTool
-{
- //private readonly IUIMultilineLineTextInput _editor = MultilineTextInput().Language("json").CanCopyWhenEditable();
- private readonly IUIButton _button = Button();
- private readonly IUIButton _button2 = Button();
- private readonly IUIButton _button3 = Button();
- private readonly IUIButton _button4 = Button();
- private readonly IUIButton _button5 = Button();
- private readonly IUIButton _button6 = Button();
- private readonly IUIButton _button7 = Button();
- private readonly IUIButton _button8 = Button();
- private readonly IUIButton _button9 = Button();
- private readonly IUIButton _button10 = Button();
- private readonly IUIButton _button11 = Button();
- private readonly IUIButton _button12 = Button();
- private readonly IUIStack _mainStack = Stack();
- private readonly IUIStack _subStack = Stack();
-
- public UIToolView View =>
- new(
- _mainStack
- .Vertical()
- .WithChildren(
- _button.Text("I'm in a StackPanel. Click me to disable the parent StackPanel and all its children").OnClick(OnClick),
- _subStack
- .Vertical()
- .WithChildren(
- _button2.Text("Hello !"),
- _button3.Text("Hello !"),
- _button4.Text("Hello !"),
- _button5.Text("Hello !"),
- _button6.Text("Hello !"),
- _button7.Text("Hello !"),
- _button8.Text("Hello !"),
- _button9.Text("Hello !"),
- _button10.Text("Hello !"),
- _button11.Text("Hello !"),
- _button12.Text("Hello !"))));
-
- private ValueTask OnClick()
- {
- _button.Text("Done !");
- //_button.AccentAppearance();
- _mainStack.Disable();
- //_button.Hide();
- return ValueTask.CompletedTask;
- }
-
- public void OnDataReceived(string dataTypeName, object? parsedData)
- {
- if (dataTypeName == PredefinedCommonDataTypeNames.Json && parsedData is Tuple<JsonDocument, string> strongTypedParsedData)
- {
- //_editor.Text(strongTypedParsedData.Item2);
- //_editor.Highlight(new TextSpan(3, 6));
- }
- }
-}
-
-[Export(typeof(IGuiTool))]
-[Name("Sample tool2")]
-[ToolDisplayInformation(
- IconFontName = "FluentSystemIcons",
- IconGlyph = '\uE670',
- GroupName = "Encoders / Decoders",
- ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
- ResourceManagerBaseName = "DevToys.Tools.Tools.Sample.Sample",
- ShortDisplayTitleResourceName = nameof(Sample.CommandDescription),
- LongDisplayTitleResourceName = nameof(Sample.CommandDescription),
- DescriptionResourceName = nameof(Sample.CommandDescription),
- AccessibleNameResourceName = nameof(Sample.CommandDescription),
- SearchKeywordsResourceName = nameof(Sample.CommandDescription))]
-[TargetPlatform(Platform.Windows)] // Optional. Not putting any attribute means every platforms are supported.
-[TargetPlatform(Platform.Linux)]
-[TargetPlatform(Platform.MacCatalyst)]
-[TargetPlatform(Platform.WASM)]
-internal sealed class SampleGuiTool2 : IGuiTool
-{
- public UIToolView View => null!;
-
- public void OnDataReceived(string dataTypeName, object? parsedData)
- {
- }
-}
diff --git a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj
index fb788e5ec..459c59f74 100644
--- a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj
+++ b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj
@@ -25,6 +25,7 @@
<ProjectReference Include="..\..\dev\DevToys.Blazor\DevToys.Blazor.csproj" />
<ProjectReference Include="..\..\dev\DevToys.Business\DevToys.Business.csproj" />
<ProjectReference Include="..\..\dev\DevToys.Core\DevToys.Core.csproj" />
+ <ProjectReference Include="..\..\dev\DevToys.Tools\DevToys.Tools.csproj" />
</ItemGroup>
<ItemGroup>
diff --git a/src/app/tests/DevToys.UnitTests/MefBasedTest.cs b/src/app/tests/DevToys.UnitTests/MefBasedTest.cs
index 278d352c0..39c0fb367 100644
--- a/src/app/tests/DevToys.UnitTests/MefBasedTest.cs
+++ b/src/app/tests/DevToys.UnitTests/MefBasedTest.cs
@@ -1,6 +1,7 @@
using System.Globalization;
using System.Reflection;
using DevToys.Core.Mef;
+using Microsoft.Extensions.Logging;
namespace DevToys.UnitTests;
@@ -18,6 +19,11 @@ public abstract class MefBasedTest
typeof(MefBasedTest).Assembly
};
+ if (LoggingExtensions.LoggerFactory is null)
+ {
+ LoggingExtensions.LoggerFactory = LoggerFactory.Create(builder => { });
+ }
+
// Initialize MEF.
_mefComposer
= new MefComposer(
diff --git a/src/app/tests/DevToys.UnitTests/Mocks/MockIDisposable.cs b/src/app/tests/DevToys.UnitTests/Mocks/MockIDisposable.cs
new file mode 100644
index 000000000..4109af2d7
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Mocks/MockIDisposable.cs
@@ -0,0 +1,29 @@
+namespace DevToys.UnitTests.Mocks;
+
+internal class MockIDisposable : IDisposable
+{
+ private bool _disposed = false;
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!_disposed)
+ {
+ if (disposing)
+ {
+ }
+ }
+ _disposed = true;
+ }
+
+ public void Dispose()
+ {
+ Dispose(true);
+
+ GC.SuppressFinalize(this);
+ }
+
+ ~MockIDisposable()
+ {
+ Dispose(false);
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Mocks/MockILogger.cs b/src/app/tests/DevToys.UnitTests/Mocks/MockILogger.cs
new file mode 100644
index 000000000..7b03b5946
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Mocks/MockILogger.cs
@@ -0,0 +1,19 @@
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.UnitTests.Mocks;
+internal class MockILogger : ILogger
+{
+ public IDisposable BeginScope<TState>(TState state) where TState : notnull
+ {
+ return new MockIDisposable();
+ }
+
+ public bool IsEnabled(LogLevel logLevel)
+ {
+ return true;
+ }
+
+ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
+ {
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/Base64HelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/Base64HelperTests.cs
new file mode 100644
index 000000000..9825ef7ae
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/Base64HelperTests.cs
@@ -0,0 +1,54 @@
+using System.Threading;
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+using DevToys.UnitTests.Mocks;
+
+namespace DevToys.UnitTests.Tools.Helpers;
+
+public class Base64HelperTests
+{
+ [Theory]
+ [InlineData(null, false)]
+ [InlineData("", false)]
+ [InlineData(" ", false)]
+ [InlineData("aGVsbG8gd29ybGQ=", true)]
+ [InlineData("aGVsbG8gd2f9ybGQ=", false)]
+ [InlineData("SGVsbG8gV29y", true)]
+ [InlineData("SGVsbG8gVa29y", false)]
+ public void IsValid(string input, bool expectedResult)
+ {
+ Base64Helper.IsBase64DataStrict(input).Should().Be(expectedResult);
+ }
+
+ [Theory]
+ [InlineData(null, "", Base64Encoding.Utf8)]
+ [InlineData("Hello World!", "SGVsbG8gV29ybGQh", Base64Encoding.Utf8)]
+ [InlineData("Hello World! é)à", "SGVsbG8gV29ybGQhIMOpKcOg", Base64Encoding.Utf8)]
+ [InlineData("Hello World! é)à", "SGVsbG8gV29ybGQhID8pPw==", Base64Encoding.Ascii)]
+ internal void FromTextToBase64(string input, string expectedResult, Base64Encoding encoding)
+ {
+ Base64Helper.FromTextToBase64(
+ input,
+ encoding,
+ new MockILogger(),
+ CancellationToken.None)
+ .Should()
+ .Be(expectedResult);
+ }
+
+ [Theory]
+ [InlineData(null, "", Base64Encoding.Utf8)]
+ [InlineData("SGVsbG8gV29ybGQh", "Hello World!", Base64Encoding.Utf8)]
+ [InlineData("SGVsbG8gV29ybGQhIMOpKcOg", "Hello World! é)à", Base64Encoding.Utf8)]
+ [InlineData("SGVsbG8gV29ybGQhID8pPw==", "Hello World! ?)?", Base64Encoding.Ascii)]
+ internal void FromBase64ToText(string input, string expectedResult, Base64Encoding encoding)
+ {
+ Base64Helper.FromBase64ToText(
+ input,
+ encoding,
+ new MockILogger(),
+ CancellationToken.None)
+ .Should()
+ .Be(expectedResult);
+ }
+}