A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
Added a JSONPath tester tool (#1017)
Etienne BAUDOUX398d21bf64dd
diff --git a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIDataGridRow.cs b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIDataGridRow.csindex 8051eb477..fc0efc558 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIDataGridRow.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUIDataGridRow.cs@@ -67,7 +67,7 @@ public static partial class GUI/// <param name="value">The value associated to the item.</param>/// <param name="details">The element to display as detail information in the row.</param>/// <param name="cells">The cells to display in the row.</param>- public static IUIDataGridRow Row(object? value, IUIElement details, params IUIDataGridCell[] cells)+ public static IUIDataGridRow Row(object? value, IUIElement? details, params IUIDataGridCell[] cells){var row = (UIDataGridRow)Row(value, cells);row.Details = details;@@ -80,7 +80,7 @@ public static partial class GUI/// <param name="value">The value associated to the item.</param>/// <param name="details">The element to display as detail information in the row.</param>/// <param name="cells">The cells to display in the row.</param>- public static IUIDataGridRow Row(object? value, IUIElement details, params string[] cells)+ public static IUIDataGridRow Row(object? value, IUIElement? details, params string[] cells){var row = (UIDataGridRow)Row(value, cells);row.Details = details;diff --git a/src/app/dev/DevToys.Api/Tool/GUI/Components/UIToolView.cs b/src/app/dev/DevToys.Api/Tool/GUI/Components/UIToolView.csindex d672c9130..77bb58c36 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/Components/UIToolView.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/Components/UIToolView.cs@@ -98,6 +98,7 @@ public class UIToolView : INotifyPropertyChanged/// Gets the first child element with the specified id./// </summary>/// <param name="id">The id of a child element.</param>+ /// <remarks>This method is recursive and navigate through each element in the UI. It can be slow depending on the complexity of the UI. Be cautious when using it.</remarks>/// <returns>Returns null if the element could not be found. If many elements have the name id, this method returns the first it finds</returns>public IUIElement? GetChildElementById(string id){diff --git a/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.cs b/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.csindex 5aa343074..e3c4547c5 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/PredefinedCommonToolGroupNames.cs@@ -7,5 +7,6 @@ public static class PredefinedCommonToolGroupNamespublic const string Formatters = "Formatters";public const string Generators = "Generators";public const string Graphic = "Graphic";+ public const string Testers = "Testers";public const string Text = "Text";}diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csprojindex 4df689b8e..4f5fdd6c0 100644--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj@@ -148,6 +148,16 @@<DesignTime>True</DesignTime><AutoGen>True</AutoGen></Compile>+ <Compile Update="Tools\Testers\JsonPathTester\JsonPathTester.Designer.cs">+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ <DependentUpon>JsonPathTester.resx</DependentUpon>+ </Compile>+ <Compile Update="Tools\Testers\Testers.Designer.cs">+ <DependentUpon>Testers.resx</DependentUpon>+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ </Compile><Compile Update="Tools\Text\AnalyzerAndUtilities\AnalyzerAndUtilities.Designer.cs"><DesignTime>True</DesignTime><AutoGen>True</AutoGen>@@ -163,7 +173,7 @@<AutoGen>True</AutoGen><DependentUpon>MarkdownPreview.resx</DependentUpon></Compile>- <Compile Update="Tools\Text\RegExTester\RegExTester.Designer.cs">+ <Compile Update="Tools\Testers\RegExTester\RegExTester.Designer.cs"><DesignTime>True</DesignTime><AutoGen>True</AutoGen><DependentUpon>RegExTester.resx</DependentUpon>@@ -173,10 +183,10 @@<AutoGen>True</AutoGen><DependentUpon>Text.resx</DependentUpon></Compile>- <Compile Update="Tools\Text\XMLValidator\XMLValidator.Designer.cs">+ <Compile Update="Tools\Testers\XMLTester\XMLTester.Designer.cs"><DesignTime>True</DesignTime><AutoGen>True</AutoGen>- <DependentUpon>XMLValidator.resx</DependentUpon>+ <DependentUpon>XMLTester.resx</DependentUpon></Compile></ItemGroup><ItemGroup>@@ -272,6 +282,14 @@<LastGenOutput>ImageConverter.Designer.cs</LastGenOutput><Generator>ResXFileCodeGenerator</Generator></EmbeddedResource>+ <EmbeddedResource Update="Tools\Testers\JsonPathTester\JsonPathTester.resx">+ <Generator>ResXFileCodeGenerator</Generator>+ <LastGenOutput>JsonPathTester.Designer.cs</LastGenOutput>+ </EmbeddedResource>+ <EmbeddedResource Update="Tools\Testers\Testers.resx">+ <LastGenOutput>Testers.Designer.cs</LastGenOutput>+ <Generator>ResXFileCodeGenerator</Generator>+ </EmbeddedResource><EmbeddedResource Update="Tools\Text\AnalyzerAndUtilities\AnalyzerAndUtilities.resx"><Generator>ResXFileCodeGenerator</Generator><LastGenOutput>AnalyzerAndUtilities.Designer.cs</LastGenOutput>@@ -284,7 +302,7 @@<Generator>ResXFileCodeGenerator</Generator><LastGenOutput>MarkdownPreview.Designer.cs</LastGenOutput></EmbeddedResource>- <EmbeddedResource Update="Tools\Text\RegExTester\RegExTester.resx">+ <EmbeddedResource Update="Tools\Testers\RegExTester\RegExTester.resx"><Generator>ResXFileCodeGenerator</Generator><LastGenOutput>RegExTester.Designer.cs</LastGenOutput></EmbeddedResource>@@ -292,9 +310,9 @@<Generator>ResXFileCodeGenerator</Generator><LastGenOutput>Text.Designer.cs</LastGenOutput></EmbeddedResource>- <EmbeddedResource Update="Tools\Text\XMLValidator\XMLValidator.resx">+ <EmbeddedResource Update="Tools\Testers\XMLTester\XMLTester.resx"><Generator>ResXFileCodeGenerator</Generator>- <LastGenOutput>XMLValidator.Designer.cs</LastGenOutput>+ <LastGenOutput>XMLTester.Designer.cs</LastGenOutput></EmbeddedResource></ItemGroup>diff --git a/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs b/src/app/dev/DevToys.Tools/Helpers/JsonHelper.csindex 29e9bfc22..7ca200f37 100644--- a/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs+++ b/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs@@ -14,7 +14,7 @@ internal static partial class JsonHelper/// <summary>/// Detects whether the given string is a valid JSON or not./// </summary>- internal static bool IsValid(string? input, ILogger logger)+ internal static async ValueTask<bool> IsValidAsync(string? input, ILogger logger, CancellationToken cancellationToken){if (input == null){@@ -28,7 +28,8 @@ internal static partial class JsonHelpertry{- var jtoken = JToken.Parse(input);+ using JsonReader reader = new JsonTextReader(new StringReader(input));+ JToken? jtoken = await JToken.LoadAsync(reader, settings: null, cancellationToken);return jtoken is not null;}catch (JsonReaderException)@@ -38,7 +39,7 @@ internal static partial class JsonHelper}catch (Exception ex){- logger.LogError(ex, "Invalid data detected 'input'", input);+ logger.LogError(ex, "Invalid data detected.");return false;}}@@ -130,7 +131,63 @@ internal static partial class JsonHelper}catch (Exception ex){- logger.LogError(ex, "Invalid JSON format 'indentationMode'", indentationMode);+ logger.LogError(ex, "Invalid JSON format '{indentationMode}'", indentationMode);+ return new(ex.Message, false);+ }+ }++ /// <summary>+ /// Get the data of a JSON object in the given JSONPath.+ /// </summary>+ internal static async Task<ResultInfo<string>> TestJsonPathAsync(string json, string jsonPath, ILogger logger, CancellationToken cancellationToken)+ {+ if (string.IsNullOrEmpty(json) || string.IsNullOrEmpty(jsonPath))+ {+ return new(string.Empty, false);+ }++ try+ {+ using JsonReader reader = new JsonTextReader(new StringReader(json));+ JObject? jsonObject = await JObject.LoadAsync(reader, settings: null, cancellationToken);+ return TestJsonPath(jsonObject, jsonPath, logger, cancellationToken);+ }+ catch (Exception ex) when (ex is OperationCanceledException or JsonReaderException)+ {+ return new(ex.Message, false);+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "Error while testing JsonPath.");+ return new(ex.Message, false);+ }+ }++ /// <summary>+ /// Get the data of a JSON object in the given JSONPath.+ /// </summary>+ internal static ResultInfo<string> TestJsonPath(JObject jsonObject, string jsonPath, ILogger logger, CancellationToken cancellationToken)+ {+ Guard.IsNotNull(logger);+ if (jsonObject is null || string.IsNullOrWhiteSpace(jsonPath))+ {+ return new(string.Empty, false);+ }++ try+ {+ IEnumerable<JToken> tokens = jsonObject.SelectTokens(jsonPath, errorWhenNoMatch: false);++ cancellationToken.ThrowIfCancellationRequested();+ return new(JsonConvert.SerializeObject(tokens, Formatting.Indented), true);+ }+ catch (OperationCanceledException)+ {+ return new(string.Empty, false);+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "Error while testing JsonPath.");return new(ex.Message, false);}}diff --git a/src/app/dev/DevToys.Tools/Helpers/XmlHelper.cs b/src/app/dev/DevToys.Tools/Helpers/XmlHelper.csindex c4aa3f743..eb21a103a 100644--- a/src/app/dev/DevToys.Tools/Helpers/XmlHelper.cs+++ b/src/app/dev/DevToys.Tools/Helpers/XmlHelper.cs@@ -39,7 +39,7 @@ internal static class XmlHelper}catch (Exception ex){- logger.LogError(ex, "Invalid data detected 'input'", input);+ logger.LogError(ex, "Invalid data detected.");return false;}}diff --git a/src/app/dev/DevToys.Tools/Helpers/XsdHelper.cs b/src/app/dev/DevToys.Tools/Helpers/XsdHelper.csindex fca2f7b13..6654451c9 100644--- a/src/app/dev/DevToys.Tools/Helpers/XsdHelper.cs+++ b/src/app/dev/DevToys.Tools/Helpers/XsdHelper.cs@@ -4,7 +4,7 @@ using System.Xml.Linq;using System.Xml.Schema;using System.Xml.XPath;using DevToys.Tools.Models;-using DevToys.Tools.Tools.Text.XMLValidator;+using DevToys.Tools.Tools.Testers.XMLTester;using Microsoft.Extensions.Logging;namespace DevToys.Tools.Helpers;@@ -33,19 +33,19 @@ internal static class XsdHelper}}- internal static ResultInfo<string, XmlValidatorResultSeverity> ValidateXmlAgainstXsd(string xsd, string xml, ILogger logger, CancellationToken cancellationToken)+ internal static ResultInfo<string, XMLTesterResultSeverity> ValidateXmlAgainstXsd(string xsd, string xml, ILogger logger, CancellationToken cancellationToken){Guard.IsNotNullOrWhiteSpace(xsd);Guard.IsNotNullOrWhiteSpace(xml);try{- XmlValidatorResultSeverity hasSucceeded = XmlValidatorResultSeverity.Success;+ XMLTesterResultSeverity hasSucceeded = XMLTesterResultSeverity.Success;var errors = new StringBuilder();void ValidationErrorCallBack(object? sender, ValidationEventArgs e){cancellationToken.ThrowIfCancellationRequested();- hasSucceeded = e.Severity == XmlSeverityType.Warning ? XmlValidatorResultSeverity.Warning : XmlValidatorResultSeverity.Error;+ hasSucceeded = e.Severity == XmlSeverityType.Warning ? XMLTesterResultSeverity.Warning : XMLTesterResultSeverity.Error;errors.AppendLine(e.Message);}@@ -66,7 +66,7 @@ internal static class XsdHelper}catch (XmlException ex){- return new ResultInfo<string, XmlValidatorResultSeverity>($"XML: {ex.Message}", XmlValidatorResultSeverity.Error);+ return new ResultInfo<string, XMLTesterResultSeverity>($"XML: {ex.Message}", XMLTesterResultSeverity.Error);}cancellationToken.ThrowIfCancellationRequested();@@ -74,7 +74,7 @@ internal static class XsdHelper// Validate XML against the XSD.xmlDocument.Validate(xmlSchemaSet, ValidationErrorCallBack);- if (hasSucceeded == XmlValidatorResultSeverity.Success)+ if (hasSucceeded == XMLTesterResultSeverity.Success){// XML will always be valid if it doesn't define a namespace. Let's verify that namespaces aren't missing.var xsdDocument = XDocument.Parse(xsd);@@ -90,14 +90,14 @@ internal static class XsdHelperif (!areAllNamespacesDefinedInXsd){string missingNamespacesFormatted = FormatNamespaces(namespacesMissingInXsd);- return new ResultInfo<string, XmlValidatorResultSeverity>(string.Format(XMLValidator.XsdNamespacesInconsistentMsg, missingNamespacesFormatted), XmlValidatorResultSeverity.Warning);+ return new ResultInfo<string, XMLTesterResultSeverity>(string.Format(XMLTester.XsdNamespacesInconsistentMsg, missingNamespacesFormatted), XMLTesterResultSeverity.Warning);}bool isTargetNamespaceReferenceMissingInXml= DetectMissingTargetNamespaceInXml(xmlSchema.TargetNamespace, xmlNamespaces, out string? missingTargetNamespaceUri);if (isTargetNamespaceReferenceMissingInXml){- return new ResultInfo<string, XmlValidatorResultSeverity>(string.Format(XMLValidator.TargetNamespaceNotDefinedInXml, missingTargetNamespaceUri), XmlValidatorResultSeverity.Warning);+ return new ResultInfo<string, XMLTesterResultSeverity>(string.Format(XMLTester.TargetNamespaceNotDefinedInXml, missingTargetNamespaceUri), XMLTesterResultSeverity.Warning);}IEnumerable<XmlNamespace> namespacesMissingInXml@@ -107,23 +107,23 @@ internal static class XsdHelperif (!areAllNamespacesDefinedInXml){string missingNamespacesFormatted = FormatNamespaces(namespacesMissingInXml);- return new ResultInfo<string, XmlValidatorResultSeverity>(string.Format(XMLValidator.XmlNamespacesInconsistentMsg, missingNamespacesFormatted), XmlValidatorResultSeverity.Warning);+ return new ResultInfo<string, XMLTesterResultSeverity>(string.Format(XMLTester.XmlNamespacesInconsistentMsg, missingNamespacesFormatted), XMLTesterResultSeverity.Warning);}}}- return new ResultInfo<string, XmlValidatorResultSeverity>(errors.ToString(), hasSucceeded);+ return new ResultInfo<string, XMLTesterResultSeverity>(errors.ToString(), hasSucceeded);}catch (Exception ex) when (ex is XmlException || ex is XmlSchemaException){- return new ResultInfo<string, XmlValidatorResultSeverity>($"XSD: {ex.Message}", XmlValidatorResultSeverity.Error);+ return new ResultInfo<string, XMLTesterResultSeverity>($"XSD: {ex.Message}", XMLTesterResultSeverity.Error);}catch (Exception ex){logger.LogError(ex, "Error while validation XML against XSD.");}- return new ResultInfo<string, XmlValidatorResultSeverity>(string.Empty, XmlValidatorResultSeverity.Error);+ return new ResultInfo<string, XMLTesterResultSeverity>(string.Empty, XMLTesterResultSeverity.Error);}/// <summary>diff --git a/src/app/dev/DevToys.Tools/Helpers/YamlHelper.cs b/src/app/dev/DevToys.Tools/Helpers/YamlHelper.csindex 3eff0d785..b8ffeed6c 100644--- a/src/app/dev/DevToys.Tools/Helpers/YamlHelper.cs+++ b/src/app/dev/DevToys.Tools/Helpers/YamlHelper.cs@@ -42,7 +42,7 @@ internal static partial class YamlHelper}catch (Exception ex){- logger.LogError(ex, "Invalid data detected: 'input'", input);+ logger.LogError(ex, "Invalid data detected.");return false;}}diff --git a/src/app/dev/DevToys.Tools/Models/XmlValidatorResultSeverity.cs b/src/app/dev/DevToys.Tools/Models/XMLTesterResultSeverity.cssimilarity index 64%rename from src/app/dev/DevToys.Tools/Models/XmlValidatorResultSeverity.csrename to src/app/dev/DevToys.Tools/Models/XMLTesterResultSeverity.csindex 2fa4df2d5..a873e36a6 100644--- a/src/app/dev/DevToys.Tools/Models/XmlValidatorResultSeverity.cs+++ b/src/app/dev/DevToys.Tools/Models/XMLTesterResultSeverity.cs@@ -1,6 +1,6 @@namespace DevToys.Tools.Models;-internal enum XmlValidatorResultSeverity+internal enum XMLTesterResultSeverity{Success,Warning,diff --git a/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.csindex 30980c51a..ef112b431 100644--- a/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs+++ b/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs@@ -15,7 +15,7 @@ internal sealed partial class JsonDataTypeDetector : IDataTypeDetector_logger = this.Log();}- public ValueTask<DataDetectionResult> TryDetectDataAsync(+ public async ValueTask<DataDetectionResult> TryDetectDataAsync(object data,DataDetectionResult? resultFromBaseDetector,CancellationToken cancellationToken)@@ -24,12 +24,12 @@ internal sealed partial class JsonDataTypeDetector : IDataTypeDetector&& resultFromBaseDetector.Data is string dataString&& !long.TryParse(dataString, out _)){- if (JsonHelper.IsValid(dataString, _logger))+ if (await JsonHelper.IsValidAsync(dataString, _logger, cancellationToken)){- return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataString));+ return new DataDetectionResult(Success: true, Data: dataString);}}- return ValueTask.FromResult(DataDetectionResult.Unsuccessful);+ return DataDetectionResult.Unsuccessful;}}diff --git a/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTester.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTester.Designer.csnew file mode 100644index 000000000..d15cec8bd--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTester.Designer.cs@@ -0,0 +1,315 @@+//------------------------------------------------------------------------------+// <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.Testers.JsonPathTester {+ 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 JsonPathTester {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal JsonPathTester() {+ }++ /// <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.Testers.JsonPathTester.JsonPathTester", typeof(JsonPathTester).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 JSONPath Tester tool.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Array slice operator.+ /// </summary>+ internal static string CheatSheetArraySliceOperator {+ get {+ return ResourceManager.GetString("CheatSheetArraySliceOperator", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Bracket-notated child or children.+ /// </summary>+ internal static string CheatSheetBracketNotedChildOperator {+ get {+ return ResourceManager.GetString("CheatSheetBracketNotedChildOperator", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Used for filter expressions. Refers to the current node for further processing..+ /// </summary>+ internal static string CheatSheetCurrentObjectElement {+ get {+ return ResourceManager.GetString("CheatSheetCurrentObjectElement", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Description.+ /// </summary>+ internal static string CheatSheetDescription {+ get {+ return ResourceManager.GetString("CheatSheetDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Dot-notated child.+ /// </summary>+ internal static string CheatSheetDotNotedChildOperator {+ get {+ return ResourceManager.GetString("CheatSheetDotNotedChildOperator", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Selects all elements in an object or array that match the specified boolean expression. Returns a list..+ /// </summary>+ internal static string CheatSheetFilterExpression {+ get {+ return ResourceManager.GetString("CheatSheetFilterExpression", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Performs a deep scan for the specified property in all available objects. Always returns a list, even for a single match..+ /// </summary>+ internal static string CheatSheetRecursiveDescent {+ get {+ return ResourceManager.GetString("CheatSheetRecursiveDescent", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to The root object or array..+ /// </summary>+ internal static string CheatSheetRootObjectElement {+ get {+ return ResourceManager.GetString("CheatSheetRootObjectElement", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Script expression..+ /// </summary>+ internal static string CheatSheetScriptExpression {+ get {+ return ResourceManager.GetString("CheatSheetScriptExpression", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Selects the n-th element from an array. Indexes start from 0..+ /// </summary>+ internal static string CheatSheetSubscriptOperator {+ get {+ return ResourceManager.GetString("CheatSheetSubscriptOperator", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Syntax.+ /// </summary>+ internal static string CheatSheetSyntax {+ get {+ return ResourceManager.GetString("CheatSheetSyntax", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Cheat sheet.+ /// </summary>+ internal static string CheatSheetTitle {+ get {+ return ResourceManager.GetString("CheatSheetTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Selects n1 and n2 array items. Returns a list..+ /// </summary>+ internal static string CheatSheetUnionOperator {+ get {+ return ResourceManager.GetString("CheatSheetUnionOperator", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Wildcard. Selects all elements in an object or array, regardless of their names or indexes..+ /// </summary>+ internal static string CheatSheetWildcard {+ get {+ return ResourceManager.GetString("CheatSheetWildcard", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Test a JSONPath.+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", 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.+ /// </summary>+ internal static string InputJsonOptionDescription {+ get {+ return ResourceManager.GetString("InputJsonOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Text or path to a file containing the JSONPath.+ /// </summary>+ internal static string InputJsonPathOptionDescription {+ get {+ return ResourceManager.GetString("InputJsonPathOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to JSONPath.+ /// </summary>+ internal static string InputJsonPathTitle {+ get {+ return ResourceManager.GetString("InputJsonPathTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to JSON.+ /// </summary>+ internal static string InputTitle {+ get {+ return ResourceManager.GetString("InputTitle", 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 JSONPath Tester.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to No match found.+ /// </summary>+ internal static string NoMatchFound {+ get {+ return ResourceManager.GetString("NoMatchFound", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Test result.+ /// </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 path json.+ /// </summary>+ internal static string SearchKeywords {+ get {+ return ResourceManager.GetString("SearchKeywords", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to JSONPath.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTester.resx b/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTester.resxnew file mode 100644index 000000000..ca03424e6--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTester.resx@@ -0,0 +1,204 @@+<?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>JSONPath Tester tool</value>+ </data>+ <data name="CheatSheetArraySliceOperator" xml:space="preserve">+ <value>Array slice operator</value>+ </data>+ <data name="CheatSheetBracketNotedChildOperator" xml:space="preserve">+ <value>Bracket-notated child or children</value>+ </data>+ <data name="CheatSheetCurrentObjectElement" xml:space="preserve">+ <value>Used for filter expressions. Refers to the current node for further processing.</value>+ </data>+ <data name="CheatSheetDescription" xml:space="preserve">+ <value>Description</value>+ </data>+ <data name="CheatSheetDotNotedChildOperator" xml:space="preserve">+ <value>Dot-notated child</value>+ </data>+ <data name="CheatSheetFilterExpression" xml:space="preserve">+ <value>Selects all elements in an object or array that match the specified boolean expression. Returns a list.</value>+ </data>+ <data name="CheatSheetRecursiveDescent" xml:space="preserve">+ <value>Performs a deep scan for the specified property in all available objects. Always returns a list, even for a single match.</value>+ </data>+ <data name="CheatSheetRootObjectElement" xml:space="preserve">+ <value>The root object or array.</value>+ </data>+ <data name="CheatSheetScriptExpression" xml:space="preserve">+ <value>Script expression.</value>+ </data>+ <data name="CheatSheetSubscriptOperator" xml:space="preserve">+ <value>Selects the n-th element from an array. Indexes start from 0.</value>+ </data>+ <data name="CheatSheetSyntax" xml:space="preserve">+ <value>Syntax</value>+ </data>+ <data name="CheatSheetTitle" xml:space="preserve">+ <value>Cheat sheet</value>+ </data>+ <data name="CheatSheetUnionOperator" xml:space="preserve">+ <value>Selects n1 and n2 array items. Returns a list.</value>+ </data>+ <data name="CheatSheetWildcard" xml:space="preserve">+ <value>Wildcard. Selects all elements in an object or array, regardless of their names or indexes.</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Test a JSONPath</value>+ </data>+ <data name="InputFileNotFound" xml:space="preserve">+ <value>Input file selected doesn't exist.</value>+ </data>+ <data name="InputJsonOptionDescription" xml:space="preserve">+ <value>Text or path to a file containing the JSON</value>+ </data>+ <data name="InputJsonPathOptionDescription" xml:space="preserve">+ <value>Text or path to a file containing the JSONPath</value>+ </data>+ <data name="InputJsonPathTitle" xml:space="preserve">+ <value>JSONPath</value>+ </data>+ <data name="InputTitle" xml:space="preserve">+ <value>JSON</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>JSONPath Tester</value>+ </data>+ <data name="NoMatchFound" xml:space="preserve">+ <value>No match found</value>+ </data>+ <data name="Output" xml:space="preserve">+ <value>Test result</value>+ </data>+ <data name="OutputFileOptionDescription" xml:space="preserve">+ <value>Path to the output file</value>+ </data>+ <data name="SearchKeywords" xml:space="preserve">+ <value>path json</value>+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>JSONPath</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTesterCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTesterCommandLineTool.csnew file mode 100644index 000000000..19216fc48--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTesterCommandLineTool.cs@@ -0,0 +1,82 @@+using DevToys.Tools.Helpers;+using Microsoft.Extensions.Logging;+using OneOf;++namespace DevToys.Tools.Tools.Testers.JsonPathTester;++[Export(typeof(ICommandLineTool))]+[Name("JSONPathTester")]+[CommandName(+ Name = "jsonpathtester",+ Alias = "jpt",+ ResourceManagerBaseName = "DevToys.Tools.Tools.Testers.JsonPathTester.JsonPathTester",+ DescriptionResourceName = nameof(JsonPathTester.Description))]+internal sealed class JsonPathTesterCommandLineTool : ICommandLineTool+{+#pragma warning disable IDE0044 // Add readonly modifier+ [Import]+ private IFileStorage _fileStorage = null!;+#pragma warning restore IDE0044 // Add readonly modifier++ [CommandLineOption(+ Name = "json",+ Alias = "j",+ IsRequired = true,+ DescriptionResourceName = nameof(JsonPathTester.InputJsonOptionDescription))]+ internal OneOf<FileInfo, string>? InputJson { get; set; }++ [CommandLineOption(+ Name = "path",+ Alias = "p",+ IsRequired = true,+ DescriptionResourceName = nameof(JsonPathTester.InputJsonPathOptionDescription))]+ internal OneOf<FileInfo, string>? InputJsonPath { get; set; }++ [CommandLineOption(+ Name = "outputFile",+ Alias = "o",+ DescriptionResourceName = nameof(JsonPathTester.OutputFileOptionDescription))]+ internal FileInfo? OutputFile { get; set; }++ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ if (!InputJson.HasValue || !InputJsonPath.HasValue)+ {+ Console.Error.WriteLine(JsonPathTester.InvalidInputOrFileCommand);+ return -1;+ }++ ResultInfo<string> inputJson = await InputJson.Value.ReadAllTextAsync(_fileStorage, cancellationToken);+ if (!inputJson.HasSucceeded)+ {+ Console.Error.WriteLine(JsonPathTester.InputFileNotFound);+ return -1;+ }++ ResultInfo<string> inputJsonPath = await InputJsonPath.Value.ReadAllTextAsync(_fileStorage, cancellationToken);+ if (!inputJsonPath.HasSucceeded)+ {+ Console.Error.WriteLine(JsonPathTester.InputFileNotFound);+ return -1;+ }++ Guard.IsNotNull(inputJson.Data);+ Guard.IsNotNull(inputJsonPath.Data);+ ResultInfo<string> formatResult = await JsonHelper.TestJsonPathAsync(+ inputJson.Data,+ inputJsonPath.Data,+ 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/Testers/JsonPathTester/JsonPathTesterGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTesterGuiTool.csnew file mode 100644index 000000000..05784b7d3--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Testers/JsonPathTester/JsonPathTesterGuiTool.cs@@ -0,0 +1,223 @@+using DevToys.Tools.Helpers;+using Microsoft.Extensions.Logging;+using Newtonsoft.Json;+using Newtonsoft.Json.Linq;++namespace DevToys.Tools.Tools.Testers.JsonPathTester;++[Export(typeof(IGuiTool))]+[Name("JSONPathTester")]+[ToolDisplayInformation(+ IconFontName = "DevToys-Tools-Icons",+ IconGlyph = '\u0108', // TODO: Create an icon for this tool+ GroupName = PredefinedCommonToolGroupNames.Testers,+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.Testers.JsonPathTester.JsonPathTester",+ ShortDisplayTitleResourceName = nameof(JsonPathTester.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(JsonPathTester.LongDisplayTitle),+ DescriptionResourceName = nameof(JsonPathTester.Description),+ AccessibleNameResourceName = nameof(JsonPathTester.AccessibleName),+ SearchKeywordsResourceName = nameof(JsonPathTester.SearchKeywords))]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Json)]+internal sealed class JsonPathTesterGuiTool : IGuiTool, IDisposable+{+ private static readonly IUIDataGridRow[] cheatSheetRows+ = new[]+ {+ CreateCheatSheetRow(@"$", JsonPathTester.CheatSheetRootObjectElement),+ CreateCheatSheetRow(@"@", JsonPathTester.CheatSheetCurrentObjectElement),+ CreateCheatSheetRow(@"object.property", JsonPathTester.CheatSheetDotNotedChildOperator),+ CreateCheatSheetRow(@"['object'].['property']", JsonPathTester.CheatSheetBracketNotedChildOperator),+ CreateCheatSheetRow(@"..property", JsonPathTester.CheatSheetRecursiveDescent),+ CreateCheatSheetRow(@"*", JsonPathTester.CheatSheetWildcard),+ CreateCheatSheetRow(@"[n]", JsonPathTester.CheatSheetSubscriptOperator),+ CreateCheatSheetRow(@"[n1,n2]", JsonPathTester.CheatSheetUnionOperator),+ CreateCheatSheetRow(@"[start:end:step]", JsonPathTester.CheatSheetArraySliceOperator),+ CreateCheatSheetRow(@"?(expression)", JsonPathTester.CheatSheetFilterExpression),+ CreateCheatSheetRow(@"(expression)", JsonPathTester.CheatSheetScriptExpression)+ };++ private enum GridRows+ {+ TopAuto,+ Stretch,+ }++ private enum GridColumns+ {+ Stretch+ }++ private readonly DisposableSemaphore _semaphore = new();+ private readonly ILogger _logger;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IUIMultiLineTextInput _inputJson = MultilineTextInput("input-json-json-path-tester");+ private readonly IUISingleLineTextInput _inputJsonPath = SingleLineTextInput("input-json-path-json-path-tester");+ private readonly IUIMultiLineTextInput _outputJson = MultilineTextInput("output-json-path-tester");++ private CancellationTokenSource? _cancellationTokenSource;+ private string _lastTreatedInputJson = string.Empty;+ private JObject? _inputJsonObjectBackup = null;++ [ImportingConstructor]+ public JsonPathTesterGuiTool(ISettingsProvider settingsProvider)+ {+ _logger = this.Log();+ _settingsProvider = settingsProvider;+ }++ // For unit tests.+ internal Task? WorkTask { get; private set; }++ public UIToolView View+ => new(+ isScrollable: false,+ SplitGrid()+ .Vertical()+ .LeftPaneLength(new UIGridLength(1, UIGridUnitType.Fraction))+ .RightPaneLength(new UIGridLength(1, UIGridUnitType.Fraction))++ .WithLeftPaneChild(+ _inputJson+ .Title(JsonPathTester.InputTitle)+ .Language("json")+ .OnTextChanged(OnInputJsonChanged))++ .WithRightPaneChild(+ SplitGrid()+ .Horizontal()++ .WithTopPaneChild(+ Grid()+ .ColumnSmallSpacing()++ .Rows(+ (GridRows.TopAuto, Auto),+ (GridRows.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Columns(+ (GridColumns.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))++ .Cells(+ Cell(+ GridRows.TopAuto,+ GridColumns.Stretch,++ _inputJsonPath+ .Title(JsonPathTester.InputJsonPathTitle)+ .OnTextChanged(OnInputJsonPathChanged)),++ Cell(+ GridRows.Stretch,+ GridColumns.Stretch,++ _outputJson+ .ReadOnly()+ .Extendable()+ .Language("json")+ .Title(JsonPathTester.Output))))++ .WithBottomPaneChild(+ DataGrid()+ .Title(JsonPathTester.CheatSheetTitle)+ .Extendable()+ .WithColumns(JsonPathTester.CheatSheetSyntax, JsonPathTester.CheatSheetDescription)+ .WithRows(cheatSheetRows))));++ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ if (dataTypeName == PredefinedCommonDataTypeNames.Json && parsedData is string json)+ {+ _inputJson.Text(json);+ }+ }++ public void Dispose()+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _semaphore.Dispose();+ }++ private void OnInputJsonChanged(string json)+ {+ StartTest();+ }++ private void OnInputJsonPathChanged(string jsonPath)+ {+ StartTest();+ }++ private void StartTest()+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _cancellationTokenSource = new CancellationTokenSource();++ WorkTask = TestJsonPathAsync(_inputJson.Text, _inputJsonPath.Text, _cancellationTokenSource.Token);+ }++ private async Task TestJsonPathAsync(string json, string jsonPath, CancellationToken cancellationToken)+ {+ using (await _semaphore.WaitAsync(cancellationToken))+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ string result = JsonPathTester.NoMatchFound;+ try+ {+ if (!string.IsNullOrWhiteSpace(jsonPath))+ {+ if (string.Equals(_lastTreatedInputJson, json, StringComparison.Ordinal))+ {+ // We can reuse the previous JObject. Let's avoid parsing it too often to improve performance.+ _inputJsonObjectBackup ??= JObject.Parse(json);+ }+ else+ {+ // We need to parse the new JObject.+ _inputJsonObjectBackup = JObject.Parse(json);+ _lastTreatedInputJson = json;+ }++ cancellationToken.ThrowIfCancellationRequested();++ JObject jsonObject = _inputJsonObjectBackup;++ ResultInfo<string> resultInfo = JsonHelper.TestJsonPath(jsonObject, jsonPath, _logger, cancellationToken);+ if (resultInfo.HasSucceeded)+ {+ result = resultInfo.Data;+ }+ }+ }+ catch (Exception ex) when (ex is OperationCanceledException or JsonReaderException)+ {+ // Ignore+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "Error while testing JsonPath.");+ }+ finally+ {+ _outputJson.Text(result);+ }+ }+ }++ private static IUIDataGridRow CreateCheatSheetRow(string syntax, string description)+ => Row(+ null,+ details: null,+ Cell(+ Label()+ .NeverWrap()+ .Style(UILabelStyle.BodyStrong)+ .Text($"\t{syntax}\t")),+ Cell(+ Label()+ .NeverWrap()+ .Text(description)));+}diff --git a/src/app/dev/DevToys.Tools/Tools/Text/RegExTester/README.md b/src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/README.mdsimilarity index 100%rename from src/app/dev/DevToys.Tools/Tools/Text/RegExTester/README.mdrename to src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/README.mddiff --git a/src/app/dev/DevToys.Tools/Tools/Text/RegExTester/RegExTester.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/RegExTester.Designer.cssimilarity index 99%rename from src/app/dev/DevToys.Tools/Tools/Text/RegExTester/RegExTester.Designer.csrename to src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/RegExTester.Designer.csindex a255bc90a..231956ead 100644--- a/src/app/dev/DevToys.Tools/Tools/Text/RegExTester/RegExTester.Designer.cs+++ b/src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/RegExTester.Designer.cs@@ -8,7 +8,7 @@// </auto-generated>//-------------------------------------------------------------------------------namespace DevToys.Tools.Tools.Text.RegExTester {+namespace DevToys.Tools.Tools.Testers.RegExTester {using System;@@ -39,7 +39,7 @@ namespace DevToys.Tools.Tools.Text.RegExTester {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.Text.RegExTester.RegExTester", typeof(RegExTester).Assembly);+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Testers.RegExTester.RegExTester", typeof(RegExTester).Assembly);resourceMan = temp;}return resourceMan;@@ -1762,7 +1762,7 @@ namespace DevToys.Tools.Tools.Text.RegExTester {}/// <summary>- /// Looks up a localized string similar to RegEx Tester.+ /// Looks up a localized string similar to RegEx./// </summary>internal static string ShortDisplayTitle {get {diff --git a/src/app/dev/DevToys.Tools/Tools/Text/RegExTester/RegExTester.resx b/src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/RegExTester.resxsimilarity index 99%rename from src/app/dev/DevToys.Tools/Tools/Text/RegExTester/RegExTester.resxrename to src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/RegExTester.resxindex e81e5b48f..7066b7cf4 100644--- a/src/app/dev/DevToys.Tools/Tools/Text/RegExTester/RegExTester.resx+++ b/src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/RegExTester.resx@@ -715,7 +715,7 @@ Within a character set, only \, -, and ] need to be escaped.</value><value>regular expression</value></data><data name="ShortDisplayTitle" xml:space="preserve">- <value>RegEx Tester</value>+ <value>RegEx</value></data><data name="Singleline" xml:space="preserve"><value>Singleline</value>diff --git a/src/app/dev/DevToys.Tools/Tools/Text/RegExTester/RegExTesterGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/RegExTesterGuiTool.cssimilarity index 98%rename from src/app/dev/DevToys.Tools/Tools/Text/RegExTester/RegExTesterGuiTool.csrename to src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/RegExTesterGuiTool.csindex cabb7737e..96dd0d4f8 100644--- a/src/app/dev/DevToys.Tools/Tools/Text/RegExTester/RegExTesterGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/Testers/RegExTester/RegExTesterGuiTool.cs@@ -1,21 +1,22 @@using System.Text.RegularExpressions;using Microsoft.Extensions.Logging;-namespace DevToys.Tools.Tools.Text.RegExTester;+namespace DevToys.Tools.Tools.Testers.RegExTester;[Export(typeof(IGuiTool))][Name("RegExTester")][ToolDisplayInformation(IconFontName = "DevToys-Tools-Icons",IconGlyph = '\u0113',- GroupName = PredefinedCommonToolGroupNames.Text,+ GroupName = PredefinedCommonToolGroupNames.Testers,ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),- ResourceManagerBaseName = "DevToys.Tools.Tools.Text.RegExTester.RegExTester",+ ResourceManagerBaseName = "DevToys.Tools.Tools.Testers.RegExTester.RegExTester",ShortDisplayTitleResourceName = nameof(RegExTester.ShortDisplayTitle),LongDisplayTitleResourceName = nameof(RegExTester.LongDisplayTitle),DescriptionResourceName = nameof(RegExTester.Description),AccessibleNameResourceName = nameof(RegExTester.AccessibleName),SearchKeywordsResourceName = nameof(RegExTester.SearchKeywords))]+[NoCompactOverlaySupport] // UI is too crowded for it. TODO: Consider adding an event to IThemeListener to notify when entering Picture-in-Picture mode and update the UI accordingly.[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Text)]internal sealed class RegExTesterGuiTool : IGuiTool, IDisposable{diff --git a/src/app/dev/DevToys.Tools/Tools/Testers/Testers.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Testers/Testers.Designer.csnew file mode 100644index 000000000..72227a978--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Testers/Testers.Designer.cs@@ -0,0 +1,81 @@+//------------------------------------------------------------------------------+// <auto-generated>+// This code was generated by a tool.+// Runtime Version:4.0.30319.42000+//+// Changes to this file may cause incorrect behavior and will be lost if+// the code is regenerated.+// </auto-generated>+//------------------------------------------------------------------------------++namespace DevToys.Tools.Tools.Testers {+ 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 Testers {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal Testers() {+ }++ /// <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.Testers.Testers", typeof(Testers).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 Testers.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Testers.+ /// </summary>+ internal static string DisplayTitle {+ get {+ return ResourceManager.GetString("DisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Testers/Testers.resx b/src/app/dev/DevToys.Tools/Tools/Testers/Testers.resxnew file mode 100644index 000000000..99ba22094--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Testers/Testers.resx@@ -0,0 +1,126 @@+<?xml version="1.0" encoding="utf-8"?>+<root>+ <!--+ Microsoft ResX Schema++ Version 2.0++ The primary goals of this format is to allow a simple XML format+ that is mostly human readable. The generation and parsing of the+ various data types are done through the TypeConverter classes+ associated with the data types.++ Example:++ ... ado.net/XML headers & schema ...+ <resheader name="resmimetype">text/microsoft-resx</resheader>+ <resheader name="version">2.0</resheader>+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">+ <value>[base64 mime encoded serialized .NET Framework object]</value>+ </data>+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>+ <comment>This is a comment</comment>+ </data>++ There are any number of "resheader" rows that contain simple+ name/value pairs.++ Each data row contains a name, and value. The row also contains a+ type or mimetype. Type corresponds to a .NET class that support+ text/value conversion through the TypeConverter architecture.+ Classes that don't support this are serialized and stored with the+ mimetype set.++ The mimetype is used for serialized objects, and tells the+ ResXResourceReader how to depersist the object. This is currently not+ extensible. For a given mimetype the value must be set accordingly:++ Note - application/x-microsoft.net.object.binary.base64 is the format+ that the ResXResourceWriter will generate, however the reader can+ read any of the formats listed below.++ mimetype: application/x-microsoft.net.object.binary.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.soap.base64+ value : The object must be serialized with+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter+ : and then encoded with base64 encoding.++ mimetype: application/x-microsoft.net.object.bytearray.base64+ value : The object must be serialized into a byte array+ : using a System.ComponentModel.TypeConverter+ : and then encoded with base64 encoding.+ -->+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />+ <xsd:element name="root" msdata:IsDataSet="true">+ <xsd:complexType>+ <xsd:choice maxOccurs="unbounded">+ <xsd:element name="metadata">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" />+ </xsd:sequence>+ <xsd:attribute name="name" use="required" type="xsd:string" />+ <xsd:attribute name="type" type="xsd:string" />+ <xsd:attribute name="mimetype" type="xsd:string" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="assembly">+ <xsd:complexType>+ <xsd:attribute name="alias" type="xsd:string" />+ <xsd:attribute name="name" type="xsd:string" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="data">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />+ <xsd:attribute ref="xml:space" />+ </xsd:complexType>+ </xsd:element>+ <xsd:element name="resheader">+ <xsd:complexType>+ <xsd:sequence>+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />+ </xsd:sequence>+ <xsd:attribute name="name" type="xsd:string" use="required" />+ </xsd:complexType>+ </xsd:element>+ </xsd:choice>+ </xsd:complexType>+ </xsd:element>+ </xsd:schema>+ <resheader name="resmimetype">+ <value>text/microsoft-resx</value>+ </resheader>+ <resheader name="version">+ <value>2.0</value>+ </resheader>+ <resheader name="reader">+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <resheader name="writer">+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>+ </resheader>+ <data name="AccessibleName" xml:space="preserve">+ <value>Testers</value>+ </data>+ <data name="DisplayTitle" xml:space="preserve">+ <value>Testers</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Testers/TestersGroup.cs b/src/app/dev/DevToys.Tools/Tools/Testers/TestersGroup.csnew file mode 100644index 000000000..00c80a71e--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Testers/TestersGroup.cs@@ -0,0 +1,15 @@+namespace DevToys.Tools.Tools.Testers;++[Export(typeof(GuiToolGroup))]+[Name(PredefinedCommonToolGroupNames.Testers)]+internal sealed class TestersGroup : GuiToolGroup+{+ [ImportingConstructor]+ internal TestersGroup()+ {+ IconFontName = "FluentSystemIcons";+ IconGlyph = '\uE33B';+ DisplayTitle = Testers.DisplayTitle;+ AccessibleName = Testers.AccessibleName;+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTester.Designer.cssimilarity index 97%rename from src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.Designer.csrename to src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTester.Designer.csindex 699102e50..e5c874059 100644--- a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.Designer.cs+++ b/src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTester.Designer.cs@@ -8,7 +8,7 @@// </auto-generated>//-------------------------------------------------------------------------------namespace DevToys.Tools.Tools.Text.XMLValidator {+namespace DevToys.Tools.Tools.Testers.XMLTester {using System;@@ -22,14 +22,14 @@ namespace DevToys.Tools.Tools.Text.XMLValidator {[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")][global::System.Diagnostics.DebuggerNonUserCodeAttribute()][global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]- internal class XMLValidator {+ internal class XMLTester {private static global::System.Resources.ResourceManager resourceMan;private static global::System.Globalization.CultureInfo resourceCulture;[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]- internal XMLValidator() {+ internal XMLTester() {}/// <summary>@@ -39,7 +39,7 @@ namespace DevToys.Tools.Tools.Text.XMLValidator {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.Text.XMLValidator.XMLValidator", typeof(XMLValidator).Assembly);+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DevToys.Tools.Tools.Testers.XMLTester.XMLTester", typeof(XMLTester).Assembly);resourceMan = temp;}return resourceMan;diff --git a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.resx b/src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTester.resxsimilarity index 100%rename from src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.resxrename to src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTester.resxdiff --git a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTesterCommandLineTool.cssimilarity index 62%rename from src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorCommandLineTool.csrename to src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTesterCommandLineTool.csindex 7f5f59782..37cb4c5cf 100644--- a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorCommandLineTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTesterCommandLineTool.cs@@ -3,16 +3,16 @@ using DevToys.Tools.Models;using Microsoft.Extensions.Logging;using OneOf;-namespace DevToys.Tools.Tools.Text.XMLValidator;+namespace DevToys.Tools.Tools.Testers.XMLTester;[Export(typeof(ICommandLineTool))]-[Name("XMLValidator")]+[Name("XMLTester")][CommandName(- Name = "xmlvalidator",+ Name = "xmltester",Alias = "xsd",- ResourceManagerBaseName = "DevToys.Tools.Tools.Text.XMLValidator.XMLValidator",- DescriptionResourceName = nameof(XMLValidator.Description))]-internal sealed class XMLValidatorCommandLineTool : ICommandLineTool+ ResourceManagerBaseName = "DevToys.Tools.Tools.Testers.XMLTester.XMLTester",+ DescriptionResourceName = nameof(XMLTester.Description))]+internal sealed class XMLTesterCommandLineTool : ICommandLineTool{#pragma warning disable IDE0044 // Add readonly modifier[Import]@@ -23,60 +23,60 @@ internal sealed class XMLValidatorCommandLineTool : ICommandLineToolName = "xsd",Alias = "s",IsRequired = true,- DescriptionResourceName = nameof(XMLValidator.XsdOptionDescription))]+ DescriptionResourceName = nameof(XMLTester.XsdOptionDescription))]private OneOf<FileInfo, string>? XsdFile { get; set; }[CommandLineOption(Name = "xml",Alias = "x",IsRequired = true,- DescriptionResourceName = nameof(XMLValidator.XmlOptionDescription))]+ DescriptionResourceName = nameof(XMLTester.XmlOptionDescription))]private OneOf<FileInfo, string>? XmlFile { get; set; }public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken){if (!XsdFile.HasValue){- Console.Error.WriteLine(XMLValidator.InvalidXsdOrFileCommand);+ Console.Error.WriteLine(XMLTester.InvalidXsdOrFileCommand);return -1;}ResultInfo<string> xsd = await XsdFile.Value.ReadAllTextAsync(_fileStorage, cancellationToken);if (!xsd.HasSucceeded){- Console.Error.WriteLine(XMLValidator.XsdFileNotFound);+ Console.Error.WriteLine(XMLTester.XsdFileNotFound);return -1;}if (!XmlFile.HasValue){- Console.Error.WriteLine(XMLValidator.InvalidXmlOrFileCommand);+ Console.Error.WriteLine(XMLTester.InvalidXmlOrFileCommand);return -1;}ResultInfo<string> xml = await XmlFile.Value.ReadAllTextAsync(_fileStorage, cancellationToken);if (!xml.HasSucceeded){- Console.Error.WriteLine(XMLValidator.XmlFileNotFound);+ Console.Error.WriteLine(XMLTester.XmlFileNotFound);return -1;}- ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsd.Data, xml.Data, logger, cancellationToken);+ ResultInfo<string, XMLTesterResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsd.Data, xml.Data, logger, cancellationToken);switch (result.Severity){- case XmlValidatorResultSeverity.Success:+ case XMLTesterResultSeverity.Success:return 0;- case XmlValidatorResultSeverity.Warning:+ case XMLTesterResultSeverity.Warning:Console.Error.WriteLine(result.Data);return -1;- case XmlValidatorResultSeverity.Error:+ case XMLTesterResultSeverity.Error:string errorDescription;if (string.IsNullOrWhiteSpace(result.Data)){- errorDescription = XMLValidator.XmlInvalidMessage;+ errorDescription = XMLTester.XmlInvalidMessage;}else{diff --git a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTesterGuiTool.cssimilarity index 77%rename from src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorGuiTool.csrename to src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTesterGuiTool.csindex e0c6a5a2a..86cab596d 100644--- a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorGuiTool.cs+++ b/src/app/dev/DevToys.Tools/Tools/Testers/XMLTester/XMLTesterGuiTool.cs@@ -2,24 +2,24 @@using DevToys.Tools.Models;using Microsoft.Extensions.Logging;-namespace DevToys.Tools.Tools.Text.XMLValidator;+namespace DevToys.Tools.Tools.Testers.XMLTester;[Export(typeof(IGuiTool))]-[Name("XMLValidator")]+[Name("XMLTester")][ToolDisplayInformation(IconFontName = "DevToys-Tools-Icons",IconGlyph = '\u0116',- GroupName = PredefinedCommonToolGroupNames.Text,+ GroupName = PredefinedCommonToolGroupNames.Testers,ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),- ResourceManagerBaseName = "DevToys.Tools.Tools.Text.XMLValidator.XMLValidator",- ShortDisplayTitleResourceName = nameof(XMLValidator.ShortDisplayTitle),- LongDisplayTitleResourceName = nameof(XMLValidator.LongDisplayTitle),- DescriptionResourceName = nameof(XMLValidator.Description),- AccessibleNameResourceName = nameof(XMLValidator.AccessibleName),- SearchKeywordsResourceName = nameof(XMLValidator.SearchKeywords))]+ ResourceManagerBaseName = "DevToys.Tools.Tools.Testers.XMLTester.XMLTester",+ ShortDisplayTitleResourceName = nameof(XMLTester.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(XMLTester.LongDisplayTitle),+ DescriptionResourceName = nameof(XMLTester.Description),+ AccessibleNameResourceName = nameof(XMLTester.AccessibleName),+ SearchKeywordsResourceName = nameof(XMLTester.SearchKeywords))][AcceptedDataTypeName(PredefinedCommonDataTypeNames.Xml)][AcceptedDataTypeName(PredefinedCommonDataTypeNames.Xsd)]-internal sealed class XMLValidatorGuiTool : IGuiTool, IDisposable+internal sealed class XMLTesterGuiTool : IGuiTool, IDisposable{private enum GridRows{@@ -41,7 +41,7 @@ internal sealed class XMLValidatorGuiTool : IGuiTool, IDisposableprivate CancellationTokenSource? _cancellationTokenSource;[ImportingConstructor]- internal XMLValidatorGuiTool()+ internal XMLTesterGuiTool(){_logger = this.Log();}@@ -71,7 +71,7 @@ internal sealed class XMLValidatorGuiTool : IGuiTool, IDisposable.Vertical().WithLeftPaneChild(_xsdInputText- .Title(XMLValidator.XsdScheme)+ .Title(XMLTester.XsdScheme).Language("xml").CanCopyWhenEditable().Extendable()@@ -79,7 +79,7 @@ internal sealed class XMLValidatorGuiTool : IGuiTool, IDisposable.WithRightPaneChild(_xmlInputText- .Title(XMLValidator.XmlData)+ .Title(XMLTester.XmlData).Language("xml").CanCopyWhenEditable().Extendable()@@ -126,34 +126,34 @@ internal sealed class XMLValidatorGuiTool : IGuiTool, IDisposableif (string.IsNullOrWhiteSpace(xsd) || string.IsNullOrWhiteSpace(xml)){_infoBar- .Description(XMLValidator.ValidationImpossibleMsg)+ .Description(XMLTester.ValidationImpossibleMsg).Informational();return;}await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);- ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsd, xml, _logger, cancellationToken);+ ResultInfo<string, XMLTesterResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsd, xml, _logger, cancellationToken);switch (result.Severity){- case XmlValidatorResultSeverity.Success:+ case XMLTesterResultSeverity.Success:_infoBar- .Description(XMLValidator.XmlValidMessage)+ .Description(XMLTester.XmlValidMessage).Success();break;- case XmlValidatorResultSeverity.Warning:+ case XMLTesterResultSeverity.Warning:_infoBar.Description(result.Data).Warning();break;- case XmlValidatorResultSeverity.Error:+ case XMLTesterResultSeverity.Error:string errorDescription;if (string.IsNullOrWhiteSpace(result.Data)){- errorDescription = XMLValidator.XmlInvalidMessage;+ errorDescription = XMLTester.XmlInvalidMessage;}else{diff --git a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csprojindex cda81f693..c357e6bbf 100644--- a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj+++ b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj@@ -18,6 +18,9 @@<Content Include="Tools\TestData\HashAndChecksumGenerator\File.txt"><CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory></Content>+ <EmbeddedResource Include="Tools\TestData\JsonPathTester\sample.json">+ <CopyToOutputDirectory>Never</CopyToOutputDirectory>+ </EmbeddedResource><Content Include="Tools\TestData\JsonYamlConverter\FourSpaces.json"><CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory></Content>@@ -57,15 +60,15 @@</ItemGroup><ItemGroup>- <EmbeddedResource Include="Tools\TestData\XmlValidator\InvalidXml.xml" />- <EmbeddedResource Include="Tools\TestData\XmlValidator\InvalidXsd.xml" />- <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXml.xml" />- <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXmlWithNamespace.xml" />- <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXmlWithoutNamespace.xml" />- <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXsd.xml" />- <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXsdOnlyWithTargetNamespace.xml" />- <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXsdWithNamespace.xml" />- <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXsdWithoutNamespace.xml" />+ <EmbeddedResource Include="Tools\TestData\XMLTester\InvalidXml.xml" />+ <EmbeddedResource Include="Tools\TestData\XMLTester\InvalidXsd.xml" />+ <EmbeddedResource Include="Tools\TestData\XMLTester\ValidXml.xml" />+ <EmbeddedResource Include="Tools\TestData\XMLTester\ValidXmlWithNamespace.xml" />+ <EmbeddedResource Include="Tools\TestData\XMLTester\ValidXmlWithoutNamespace.xml" />+ <EmbeddedResource Include="Tools\TestData\XMLTester\ValidXsd.xml" />+ <EmbeddedResource Include="Tools\TestData\XMLTester\ValidXsdOnlyWithTargetNamespace.xml" />+ <EmbeddedResource Include="Tools\TestData\XMLTester\ValidXsdWithNamespace.xml" />+ <EmbeddedResource Include="Tools\TestData\XMLTester\ValidXsdWithoutNamespace.xml" /></ItemGroup><ItemGroup>diff --git a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.cs b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.csindex 1cbc2c7c7..42eb93738 100644--- a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.cs+++ b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.cs@@ -9,19 +9,19 @@ namespace DevToys.UnitTests.Mocks.Tools;[DataTypeName("JSON", baseName: "text")]internal class MockJsonDataTypeDetector : IDataTypeDetector{- public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult resultFromBaseDetector, CancellationToken cancellationToken)+ public async ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult resultFromBaseDetector, CancellationToken cancellationToken){if (resultFromBaseDetector is not null&& resultFromBaseDetector.Data is string dataString&& !long.TryParse(dataString, out _)){- if (JsonHelper.IsValid(dataString, new MockILogger()))+ if (await JsonHelper.IsValidAsync(dataString, new MockILogger(), cancellationToken)){- return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataString));+ return new DataDetectionResult(Success: true, Data: dataString);}}- return ValueTask.FromResult(DataDetectionResult.Unsuccessful);+ return DataDetectionResult.Unsuccessful;}}diff --git a/src/app/tests/DevToys.UnitTests/TestDataProvider.cs b/src/app/tests/DevToys.UnitTests/TestDataProvider.csindex 32a868721..b93f3ab26 100644--- a/src/app/tests/DevToys.UnitTests/TestDataProvider.cs+++ b/src/app/tests/DevToys.UnitTests/TestDataProvider.cs@@ -11,7 +11,7 @@ internal static class TestDataProvider/// </summary>/// <param name="filePath">Path to the file relative to <c>DevToys.Tests.Providers.TestData</c></param>/// <returns></returns>- public static async Task<string> GetFileContent(string filePath)+ public static async Task<string> GetEmbeddedFileContent(string filePath){var assembly = Assembly.GetExecutingAssembly();using Stream resourceStream = assembly.GetManifestResourceStream(filePath);diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.csindex c20aaacfd..be28cd061 100644--- a/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs@@ -17,9 +17,10 @@ public class JsonHelperTests[InlineData(" [ ] ", true)][InlineData(" { \"foo\": 123 } ", true)][InlineData(" bar { \"foo\": 123 } ", false)]- public void IsValid(string input, bool expectedResult)+ public async Task IsValid(string input, bool expectedResult){- JsonHelper.IsValid(input, new MockILogger()).Should().Be(expectedResult);+ (await JsonHelper.IsValidAsync(input, new MockILogger(), CancellationToken.None))+ .Should().Be(expectedResult);}[Theory]@@ -167,4 +168,13 @@ public class JsonHelperTestsCancellationToken.None);result.Data.Should().Be(expectedResult);}++ [Theory]+ [InlineData(null, null, "")]+ [InlineData("{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": [{\"a\": \"asdf\", \"c\" : 545, \"b\": 42, \"array\": []}]}", "array.[0].b", "[\r\n 42\r\n]")]+ public async Task JsonPathTests(string json, string jsonPath, string expectedResult)+ {+ (await JsonHelper.TestJsonPathAsync(json, jsonPath, new MockILogger(), CancellationToken.None))+ .Data.Should().Be(expectedResult);+ }}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/XsdHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/XsdHelperTests.csindex a03a4aa1c..93fb833c2 100644--- a/src/app/tests/DevToys.UnitTests/Tools/Helpers/XsdHelperTests.cs+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/XsdHelperTests.cs@@ -11,88 +11,88 @@ public class XsdHelperTests[Fact]public async Task ValidateXml_InvalidXmlFile(){- string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsd.xml");- string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.InvalidXml.xml");+ string xsdSchemaString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXsd.xml");+ string xmlDataString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.InvalidXml.xml");- ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);+ ResultInfo<string, XMLTesterResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);- result.Severity.Should().Be(XmlValidatorResultSeverity.Error);+ result.Severity.Should().Be(XMLTesterResultSeverity.Error);}[Fact]public async Task ValidateXml_ValidXmlSchema(){- string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsd.xml");- string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXml.xml");+ string xsdSchemaString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXsd.xml");+ string xmlDataString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXml.xml");- ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);+ ResultInfo<string, XMLTesterResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);- result.Severity.Should().Be(XmlValidatorResultSeverity.Success);+ result.Severity.Should().Be(XMLTesterResultSeverity.Success);}[Fact]public async Task ValidateXml_InvalidXsdSchema(){- string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.InvalidXsd.xml");- string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXml.xml");+ string xsdSchemaString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.InvalidXsd.xml");+ string xmlDataString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXml.xml");- ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);+ ResultInfo<string, XMLTesterResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);- result.Severity.Should().Be(XmlValidatorResultSeverity.Error);+ result.Severity.Should().Be(XMLTesterResultSeverity.Error);}[Fact]public async Task ValidateXml_NoNamespacesMissing(){- string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsdWithNamespace.xml");- string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXmlWithNamespace.xml");+ string xsdSchemaString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXsdWithNamespace.xml");+ string xmlDataString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXmlWithNamespace.xml");- ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);+ ResultInfo<string, XMLTesterResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);- result.Severity.Should().Be(XmlValidatorResultSeverity.Success);+ result.Severity.Should().Be(XMLTesterResultSeverity.Success);}[Fact]public async Task ValidateXml_XsdTargetNamespaceIsNotPredefinedElsewhereInXsdHeader(){- string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsd.xml");- string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXml.xml");+ string xsdSchemaString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXsd.xml");+ string xmlDataString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXml.xml");- ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);+ ResultInfo<string, XMLTesterResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);- result.Severity.Should().Be(XmlValidatorResultSeverity.Success);+ result.Severity.Should().Be(XMLTesterResultSeverity.Success);}[Fact]public async Task ValidateXml_NamespacesMissingInXml(){- string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsdWithNamespace.xml");- string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXmlWithoutNamespace.xml");+ string xsdSchemaString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXsdWithNamespace.xml");+ string xmlDataString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXmlWithoutNamespace.xml");- ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);+ ResultInfo<string, XMLTesterResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);- result.Severity.Should().Be(XmlValidatorResultSeverity.Warning);+ result.Severity.Should().Be(XMLTesterResultSeverity.Warning);}[Fact]public async Task ValidateXml_NamespacesMissingInXsd(){- string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsdWithoutNamespace.xml");- string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXmlWithNamespace.xml");+ string xsdSchemaString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXsdWithoutNamespace.xml");+ string xmlDataString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXmlWithNamespace.xml");- ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);+ ResultInfo<string, XMLTesterResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);- result.Severity.Should().Be(XmlValidatorResultSeverity.Warning);+ result.Severity.Should().Be(XMLTesterResultSeverity.Warning);}[Fact]public async Task ValidateXml_XmlIsMissingTargetedNamespace(){- string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsdOnlyWithTargetNamespace.xml");- string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXmlWithoutNamespace.xml");+ string xsdSchemaString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXsdOnlyWithTargetNamespace.xml");+ string xmlDataString = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.XMLTester.ValidXmlWithoutNamespace.xml");- ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);+ ResultInfo<string, XMLTesterResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);- result.Severity.Should().Be(XmlValidatorResultSeverity.Warning);+ result.Severity.Should().Be(XMLTesterResultSeverity.Warning);}}diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonPathTester/sample.json b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonPathTester/sample.jsonnew file mode 100644index 000000000..2876c5306--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonPathTester/sample.json@@ -0,0 +1,20 @@+{+ "firstName": "John",+ "lastName": "doe",+ "age": 26,+ "address": {+ "streetAddress": "naist street",+ "city": "Nara",+ "postalCode": "630-0192"+ },+ "phoneNumbers": [+ {+ "type": "iPhone",+ "number": "0123-4567-8888"+ },+ {+ "type": "home",+ "number": "0123-4567-8910"+ }+ ]+}\ No newline at end of filediff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/InvalidXml.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/InvalidXml.xmlsimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/InvalidXml.xmlrename to src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/InvalidXml.xmldiff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/InvalidXsd.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/InvalidXsd.xmlsimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/InvalidXsd.xmlrename to src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/InvalidXsd.xmldiff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXml.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXml.xmlsimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXml.xmlrename to src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXml.xmldiff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXmlWithNamespace.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXmlWithNamespace.xmlsimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXmlWithNamespace.xmlrename to src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXmlWithNamespace.xmldiff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXmlWithoutNamespace.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXmlWithoutNamespace.xmlsimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXmlWithoutNamespace.xmlrename to src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXmlWithoutNamespace.xmldiff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsd.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXsd.xmlsimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsd.xmlrename to src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXsd.xmldiff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdOnlyWithTargetNamespace.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXsdOnlyWithTargetNamespace.xmlsimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdOnlyWithTargetNamespace.xmlrename to src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXsdOnlyWithTargetNamespace.xmldiff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdWithNamespace.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXsdWithNamespace.xmlsimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdWithNamespace.xmlrename to src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXsdWithNamespace.xmldiff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdWithoutNamespace.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXsdWithoutNamespace.xmlsimilarity index 100%rename from src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdWithoutNamespace.xmlrename to src/app/tests/DevToys.UnitTests/Tools/TestData/XMLTester/ValidXsdWithoutNamespace.xmldiff --git a/src/app/tests/DevToys.UnitTests/Tools/Testers/JsonPathTester/JsonPathTesterCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Testers/JsonPathTester/JsonPathTesterCommandLineToolTests.csnew file mode 100644index 000000000..f2c14d899--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Testers/JsonPathTester/JsonPathTesterCommandLineToolTests.cs@@ -0,0 +1,53 @@+using System.IO;+using System.Threading;+using System.Threading.Tasks;+using DevToys.CLI;+using DevToys.Tools.Tools.Testers.JsonPathTester;++namespace DevToys.UnitTests.Tools.Testers.JsonPathTester;++public sealed class JsonPathTesterCommandLineToolTests : MefBasedTest+{+ private readonly JsonPathTesterCommandLineTool _tool;++ public JsonPathTesterCommandLineToolTests()+ : base(typeof(JsonPathTesterCommandLineTool).Assembly)+ {+ _tool = (JsonPathTesterCommandLineTool)MefProvider.ImportMany<ICommandLineTool, CommandLineToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "JSONPathTester")+ .Value;+ }++ [Fact]+ public async Task TestJsonPathUi()+ {+ string inputJson = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.JsonPathTester.sample.json");++ _tool.InputJson = inputJson;+ _tool.InputJsonPath = "$.phoneNumbers[:1].type";++ using var consoleOutput = new ConsoleOutputMonitor();+ await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);++ string result = consoleOutput.GetOutput().Trim();+ result.Should().Be(+ @"[+ ""iPhone""+]");+ }++ [Fact]+ public async Task TestJsonPathUiFailed()+ {+ string inputJson = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.JsonPathTester.sample.json");++ _tool.InputJson = inputJson;+ _tool.InputJsonPath = "$.TEST";++ using var consoleOutput = new ConsoleOutputMonitor();+ await _tool.InvokeAsync(new MockILogger(), CancellationToken.None);++ string result = consoleOutput.GetOutput().Trim();+ result.Should().Be("[]");+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Testers/JsonPathTester/JsonPathTesterGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Testers/JsonPathTester/JsonPathTesterGuiToolTests.csnew file mode 100644index 000000000..3b6b39c4c--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Testers/JsonPathTester/JsonPathTesterGuiToolTests.cs@@ -0,0 +1,57 @@+using System.IO;+using System.Threading.Tasks;+using DevToys.Core.Tools.Metadata;+using DevToys.Tools.Tools.Testers.JsonPathTester;++namespace DevToys.UnitTests.Tools.Testers.JsonPathTester;++public sealed class JsonPathTesterGuiToolTests : MefBasedTest+{+ private readonly JsonPathTesterGuiTool _tool;+ private readonly UIToolView _toolView;+ private readonly IUIMultiLineTextInput _inputBox;+ private readonly IUISingleLineTextInput _jsonPathInputBox;+ private readonly IUIMultiLineTextInput _outputBox;+ private readonly string _baseTestDataDirectory = Path.Combine("Tools", "TestData", nameof(JsonPathTester));++ public JsonPathTesterGuiToolTests()+ : base(typeof(JsonPathTesterGuiTool).Assembly)+ {+ _tool = (JsonPathTesterGuiTool)MefProvider.ImportMany<IGuiTool, GuiToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "JSONPathTester")+ .Value;++ _toolView = _tool.View;++ _inputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("input-json-json-path-tester");+ _jsonPathInputBox = (IUISingleLineTextInput)_toolView.GetChildElementById("input-json-path-json-path-tester");+ _outputBox = (IUIMultiLineTextInput)_toolView.GetChildElementById("output-json-path-tester");+ }++ [Fact]+ public async Task TestJsonPathUi()+ {+ string inputJson = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.JsonPathTester.sample.json");++ _inputBox.Text(inputJson);+ _jsonPathInputBox.Text("$.phoneNumbers[:1].type");+ await _tool.WorkTask;++ _outputBox.Text.Should().Be(+ @"[+ ""iPhone""+]");+ }++ [Fact]+ public async Task TestJsonPathUiFailed()+ {+ string inputJson = await TestDataProvider.GetEmbeddedFileContent("DevToys.UnitTests.Tools.TestData.JsonPathTester.sample.json");++ _inputBox.Text(inputJson);+ _jsonPathInputBox.Text("$.TEST");+ await _tool.WorkTask;++ _outputBox.Text.Should().Be("[]");+ }+}