A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Add JSON formatter to DevToys 2.0 (#1013)
Laurel Baudoux8266feacd130
diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csprojindex fddb3b585..8d0dece8a 100644--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj@@ -38,6 +38,11 @@<AutoGen>True</AutoGen><DependentUpon>GlobalStrings.resx</DependentUpon></Compile>+ <Compile Update="Tools\Formatters\Json\JsonFormatter.Designer.cs">+ <DependentUpon>JsonFormatter.resx</DependentUpon>+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ </Compile><Compile Update="Tools\Formatters\Xml\XmlFormatter.Designer.cs"><DependentUpon>XmlFormatter.resx</DependentUpon><DesignTime>True</DesignTime>@@ -173,6 +178,10 @@<LastGenOutput>JsonTableConverter.Designer.cs</LastGenOutput><Generator>ResXFileCodeGenerator</Generator></EmbeddedResource>+ <EmbeddedResource Update="Tools\Formatters\Json\JsonFormatter.resx">+ <LastGenOutput>JsonFormatter.Designer.cs</LastGenOutput>+ <Generator>ResXFileCodeGenerator</Generator>+ </EmbeddedResource><EmbeddedResource Update="Tools\Formatters\Xml\XmlFormatter.resx"><LastGenOutput>XmlFormatter.Designer.cs</LastGenOutput><Generator>ResXFileCodeGenerator</Generator>diff --git a/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs b/src/app/dev/DevToys.Tools/Helpers/JsonHelper.csindex ab27d50d5..29e9bfc22 100644--- a/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs+++ b/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs@@ -16,8 +16,6 @@ internal static partial class JsonHelper/// </summary>internal static bool IsValid(string? input, ILogger logger){- input = input?.Trim();-if (input == null){return true;@@ -48,16 +46,16 @@ internal static partial class JsonHelper/// <summary>/// Format a string to the specified JSON format./// </summary>- internal static async ValueTask<string> Format(+ internal static async Task<ResultInfo<string>> FormatAsync(string? input,Indentation indentationMode,bool sortProperties,ILogger logger,CancellationToken cancellationToken){- if (input == null || !IsValid(input, logger))+ if (string.IsNullOrWhiteSpace(input)){- return string.Empty;+ return new(string.Empty, false);}try@@ -124,16 +122,16 @@ internal static partial class JsonHelperjToken.WriteTo(jsonTextWriter);}- return stringBuilder.ToString();+ return new(stringBuilder.ToString(), true);}catch (JsonReaderException ex){- return ex.Message;+ return new(ex.Message, false);}catch (Exception ex){logger.LogError(ex, "Invalid JSON format 'indentationMode'", indentationMode);- return ex.Message;+ return new(ex.Message, false);}}diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.csindex fc72775f9..091c99922 100644--- a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs@@ -199,10 +199,10 @@ internal sealed partial class JsonYamlConverterGuiTool : IGuiTool, IDisposable_cancellationTokenSource?.Dispose();_cancellationTokenSource = new CancellationTokenSource();- WorkTask = ConvertAsync(text, _cancellationTokenSource.Token);+ WorkTask = ConvertAsync(text, _settingsProvider.GetSetting(conversionMode), _settingsProvider.GetSetting(indentationMode), _cancellationTokenSource.Token);}- private async Task ConvertAsync(string input, CancellationToken cancellationToken)+ private async Task ConvertAsync(string input, JsonToYamlConversion conversionModeSetting, Indentation indentationModeSetting, CancellationToken cancellationToken){using (await _semaphore.WaitAsync(cancellationToken)){@@ -210,8 +210,8 @@ internal sealed partial class JsonYamlConverterGuiTool : IGuiTool, IDisposableResultInfo<string> conversionResult = await JsonYamlHelper.ConvertAsync(input,- _settingsProvider.GetSetting(conversionMode),- _settingsProvider.GetSetting(indentationMode),+ conversionModeSetting,+ indentationModeSetting,_logger,cancellationToken);_outputTextArea.Text(conversionResult.Data);diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.csindex d4cc125e0..b4b766c52 100644--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Base64Text/Base64TextEncoderDecoderGuiTool.cs@@ -213,10 +213,10 @@ internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDispo_cancellationTokenSource?.Dispose();_cancellationTokenSource = new CancellationTokenSource();- WorkTask = ConvertAsync(text, _cancellationTokenSource.Token);+ WorkTask = ConvertAsync(text, _settingsProvider.GetSetting(encoder), _cancellationTokenSource.Token);}- private async Task ConvertAsync(string input, CancellationToken cancellationToken)+ private async Task ConvertAsync(string input, Base64Encoding encoderSetting, CancellationToken cancellationToken){using (await _semaphore.WaitAsync(cancellationToken)){@@ -230,7 +230,7 @@ internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDispoconversionResult= Base64Helper.FromTextToBase64(input,- _settingsProvider.GetSetting(encoder),+ encoderSetting,_logger,cancellationToken);break;@@ -246,7 +246,7 @@ internal sealed partial class Base64TextEncoderDecoderGuiTool : IGuiTool, IDispoconversionResult= Base64Helper.FromBase64ToText(input,- _settingsProvider.GetSetting(encoder),+ encoderSetting,_logger,cancellationToken);break;diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.csindex 53bd38cfb..31f7db380 100644--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/GZip/GZipEncoderDecoderGuiTool.cs@@ -193,10 +193,10 @@ internal sealed partial class GZipEncoderDecoderGuiTool : IGuiTool, IDisposable_cancellationTokenSource?.Dispose();_cancellationTokenSource = new CancellationTokenSource();- WorkTask = ConvertAsync(text, _cancellationTokenSource.Token);+ WorkTask = ConvertAsync(text, _settingsProvider.GetSetting(compressionMode), _cancellationTokenSource.Token);}- private async Task ConvertAsync(string input, CancellationToken cancellationToken)+ private async Task ConvertAsync(string input, CompressionMode compressionModeSetting, CancellationToken cancellationToken){using (await _semaphore.WaitAsync(cancellationToken)){@@ -205,7 +205,7 @@ internal sealed partial class GZipEncoderDecoderGuiTool : IGuiTool, IDisposable(string data, double differencePercentage) conversionResult= await GZipHelper.CompressOrDecompressAsync(input,- _settingsProvider.GetSetting(compressionMode),+ compressionModeSetting,_logger,cancellationToken);diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.csindex 7a6be30ad..509afad8c 100644--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Html/HtmlEncoderDecoderGuiTool.cs@@ -158,10 +158,10 @@ internal sealed partial class HtmlEncoderDecoderGuiTool : IGuiTool, IDisposable_cancellationTokenSource?.Dispose();_cancellationTokenSource = new CancellationTokenSource();- WorkTask = ConvertAsync(text, _cancellationTokenSource.Token);+ WorkTask = ConvertAsync(text, _settingsProvider.GetSetting(conversionMode), _cancellationTokenSource.Token);}- private async Task ConvertAsync(string input, CancellationToken cancellationToken)+ private async Task ConvertAsync(string input, EncodingConversion conversionModeSetting, CancellationToken cancellationToken){using (await _semaphore.WaitAsync(cancellationToken)){@@ -170,7 +170,7 @@ internal sealed partial class HtmlEncoderDecoderGuiTool : IGuiTool, IDisposable_outputText.Text(HtmlHelper.EncodeOrDecode(input,- _settingsProvider.GetSetting(conversionMode),+ conversionModeSetting,_logger,cancellationToken));}diff --git a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.csindex 2bd485c0e..a2ebe2a05 100644--- a/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/EncodersDecoders/Url/UrlEncoderDecoderGuiTool.cs@@ -158,10 +158,10 @@ internal sealed partial class UrlEncoderDecoderGuiTool : IGuiTool, IDisposable_cancellationTokenSource?.Dispose();_cancellationTokenSource = new CancellationTokenSource();- WorkTask = ConvertAsync(text, _cancellationTokenSource.Token);+ WorkTask = ConvertAsync(text, _settingsProvider.GetSetting(conversionMode), _cancellationTokenSource.Token);}- private async Task ConvertAsync(string input, CancellationToken cancellationToken)+ private async Task ConvertAsync(string input, EncodingConversion conversionModeSetting, CancellationToken cancellationToken){using (await _semaphore.WaitAsync(cancellationToken)){@@ -170,7 +170,7 @@ internal sealed partial class UrlEncoderDecoderGuiTool : IGuiTool, IDisposable_outputText.Text(UrlHelper.EncodeOrDecode(input,- _settingsProvider.GetSetting(conversionMode),+ conversionModeSetting,_logger,cancellationToken));}diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatter.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatter.Designer.csnew file mode 100644index 000000000..baacbb0db--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatter.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.Formatters.Json {+ 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 JsonFormatter {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal JsonFormatter() {+ }++ /// <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.Formatters.Json.JsonFormatter", typeof(JsonFormatter).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 JSON Formatter 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 Configuration {+ get {+ return ResourceManager.GetString("Configuration", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Indent or minify JSON data.+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to 4 spaces.+ /// </summary>+ internal static string FourSpaces {+ get {+ return ResourceManager.GetString("FourSpaces", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Indentation.+ /// </summary>+ internal static string Indentation {+ get {+ return ResourceManager.GetString("Indentation", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Select which indentation you want to use.+ /// </summary>+ internal static string IndentationOptionDescription {+ get {+ return ResourceManager.GetString("IndentationOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Input.+ /// </summary>+ internal static string Input {+ get {+ return ResourceManager.GetString("Input", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Input file selected doesn't exist..+ /// </summary>+ internal static string InputFileNotFound {+ get {+ return ResourceManager.GetString("InputFileNotFound", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Text or path to a file containing the JSON to format.+ /// </summary>+ internal static string InputOptionDescription {+ get {+ return ResourceManager.GetString("InputOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Please specify an input text or an input file.+ /// </summary>+ internal static string InvalidInputOrFileCommand {+ get {+ return ResourceManager.GetString("InvalidInputOrFileCommand", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to JSON Formatter.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Minified.+ /// </summary>+ internal static string Minified {+ get {+ return ResourceManager.GetString("Minified", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to 1 tab.+ /// </summary>+ internal static string OneTab {+ get {+ return ResourceManager.GetString("OneTab", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Output.+ /// </summary>+ internal static string Output {+ get {+ return ResourceManager.GetString("Output", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Path to the output file.+ /// </summary>+ internal static string OutputFileOptionDescription {+ get {+ return ResourceManager.GetString("OutputFileOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to JSON Formatter.+ /// </summary>+ internal static string SearchDisplayName {+ get {+ return ResourceManager.GetString("SearchDisplayName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to JSON.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Sort Properties.+ /// </summary>+ internal static string SortProperties {+ get {+ return ResourceManager.GetString("SortProperties", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether properties within the JSON should be sorted alphabetically.+ /// </summary>+ internal static string SortPropertiesOptionDescription {+ get {+ return ResourceManager.GetString("SortPropertiesOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to 2 spaces.+ /// </summary>+ internal static string TwoSpaces {+ get {+ return ResourceManager.GetString("TwoSpaces", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatter.resx b/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatter.resxnew file mode 100644index 000000000..93ada4ce8--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatter.resx@@ -0,0 +1,180 @@+<?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>JSON Formatter tool</value>+ </data>+ <data name="Configuration" xml:space="preserve">+ <value>Configuration</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Indent or minify JSON data</value>+ </data>+ <data name="FourSpaces" xml:space="preserve">+ <value>4 spaces</value>+ </data>+ <data name="Indentation" xml:space="preserve">+ <value>Indentation</value>+ </data>+ <data name="IndentationOptionDescription" xml:space="preserve">+ <value>Select which indentation you want to use</value>+ </data>+ <data name="Input" xml:space="preserve">+ <value>Input</value>+ </data>+ <data name="InputFileNotFound" xml:space="preserve">+ <value>Input file selected doesn't exist.</value>+ </data>+ <data name="InputOptionDescription" xml:space="preserve">+ <value>Text or path to a file containing the JSON to format</value>+ </data>+ <data name="InvalidInputOrFileCommand" xml:space="preserve">+ <value>Please specify an input text or an input file</value>+ </data>+ <data name="LongDisplayTitle" xml:space="preserve">+ <value>JSON Formatter</value>+ </data>+ <data name="Minified" xml:space="preserve">+ <value>Minified</value>+ </data>+ <data name="OneTab" xml:space="preserve">+ <value>1 tab</value>+ </data>+ <data name="Output" xml:space="preserve">+ <value>Output</value>+ </data>+ <data name="OutputFileOptionDescription" xml:space="preserve">+ <value>Path to the output file</value>+ </data>+ <data name="SearchDisplayName" xml:space="preserve">+ <value>JSON Formatter</value>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>JSON</value>+ </data>+ <data name="SortProperties" xml:space="preserve">+ <value>Sort Properties</value>+ </data>+ <data name="SortPropertiesOptionDescription" xml:space="preserve">+ <value>Whether properties within the JSON should be sorted alphabetically</value>+ </data>+ <data name="TwoSpaces" xml:space="preserve">+ <value>2 spaces</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatterCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatterCommandLineTool.csnew file mode 100644index 000000000..c4fc415b1--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatterCommandLineTool.cs@@ -0,0 +1,79 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;+using OneOf;++namespace DevToys.Tools.Tools.Formatters.Json;++[Export(typeof(ICommandLineTool))]+[Name("JsonFormatter")]+[CommandName(+ Name = "JsonFormatter",+ Alias = "Jsonf",+ ResourceManagerBaseName = "DevToys.Tools.Tools.Formatters.Json.JsonFormatter",+ DescriptionResourceName = nameof(JsonFormatter.Description))]+internal sealed class JsonFormatterCommandLineTool : ICommandLineTool+{+#pragma warning disable IDE0044 // Add readonly modifier+ [Import]+ private IFileStorage _fileStorage = null!;+#pragma warning restore IDE0044 // Add readonly modifier++ [CommandLineOption(+ Name = "input",+ Alias = "i",+ IsRequired = true,+ DescriptionResourceName = nameof(JsonFormatter.InputOptionDescription))]+ internal OneOf<FileInfo, string>? Input { get; set; }++ [CommandLineOption(+ Name = "outputFile",+ Alias = "o",+ DescriptionResourceName = nameof(JsonFormatter.OutputFileOptionDescription))]+ internal FileInfo? OutputFile { get; set; }++ [CommandLineOption(+ Name = "indentation",+ DescriptionResourceName = nameof(JsonFormatter.IndentationOptionDescription))]+ internal Indentation IndentationMode { get; set; } = Indentation.TwoSpaces;++ [CommandLineOption(+ Name = "sortProperties",+ DescriptionResourceName = nameof(JsonFormatter.SortPropertiesOptionDescription))]+ internal bool SortProperties { get; set; } = false;++ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ if (!Input.HasValue)+ {+ Console.Error.WriteLine(JsonFormatter.InvalidInputOrFileCommand);+ return -1;+ }++ ResultInfo<string> input = await Input.Value.ReadAllTextAsync(_fileStorage, cancellationToken);+ if (!input.HasSucceeded)+ {+ Console.Error.WriteLine(JsonFormatter.InputFileNotFound);+ return -1;+ }++ Guard.IsNotNull(input.Data);+ ResultInfo<string> formatResult = await JsonHelper.FormatAsync(+ input.Data,+ IndentationMode,+ SortProperties,+ logger,+ cancellationToken);++ cancellationToken.ThrowIfCancellationRequested();++ if (!formatResult.HasSucceeded)+ {+ Console.Error.WriteLine(formatResult.Data);+ return -1;+ }++ await FileHelper.WriteOutputAsync(formatResult.Data, OutputFile, cancellationToken);+ return 0;+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatterGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatterGuiTool.csnew file mode 100644index 000000000..54521353f--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Json/JsonFormatterGuiTool.cs@@ -0,0 +1,182 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.Formatters.Json;++[Export(typeof(IGuiTool))]+[Name("JsonFormatter")]+[ToolDisplayInformation(+ IconFontName = "DevToys-Tools-Icons",+ IconGlyph = '\u0108',+ GroupName = PredefinedCommonToolGroupNames.Formatters,+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.Formatters.Json.JsonFormatter",+ ShortDisplayTitleResourceName = nameof(JsonFormatter.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(JsonFormatter.LongDisplayTitle),+ DescriptionResourceName = nameof(JsonFormatter.Description),+ AccessibleNameResourceName = nameof(JsonFormatter.AccessibleName))]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Json)]+internal sealed partial class JsonFormatterGuiTool : IGuiTool, IDisposable+{+ /// <summary>+ /// Which indentation the tool need to use.+ /// </summary>+ private static readonly SettingDefinition<Indentation> indentationMode+ = new(name: $"{nameof(JsonFormatterGuiTool)}.{nameof(indentationMode)}", defaultValue: Indentation.TwoSpaces);++ /// <summary>+ /// Whether properties within the JSON should be sorted alphabetically+ /// </summary>+ private static readonly SettingDefinition<bool> sortProperties+ = new(name: $"{nameof(JsonFormatterGuiTool)}.{nameof(sortProperties)}", defaultValue: false);++ private enum GridColumn+ {+ Content+ }++ private enum GridRow+ {+ Header,+ Content,+ Footer+ }++ private readonly DisposableSemaphore _semaphore = new();+ private readonly ILogger _logger;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IUIMultiLineTextInput _inputTextArea = MultilineTextInput("json-input-text-area");+ private readonly IUIMultiLineTextInput _outputTextArea = MultilineTextInput("json-output-text-area");++ private CancellationTokenSource? _cancellationTokenSource;++ [ImportingConstructor]+ public JsonFormatterGuiTool(ISettingsProvider settingsProvider)+ {+ _logger = this.Log();+ _settingsProvider = settingsProvider;+ }++ internal Task? WorkTask { get; private set; }++ public UIToolView View+ => new(+ isScrollable: true,+ Grid()+ .ColumnLargeSpacing()+ .RowLargeSpacing()+ .Rows(+ (GridRow.Header, Auto),+ (GridRow.Content, new UIGridLength(1, UIGridUnitType.Fraction))+ )+ .Columns(+ (GridColumn.Content, new UIGridLength(1, UIGridUnitType.Fraction))+ )+ .Cells(+ Cell(+ GridRow.Header,+ GridColumn.Content,+ Stack().Vertical().WithChildren(+ Label().Text(JsonFormatter.Configuration),+ Setting("json-text-indentation-setting")+ .Icon("FluentSystemIcons", '\uF6F8')+ .Title(JsonFormatter.Indentation)+ .Handle(+ _settingsProvider,+ indentationMode,+ OnIndentationModelChanged,+ Item(JsonFormatter.TwoSpaces, Indentation.TwoSpaces),+ Item(JsonFormatter.FourSpaces, Indentation.FourSpaces),+ Item(JsonFormatter.OneTab, Indentation.OneTab),+ Item(JsonFormatter.Minified, Indentation.Minified)+ ),+ Setting("json-text-sortProperties-setting")+ .Icon("FluentSystemIcons", '\uf7ed')+ .Title(JsonFormatter.SortProperties)+ .Description(JsonFormatter.SortPropertiesOptionDescription)+ .Handle(+ _settingsProvider,+ sortProperties,+ OnSettingChanged+ )+ )+ ),+ Cell(+ GridRow.Content,+ GridColumn.Content,+ SplitGrid()+ .Vertical()+ .WithLeftPaneChild(+ _inputTextArea+ .Title(JsonFormatter.Input)+ .Language("json")+ .OnTextChanged(OnInputTextChanged))+ .WithRightPaneChild(+ _outputTextArea+ .Title(JsonFormatter.Output)+ .Language("json")+ .ReadOnly()+ .Extendable())+ )+ )+ );++ // Smart detection handler.+ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ if (dataTypeName == PredefinedCommonDataTypeNames.Json &&+ parsedData is string jsonStrongTypedParsedData)+ {+ _inputTextArea.Text(jsonStrongTypedParsedData);+ }+ }++ public void Dispose()+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _semaphore.Dispose();+ }++ private void OnSettingChanged(bool value)+ {+ StartFormat(_inputTextArea.Text);+ }++ private void OnIndentationModelChanged(Indentation indentationMode)+ {+ StartFormat(_inputTextArea.Text);+ }++ private void OnInputTextChanged(string text)+ {+ StartFormat(text);+ }++ private void StartFormat(string text)+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _cancellationTokenSource = new CancellationTokenSource();++ WorkTask = FormatAsync(text, _settingsProvider.GetSetting(indentationMode), _settingsProvider.GetSetting(sortProperties), _cancellationTokenSource.Token);+ }++ private async Task FormatAsync(string input, Indentation indentationSetting, bool sortPropertiesSetting, CancellationToken cancellationToken)+ {+ using (await _semaphore.WaitAsync(cancellationToken))+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ ResultInfo<string> formatResult = await JsonHelper.FormatAsync(+ input,+ indentationSetting,+ sortPropertiesSetting,+ _logger,+ cancellationToken);++ _outputTextArea.Text(formatResult.Data);+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatterGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatterGuiTool.csindex bc66a44aa..f910a8c21 100644--- a/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatterGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/Formatters/Xml/XmlFormatterGuiTool.cs@@ -19,8 +19,6 @@ namespace DevToys.Tools.Tools.Formatters.Xml;[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Xml)]internal sealed partial class XmlFormatterGuiTool : IGuiTool, IDisposable{- private const string XmlLanguage = "xml";-/// <summary>/// Which indentation the tool need to use./// </summary>@@ -130,8 +128,6 @@ internal sealed partial class XmlFormatterGuiTool : IGuiTool, IDisposableif (dataTypeName == PredefinedCommonDataTypeNames.Xml &&parsedData is string xmlStrongTypedParsedData){- _inputTextArea.Language(XmlLanguage);- _outputTextArea.Language(XmlLanguage);_inputTextArea.Text(xmlStrongTypedParsedData);}}@@ -164,10 +160,10 @@ internal sealed partial class XmlFormatterGuiTool : IGuiTool, IDisposable_cancellationTokenSource?.Dispose();_cancellationTokenSource = new CancellationTokenSource();- WorkTask = FormatAsync(text, _cancellationTokenSource.Token, indentationMode, newLineOnAttributes);+ WorkTask = FormatAsync(text, _settingsProvider.GetSetting(indentationMode), _settingsProvider.GetSetting(newLineOnAttributes), _cancellationTokenSource.Token);}- private async Task FormatAsync(string input, CancellationToken cancellationToken, SettingDefinition<Indentation> indentationSetting, SettingDefinition<bool> newLineOnAttributesetting)+ private async Task FormatAsync(string input, Indentation indentationSetting, bool newLineOnAttributeSetting, CancellationToken cancellationToken){using (await _semaphore.WaitAsync(cancellationToken)){@@ -175,8 +171,8 @@ internal sealed partial class XmlFormatterGuiTool : IGuiTool, IDisposableResultInfo<string> formatResult = XmlHelper.Format(input,- _settingsProvider.GetSetting(indentationSetting),- _settingsProvider.GetSetting(newLineOnAttributesetting),+ indentationSetting,+ newLineOnAttributeSetting,_logger);_outputTextArea.Text(formatResult.Data);diff --git a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorGuiTool.csindex f08773ac8..191fd34ff 100644--- a/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/Generators/HashAndChecksum/HashAndChecksumGeneratorGuiTool.cs@@ -290,6 +290,7 @@ internal sealed class HashAndChecksumGeneratorGuiTool : IGuiTool, IDisposable= ComputeHashAsync(_input.Value,_settingsProvider.GetSetting(hashAlgorithm),+ _settingsProvider.GetSetting(uppercase),_hmacSecretKeyInput.Text,_cancellationTokenSource.Token);}@@ -302,6 +303,7 @@ internal sealed class HashAndChecksumGeneratorGuiTool : IGuiTool, IDisposableprivate async Task ComputeHashAsync(OneOf<string, SandboxedFileReader> input,HashAlgorithmType hashAlgorithm,+ bool uppercase,string hmacSecretKey,CancellationToken cancellationToken){@@ -335,6 +337,7 @@ internal sealed class HashAndChecksumGeneratorGuiTool : IGuiTool, IDisposable= await ComputeHashFromStreamAsync(inputStream,hashAlgorithm,+ uppercase,hmacSecretKey,UpdateProgress,cancellationToken);@@ -353,6 +356,7 @@ internal sealed class HashAndChecksumGeneratorGuiTool : IGuiTool, IDisposableprivate async Task<string> ComputeHashFromStreamAsync(Stream inputStream,HashAlgorithmType hashAlgorithm,+ bool uppercase,string hmacSecretKey,Action<HashingProgress> progressCallback,CancellationToken cancellationToken)@@ -367,7 +371,7 @@ internal sealed class HashAndChecksumGeneratorGuiTool : IGuiTool, IDisposableprogressCallback,cancellationToken);- if (!_settingsProvider.GetSetting(uppercase))+ if (!uppercase){return fileHashString.ToLowerInvariant();}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Formatters/Json/JsonFormatterCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Formatters/Json/JsonFormatterCommandLineToolTests.csnew file mode 100644index 000000000..5d24ba72d--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Formatters/Json/JsonFormatterCommandLineToolTests.cs@@ -0,0 +1,179 @@+using System.IO;+using System.Threading.Tasks;+using DevToys.CLI;+using DevToys.Tools.Models;+using DevToys.Tools.Tools.Converters.JsonYaml;+using DevToys.Tools.Tools.Formatters.Json;+using DevToys.UnitTests.Mocks;+using Microsoft.Extensions.Logging;++namespace DevToys.UnitTests.Tools.Formatters.Json;++[Collection(nameof(TestParallelizationDisabled))]+public sealed class JsonFormatterCommandLineToolTests : MefBasedTest+{+ private readonly StringWriter _consoleWriter = new();+ private readonly StringWriter _consoleErrorWriter = new();+ private readonly JsonFormatterCommandLineTool _tool;+ private readonly Mock<ILogger> _loggerMock;+ private readonly string _baseTestDataDirectory = Path.Combine("Tools", "TestData", "JsonYamlConverter");++ public JsonFormatterCommandLineToolTests()+ : base(typeof(JsonFormatterCommandLineTool).Assembly)+ {+ _tool = (JsonFormatterCommandLineTool)MefProvider.ImportMany<ICommandLineTool, CommandLineToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "JsonFormatter").Value;++ _loggerMock = new Mock<ILogger>();+ Console.SetOut(_consoleWriter);+ Console.SetError(_consoleErrorWriter);+ }++ [Theory(DisplayName = "Format with invalid input should return error exit code")]+ [InlineData("")]+ [InlineData(" ")]+ public async Task FormatJsonInvalidInputShouldReturnErrorExitCode(string input)+ {+ _tool.Input = input;++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(-1);+ string consoleOutput = _consoleErrorWriter.ToString().Trim();+ consoleOutput.Should().Be("");+ }++ [Fact(DisplayName = "Format json with invalid json should output invalid json error")]+ public async Task FormatJsonInvalidJsonShouldOutputInvalidJsonError()+ {+ _tool.Input = " bar { \"foo\": 123 } ";++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(-1);+ string consoleOutput = _consoleErrorWriter.ToString().Trim();+ consoleOutput.Should().Be("Unexpected character encountered while parsing value: b. Path '', line 1, position 3.");+ }++ [Theory(DisplayName = "Format json with valid json and two spaces indentation should output valid json")]+ [InlineData(true, "{\r\n \"a\": \"asdf\",\r\n \"array\": [\r\n {\r\n \"a\": \"asdf\",\r\n \"array\": [],\r\n \"b\": 33,\r\n \"c\": 545\r\n }\r\n ],\r\n \"b\": 33,\r\n \"c\": 545\r\n}")]+ [InlineData(false, "{\r\n \"a\": \"asdf\",\r\n \"c\": 545,\r\n \"b\": 33,\r\n \"array\": [\r\n {\r\n \"a\": \"asdf\",\r\n \"c\": 545,\r\n \"b\": 33,\r\n \"array\": []\r\n }\r\n ]\r\n}")]+ public async Task FormatJsonWithValidJsonAndTwoSpacesShouldOutputValidJson(bool sortProperties, string expectedResult)+ {+ _tool.SortProperties = sortProperties;+ _tool.Input = "{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": [{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": []}]}";++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string consoleOutput = _consoleWriter.ToString().Trim();+ consoleOutput.Should().Be(expectedResult);+ }++ [Theory(DisplayName = "Format json with valid json and four spaces indentation should output valid json")]+ [InlineData(true, "{\r\n \"a\": \"asdf\",\r\n \"array\": [\r\n {\r\n \"a\": \"asdf\",\r\n \"array\": [],\r\n \"b\": 33,\r\n \"c\": 545\r\n }\r\n ],\r\n \"b\": 33,\r\n \"c\": 545\r\n}")]+ [InlineData(false, "{\r\n \"a\": \"asdf\",\r\n \"c\": 545,\r\n \"b\": 33,\r\n \"array\": [\r\n {\r\n \"a\": \"asdf\",\r\n \"c\": 545,\r\n \"b\": 33,\r\n \"array\": []\r\n }\r\n ]\r\n}")]+ public async Task FormatJsonWithValidJsonAndFourSpacesShouldOutputValidJson(bool sortProperties, string expectedResult)+ {+ _tool.IndentationMode = Indentation.FourSpaces;+ _tool.SortProperties = sortProperties;+ _tool.Input = "{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": [{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": []}]}";++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string consoleOutput = _consoleWriter.ToString().Trim();+ consoleOutput.Should().Be(expectedResult);+ }++ [Theory(DisplayName = "Format json with valid json and one tab indentation should output valid json")]+ [InlineData(true, "{\r\n\t\"a\": \"asdf\",\r\n\t\"array\": [\r\n\t\t{\r\n\t\t\t\"a\": \"asdf\",\r\n\t\t\t\"array\": [],\r\n\t\t\t\"b\": 33,\r\n\t\t\t\"c\": 545\r\n\t\t}\r\n\t],\r\n\t\"b\": 33,\r\n\t\"c\": 545\r\n}")]+ [InlineData(false, "{\r\n\t\"a\": \"asdf\",\r\n\t\"c\": 545,\r\n\t\"b\": 33,\r\n\t\"array\": [\r\n\t\t{\r\n\t\t\t\"a\": \"asdf\",\r\n\t\t\t\"c\": 545,\r\n\t\t\t\"b\": 33,\r\n\t\t\t\"array\": []\r\n\t\t}\r\n\t]\r\n}")]+ public async Task FormatJsonWithValidJsonAndOneTabShouldOutputValidJson(bool sortProperties, string expectedResult)+ {+ _tool.IndentationMode = Indentation.OneTab;+ _tool.SortProperties = sortProperties;+ _tool.Input = "{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": [{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": []}]}";++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string consoleOutput = _consoleWriter.ToString().Trim();+ consoleOutput.Should().Be(expectedResult);+ }++ [Theory(DisplayName = "Format json with valid json and minified indentation should output valid json")]+ [InlineData(true, "{\"a\":\"asdf\",\"array\":[{\"a\":\"asdf\",\"array\":[],\"b\":33,\"c\":545}],\"b\":33,\"c\":545}")]+ [InlineData(false, "{\"a\":\"asdf\",\"c\":545,\"b\":33,\"array\":[{\"a\":\"asdf\",\"c\":545,\"b\":33,\"array\":[]}]}")]+ public async Task FormatJsonWithValidJsonAndMinifiedShouldOutputValidJson(bool sortProperties, string expectedResult)+ {+ _tool.IndentationMode = Indentation.Minified;+ _tool.SortProperties = sortProperties;+ _tool.Input = "{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": [{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": []}]}";++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string consoleOutput = _consoleWriter.ToString().Trim();+ consoleOutput.Should().Be(expectedResult);+ }++ [Fact(DisplayName = "Format json with unknown json file should output invalid json error")]+ public async Task FormatJsonWithUnknownFileInputShouldReturnErrorExitCode()+ {+ string filePath = Path.Combine(_baseTestDataDirectory, "Unknown.json");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.Input = inputFile;+ _tool.OutputFile = new FileInfo("Dummy.json");+ ((MockIFileStorage)MefProvider.Import<IFileStorage>()).FileExistsResult = false;++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(-1);+ string consoleOutput = _consoleErrorWriter.ToString().Trim();+ consoleOutput.Should().Be(JsonFormatter.InputFileNotFound);+ }++ [Fact(DisplayName = "Format json with valid json file and two spaces indentation should output valid json file")]+ public async Task FormatJsonWithValidFileInputAndTwoSpacesShouldOutputValidJsonFile()+ {+ string expectedFilePath = Path.Combine(_baseTestDataDirectory, "TwoSpaces.json");+ string expectedContent = File.ReadAllText(expectedFilePath);++ string filePath = Path.Combine(_baseTestDataDirectory, "FourSpaces.json");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.Input = inputFile;+ _tool.OutputFile = new FileInfo("OutputTwoSpaces.json");++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);+ outputContent.Should().Be(expectedContent);+ }++ [Fact(DisplayName = "Format json with valid json file and four spaces indentation should output valid json file")]+ public async Task FormatJsonWithValidFileInputAndFourSpacesShouldOutputValidJsonFile()+ {+ string expectedFilePath = Path.Combine(_baseTestDataDirectory, "FourSpaces.json");+ string expectedContent = File.ReadAllText(expectedFilePath);++ string filePath = Path.Combine(_baseTestDataDirectory, "TwoSpaces.json");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.Input = inputFile;+ _tool.IndentationMode = Indentation.FourSpaces;+ _tool.OutputFile = new FileInfo("OutputFourSpaces.json");++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);+ outputContent.Should().Be(expectedContent);+ }++ [Fact(DisplayName = "Format json with json file containing invalid json should output invalid json error")]+ public async Task FormatJsonWithFileInputWithInvalidJsonShouldOutputInvalidJsonError()+ {+ string filePath = Path.Combine(_baseTestDataDirectory, "Invalid.json");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.Input = inputFile;+ _tool.IndentationMode = Indentation.OneTab;+ _tool.OutputFile = new FileInfo("OutputOneTab.json");++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(-1);+ string consoleOutput = _consoleErrorWriter.ToString().Trim();+ consoleOutput.Should().Be("Unexpected character encountered while parsing value: b. Path '', line 1, position 3.");+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Formatters/Json/JsonFormatterGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Formatters/Json/JsonFormatterGuiToolTests.csnew file mode 100644index 000000000..be0ee03aa--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Formatters/Json/JsonFormatterGuiToolTests.cs@@ -0,0 +1,116 @@+using System.Globalization;+using System.Threading.Tasks;+using DevToys.Core.Tools.Metadata;+using DevToys.Tools.Tools.Formatters.Json;++namespace DevToys.UnitTests.Tools.Formatters.Json;++public class JsonFormatterGuiToolTests : MefBasedTest+{+ private readonly UIToolView _toolView;+ private readonly JsonFormatterGuiTool _tool;+ private readonly IUIMultiLineTextInput _inputTextArea;+ private readonly IUIMultiLineTextInput _outputTextArea;++ public JsonFormatterGuiToolTests()+ : base(typeof(JsonFormatterGuiTool).Assembly)+ {+ _tool = (JsonFormatterGuiTool)MefProvider.ImportMany<IGuiTool, GuiToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "JsonFormatter")+ .Value;++ _toolView = _tool.View;++ _inputTextArea = (IUIMultiLineTextInput)_toolView.GetChildElementById("json-input-text-area");+ _outputTextArea = (IUIMultiLineTextInput)_toolView.GetChildElementById("json-output-text-area");+ CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;+ CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;+ }++ [Theory(DisplayName = "Format json with invalid json should return empty string")]+ [InlineData(null)]+ [InlineData("")]+ [InlineData(" ")]+ public async Task FormatJsonWithInvalidJsonShouldReturnJsonError(string input)+ {+ _inputTextArea.Text("abc");+ _inputTextArea.Text(input);+ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("");+ }++ [Fact(DisplayName = "Format json with invalid json should return json exception message")]+ public async Task FormatJsonWithInvalidJsonShouldReturnJsonExceptionMessage()+ {+ _inputTextArea.Text(" bar { \"foo\": 123 } ");+ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("Unexpected character encountered while parsing value: b. Path '', line 1, position 3.");+ }++ [Fact(DisplayName = "Format json with valid json and two spaces indentation should return valid json")]+ public async Task FormatJsonWithValidJsonAndTwoSpacesShouldReturnValidJson()+ {+ _inputTextArea.Text("{ \"foo\": 123 }");++ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-text-indentation-setting")).InteractiveElement;+ indentationOptions.Select(0); // Select TwoSpaces++ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("{\r\n \"foo\": 123\r\n}");+ }++ [Fact(DisplayName = "Format json with valid json and four spaces indentation should return valid json")]+ public async Task FormatJsonWithValidJsonAndFourSpacesShouldReturnValidJson()+ {+ _inputTextArea.Text("{ \"foo\": 123 }");++ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-text-indentation-setting")).InteractiveElement;+ indentationOptions.Select(1); // Select FourSpaces++ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("{\r\n \"foo\": 123\r\n}");+ }++ [Fact(DisplayName = "Format json with valid json and one tab indentation should return valid json")]+ public async Task FormatJsonWithValidJsonAndOneTabShouldReturnValidJson()+ {+ _inputTextArea.Text("{ \"foo\": 123 }");++ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-text-indentation-setting")).InteractiveElement;+ indentationOptions.Select(2); // Select OneTab++ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("{\r\n\t\"foo\": 123\r\n}");+ }++ [Fact(DisplayName = "Format json with valid json and minified should return valid json")]+ public async Task FormatJsonWithValidJsonAndMinifiedShouldReturnValidJson()+ {+ _inputTextArea.Text("{ \"foo\": 123 }");++ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-text-indentation-setting")).InteractiveElement;+ indentationOptions.Select(3); // Select Minified++ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("{\"foo\":123}");+ }++ [Fact(DisplayName = "Format json with valid json and sort properties should return valid json")]+ public async Task FormatJsonWithValidJsonAndSortPropertiesShouldReturnValidJson()+ {+ _inputTextArea.Text("{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": [{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": []}]}");+ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-text-indentation-setting")).InteractiveElement;+ indentationOptions.Select(0); // Select TwoSpaces++ var newLineOnAttributesOptions = (IUISwitch)((IUISetting)_toolView.GetChildElementById("json-text-sortProperties-setting")).InteractiveElement;+ newLineOnAttributesOptions.On();++ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("{\r\n \"a\": \"asdf\",\r\n \"array\": [\r\n {\r\n \"a\": \"asdf\",\r\n \"array\": [],\r\n \"b\": 33,\r\n \"c\": 545\r\n }\r\n ],\r\n \"b\": 33,\r\n \"c\": 545\r\n}");++ newLineOnAttributesOptions.Off();++ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("{\r\n \"a\": \"asdf\",\r\n \"c\": 545,\r\n \"b\": 33,\r\n \"array\": [\r\n {\r\n \"a\": \"asdf\",\r\n \"c\": 545,\r\n \"b\": 33,\r\n \"array\": []\r\n }\r\n ]\r\n}");+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Formatters/XmlFormatterCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Formatters/Xml/XmlFormatterCommandLineToolTests.cssimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/Formatters/XmlFormatterCommandLineToolTests.csrename to src/app/tests/DevToys.UnitTests/Tools/Formatters/Xml/XmlFormatterCommandLineToolTests.csdiff --git a/src/app/tests/DevToys.UnitTests/Tools/Formatters/XmlFormatterGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Formatters/Xml/XmlFormatterGuiToolTests.cssimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/Formatters/XmlFormatterGuiToolTests.csrename to src/app/tests/DevToys.UnitTests/Tools/Formatters/Xml/XmlFormatterGuiToolTests.csdiff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.csindex 925636614..c20aaacfd 100644--- a/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs@@ -31,8 +31,8 @@ public class JsonHelperTests[InlineData(" { \"foo\": 123 } ", "{\r\n \"foo\": 123\r\n}")]public async Task FormatTwoSpaces(string input, string expectedResult){- string result = await JsonHelper.Format(input, Indentation.TwoSpaces, false, new MockILogger(), CancellationToken.None);- result.Should().Be(expectedResult);+ ResultInfo<string> result = await JsonHelper.FormatAsync(input, Indentation.TwoSpaces, false, new MockILogger(), CancellationToken.None);+ result.Data.Should().Be(expectedResult);}[Theory]@@ -44,8 +44,8 @@ public class JsonHelperTests[InlineData(" { \"foo\": 123 } ", "{\r\n \"foo\": 123\r\n}")]public async Task FormatFourSpaces(string input, string expectedResult){- string result = await JsonHelper.Format(input, Indentation.FourSpaces, false, new MockILogger(), CancellationToken.None);- result.Should().Be(expectedResult);+ ResultInfo<string> result = await JsonHelper.FormatAsync(input, Indentation.FourSpaces, false, new MockILogger(), CancellationToken.None);+ result.Data.Should().Be(expectedResult);}[Theory]@@ -57,8 +57,8 @@ public class JsonHelperTests[InlineData(" { \"foo\": 123 } ", "{\r\n\t\"foo\": 123\r\n}")]public async Task FormatOneTab(string input, string expectedResult){- string result = await JsonHelper.Format(input, Indentation.OneTab, false, new MockILogger(), CancellationToken.None);- result.Should().Be(expectedResult);+ ResultInfo<string> result = await JsonHelper.FormatAsync(input, Indentation.OneTab, false, new MockILogger(), CancellationToken.None);+ result.Data.Should().Be(expectedResult);}[Theory]@@ -70,16 +70,16 @@ public class JsonHelperTests[InlineData(" { \"foo\": 123 } ", "{\"foo\":123}")]public async Task FormatMinifiedAsync(string input, string expectedResult){- string result = await JsonHelper.Format(input, Indentation.Minified, false, new MockILogger(), CancellationToken.None);- result.Should().Be(expectedResult);+ ResultInfo<string> result = await JsonHelper.FormatAsync(input, Indentation.Minified, false, new MockILogger(), CancellationToken.None);+ result.Data.Should().Be(expectedResult);}[Theory][InlineData("{ \"Date\": \"2012-04-21T18:25:43-05:00\" }", "{\"Date\":\"2012-04-21T18:25:43-05:00\"}")]public async Task FormatDoesNotAlterateDateTimesAsync(string input, string expectedResult){- string result = await JsonHelper.Format(input, Indentation.Minified, false, new MockILogger(), CancellationToken.None);- result.Should().Be(expectedResult);+ ResultInfo<string> result = await JsonHelper.FormatAsync(input, Indentation.Minified, false, new MockILogger(), CancellationToken.None);+ result.Data.Should().Be(expectedResult);}[Theory]@@ -88,8 +88,8 @@ public class JsonHelperTests"{\"a\":\"asdf\",\"array\":[{\"a\":\"asdf\",\"array\":[],\"b\":33,\"c\":545}],\"b\":33,\"c\":545}")]public async Task FormatSortPropertiesAlphabeticallyAsync(string input, string expectedResult){- string result = await JsonHelper.Format(input, Indentation.Minified, true, new MockILogger(), CancellationToken.None);- result.Should().Be(expectedResult);+ ResultInfo<string> result = await JsonHelper.FormatAsync(input, Indentation.Minified, true, new MockILogger(), CancellationToken.None);+ result.Data.Should().Be(expectedResult);}[Theory]