A Swiss Army knife for developers.
C# blazorcross-platformcsharpdesktopdesktop-appdesktop-applicationdeveloper-toolsextensiblefluentfluent-designlinuxmacosmicasyntax-highlightingtypescriptwindowswindows-10windows-11winui
[DevToys 2.0] Added JsonToYaml Converter (#925)
Benjamin TITEUX81c9111d0efe
diff --git a/.gitignore b/.gitignoreindex 13abc3ff2..d2b63d531 100644--- a/.gitignore+++ b/.gitignore@@ -424,6 +424,7 @@ package-lock.json*.js.mapsrc/app/dev/DevToys.Blazor/Assets/**/*.jssrc/app/dev/DevToys.Blazor/Assets/**/*.css+src/app/dev/DevToys.Blazor/Components/**/*.razor.js# Nuke Build.nuke/temp/diff --git a/src/DevToys-Windows.lutconfig b/src/DevToys-Windows.lutconfignew file mode 100644index 000000000..ff7fdf3f6--- /dev/null+++ b/src/DevToys-Windows.lutconfig@@ -0,0 +1,6 @@+<LUTConfig Version="1.0">+ <Repository>..\</Repository>+ <ParallelBuilds>true</ParallelBuilds>+ <ParallelTestRuns>true</ParallelTestRuns>+ <TestCaseTimeout>180000</TestCaseTimeout>+</LUTConfig>\ No newline at end of filediff --git a/src/Directory.Packages.props b/src/Directory.Packages.propsindex 643906268..5d425ccec 100644--- a/src/Directory.Packages.props+++ b/src/Directory.Packages.props@@ -22,8 +22,9 @@<PackageVersion Include="Microsoft.Extensions.Logging.Debug" Version="$(DotNetVersion)" Condition="'$(UseMaui)' != 'true'" /><PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.1.0" /><PackageVersion Include="Microsoft.TypeScript.MSBuild" Version="5.1.5" />- <PackageVersion Include="Microsoft.Windows.CsWin32" Version="0.3.18-beta"/>+ <PackageVersion Include="Microsoft.Windows.CsWin32" Version="0.3.18-beta" /><PackageVersion Include="Moq" Version="4.18.4" />+ <PackageVersion Include="Newtonsoft.Json" Version="13.0.3" /><PackageVersion Include="NuGet.Packaging" Version="6.6.1" /><PackageVersion Include="Nuke.Common" Version="7.0.2" /><PackageVersion Include="System.Text.Json" Version="$(DotNetVersion)" />@@ -32,5 +33,6 @@<PackageVersion Include="System.Threading.Tasks.Extensions" Version="4.5.4" /><PackageVersion Include="xunit" Version="$(XUnit)" /><PackageVersion Include="xunit.runner.visualstudio" Version="$(XUnit)" />+ <PackageVersion Include="YamlDotNet" Version="13.0.0" /></ItemGroup></Project>\ No newline at end of filediff --git a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISetting.cs b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISetting.csindex 2dee3d174..4247d644c 100644--- a/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISetting.cs+++ b/src/app/dev/DevToys.Api/Tool/GUI/Components/IUISetting.cs@@ -312,23 +312,7 @@ public static partial class GUIT currentSettingValue = settingsProvider.GetSetting(settingDefinition);- dropDownList.Select(- dropDownList.Items?.FirstOrDefault((IUIDropDownListItem item) =>- {- if (item.Value is null)- {- if (currentSettingValue is null)- {- return true;- }-- return false;- }-- Guard.IsOfType<T>(item.Value);-- return item.Value.Equals(currentSettingValue);- }));+ dropDownList.Select(FindItemInDropDownList<T>(dropDownList, currentSettingValue));dropDownList.OnItemSelected((IUIDropDownListItem? item) =>{@@ -344,6 +328,19 @@ public static partial class GUIreturn ValueTask.CompletedTask;});+ settingsProvider.SettingChanged += (object? sender, SettingChangedEventArgs e) =>+ {+ if (e.SettingName == settingDefinition.Name)+ {+ IUIDropDownListItem? itemToSelect = FindItemInDropDownList<T>(dropDownList, e.NewValue);++ if (itemToSelect is not null && dropDownList.SelectedItem != itemToSelect)+ {+ dropDownList.Select(itemToSelect);+ }+ }+ };+settingElement.InteractiveElement(dropDownList);return element;}@@ -400,7 +397,62 @@ public static partial class GUIreturn ValueTask.CompletedTask;});+ settingsProvider.SettingChanged += (object? sender, SettingChangedEventArgs e) =>+ {+ if (e.SettingName == settingDefinition.Name)+ {+ Guard.IsOfType<bool>(e.NewValue!);+ bool settingValue = (bool)e.NewValue!;+ if (settingValue)+ {+ if (!toggleSwitch.IsOn)+ {+ toggleSwitch.On();+ if (!ignoreStateDescription)+ {+ settingElement.StateDescription = stateDescriptionWhenOn;+ }+ }+ }+ else+ {+ if (toggleSwitch.IsOn)+ {+ toggleSwitch.Off();+ if (!ignoreStateDescription)+ {+ settingElement.StateDescription = stateDescriptionWhenOff;+ }+ }+ }+ }+ };+settingElement.InteractiveElement(toggleSwitch);return element;}++ private static IUIDropDownListItem? FindItemInDropDownList<T>(IUISelectDropDownList element, object? value)+ {+ return element.Items?.FirstOrDefault((IUIDropDownListItem item) =>+ {+ if (item.Value is null)+ {+ if (value is null)+ {+ return true;+ }++ return false;+ }++ Guard.IsOfType<T>(item.Value);+ if (value is not null)+ {+ Guard.IsOfType<T>(value);+ }++ return item.Value.Equals(value);+ });+ }}diff --git a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.csindex 58ba99452..a0a2fe553 100644--- a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs+++ b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs@@ -4,6 +4,7 @@ public static class PredefinedCommonDataTypeNames{public const string Text = "text";public const string Json = "json";+ public const string Yaml = "yaml";public const string Base64Text = "base64Text";public const string Image = "image";public const string File = "file";diff --git a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditor.razor.cs b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditor.razor.csindex 0cd1b1e3d..eef9fcdb1 100644--- a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditor.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditor.razor.cs@@ -102,7 +102,7 @@ public partial class MonacoEditor : RicherMonacoEditorBaseawait MonacoEditorHelper.CreateMonacoEditorInstanceAsync(JSRuntime, Id, options, null, Reference);}- if (IsActuallyEnabled != _oldIsActuallyEnabled)+ if (IsActuallyEnabled != _oldIsActuallyEnabled && !_isDisposed){_oldIsActuallyEnabled = IsActuallyEnabled;@@ -146,23 +146,32 @@ public partial class MonacoEditor : RicherMonacoEditorBase{_isLoaded = true;ShowLoading = false;++ if (_settingsProvider is not null)+ {+ SettingsProvider_SettingChanged(_settingsProvider, null!);+ }+StateHasChanged();}}private void SettingsProvider_SettingChanged(object? sender, SettingChangedEventArgs e){- var options = new EditorUpdateOptions()+ if (_isLoaded){- FontFamily = _settingsProvider.GetSetting(PredefinedSettings.TextEditorFont),- LineNumbers = _settingsProvider.GetSetting(PredefinedSettings.TextEditorLineNumbers) ? "on" : "off",- RenderLineHighlight = _settingsProvider.GetSetting(PredefinedSettings.TextEditorHighlightCurrentLine) ? "all" : "none",- RenderWhitespace = _settingsProvider.GetSetting(PredefinedSettings.TextEditorRenderWhitespace) ? "all" : "none"- };+ var options = new EditorUpdateOptions()+ {+ FontFamily = _settingsProvider.GetSetting(PredefinedSettings.TextEditorFont),+ LineNumbers = _settingsProvider.GetSetting(PredefinedSettings.TextEditorLineNumbers) ? "on" : "off",+ RenderLineHighlight = _settingsProvider.GetSetting(PredefinedSettings.TextEditorHighlightCurrentLine) ? "all" : "none",+ RenderWhitespace = _settingsProvider.GetSetting(PredefinedSettings.TextEditorRenderWhitespace) ? "all" : "none"+ };- ApplyWordWrapOption(options);+ ApplyWordWrapOption(options);- UpdateOptionsAsync(options);+ UpdateOptionsAsync(options);+ }}private void ThemeListener_ThemeChanged(object? sender, EventArgs e)diff --git a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditorBase.cs b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditorBase.csindex c0b9d3cd6..2422b59ca 100644--- a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditorBase.cs+++ b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/MonacoEditorBase.cs@@ -9,6 +9,8 @@ public abstract class MonacoEditorBase : MefComponentBase, IFocusableprivate static readonly object themeDefinedLock = new();private static bool isThemeDefined;+ protected bool _isDisposed;+[Parameter]public EventCallback OnDidDispose { get; set; }@@ -111,6 +113,8 @@ public abstract class MonacoEditorBase : MefComponentBase, IFocusablepublic override async ValueTask DisposeAsync(){+ _isDisposed = true;+try{await JSRuntime.InvokeVoidWithErrorHandlingAsync("devtoys.MonacoEditor.dispose", Id);diff --git a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/RicherMonacoEditorBase.cs b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/RicherMonacoEditorBase.csindex dd97751af..99940ec55 100644--- a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/RicherMonacoEditorBase.cs+++ b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/RicherMonacoEditorBase.cs@@ -176,6 +176,11 @@ public class RicherMonacoEditorBase : MonacoEditorBaseinternal override async Task SetEventListenersAsync(){+ if (_isDisposed)+ {+ return;+ }+if (OnDidCompositionEnd.HasDelegate){await SetEventListenerAsync(nameof(OnDidCompositionEnd));@@ -315,141 +320,144 @@ public class RicherMonacoEditorBase : MonacoEditorBaseeventJson ??= string.Empty;var jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };- switch (eventName)- {- case nameof(OnDidCompositionEnd):- await OnDidCompositionEnd.InvokeAsync(this);- break;-- case nameof(OnDidCompositionStart):- await OnDidCompositionStart.InvokeAsync(this);- break;-- case nameof(OnContextMenu):- if (!string.IsNullOrEmpty(eventJson))- {- await OnContextMenu.InvokeAsync(JsonSerializer.Deserialize<EditorMouseEvent>(eventJson, jsonOptions));- }- break;-- case nameof(OnDidBlurEditorText):- await OnDidBlurEditorText.InvokeAsync(this);- break;-- case nameof(OnDidBlurEditorWidget):- await OnDidBlurEditorWidget.InvokeAsync(this);- break;-- case nameof(OnDidChangeConfiguration):- await OnDidChangeConfiguration.InvokeAsync(new ConfigurationChangedEvent(JsonSerializer.Deserialize<List<bool>?>(eventJson, jsonOptions)));- break;-- case nameof(OnDidChangeCursorPosition):- await OnDidChangeCursorPosition.InvokeAsync(JsonSerializer.Deserialize<CursorPositionChangedEvent>(eventJson, jsonOptions));- break;-- case nameof(OnDidChangeCursorSelection):- await OnDidChangeCursorSelection.InvokeAsync(JsonSerializer.Deserialize<CursorSelectionChangedEvent>(eventJson, jsonOptions));- break;-- case nameof(OnDidChangeModel):- await OnDidChangeModel.InvokeAsync(JsonSerializer.Deserialize<ModelChangedEvent>(eventJson, jsonOptions));- break;-- case nameof(OnDidChangeModelContent):- await OnDidChangeModelContent.InvokeAsync(JsonSerializer.Deserialize<ModelContentChangedEvent>(eventJson, jsonOptions));- break;-- case nameof(OnDidChangeModelDecorations):- await OnDidChangeModelDecorations.InvokeAsync(JsonSerializer.Deserialize<ModelDecorationsChangedEvent>(eventJson, jsonOptions));- break;-- case nameof(OnDidChangeModelLanguage):- await OnDidChangeModelLanguage.InvokeAsync(JsonSerializer.Deserialize<ModelLanguageChangedEvent>(eventJson, jsonOptions));- break;-- case nameof(OnDidChangeModelLanguageConfiguration):- await OnDidChangeModelLanguageConfiguration.InvokeAsync(JsonSerializer.Deserialize<ModelLanguageConfigurationChangedEvent>(eventJson, jsonOptions));- break;-- case nameof(OnDidChangeModelOptions):- await OnDidChangeModelOptions.InvokeAsync(JsonSerializer.Deserialize<ModelOptionsChangedEvent>(eventJson, jsonOptions));- break;-- case nameof(OnDidContentSizeChange):- await OnDidContentSizeChange.InvokeAsync(JsonSerializer.Deserialize<ContentSizeChangedEvent>(eventJson, jsonOptions));- break;-- case nameof(OnDidFocusEditorText):- await OnDidFocusEditorText.InvokeAsync(this);- break;-- case nameof(OnDidFocusEditorWidget):- await OnDidFocusEditorWidget.InvokeAsync(this);- break;-- case nameof(OnDidLayoutChange):- if (!string.IsNullOrEmpty(eventJson))- {- await OnDidLayoutChange.InvokeAsync(JsonSerializer.Deserialize<EditorLayoutInfo>(eventJson, jsonOptions));- }- break;-- case nameof(OnDidPaste):- if (!string.IsNullOrEmpty(eventJson))- {- await OnDidPaste.InvokeAsync(JsonSerializer.Deserialize<PasteEvent>(eventJson, jsonOptions));- }- break;-- case nameof(OnDidScrollChange):- if (!string.IsNullOrEmpty(eventJson))- {- await OnDidScrollChange.InvokeAsync(JsonSerializer.Deserialize<ScrollEvent>(eventJson, jsonOptions));- }- break;-- case nameof(OnKeyDown):- if (!string.IsNullOrEmpty(eventJson))- {- await OnKeyDown.InvokeAsync(JsonSerializer.Deserialize<KeyboardEvent>(eventJson, jsonOptions));- }- break;-- case nameof(OnKeyUp):- if (!string.IsNullOrEmpty(eventJson))- {- await OnKeyUp.InvokeAsync(JsonSerializer.Deserialize<KeyboardEvent>(eventJson, jsonOptions));- }- break;-- case nameof(OnMouseDown):- if (!string.IsNullOrEmpty(eventJson))- {- await OnMouseDown.InvokeAsync(JsonSerializer.Deserialize<EditorMouseEvent>(eventJson, jsonOptions));- }- break;-- case nameof(OnMouseLeave):- if (!string.IsNullOrEmpty(eventJson))- {- await OnMouseLeave.InvokeAsync(JsonSerializer.Deserialize<PartialEditorMouseEvent>(eventJson, jsonOptions));- }- break;-- case nameof(OnMouseMove):- if (!string.IsNullOrEmpty(eventJson))- {- await OnMouseMove.InvokeAsync(JsonSerializer.Deserialize<EditorMouseEvent>(eventJson, jsonOptions));- }- break;-- case nameof(OnMouseUp):- if (!string.IsNullOrEmpty(eventJson))- {- await OnMouseUp.InvokeAsync(JsonSerializer.Deserialize<EditorMouseEvent>(eventJson, jsonOptions));- }- break;+ if (!_isDisposed)+ {+ switch (eventName)+ {+ case nameof(OnDidCompositionEnd):+ await OnDidCompositionEnd.InvokeAsync(this);+ break;++ case nameof(OnDidCompositionStart):+ await OnDidCompositionStart.InvokeAsync(this);+ break;++ case nameof(OnContextMenu):+ if (!string.IsNullOrEmpty(eventJson))+ {+ await OnContextMenu.InvokeAsync(JsonSerializer.Deserialize<EditorMouseEvent>(eventJson, jsonOptions));+ }+ break;++ case nameof(OnDidBlurEditorText):+ await OnDidBlurEditorText.InvokeAsync(this);+ break;++ case nameof(OnDidBlurEditorWidget):+ await OnDidBlurEditorWidget.InvokeAsync(this);+ break;++ case nameof(OnDidChangeConfiguration):+ await OnDidChangeConfiguration.InvokeAsync(new ConfigurationChangedEvent(JsonSerializer.Deserialize<List<bool>?>(eventJson, jsonOptions)));+ break;++ case nameof(OnDidChangeCursorPosition):+ await OnDidChangeCursorPosition.InvokeAsync(JsonSerializer.Deserialize<CursorPositionChangedEvent>(eventJson, jsonOptions));+ break;++ case nameof(OnDidChangeCursorSelection):+ await OnDidChangeCursorSelection.InvokeAsync(JsonSerializer.Deserialize<CursorSelectionChangedEvent>(eventJson, jsonOptions));+ break;++ case nameof(OnDidChangeModel):+ await OnDidChangeModel.InvokeAsync(JsonSerializer.Deserialize<ModelChangedEvent>(eventJson, jsonOptions));+ break;++ case nameof(OnDidChangeModelContent):+ await OnDidChangeModelContent.InvokeAsync(JsonSerializer.Deserialize<ModelContentChangedEvent>(eventJson, jsonOptions));+ break;++ case nameof(OnDidChangeModelDecorations):+ await OnDidChangeModelDecorations.InvokeAsync(JsonSerializer.Deserialize<ModelDecorationsChangedEvent>(eventJson, jsonOptions));+ break;++ case nameof(OnDidChangeModelLanguage):+ await OnDidChangeModelLanguage.InvokeAsync(JsonSerializer.Deserialize<ModelLanguageChangedEvent>(eventJson, jsonOptions));+ break;++ case nameof(OnDidChangeModelLanguageConfiguration):+ await OnDidChangeModelLanguageConfiguration.InvokeAsync(JsonSerializer.Deserialize<ModelLanguageConfigurationChangedEvent>(eventJson, jsonOptions));+ break;++ case nameof(OnDidChangeModelOptions):+ await OnDidChangeModelOptions.InvokeAsync(JsonSerializer.Deserialize<ModelOptionsChangedEvent>(eventJson, jsonOptions));+ break;++ case nameof(OnDidContentSizeChange):+ await OnDidContentSizeChange.InvokeAsync(JsonSerializer.Deserialize<ContentSizeChangedEvent>(eventJson, jsonOptions));+ break;++ case nameof(OnDidFocusEditorText):+ await OnDidFocusEditorText.InvokeAsync(this);+ break;++ case nameof(OnDidFocusEditorWidget):+ await OnDidFocusEditorWidget.InvokeAsync(this);+ break;++ case nameof(OnDidLayoutChange):+ if (!string.IsNullOrEmpty(eventJson))+ {+ await OnDidLayoutChange.InvokeAsync(JsonSerializer.Deserialize<EditorLayoutInfo>(eventJson, jsonOptions));+ }+ break;++ case nameof(OnDidPaste):+ if (!string.IsNullOrEmpty(eventJson))+ {+ await OnDidPaste.InvokeAsync(JsonSerializer.Deserialize<PasteEvent>(eventJson, jsonOptions));+ }+ break;++ case nameof(OnDidScrollChange):+ if (!string.IsNullOrEmpty(eventJson))+ {+ await OnDidScrollChange.InvokeAsync(JsonSerializer.Deserialize<ScrollEvent>(eventJson, jsonOptions));+ }+ break;++ case nameof(OnKeyDown):+ if (!string.IsNullOrEmpty(eventJson))+ {+ await OnKeyDown.InvokeAsync(JsonSerializer.Deserialize<KeyboardEvent>(eventJson, jsonOptions));+ }+ break;++ case nameof(OnKeyUp):+ if (!string.IsNullOrEmpty(eventJson))+ {+ await OnKeyUp.InvokeAsync(JsonSerializer.Deserialize<KeyboardEvent>(eventJson, jsonOptions));+ }+ break;++ case nameof(OnMouseDown):+ if (!string.IsNullOrEmpty(eventJson))+ {+ await OnMouseDown.InvokeAsync(JsonSerializer.Deserialize<EditorMouseEvent>(eventJson, jsonOptions));+ }+ break;++ case nameof(OnMouseLeave):+ if (!string.IsNullOrEmpty(eventJson))+ {+ await OnMouseLeave.InvokeAsync(JsonSerializer.Deserialize<PartialEditorMouseEvent>(eventJson, jsonOptions));+ }+ break;++ case nameof(OnMouseMove):+ if (!string.IsNullOrEmpty(eventJson))+ {+ await OnMouseMove.InvokeAsync(JsonSerializer.Deserialize<EditorMouseEvent>(eventJson, jsonOptions));+ }+ break;++ case nameof(OnMouseUp):+ if (!string.IsNullOrEmpty(eventJson))+ {+ await OnMouseUp.InvokeAsync(JsonSerializer.Deserialize<EditorMouseEvent>(eventJson, jsonOptions));+ }+ break;+ }}await base.EventCallbackAsync(eventName, eventJson);@@ -710,6 +718,11 @@ public class RicherMonacoEditorBase : MonacoEditorBaseinternal ValueTask<bool> UpdateOptionsAsync(EditorUpdateOptions newOptions){+ if (_isDisposed)+ {+ return new ValueTask<bool>(false);+ }+// Convert the options object into a JsonElement to get rid of the properties with null valuesstring optionsJson = JsonSerializer.Serialize(newOptions, new JsonSerializerOptions{diff --git a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/RicherMonacoEditorDiffBase.cs b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/RicherMonacoEditorDiffBase.csindex 661fc5c4e..08831a927 100644--- a/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/RicherMonacoEditorDiffBase.cs+++ b/src/app/dev/DevToys.Blazor/Components/Text/MonacoEditor/RicherMonacoEditorDiffBase.cs@@ -302,10 +302,14 @@ public abstract class RicherMonacoEditorDiffBase : MonacoEditorBase[JSInvokable]public override async Task EventCallbackAsync(string eventName, string eventJson){- switch (eventName)+ if (!_isDisposed){- case "OnDidUpdateDiff": await OnDidUpdateDiff.InvokeAsync(this); break;+ switch (eventName)+ {+ case "OnDidUpdateDiff": await OnDidUpdateDiff.InvokeAsync(this); break;+ }}+await base.EventCallbackAsync(eventName, eventJson);}diff --git a/src/app/dev/DevToys.Blazor/Components/UIElements/UIDiffTextInputPresenter.razor.cs b/src/app/dev/DevToys.Blazor/Components/UIElements/UIDiffTextInputPresenter.razor.csindex e198337b8..56d7c92ff 100644--- a/src/app/dev/DevToys.Blazor/Components/UIElements/UIDiffTextInputPresenter.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/UIElements/UIDiffTextInputPresenter.razor.cs@@ -3,7 +3,7 @@ using DevToys.Blazor.Components.Monaco.Editor;namespace DevToys.Blazor.Components.UIElements;-public partial class UIDiffTextInputPresenter : JSStyledComponentBase, IDisposable+public partial class UIDiffTextInputPresenter : JSStyledComponentBase{private MonacoEditorDiff _monacoEditor = default!;private bool _isInFullScreenMode;@@ -32,13 +32,13 @@ public partial class UIDiffTextInputPresenter : JSStyledComponentBase, IDisposabUIDiffTextInput.InlineModeChanged += UIDiffTextInput_InlineModeChanged;}- public void Dispose()+ public override ValueTask DisposeAsync(){UIDiffTextInput.TextChanged -= UIMultiLineTextInput_TextChanged;UIDiffTextInput.ModifiedTextChanged -= UIDiffTextInput_RightTextChanged;UIDiffTextInput.IsReadOnlyChanged -= UIMultiLineTextInput_IsReadOnlyChanged;UIDiffTextInput.InlineModeChanged -= UIDiffTextInput_InlineModeChanged;- GC.SuppressFinalize(this);+ return base.DisposeAsync();}private async Task OnMonacoEditorInitializedAsync()diff --git a/src/app/dev/DevToys.Blazor/Components/UIElements/UIMultiLineTextInputPresenter.razor.cs b/src/app/dev/DevToys.Blazor/Components/UIElements/UIMultiLineTextInputPresenter.razor.csindex bdbd38982..3b097a245 100644--- a/src/app/dev/DevToys.Blazor/Components/UIElements/UIMultiLineTextInputPresenter.razor.cs+++ b/src/app/dev/DevToys.Blazor/Components/UIElements/UIMultiLineTextInputPresenter.razor.cs@@ -3,8 +3,10 @@ using DevToys.Blazor.Components.Monaco.Editor;namespace DevToys.Blazor.Components.UIElements;-public partial class UIMultiLineTextInputPresenter : JSStyledComponentBase, IDisposable+public partial class UIMultiLineTextInputPresenter : JSStyledComponentBase{+ private readonly TaskCompletionSource _monacoInitializationAwaiter = new();+private MonacoEditor _monacoEditor = default!;private UITextInputWrapper _textInputWrapper = default!;private bool _ignoreChangeComingFromUIMultiLineTextInput;@@ -22,29 +24,33 @@ public partial class UIMultiLineTextInputPresenter : JSStyledComponentBase, IDisUIMultiLineTextInput.IsReadOnlyChanged += UIMultiLineTextInput_IsReadOnlyChanged;}- public void Dispose()+ public override ValueTask DisposeAsync(){UIMultiLineTextInput.SyntaxColorizationLanguageNameChanged -= UIMultiLineTextInput_SyntaxColorizationLanguageNameChanged;UIMultiLineTextInput.TextChanged -= UIMultiLineTextInput_TextChanged;UIMultiLineTextInput.IsReadOnlyChanged -= UIMultiLineTextInput_IsReadOnlyChanged;- GC.SuppressFinalize(this);++ return base.DisposeAsync();}- private void UIMultiLineTextInput_TextChanged(object? sender, EventArgs e)+ private async void UIMultiLineTextInput_TextChanged(object? sender, EventArgs e){if (!_ignoreChangeComingFromUIMultiLineTextInput){- _ = _monacoEditor.SetValueAsync(UIMultiLineTextInput.Text);+ await _monacoInitializationAwaiter.Task;+ await _monacoEditor.SetValueAsync(UIMultiLineTextInput.Text);}}private async void UIMultiLineTextInput_SyntaxColorizationLanguageNameChanged(object? sender, EventArgs e){+ await _monacoInitializationAwaiter.Task;await _monacoEditor.SetLanguageAsync(UIMultiLineTextInput.SyntaxColorizationLanguageName);}private async void UIMultiLineTextInput_IsReadOnlyChanged(object? sender, EventArgs e){+ await _monacoInitializationAwaiter.Task;await _monacoEditor.UpdateOptionsAsync(new EditorUpdateOptions{ReadOnly = UIMultiLineTextInput.IsReadOnly@@ -53,9 +59,16 @@ public partial class UIMultiLineTextInputPresenter : JSStyledComponentBase, IDisprivate async Task OnMonacoEditorTextChangedAsync(ModelContentChangedEvent ev){- _ignoreChangeComingFromUIMultiLineTextInput = true;- UIMultiLineTextInput.Text(await _monacoEditor.GetValueAsync(preserveBOM: null, lineEnding: null));- _ignoreChangeComingFromUIMultiLineTextInput = false;+ if (ev.Changes is not null)+ {+ _ignoreChangeComingFromUIMultiLineTextInput = true;++ string documentText = await _monacoEditor.GetValueAsync(preserveBOM: null, lineEnding: null);++ UIMultiLineTextInput.Text(documentText);++ _ignoreChangeComingFromUIMultiLineTextInput = false;+ }}private async Task OnMonacoEditorInitializedAsync()@@ -77,6 +90,8 @@ public partial class UIMultiLineTextInputPresenter : JSStyledComponentBase, IDis// Set the text of modelawait textModel.SetValueAsync(JSRuntime, UIMultiLineTextInput.Text);++ _monacoInitializationAwaiter.TrySetResult();}private StandaloneEditorConstructionOptions OnMonacoConstructionOptions(MonacoEditor monacoEditor)diff --git a/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs b/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.csindex 3753cbff9..49d3161f2 100644--- a/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs+++ b/src/app/dev/DevToys.Business/ViewModels/MainWindowViewModel.cs@@ -116,6 +116,7 @@ internal sealed partial class MainWindowViewModel : ObservableRecipient= _oldSmartDetectedTools.FirstOrDefault(tool => tool.ToolInstance == guiToolViewItem.ToolInstance);if (smartDetectedTool is not null){+ _ = guiToolViewItem.ToolInstance.View; // Do nothing with the view but trigger to instance because PassSmartDetectedData may assume the UI is instantiated.guiToolViewItem.ToolInstance.PassSmartDetectedData(smartDetectedTool.DataTypeName, smartDetectedTool.ParsedData);}}@@ -352,7 +353,6 @@ internal sealed partial class MainWindowViewModel : ObservableRecipient{// Select the actual menu item in the navigation view. This will trigger the navigation.SelectedMenuItem = GetBestMenuItemToSelect(message.Value);- message.SmartDetectionInfo?.ToolInstance.PassSmartDetectedData(message.SmartDetectionInfo.DataTypeName, message.SmartDetectionInfo.ParsedData);}[LoggerMessage(1, LogLevel.Warning, "Failed to perform smart detection.")]diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csprojindex 56be91027..b1fbf42bb 100644--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj@@ -39,6 +39,16 @@<DesignTime>True</DesignTime><AutoGen>True</AutoGen></Compile>+ <Compile Update="Tools\Converters\Converters.Designer.cs">+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ <DependentUpon>Converters.resx</DependentUpon>+ </Compile>+ <Compile Update="Tools\Converters\JsonYaml\JsonYamlConverter.Designer.cs">+ <DesignTime>True</DesignTime>+ <AutoGen>True</AutoGen>+ <DependentUpon>JsonYamlConverter.resx</DependentUpon>+ </Compile><Compile Update="Tools\EncodersDecoders\Html\HtmlEncoderDecoder.Designer.cs"><DependentUpon>HtmlEncoderDecoder.resx</DependentUpon><DesignTime>True</DesignTime>@@ -69,6 +79,14 @@<LastGenOutput>UrlEncoderDecoder.Designer.cs</LastGenOutput><Generator>ResXFileCodeGenerator</Generator></EmbeddedResource>+ <EmbeddedResource Update="Tools\Converters\Converters.resx">+ <Generator>ResXFileCodeGenerator</Generator>+ <LastGenOutput>Converters.Designer.cs</LastGenOutput>+ </EmbeddedResource>+ <EmbeddedResource Update="Tools\Converters\JsonYaml\JsonYamlConverter.resx">+ <Generator>ResXFileCodeGenerator</Generator>+ <LastGenOutput>JsonYamlConverter.Designer.cs</LastGenOutput>+ </EmbeddedResource><EmbeddedResource Update="Tools\EncodersDecoders\Html\HtmlEncoderDecoder.resx"><LastGenOutput>HtmlEncoderDecoder.Designer.cs</LastGenOutput><Generator>ResXFileCodeGenerator</Generator>@@ -92,10 +110,22 @@</ItemGroup><ItemGroup>+ <PackageReference Include="Newtonsoft.Json" /><PackageReference Include="System.Text.Json" />+ <PackageReference Include="YamlDotNet" /></ItemGroup>- <Target Name="CopyPluginAfterBuild" AfterTargets="Pack">+ <Target Name="IncludeAllFilesInTargetDir" AfterTargets="Build">+ <ItemGroup>+ <None Include="$(OutputPath)\**">+ <Pack>true</Pack>+ <PackagePath>lib</PackagePath>+ </None>+ </ItemGroup>+ </Target>++ <Target DependsOnTargets="IncludeAllFilesInTargetDir" Name="CopyPluginAfterBuild" AfterTargets="Pack"><Copy SourceFiles="$(PackageOutputPath)\$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(PluginNupkgPath)" SkipUnchangedFiles="false" OverwriteReadOnlyFiles="true" Retries="10" RetryDelayMilliseconds="1000" /></Target>+</Project>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Helpers/Base64Helper.cs b/src/app/dev/DevToys.Tools/Helpers/Base64Helper.csindex 223e78c70..62f9f281a 100644--- a/src/app/dev/DevToys.Tools/Helpers/Base64Helper.cs+++ b/src/app/dev/DevToys.Tools/Helpers/Base64Helper.cs@@ -169,12 +169,12 @@ internal static partial class Base64Helperprivate static void LogFailEncodeBase64(ILogger logger, Exception exception, Base64Encoding encoding){- logger.LogError(0, exception, $"Failed to encode text to Base64. Encoding mode: {encoding}");+ logger.LogError(0, exception, "Failed to encode text to Base64. Encoding mode: '{encoding}'", encoding);}private static void LogFailDecodeBase64(ILogger logger, Exception exception, Base64Encoding encoding){- logger.LogError(1, exception, $"Failed to decode Base64t to text. Encoding mode: {encoding}");+ logger.LogError(1, exception, "Failed to decode Base64t to text. Encoding mode: '{encoding}'", encoding);}[GeneratedRegex("[^A-Z0-9+/=]", RegexOptions.IgnoreCase, "en-US")]diff --git a/src/app/dev/DevToys.Tools/Helpers/Core/BooleanYamlTypeResolver.cs b/src/app/dev/DevToys.Tools/Helpers/Core/BooleanYamlTypeResolver.csnew file mode 100644index 000000000..21a351f49--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/Core/BooleanYamlTypeResolver.cs@@ -0,0 +1,26 @@+using YamlDotNet.Core;+using YamlDotNet.Core.Events;+using YamlDotNet.Serialization;++namespace DevToys.Tools.Helpers.Core;++internal class BooleanYamlTypeResolver : INodeTypeResolver+{+ public bool Resolve(NodeEvent? nodeEvent, ref Type currentType)+ {+ if (nodeEvent is Scalar scalar)+ {+ // avoid unnecessary parsing attempts+ bool couldBeBoolean+ = scalar.Style is ScalarStyle.Plain+ && (string.Equals(scalar.Value, bool.FalseString, StringComparison.OrdinalIgnoreCase) || string.Equals(scalar.Value, bool.TrueString, StringComparison.OrdinalIgnoreCase));++ if (couldBeBoolean && bool.TryParse(scalar.Value, out _))+ {+ currentType = typeof(bool);+ return true;+ }+ }+ return false;+ }+}diff --git a/src/app/dev/DevToys.Tools/Helpers/Core/DecimalJsonConverter.cs b/src/app/dev/DevToys.Tools/Helpers/Core/DecimalJsonConverter.csnew file mode 100644index 000000000..599812caf--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/Core/DecimalJsonConverter.cs@@ -0,0 +1,21 @@+using Newtonsoft.Json;++namespace DevToys.Tools.Helpers.Core;+internal class DecimalJsonConverter : JsonConverter<decimal>+{+ public override decimal ReadJson(+ JsonReader reader,+ Type objectType,+ decimal existingValue,+ bool hasExistingValue,+ JsonSerializer serializer)+ {+ throw new NotImplementedException();+ }++ public override void WriteJson(JsonWriter writer, decimal value, JsonSerializer serializer)+ {+ // prevent adding trailing zeros+ writer.WriteRawValue(value.ToString());+ }+}diff --git a/src/app/dev/DevToys.Tools/Helpers/Core/DecimalYamlTypeResolver.cs b/src/app/dev/DevToys.Tools/Helpers/Core/DecimalYamlTypeResolver.csnew file mode 100644index 000000000..91a1e53b1--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/Core/DecimalYamlTypeResolver.cs@@ -0,0 +1,27 @@+using YamlDotNet.Core;+using YamlDotNet.Core.Events;+using YamlDotNet.Serialization;++namespace DevToys.Tools.Helpers.Core;++internal class DecimalYamlTypeResolver : INodeTypeResolver+{+ public bool Resolve(NodeEvent? nodeEvent, ref Type currentType)+ {+ if (nodeEvent is Scalar scalar)+ {+ // avoid unnecessary parsing attempts+ bool couldBeNumber =+ scalar.Style is not ScalarStyle.SingleQuoted and not ScalarStyle.DoubleQuoted &&+ scalar.Value.Length != 0 &&+ (scalar.Value[0] is >= '0' and <= '9' || scalar.Value[0] == '-');++ if (couldBeNumber && decimal.TryParse(scalar.Value, out _))+ {+ currentType = typeof(decimal);+ return true;+ }+ }+ return false;+ }+}diff --git a/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs b/src/app/dev/DevToys.Tools/Helpers/JsonHelper.csnew file mode 100644index 000000000..27beb23b6--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/JsonHelper.cs@@ -0,0 +1,255 @@+using System.Text;+using DevToys.Tools.Helpers.Core;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;+using Newtonsoft.Json;+using Newtonsoft.Json.Linq;+using YamlDotNet.Core;+using YamlDotNet.Serialization;++namespace DevToys.Tools.Helpers;++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)+ {+ input = input?.Trim();++ if (input == null)+ {+ return true;+ }++ if (long.TryParse(input, out _))+ {+ return false;+ }++ try+ {+ var jtoken = JToken.Parse(input);+ return jtoken is not null;+ }+ catch (JsonReaderException)+ {+ // Exception in parsing json. It likely mean the text isn't a JSON.+ return false;+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "Invalid data detected 'input'", input);+ return false;+ }+ }++ /// <summary>+ /// Format a string to the specified JSON format.+ /// </summary>+ internal static async ValueTask<string> Format(+ string? input,+ Indentation indentationMode,+ bool sortProperties,+ ILogger logger,+ CancellationToken cancellationToken)+ {+ if (input == null || !IsValid(input, logger))+ {+ return string.Empty;+ }++ try+ {+ var jsonLoadSettings = new JsonLoadSettings()+ {+ CommentHandling = CommentHandling.Ignore,+ DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Ignore,+ LineInfoHandling = LineInfoHandling.Load+ };++ JToken jToken;+ using (var jsonReader = new JsonTextReader(new StringReader(input)))+ {+ jsonReader.DateParseHandling = DateParseHandling.None;+ jsonReader.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;++ jToken = await JToken.LoadAsync(jsonReader, jsonLoadSettings, cancellationToken);+ }++ if (sortProperties)+ {+ if (jToken is JObject obj)+ {+ SortJsonPropertiesAlphabetically(obj);+ }+ else if (jToken is JArray array)+ {+ SortJsonPropertiesAlphabetically(array);+ }+ }++ var stringBuilder = new StringBuilder();+ using (var stringWriter = new StringWriter(stringBuilder))+ using (var jsonTextWriter = new JsonTextWriter(stringWriter))+ {+ switch (indentationMode)+ {+ case Indentation.TwoSpaces:+ jsonTextWriter.Formatting = Formatting.Indented;+ jsonTextWriter.IndentChar = ' ';+ jsonTextWriter.Indentation = 2;+ break;+ case Indentation.FourSpaces:+ jsonTextWriter.Formatting = Formatting.Indented;+ jsonTextWriter.IndentChar = ' ';+ jsonTextWriter.Indentation = 4;+ break;+ case Indentation.OneTab:+ jsonTextWriter.Formatting = Formatting.Indented;+ jsonTextWriter.IndentChar = '\t';+ jsonTextWriter.Indentation = 1;+ break;+ case Indentation.Minified:+ jsonTextWriter.Formatting = Formatting.None;+ break;+ default:+ throw new NotSupportedException();+ }++ jsonTextWriter.DateFormatHandling = DateFormatHandling.IsoDateFormat;+ jsonTextWriter.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;++ jToken.WriteTo(jsonTextWriter);+ }++ return stringBuilder.ToString();+ }+ catch (JsonReaderException ex)+ {+ return ex.Message;+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "Invalid JSON format 'indentationMode'", indentationMode);+ return ex.Message;+ }+ }++ /// <summary>+ /// Convert a Yaml string to Json+ /// </summary>+ internal static ToolResult<string> ConvertFromYaml(+ string? input,+ Indentation indentationMode,+ ILogger logger,+ CancellationToken cancellationToken)+ {+ if (string.IsNullOrWhiteSpace(input))+ {+ return new(string.Empty, false);+ }++ try+ {+ using var stringReader = new StringReader(input);++ IDeserializer deserializer = new DeserializerBuilder()+ .WithNodeTypeResolver(new DecimalYamlTypeResolver())+ .WithNodeTypeResolver(new BooleanYamlTypeResolver())+ .Build();++ object? yamlObject = deserializer.Deserialize(stringReader);++ if (yamlObject is null or string)+ {+ return new(string.Empty, false);+ }++ var stringBuilder = new StringBuilder();+ using (var stringWriter = new StringWriter(stringBuilder))+ using (var jsonTextWriter = new JsonTextWriter(stringWriter))+ {+ switch (indentationMode)+ {+ case Indentation.TwoSpaces:+ jsonTextWriter.Formatting = Formatting.Indented;+ jsonTextWriter.IndentChar = ' ';+ jsonTextWriter.Indentation = 2;+ break;++ case Indentation.FourSpaces:+ jsonTextWriter.Formatting = Formatting.Indented;+ jsonTextWriter.IndentChar = ' ';+ jsonTextWriter.Indentation = 4;+ break;++ default:+ throw new NotSupportedException();+ }++ var jsonSerializer = JsonSerializer.CreateDefault(new JsonSerializerSettings()+ {+ Converters = { new DecimalJsonConverter() }+ });+ jsonSerializer.Serialize(jsonTextWriter, yamlObject);+ }++ cancellationToken.ThrowIfCancellationRequested();+ return new(stringBuilder.ToString());++ }+ catch (SemanticErrorException ex)+ {+ return new(ex.Message, false);+ }+ catch (OperationCanceledException)+ {+ return new(string.Empty, false);+ }+ catch (Exception ex)+ {+ logger.LogError("Yaml to Json Converter", ex);+ return new(string.Empty, false);+ }+ }++ private static void SortJsonPropertiesAlphabetically(JObject jObject)+ {+ var properties = jObject.Properties().ToList();+ foreach (JProperty? property in properties)+ {+ property.Remove();+ }++ foreach (JProperty? property in properties.OrderBy(p => p.Name))+ {+ jObject.Add(property);+ if (property.Value is JObject obj)+ {+ SortJsonPropertiesAlphabetically(obj);+ }+ else if (property.Value is JArray array)+ {+ SortJsonPropertiesAlphabetically(array);+ }+ }+ }++ private static void SortJsonPropertiesAlphabetically(JArray jArray)+ {+ foreach (JToken? arrayItem in jArray)+ {+ if (arrayItem is JObject arrayObj)+ {+ SortJsonPropertiesAlphabetically(arrayObj);+ }+ else if (arrayItem is JArray array)+ {+ SortJsonPropertiesAlphabetically(array);+ }+ }+ }+}+diff --git a/src/app/dev/DevToys.Tools/Helpers/JsonYamlHelper.cs b/src/app/dev/DevToys.Tools/Helpers/JsonYamlHelper.csnew file mode 100644index 000000000..e38bd7578--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/JsonYamlHelper.cs@@ -0,0 +1,44 @@+using DevToys.Tools.Models;+using DevToys.Tools.Tools.Converters.JsonYaml;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Helpers;++internal static class JsonYamlHelper+{+ public static async ValueTask<ToolResult<string>> ConvertAsync(+ string input,+ JsonToYamlConversion conversion,+ Indentation indentation,+ ILogger logger,+ CancellationToken cancellationToken)+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ ToolResult<string> conversionResult;+ switch (conversion)+ {+ case JsonToYamlConversion.JsonToYaml:+ conversionResult = YamlHelper.ConvertFromJson(input, indentation, logger, cancellationToken);+ if (!conversionResult.HasSucceeded && string.IsNullOrWhiteSpace(conversionResult.Data))+ {+ cancellationToken.ThrowIfCancellationRequested();+ return new(JsonYamlConverter.InvalidJson, false);+ }+ break;+ case JsonToYamlConversion.YamlToJson:+ conversionResult = JsonHelper.ConvertFromYaml(input, indentation, logger, cancellationToken);+ if (!conversionResult.HasSucceeded && string.IsNullOrWhiteSpace(conversionResult.Data))+ {+ cancellationToken.ThrowIfCancellationRequested();+ return new(JsonYamlConverter.InvalidYaml, false);+ }+ break;+ default:+ throw new NotSupportedException();+ }++ cancellationToken.ThrowIfCancellationRequested();+ return conversionResult;+ }+}diff --git a/src/app/dev/DevToys.Tools/Helpers/YamlHelper.cs b/src/app/dev/DevToys.Tools/Helpers/YamlHelper.csnew file mode 100644index 000000000..f17516c9e--- /dev/null+++ b/src/app/dev/DevToys.Tools/Helpers/YamlHelper.cs@@ -0,0 +1,148 @@+using System.Text.Json;+using System.Text.Json.Nodes;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;+using YamlDotNet.Core;+using YamlDotNet.Serialization;++namespace DevToys.Tools.Helpers;++internal static partial class YamlHelper+{+ /// <summary>+ /// Detects whether the given string is a valid YAML or not.+ /// </summary>+ internal static bool IsValid(string? input, ILogger logger)+ {+ if (string.IsNullOrWhiteSpace(input))+ {+ return false;+ }++ input = input!.Trim();++ if (long.TryParse(input, out _))+ {+ return false;+ }++ /// We check if the first and last characters are the ones that are expected for JSON.+ /// TODO: check if we can use a YamlDotNet in strict mode to not parse JSON.+ int length = input.Length - 1;+ if ((input[0].Equals('{') && input[length].Equals('}')) ||+ (input[0].Equals('[') && input[length].Equals(']')))+ {+ return false;+ }++ try+ {+ object? result = new DeserializerBuilder().Build().Deserialize<object>(input);+ return result is not null and not string;+ }+ catch (Exception ex)+ {+ logger.LogError(ex, "Invalid data detected: 'input'", input);+ return false;+ }+ }++ /// <summary>+ /// Convert a Json string to Yaml+ /// </summary>+ internal static ToolResult<string> ConvertFromJson(+ string? input,+ Indentation indentation,+ ILogger logger,+ CancellationToken cancellationToken)+ {+ if (string.IsNullOrWhiteSpace(input))+ {+ return new(string.Empty, false);+ }++ try+ {++ var token = JsonNode.Parse(input, documentOptions: new() { CommentHandling = JsonCommentHandling.Skip });+ if (token is null)+ {+ return new(string.Empty, false);+ }++ object? jsonObject = ConvertJTokenToObject(token, 0);+ cancellationToken.ThrowIfCancellationRequested();++ if (jsonObject is not null and not string)+ {+ int indent = 0;+ indent = indentation switch+ {+ Indentation.TwoSpaces => 2,+ Indentation.FourSpaces => 4,+ _ => throw new NotSupportedException(),+ };+ var serializer+ = Serializer.FromValueSerializer(+ new SerializerBuilder().BuildValueSerializer(),+ EmitterSettings.Default.WithBestIndent(indent).WithIndentedSequences());++ string? yaml = serializer.Serialize(jsonObject);+ if (string.IsNullOrWhiteSpace(yaml))+ {+ return new(string.Empty, false);+ }+ cancellationToken.ThrowIfCancellationRequested();+ return new(yaml);+ }+ return new(string.Empty, false);+ }+ catch (JsonException ex)+ {+ return new(ex.Message, false);+ }+ catch (Exception ex)+ {+ logger.LogError("Yaml to Json Converter", ex);+ return new(string.Empty, false);+ }+ }++ private static dynamic? ParseValue(JsonValue token)+ {+ var elem = (JsonElement)token.GetValue<object>();+ return elem.ValueKind switch+ {+ JsonValueKind.String => elem.GetString(),+ JsonValueKind.Number => elem.GetDecimal(),+ JsonValueKind.False => false,+ JsonValueKind.True => true,+ JsonValueKind.Null => null,+ JsonValueKind.Undefined or+ JsonValueKind.Object or+ JsonValueKind.Array or+ _ => throw new NotSupportedException(),+ };+ }++ private static object? ConvertJTokenToObject(JsonNode? node, int level)+ {+ if (node is null)+ {+ return null;+ }++ if (level > 10)+ {+ throw new InvalidDataException($"Json structure is not supported: nested level in array is too deep. ({level}).");+ }+ return node switch+ {+ JsonValue val => ParseValue(val),+ JsonArray arr => arr.Select(o => ConvertJTokenToObject(o, level + 1)).ToList(),+ JsonObject obj => obj.AsObject().ToDictionary(x => x.Key, x => ConvertJTokenToObject(x.Value, level)),+ null => null,+ _ => throw new InvalidOperationException("Unexpected token: " + node)+ };+ }+}diff --git a/src/app/dev/DevToys.Tools/Models/Indentation.cs b/src/app/dev/DevToys.Tools/Models/Indentation.csnew file mode 100644index 000000000..1f92c9ff6--- /dev/null+++ b/src/app/dev/DevToys.Tools/Models/Indentation.cs@@ -0,0 +1,9 @@+namespace DevToys.Tools.Models;++internal enum Indentation+{+ TwoSpaces,+ FourSpaces,+ OneTab,+ Minified+}diff --git a/src/app/dev/DevToys.Tools/Models/JsonToYamlConversion.cs b/src/app/dev/DevToys.Tools/Models/JsonToYamlConversion.csnew file mode 100644index 000000000..d8b5da6ea--- /dev/null+++ b/src/app/dev/DevToys.Tools/Models/JsonToYamlConversion.cs@@ -0,0 +1,6 @@+namespace DevToys.Tools.Models;+internal enum JsonToYamlConversion+{+ JsonToYaml,+ YamlToJson+}diff --git a/src/app/dev/DevToys.Tools/Models/ToolResult.cs b/src/app/dev/DevToys.Tools/Models/ToolResult.csnew file mode 100644index 000000000..4d5909a57--- /dev/null+++ b/src/app/dev/DevToys.Tools/Models/ToolResult.cs@@ -0,0 +1,3 @@+namespace DevToys.Tools.Models;++internal record ToolResult<T>(T Data, bool HasSucceeded = true);diff --git a/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.csindex 6aa79e12b..a332372aa 100644--- a/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs+++ b/src/app/dev/DevToys.Tools/SmartDetection/JsonDataTypeDetector.cs@@ -1,4 +1,4 @@-using System.Text.Json;+using DevToys.Tools.Helpers;using Microsoft.Extensions.Logging;namespace DevToys.Tools.SmartDetection;@@ -15,33 +15,18 @@ internal sealed partial class JsonDataTypeDetector : IDataTypeDetector_logger = this.Log();}- public ValueTask<DataDetectionResult> TryDetectDataAsync(object data, DataDetectionResult? resultFromBaseDetector, CancellationToken cancellationToken)+ public ValueTask<DataDetectionResult> TryDetectDataAsync(+ object data,+ DataDetectionResult? resultFromBaseDetector,+ CancellationToken cancellationToken){if (resultFromBaseDetector is not null&& resultFromBaseDetector.Data is string dataString&& !long.TryParse(dataString, out _)){- try+ if (JsonHelper.IsValid(dataString, _logger)){- var options = new JsonDocumentOptions- {- CommentHandling = JsonCommentHandling.Skip,- AllowTrailingCommas = true,- MaxDepth = int.MaxValue- };- var jsonDocument = JsonDocument.Parse(dataString, options);- if (jsonDocument is not null)- {- return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: new Tuple<JsonDocument, string>(jsonDocument, dataString)));- }- }- catch (JsonException)- {- // Exception in parsing json. It likely mean the text isn't a JSON.- }- catch (Exception ex) //some other exception- {- LogError(ex);+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataString));}}diff --git a/src/app/dev/DevToys.Tools/SmartDetection/YamlDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/YamlDataTypeDetector.csnew file mode 100644index 000000000..d2372d257--- /dev/null+++ b/src/app/dev/DevToys.Tools/SmartDetection/YamlDataTypeDetector.cs@@ -0,0 +1,37 @@+using DevToys.Tools.Helpers;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.SmartDetection;++[Export(typeof(IDataTypeDetector))]+[DataTypeName(PredefinedCommonDataTypeNames.Yaml, baseName: PredefinedCommonDataTypeNames.Text)]+internal sealed partial class YamlDataTypeDetector : IDataTypeDetector+{+ private readonly ILogger _logger;++ [ImportingConstructor]+ public YamlDataTypeDetector()+ {+ _logger = this.Log();+ }++ public ValueTask<DataDetectionResult> TryDetectDataAsync(+ object data,+ DataDetectionResult? resultFromBaseDetector,+ CancellationToken cancellationToken)+ {+ if (resultFromBaseDetector is not null+ && resultFromBaseDetector.Data is string dataString)+ {+ if (YamlHelper.IsValid(dataString, _logger))+ {+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataString));+ }+ }++ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);+ }++ [LoggerMessage(1, LogLevel.Error, "An unexpected exception happened while trying to detect some JSON data.")]+ partial void LogError(Exception ex);+}diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/Converters.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Converters/Converters.Designer.csnew file mode 100644index 000000000..2aef2d278--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Converters/Converters.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.Converters {+ 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 Converters {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal Converters() {+ }++ /// <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.Converters.Converters", typeof(Converters).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 Converters.+ /// </summary>+ internal static string AccessibleName {+ get {+ return ResourceManager.GetString("AccessibleName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Converters.+ /// </summary>+ internal static string DisplayTitle {+ get {+ return ResourceManager.GetString("DisplayTitle", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/Converters.resx b/src/app/dev/DevToys.Tools/Tools/Converters/Converters.resxnew file mode 100644index 000000000..bf18e98a6--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Converters/Converters.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>Converters</value>+ </data>+ <data name="DisplayTitle" xml:space="preserve">+ <value>Converters</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Converters/ConvertersGroup.cs b/src/app/dev/DevToys.Tools/Tools/Converters/ConvertersGroup.csnew file mode 100644index 000000000..f60660c29--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Converters/ConvertersGroup.cs@@ -0,0 +1,15 @@+namespace DevToys.Tools.Tools.Converters;++[Export(typeof(GuiToolGroup))]+[Name("Converters")]+internal class ConvertersGroup : GuiToolGroup+{+ [ImportingConstructor]+ internal ConvertersGroup()+ {+ IconFontName = "DevToys-Tools-Icons";+ IconGlyph = '\u0103';+ DisplayTitle = Converters.DisplayTitle;+ AccessibleName = Converters.AccessibleName;+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.Designer.csnew file mode 100644index 000000000..a3affeec5--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.Designer.cs@@ -0,0 +1,279 @@+//------------------------------------------------------------------------------+// <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.Converters.JsonYaml {+ 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 JsonYamlConverter {++ private static global::System.Resources.ResourceManager resourceMan;++ private static global::System.Globalization.CultureInfo resourceCulture;++ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]+ internal JsonYamlConverter() {+ }++ /// <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.Converters.JsonYaml.JsonYamlConverter", typeof(JsonYamlConverter).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 to YAML and YAML to JSON converter 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 Select which conversion mode you want to use.+ /// </summary>+ internal static string ConversionDescription {+ get {+ return ResourceManager.GetString("ConversionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Whether to convert from Json or Yaml.+ /// </summary>+ internal static string ConversionOptionDescription {+ get {+ return ResourceManager.GetString("ConversionOptionDescription", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Conversion.+ /// </summary>+ internal static string ConversionTitle {+ get {+ return ResourceManager.GetString("ConversionTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to Convert JSON data to YAML and vice versa.+ /// </summary>+ internal static string Description {+ get {+ return ResourceManager.GetString("Description", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to File to convert from json or yaml.+ /// </summary>+ internal static string FileOptionDescription {+ get {+ return ResourceManager.GetString("FileOptionDescription", 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 do 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 to convert from json or yaml.+ /// </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 a input file.+ /// </summary>+ internal static string InvalidInputOrFileCommand {+ get {+ return ResourceManager.GetString("InvalidInputOrFileCommand", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to <Invalid JSON data>.+ /// </summary>+ internal static string InvalidJson {+ get {+ return ResourceManager.GetString("InvalidJson", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to <Invalid Yaml data>.+ /// </summary>+ internal static string InvalidYaml {+ get {+ return ResourceManager.GetString("InvalidYaml", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to JSON to YAML.+ /// </summary>+ internal static string JsonToYaml {+ get {+ return ResourceManager.GetString("JsonToYaml", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to JSON <> YAML Converter.+ /// </summary>+ internal static string LongDisplayTitle {+ get {+ return ResourceManager.GetString("LongDisplayTitle", 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 JSON <> YAML Converter.+ /// </summary>+ internal static string SearchDisplayName {+ get {+ return ResourceManager.GetString("SearchDisplayName", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to .+ /// </summary>+ internal static string SearchKeywords {+ get {+ return ResourceManager.GetString("SearchKeywords", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to JSON <> YAML.+ /// </summary>+ internal static string ShortDisplayTitle {+ get {+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to 2 spaces.+ /// </summary>+ internal static string TwoSpaces {+ get {+ return ResourceManager.GetString("TwoSpaces", resourceCulture);+ }+ }++ /// <summary>+ /// Looks up a localized string similar to YAML to JSON.+ /// </summary>+ internal static string YamlToJson {+ get {+ return ResourceManager.GetString("YamlToJson", resourceCulture);+ }+ }+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.resx b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.resxnew file mode 100644index 000000000..4d35d89dc--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverter.resx@@ -0,0 +1,192 @@+<?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 to YAML and YAML to JSON converter tool</value>+ </data>+ <data name="Configuration" xml:space="preserve">+ <value>Configuration</value>+ </data>+ <data name="ConversionDescription" xml:space="preserve">+ <value>Select which conversion mode you want to use</value>+ </data>+ <data name="ConversionOptionDescription" xml:space="preserve">+ <value>Whether to convert from Json or Yaml</value>+ </data>+ <data name="ConversionTitle" xml:space="preserve">+ <value>Conversion</value>+ </data>+ <data name="Description" xml:space="preserve">+ <value>Convert JSON data to YAML and vice versa</value>+ </data>+ <data name="FileOptionDescription" xml:space="preserve">+ <value>File to convert from json or yaml</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 do 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 to convert from json or yaml</value>+ </data>+ <data name="InvalidInputOrFileCommand" xml:space="preserve">+ <value>Please specify an input text or a input file</value>+ </data>+ <data name="InvalidJson" xml:space="preserve">+ <value><Invalid JSON data></value>+ </data>+ <data name="InvalidYaml" xml:space="preserve">+ <value><Invalid Yaml data></value>+ </data>+ <data name="JsonToYaml" xml:space="preserve">+ <value>JSON to YAML</value>+ </data>+ <data name="LongDisplayTitle" xml:space="preserve">+ <value>JSON <> YAML Converter</value>+ </data>+ <data name="Output" xml:space="preserve">+ <value>Output</value>+ </data>+ <data name="SearchDisplayName" xml:space="preserve">+ <value>JSON <> YAML Converter</value>+ </data>+ <data name="SearchKeywords" xml:space="preserve">+ <value />+ </data>+ <data name="ShortDisplayTitle" xml:space="preserve">+ <value>JSON <> YAML</value>+ </data>+ <data name="TwoSpaces" xml:space="preserve">+ <value>2 spaces</value>+ </data>+ <data name="YamlToJson" xml:space="preserve">+ <value>YAML to JSON</value>+ </data>+</root>\ No newline at end of filediff --git a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterCommandLineTool.csnew file mode 100644index 000000000..55c04226c--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterCommandLineTool.cs@@ -0,0 +1,120 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.Converters.JsonYaml;++[Export(typeof(ICommandLineTool))]+[Name("JsonYamlConverter")]+[CommandName(+ Name = "jsonToYaml",+ ResourceManagerBaseName = "DevToys.Tools.Tools.Converters.JsonYaml.JsonYamlConverter",+ DescriptionResourceName = nameof(JsonYamlConverter.Description))]+internal sealed class JsonYamlConverterCommandLineTool : ICommandLineTool+{+ [CommandLineOption(+ Name = "input",+ Alias = "i",+ DescriptionResourceName = nameof(JsonYamlConverter.InputOptionDescription))]+ internal string? Input { get; set; }++ [CommandLineOption(+ Name = "file",+ Alias = "f",+ DescriptionResourceName = nameof(JsonYamlConverter.FileOptionDescription))]+ internal FileInfo? InputFile { get; set; }++ [CommandLineOption(+ Name = "outputFile",+ Alias = "of",+ DescriptionResourceName = nameof(JsonYamlConverter.FileOptionDescription))]+ internal FileInfo? OutputFile { get; set; }++ [CommandLineOption(+ Name = "conversion",+ Alias = "c",+ IsRequired = true,+ DescriptionResourceName = nameof(JsonYamlConverter.ConversionOptionDescription))]+ internal JsonToYamlConversion ConversionMode { get; set; } = JsonToYamlConversion.JsonToYaml;++ [CommandLineOption(+ Name = "indentation",+ DescriptionResourceName = nameof(JsonYamlConverter.IndentationOptionDescription))]+ internal Indentation IndentationMode { get; set; } = Indentation.TwoSpaces;++ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)+ {+ if (!string.IsNullOrWhiteSpace(Input))+ {+ return await InvokeCliAsync(+ logger,+ cancellationToken+ );+ }+ else if (InputFile is not null)+ {+ return await InvokeFileAsync(+ logger,+ cancellationToken+ );+ }++ Console.Error.WriteLine(JsonYamlConverter.InvalidInputOrFileCommand);+ return -1;+ }++ private async ValueTask<int> InvokeCliAsync(ILogger logger, CancellationToken cancellationToken)+ {+ Guard.IsNotNull(Input);++ ToolResult<string> conversionResult = await JsonYamlHelper.ConvertAsync(+ Input,+ ConversionMode,+ IndentationMode,+ logger,+ cancellationToken+ );++ cancellationToken.ThrowIfCancellationRequested();++ if (!conversionResult.HasSucceeded)+ {+ Console.Error.WriteLine(conversionResult.Data);+ return -1;+ }++ Console.WriteLine(conversionResult.Data);+ return 0;+ }++ private async ValueTask<int> InvokeFileAsync(ILogger logger, CancellationToken cancellationToken)+ {+ Guard.IsNotNull(InputFile);+ Guard.IsNotNull(OutputFile);++ if (!InputFile.Exists)+ {+ Console.Error.WriteLine(JsonYamlConverter.InputFileNotFound);+ return -1;+ }++ string content = File.ReadAllText(InputFile.FullName);++ ToolResult<string> conversionResult = await JsonYamlHelper.ConvertAsync(+ content!,+ ConversionMode,+ IndentationMode,+ logger,+ cancellationToken+ );++ if (!conversionResult.HasSucceeded)+ {+ Console.Error.WriteLine(conversionResult.Data);+ return -1;+ }++ File.WriteAllText(OutputFile.FullName, conversionResult.Data);+ return 0;+ }+}diff --git a/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.csnew file mode 100644index 000000000..fe42f5bdd--- /dev/null+++ b/src/app/dev/DevToys.Tools/Tools/Converters/JsonYaml/JsonYamlConverterGuiTool.cs@@ -0,0 +1,228 @@+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using Microsoft.Extensions.Logging;++namespace DevToys.Tools.Tools.Converters.JsonYaml;++[Export(typeof(IGuiTool))]+[Name("JsonYamlConverter")]+[ToolDisplayInformation(+ IconFontName = "DevToys-Tools-Icons",+ IconGlyph = '\u0109',+ GroupName = "Converters",+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),+ ResourceManagerBaseName = "DevToys.Tools.Tools.Converters.JsonYaml.JsonYamlConverter",+ ShortDisplayTitleResourceName = nameof(JsonYamlConverter.ShortDisplayTitle),+ LongDisplayTitleResourceName = nameof(JsonYamlConverter.LongDisplayTitle),+ DescriptionResourceName = nameof(JsonYamlConverter.Description),+ AccessibleNameResourceName = nameof(JsonYamlConverter.AccessibleName))]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Json)]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Yaml)]+internal sealed partial class JsonYamlConverterGuiTool : IGuiTool, IDisposable+{+ private const string JsonLanguage = "json";+ private const string YamlLanguage = "yaml";++ /// <summary>+ /// Whether the tool should convert Json to Yaml or Yaml to Json.+ /// </summary>+ private static readonly SettingDefinition<JsonToYamlConversion> conversionMode+ = new(name: $"{nameof(JsonYamlConverterGuiTool)}.{nameof(conversionMode)}", defaultValue: JsonToYamlConversion.JsonToYaml);++ /// <summary>+ /// Which indentation the tool need to use.+ /// </summary>+ private static readonly SettingDefinition<Indentation> indentationMode+ = new(name: $"{nameof(JsonYamlConverterGuiTool)}.{nameof(indentationMode)}", defaultValue: Indentation.TwoSpaces);++ private enum GridColumn+ {+ Content+ }++ private enum GridRow+ {+ Header,+ Content,+ Footer+ }++ private readonly ILogger _logger;+ private readonly ISettingsProvider _settingsProvider;+ private readonly IUIMultiLineTextInput _inputTextArea = MultilineTextInput("json-to-yaml-input-text-area");+ private readonly IUIMultiLineTextInput _outputTextArea = MultilineTextInput("json-to-yaml-output-text-area");++ private CancellationTokenSource? _cancellationTokenSource;++ [ImportingConstructor]+ public JsonYamlConverterGuiTool(ISettingsProvider settingsProvider)+ {+ _logger = this.Log();+ _settingsProvider = settingsProvider;++ switch (_settingsProvider.GetSetting(conversionMode))+ {+ case JsonToYamlConversion.JsonToYaml:+ SetJsonToYamlConversion();+ break;+ case JsonToYamlConversion.YamlToJson:+ SetYamlToJsonConversion();+ break;+ default:+ throw new NotSupportedException();+ }+ }++ 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(+ Setting("json-to-yaml-text-conversion-setting")+ .Icon("FluentSystemIcons", '\uF18D')+ .Title(JsonYamlConverter.ConversionTitle)+ .Description(JsonYamlConverter.ConversionDescription)+ .Handle(+ _settingsProvider,+ conversionMode,+ OnConversionModeChanged,+ Item(JsonYamlConverter.JsonToYaml, JsonToYamlConversion.JsonToYaml),+ Item(JsonYamlConverter.YamlToJson, JsonToYamlConversion.YamlToJson)+ ),+ Setting("json-to-yaml-text-indentation-setting")+ .Icon("FluentSystemIcons", '\uF6F8')+ .Title(JsonYamlConverter.Indentation)+ .Handle(+ _settingsProvider,+ indentationMode,+ OnIndentationModelChanged,+ Item(JsonYamlConverter.TwoSpaces, Indentation.TwoSpaces),+ Item(JsonYamlConverter.FourSpaces, Indentation.FourSpaces)+ )+ )+ ),+ Cell(+ GridRow.Content,+ GridColumn.Content,+ SplitGrid()+ .Vertical()+ .WithLeftPaneChild(+ _inputTextArea+ .Title(JsonYamlConverter.Input)+ .OnTextChanged(OnInputTextChanged))+ .WithRightPaneChild(+ _outputTextArea+ .Title(JsonYamlConverter.Output)+ .ReadOnly()+ .Extendable())+ )+ )+ );++ // Smart detection handler.+ public void OnDataReceived(string dataTypeName, object? parsedData)+ {+ if (dataTypeName == PredefinedCommonDataTypeNames.Json &&+ parsedData is string jsonStrongTypedParsedData)+ {+ _inputTextArea.Language(JsonLanguage);+ _outputTextArea.Language(YamlLanguage);+ _settingsProvider.SetSetting(conversionMode, JsonToYamlConversion.JsonToYaml);+ _inputTextArea.Text(jsonStrongTypedParsedData);+ }++ if (dataTypeName == PredefinedCommonDataTypeNames.Yaml &&+ parsedData is string yamlStrongTypedParsedData)+ {+ _inputTextArea.Language(YamlLanguage);+ _outputTextArea.Language(JsonLanguage);+ _settingsProvider.SetSetting(conversionMode, JsonToYamlConversion.YamlToJson);+ _inputTextArea.Text(yamlStrongTypedParsedData);+ }+ }++ public void Dispose()+ {+ _cancellationTokenSource?.Dispose();+ }++ private void OnConversionModeChanged(JsonToYamlConversion conversionMode)+ {+ switch (conversionMode)+ {+ case JsonToYamlConversion.JsonToYaml:+ SetJsonToYamlConversion();+ break;+ case JsonToYamlConversion.YamlToJson:+ SetYamlToJsonConversion();+ break;+ default:+ throw new NotSupportedException();+ }++ _inputTextArea.Text(_outputTextArea.Text);+ }++ private void OnIndentationModelChanged(Indentation indentationMode)+ {+ StartConvert(_inputTextArea.Text);+ }++ private void OnInputTextChanged(string text)+ {+ StartConvert(text);+ }++ private void StartConvert(string text)+ {+ _cancellationTokenSource?.Cancel();+ _cancellationTokenSource?.Dispose();+ _cancellationTokenSource = new CancellationTokenSource();++ WorkTask = ConvertAsync(text, _cancellationTokenSource.Token);+ }++ private async Task ConvertAsync(string input, CancellationToken cancellationToken)+ {+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);++ ToolResult<string> conversionResult = await JsonYamlHelper.ConvertAsync(+ input,+ _settingsProvider.GetSetting(conversionMode),+ _settingsProvider.GetSetting(indentationMode),+ _logger,+ cancellationToken);+ _outputTextArea.Text(conversionResult.Data);+ }++ private void SetJsonToYamlConversion()+ {+ _inputTextArea+ .Language(JsonLanguage);+ _outputTextArea+ .Language(YamlLanguage);+ }++ private void SetYamlToJsonConversion()+ {+ _inputTextArea+ .Language(YamlLanguage);+ _outputTextArea+ .Language(JsonLanguage);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csprojindex 459c59f74..7164fc580 100644--- a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj+++ b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj@@ -5,6 +5,12 @@<IsPackable>false</IsPackable></PropertyGroup>+ <ItemGroup>+ <Content Include="Tools\TestData\*\*.*">+ <CopyToOutputDirectory>Always</CopyToOutputDirectory>+ </Content>+ </ItemGroup>+<ItemGroup><PackageReference Include="FluentAssertions" /><PackageReference Include="Microsoft.NET.Test.Sdk" />@@ -26,6 +32,7 @@<ProjectReference Include="..\..\dev\DevToys.Business\DevToys.Business.csproj" /><ProjectReference Include="..\..\dev\DevToys.Core\DevToys.Core.csproj" /><ProjectReference Include="..\..\dev\DevToys.Tools\DevToys.Tools.csproj" />+ <ProjectReference Include="..\..\dev\platforms\desktop\DevToys.CLI\DevToys.CLI.csproj" /></ItemGroup><ItemGroup>diff --git a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.cs b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.csindex 8954588ea..4fe40b444 100644--- a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.cs+++ b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockDataTypeDetector.cs@@ -2,6 +2,7 @@using System.Text.Json;using System.Threading;using System.Threading.Tasks;+using DevToys.Tools.Helpers;namespace DevToys.UnitTests.Mocks.Tools;@@ -15,22 +16,9 @@ internal class MockJsonDataTypeDetector : IDataTypeDetector&& resultFromBaseDetector.Data is string dataString&& !long.TryParse(dataString, out _)){- try- {- var options = new JsonDocumentOptions- {- CommentHandling = JsonCommentHandling.Allow,- AllowTrailingCommas = true,- MaxDepth = int.MaxValue- };- var jsonDocument = JsonDocument.Parse(dataString, options);- if (jsonDocument is not null)- {- return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: new Tuple<JsonDocument, string>(jsonDocument, dataString)));- }- }- catch+ if (JsonHelper.IsValid(dataString, new MockILogger())){+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataString));}}diff --git a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.cs b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.csindex 40deb369d..d9a896846 100644--- a/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.cs+++ b/src/app/tests/DevToys.UnitTests/Mocks/Tools/MockIGuiTool.cs@@ -16,7 +16,7 @@ namespace DevToys.UnitTests.Mocks.Tools;DescriptionResourceName = nameof(MockToolResource.Title),AccessibleNameResourceName = nameof(MockToolResource.Title),SearchKeywordsResourceName = nameof(MockToolResource.Title))]-[AcceptedDataTypeName("text")]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Text)]internal sealed class MockIGuiTool2 : IGuiTool{public UIToolView View => null!;@@ -37,7 +37,7 @@ internal sealed class MockIGuiTool2 : IGuiToolDescriptionResourceName = nameof(MockToolResource.Title),AccessibleNameResourceName = nameof(MockToolResource.Title),SearchKeywordsResourceName = nameof(MockToolResource.Title))]-[AcceptedDataTypeName("JSON")]+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Json)]internal sealed class MockIGuiTool : IGuiTool{public UIToolView View => null!;diff --git a/src/app/tests/DevToys.UnitTests/TestDataProvider.cs b/src/app/tests/DevToys.UnitTests/TestDataProvider.csnew file mode 100644index 000000000..32a868721--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/TestDataProvider.cs@@ -0,0 +1,34 @@+using System.IO;+using System.Reflection;+using System.Threading.Tasks;++namespace DevToys.UnitTests;++internal static class TestDataProvider+{+ /// <summary>+ /// Retrieves the content of a file.+ /// </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)+ {+ var assembly = Assembly.GetExecutingAssembly();+ using Stream resourceStream = assembly.GetManifestResourceStream(filePath);+ using StreamReader streamReader = new(resourceStream);+ return await streamReader.ReadToEndAsync();+ }++ /// <summary>+ /// Retrieves the content of a file.+ /// </summary>+ /// <param name="filePath">Path to the file relative to <c>DevToys.Tests.Providers.TestData</c></param>+ /// <returns></returns>+ public static FileInfo GetFile(string filePath)+ {+ var assembly = Assembly.GetExecutingAssembly();+ string assemblyDirectory = Path.GetDirectoryName(assembly.Location);+ string resourcePath = Path.Combine(assemblyDirectory, filePath);+ return new(resourcePath);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.csnew file mode 100644index 000000000..ea6f07ddd--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterCommandLineToolTests.cs@@ -0,0 +1,235 @@+using System.Globalization;+using System.IO;+using System.Threading.Tasks;+using DevToys.CLI;+using DevToys.Tools.Models;+using DevToys.Tools.Tools.Converters.JsonYaml;+using Microsoft.AspNetCore.Components.Forms;+using Microsoft.Extensions.Logging;++namespace DevToys.UnitTests.Tools.Converters;++public sealed class JsonYamlConverterCommandLineToolTests : MefBasedTest+{+ private readonly StringWriter _consoleWriter = new();+ private readonly StringWriter _consoleErrorWriter = new();+ private readonly JsonYamlConverterCommandLineTool _tool;+ private readonly Mock<ILogger> _loggerMock;++ private static string _baseTestDataDirectory+ => Path.Combine("Tools", "TestData", nameof(JsonYamlConverter));++ public JsonYamlConverterCommandLineToolTests()+ : base(typeof(JsonYamlConverterCommandLineTool).Assembly)+ {+ _tool = (JsonYamlConverterCommandLineTool)MefProvider.ImportMany<ICommandLineTool, CommandLineToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "JsonYamlConverter").Value;++ _loggerMock = new Mock<ILogger>();+ Console.SetOut(_consoleWriter);+ Console.SetError(_consoleErrorWriter);+ }++ [Theory(DisplayName = "Convert with invalid input should return error exit code")]+ [InlineData(null)]+ [InlineData("")]+ [InlineData(" ")]+ public async Task ConvertJsonWithInvalidInputShouldReturnErrorExitCode(string input)+ {+ _tool.ConversionMode = JsonToYamlConversion.JsonToYaml;+ _tool.Input = input;++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(-1);+ }++ #region JsonToYaml++ [Fact(DisplayName = "Convert json with invalid json should output invalid json error")]+ public async Task ConvertJsonWithInvalidJsonShouldOutputInvalidJsonError()+ {+ _tool.ConversionMode = JsonToYamlConversion.JsonToYaml;+ _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("'b' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 3.");+ }++ [Fact(DisplayName = "Convert json with valid json should output valid yaml")]+ public async Task ConvertJsonWithValidJsonAndTwoSpacesShouldOutputValidYaml()+ {+ _tool.ConversionMode = JsonToYamlConversion.JsonToYaml;+ _tool.IndentationMode = Indentation.TwoSpaces;+ _tool.Input = "{\r\n \"foo\": \"bar\",\r\n \"fizz\": [\r\n \"wizz\"\r\n ]\r\n}";++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string consoleOutput = _consoleWriter.ToString().Trim();+ consoleOutput.Should().Be("foo: bar\r\nfizz:\r\n - wizz");+ }++ [Fact(DisplayName = "Convert json with valid json and four spaces indentation should output valid yaml")]+ public async Task ConvertJsonWithValidJsonAndFourSpacesShouldOutputValidYaml()+ {+ _tool.ConversionMode = JsonToYamlConversion.JsonToYaml;+ _tool.IndentationMode = Indentation.FourSpaces;+ _tool.Input = "{\r\n \"foo\": \"bar\",\r\n \"fizz\": [\r\n \"wizz\"\r\n ]\r\n}";++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string consoleOutput = _consoleWriter.ToString().Trim();+ consoleOutput.Should().Be("foo: bar\r\nfizz:\r\n - wizz");+ }++ [Fact(DisplayName = "Convert json with unknown json file should output invalid json error")]+ public async Task ConvertJsonWithUnknownFileInputShouldReturnErrorExitCode()+ {+ string filePath = Path.Combine(_baseTestDataDirectory, "Unknown.json");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.ConversionMode = JsonToYamlConversion.JsonToYaml;+ _tool.InputFile = inputFile;+ _tool.OutputFile = new FileInfo("Dummy.yaml");++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(-1);+ string consoleOutput = _consoleErrorWriter.ToString().Trim();+ consoleOutput.Should().Be(JsonYamlConverter.InputFileNotFound);+ }++ [Fact(DisplayName = "Convert json with invalid json file should output invalid json error")]+ public async Task ConvertJsonWithInvalidFileInputShouldReturnErrorExitCode()+ {+ string filePath = Path.Combine(_baseTestDataDirectory, "Invalid.json");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.ConversionMode = JsonToYamlConversion.JsonToYaml;+ _tool.InputFile = inputFile;+ _tool.OutputFile = new FileInfo("Dummy.yaml");++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(-1);+ string consoleOutput = _consoleErrorWriter.ToString().Trim();+ consoleOutput.Should().Be("'b' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 3.");+ }++ [Fact(DisplayName = "Convert json with valid json file should output valid yaml file")]+ public async Task ConvertJsonWithValidFileInputAndTwoSpacesShouldOutputValidYamlFile()+ {+ string filePath = Path.Combine(_baseTestDataDirectory, "TwoSpaces.json");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.ConversionMode = JsonToYamlConversion.JsonToYaml;+ _tool.InputFile = inputFile;+ _tool.OutputFile = new FileInfo("TwoSpaces.yaml");++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);+ outputContent.Should().Be("foo: bar\r\nfizz:\r\n - wizz\r\n");+ }++ [Fact(DisplayName = "Convert json with valid json file and four spaces should output valid yaml file")]+ public async Task ConvertJsonWithValidFileInputAndFourSpacesShouldOutputValidYamlFile()+ {+ string filePath = Path.Combine(_baseTestDataDirectory, "FourSpaces.json");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.ConversionMode = JsonToYamlConversion.JsonToYaml;+ _tool.IndentationMode = Indentation.FourSpaces;+ _tool.InputFile = inputFile;+ _tool.OutputFile = new FileInfo("FourSpaces.yaml");++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);+ outputContent.Should().Be("foo: bar\r\nfizz:\r\n - wizz\r\n");+ }++ #endregion++ #region YamlToJson++ [Fact(DisplayName = "Convert yaml with invalid yaml should output yaml exception message")]+ public async Task ConvertYamlWithInvalidYamlShouldOutputYamlExceptionMessage()+ {+ _tool.ConversionMode = JsonToYamlConversion.YamlToJson;+ _tool.Input = "'L' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0";++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(-1);+ string consoleOutput = _consoleErrorWriter.ToString().Trim();+ consoleOutput.Should().Be("While parsing a block mapping, did not find expected key.");+ }++ [Fact(DisplayName = "Convert yaml with valid yaml should output valid json")]+ public async Task ConvertYamlWithValidYamlShouldOutputValidJson()+ {+ _tool.ConversionMode = JsonToYamlConversion.YamlToJson;+ _tool.Input = "foo: bar\r\nfizz:\r\n - wizz";++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string consoleOutput = _consoleWriter.ToString().Trim();+ consoleOutput.Should().Be("{\r\n \"foo\": \"bar\",\r\n \"fizz\": [\r\n \"wizz\"\r\n ]\r\n}");+ }++ [Fact(DisplayName = "Convert yaml with valid yaml and four spaces should output valid json with four spaces")]+ public async Task ConvertYamlWithValidYamlAndFourSpacesIndentationShouldOutputValidYaml()+ {+ _tool.ConversionMode = JsonToYamlConversion.YamlToJson;+ _tool.IndentationMode = Indentation.FourSpaces;+ _tool.Input = "foo: bar\r\nfizz:\r\n - wizz";++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string consoleOutput = _consoleWriter.ToString().Trim();+ consoleOutput.Should().Be("{\r\n \"foo\": \"bar\",\r\n \"fizz\": [\r\n \"wizz\"\r\n ]\r\n}");+ }++ [Fact(DisplayName = "Convert yaml with invalid yaml file should output invalid yaml error")]+ public async Task ConvertYamlWithInvalidFileInputShouldReturnErrorExitCode()+ {+ string filePath = Path.Combine(_baseTestDataDirectory, "Invalid.yaml");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.ConversionMode = JsonToYamlConversion.YamlToJson;+ _tool.InputFile = inputFile;+ _tool.OutputFile = new FileInfo("Dummy.json");++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(-1);+ string consoleOutput = _consoleErrorWriter.ToString().Trim();+ consoleOutput.Should().Be("While parsing a block mapping, did not find expected key.");+ }++ [Fact(DisplayName = "Convert yaml with valid yaml file should output valid json file")]+ public async Task ConvertYamlWithValidFileInputAndTwoSpacesShouldOutputValidJsonFile()+ {+ string filePath = Path.Combine(_baseTestDataDirectory, "TwoSpaces.yaml");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.ConversionMode = JsonToYamlConversion.YamlToJson;+ _tool.InputFile = inputFile;+ _tool.OutputFile = new FileInfo("TwoSpaces.json");++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);+ outputContent.Should().Be("{\r\n \"foo\": \"bar\",\r\n \"fizz\": [\r\n \"wizz\"\r\n ]\r\n}");+ }++ [Fact(DisplayName = "Convert yaml with valid yaml file and four spaces should output valid json file")]+ public async Task ConvertYamlWithValidFileInputAndFourSpacesShouldOutputValidJsonFile()+ {+ string filePath = Path.Combine(_baseTestDataDirectory, "FourSpaces.yaml");+ FileInfo inputFile = TestDataProvider.GetFile(filePath);+ _tool.ConversionMode = JsonToYamlConversion.YamlToJson;+ _tool.IndentationMode = Indentation.FourSpaces;+ _tool.InputFile = inputFile;+ _tool.OutputFile = new FileInfo("FourSpaces.json");++ int result = await _tool.InvokeAsync(_loggerMock.Object, default);+ result.Should().Be(0);+ string outputContent = File.ReadAllText(_tool.OutputFile.FullName);+ outputContent.Should().Be("{\r\n \"foo\": \"bar\",\r\n \"fizz\": [\r\n \"wizz\"\r\n ]\r\n}");+ }++ #endregion+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterGuiToolTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterGuiToolTests.csnew file mode 100644index 000000000..2b2fc9f77--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Converters/JsonYamlConverterGuiToolTests.cs@@ -0,0 +1,133 @@+using System.Globalization;+using System.Threading.Tasks;+using DevToys.Core.Tools.Metadata;+using DevToys.Tools.Tools.Converters.JsonYaml;++namespace DevToys.UnitTests.Tools.Converters;++public class JsonYamlConverterGuiToolTests : MefBasedTest+{+ private readonly UIToolView _toolView;+ private readonly JsonYamlConverterGuiTool _tool;+ private readonly IUIMultiLineTextInput _inputTextArea;+ private readonly IUIMultiLineTextInput _outputTextArea;++ public JsonYamlConverterGuiToolTests()+ : base(typeof(JsonYamlConverterGuiTool).Assembly)+ {+ _tool = (JsonYamlConverterGuiTool)MefProvider.ImportMany<IGuiTool, GuiToolMetadata>()+ .Single(t => t.Metadata.InternalComponentName == "JsonYamlConverter")+ .Value;++ _toolView = _tool.View;++ _inputTextArea = (IUIMultiLineTextInput)_toolView.GetChildElementById("json-to-yaml-input-text-area");+ _outputTextArea = (IUIMultiLineTextInput)_toolView.GetChildElementById("json-to-yaml-output-text-area");+ CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;+ CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;+ }++ [Theory(DisplayName = "Convert json with invalid json should return json error")]+ [InlineData(null)]+ [InlineData("")]+ [InlineData(" ")]+ public async Task ConvertJsonWithInvalidJsonShouldReturnJsonError(string input)+ {+ _inputTextArea.Text(input);+ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be(JsonYamlConverter.InvalidJson);+ }++ [Fact(DisplayName = "Convert json with invalid json should return json exception message")]+ public async Task ConvertJsonWithInvalidJsonShouldReturnJsonExceptionMessage()+ {+ _inputTextArea.Text(" bar { \"foo\": 123 } ");+ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("'b' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 3.");+ }++ [Fact(DisplayName = "Convert json with valid json should return valid yaml")]+ public async Task ConvertJsonWithValidJsonShouldReturnValidYaml()+ {+ _inputTextArea.Text(" { \"foo\": \"bar\" } ");+ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("foo: bar\r\n");+ }++ [Fact(DisplayName = "Convert json with valid json and two spaces indentation should return valid yaml")]+ public async Task ConvertJsonWithValidJsonAndTwoSpacesShouldReturnValidYaml()+ {+ _inputTextArea.Text("{\r\n \"foo\": \"bar\",\r\n \"fizz\": [\r\n \"wizz\"\r\n ]\r\n}");++ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-to-yaml-text-indentation-setting")).InteractiveElement;+ indentationOptions.Select(0); // Select TwoSpaces++ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("foo: bar\r\nfizz:\r\n - wizz\r\n");+ }++ [Fact(DisplayName = "Convert json with valid json and four spaces indentation should return valid yaml")]+ public async Task ConvertJsonWithValidJsonAndFourSpacesShouldReturnValidYaml()+ {+ _inputTextArea.Text("{\r\n \"foo\": \"bar\",\r\n \"fizz\": [\r\n \"wizz\"\r\n ]\r\n}");++ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-to-yaml-text-indentation-setting")).InteractiveElement;+ indentationOptions.Select(1); // Select FourSpaces++ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("foo: bar\r\nfizz:\r\n - wizz\r\n");+ }++ [Theory(DisplayName = "Convert yaml with invalid input should return yaml error")]+ [InlineData(null)]+ [InlineData("")]+ [InlineData(" ")]+ public async Task ConvertYamlWithInvalidYamlShouldReturnYamlError(string input)+ {+ var conversionSettings = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-to-yaml-text-conversion-setting")).InteractiveElement;+ conversionSettings.Select(1); // Select YamlToJson++ _inputTextArea.Text(input);+ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be(JsonYamlConverter.InvalidYaml);+ }++ [Fact(DisplayName = "Convert yaml with invalid yaml should return yaml exception message")]+ public async Task ConvertYamlWithInvalidYamlShouldReturnYamlExceptionMessage()+ {+ var conversionSettings = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-to-yaml-text-conversion-setting")).InteractiveElement;+ conversionSettings.Select(1); // Select YamlToJson++ _inputTextArea.Text("'L' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.");+ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("While parsing a block mapping, did not find expected key.");+ }++ [Fact(DisplayName = "Convert yaml with valid yaml should return valid json")]+ public async Task ConvertYamlWithValidYamlShouldReturnValidJson()+ {+ var conversionSettings = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-to-yaml-text-conversion-setting")).InteractiveElement;+ conversionSettings.Select(1); // Select YamlToJson++ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-to-yaml-text-indentation-setting")).InteractiveElement;+ indentationOptions.Select(0); // Select TwoSpaces++ _inputTextArea.Text("foo: bar\r\nfizz:\r\n - wizz\r\n\r\n");+ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("{\r\n \"foo\": \"bar\",\r\n \"fizz\": [\r\n \"wizz\"\r\n ]\r\n}");+ }++ [Fact(DisplayName = "Convert yaml with valid yaml and four spaces should return valid json with four spaces")]+ public async Task ConvertYamlWithValidYamlAndFourSpacesIndentationShouldReturnValidYaml()+ {+ var conversionSettings = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-to-yaml-text-conversion-setting")).InteractiveElement;+ conversionSettings.Select(1); // Select YamlToJson++ var indentationOptions = (IUISelectDropDownList)((IUISetting)_toolView.GetChildElementById("json-to-yaml-text-indentation-setting")).InteractiveElement;+ indentationOptions.Select(1); // Select FourSpaces++ _inputTextArea.Text("foo: bar\r\nfizz:\r\n - wizz\r\n\r\n");+ await _tool.WorkTask;+ _outputTextArea.Text.Should().Be("{\r\n \"foo\": \"bar\",\r\n \"fizz\": [\r\n \"wizz\"\r\n ]\r\n}");+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.csnew file mode 100644index 000000000..36e98dd4a--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/JsonHelperTests.cs@@ -0,0 +1,171 @@+using System.Threading;+using System.Threading.Tasks;+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using DevToys.UnitTests.Mocks;++namespace DevToys.UnitTests.Tools.Helpers;++public class JsonHelperTests+{+ [Theory]+ [InlineData(null, true)]+ [InlineData("\"foo\"", true)]+ [InlineData("123", false)]+ [InlineData("", false)]+ [InlineData(" ", false)]+ [InlineData(" { } ", true)]+ [InlineData(" [ ] ", true)]+ [InlineData(" { \"foo\": 123 } ", true)]+ [InlineData(" bar { \"foo\": 123 } ", false)]+ public void IsValid(string input, bool expectedResult)+ {+ JsonHelper.IsValid(input, new MockILogger()).Should().Be(expectedResult);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("", "")]+ [InlineData(" ", "")]+ [InlineData(" { } ", "{}")]+ [InlineData(" [ ] ", "[]")]+ [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);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("", "")]+ [InlineData(" ", "")]+ [InlineData(" { } ", "{}")]+ [InlineData(" [ ] ", "[]")]+ [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);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("", "")]+ [InlineData(" ", "")]+ [InlineData(" { } ", "{}")]+ [InlineData(" [ ] ", "[]")]+ [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);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("", "")]+ [InlineData(" ", "")]+ [InlineData(" { } ", "{}")]+ [InlineData(" [ ] ", "[]")]+ [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);+ }++ [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);+ }++ [Theory]+ [InlineData(+ "{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": [{\"a\": \"asdf\", \"c\" : 545, \"b\": 33, \"array\": []}]}",+ "{\"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);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("", "")]+ [InlineData(" ", "")]+ public void ConvertFromYamlShouldReturnEmptyString(string input, string expected)+ {+ // prepare & act+ ToolResult<string> actual = JsonHelper.ConvertFromYaml(+ input,+ Indentation.FourSpaces,+ new MockILogger(),+ CancellationToken.None);+ actual.HasSucceeded.Should().BeFalse();+ actual.Data.Should().Be(expected);+ }++ [Fact(DisplayName = "Convert From Yaml with unsupported Indentation")]+ public void ConvertFromYamlWithUnsupportedIndentationShouldReturnEmptyString()+ {+ // prepare+ string input = "- key: value";+ string expected = string.Empty;++ // act+ ToolResult<string> actual = JsonHelper.ConvertFromYaml(+ input,+ Indentation.Minified,+ new MockILogger(),+ CancellationToken.None);+ actual.HasSucceeded.Should().BeFalse();+ actual.Data.Should().Be(expected);+ }++ [Fact(DisplayName = "Convert From Yaml with unsupported yaml")]+ public void ConvertFromYamlWithUnsupportedYamlShouldExceptionMessage()+ {+ // prepare+ string input = "[";+ string expected = "While parsing a node, did not find expected node content.";++ // act+ ToolResult<string> actual = JsonHelper.ConvertFromYaml(+ input,+ Indentation.Minified,+ new MockILogger(),+ CancellationToken.None);+ actual.HasSucceeded.Should().BeFalse();+ actual.Data.Should().Be(expected);+ }++ [Theory]+ [InlineData(" - key: value ", "[\r\n {\r\n \"key\": \"value\"\r\n }\r\n]")]+ [InlineData(" - key: value\r\n key2: 1", "[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]")]+ public void ConvertFromYamlWithTwoSpaces(string input, string expectedResult)+ {+ ToolResult<string> result = JsonHelper.ConvertFromYaml(+ input,+ Indentation.TwoSpaces,+ new MockILogger(),+ CancellationToken.None);+ result.Data.Should().Be(expectedResult);+ }++ [Theory]+ [InlineData(" - key: value ", "[\r\n {\r\n \"key\": \"value\"\r\n }\r\n]")]+ [InlineData(" - key: value\r\n key2: 1", "[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]")]+ public void ConvertFromYamlWithFourSpaces(string input, string expectedResult)+ {+ ToolResult<string> result = JsonHelper.ConvertFromYaml(+ input,+ Indentation.FourSpaces,+ new MockILogger(),+ CancellationToken.None);+ result.Data.Should().Be(expectedResult);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/YamlHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/YamlHelperTests.csnew file mode 100644index 000000000..45519d8ff--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/YamlHelperTests.cs@@ -0,0 +1,125 @@+using System.Threading;+using DevToys.Tools.Helpers;+using DevToys.Tools.Models;+using DevToys.UnitTests.Mocks;++namespace DevToys.UnitTests.Tools.Helpers;++public class YamlHelperTests+{+ [Theory]+ [InlineData(null, false)]+ [InlineData("", false)]+ [InlineData(" ", false)]+ [InlineData("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", false)]+ [InlineData("foo :\n bar :\n - boo: 1\n - rab: 2\n - plop: 3", true)]+ public void IsValid(string input, bool expectedResult)+ {+ YamlHelper.IsValid(input, new MockILogger()).Should().Be(expectedResult);+ }++ [Theory]+ [InlineData(null, "")]+ [InlineData("", "")]+ [InlineData(" ", "")]+ public void ConvertFromJsonShouldReturnEmptyString(string input, string expected)+ {+ // prepare & act+ ToolResult<string> actual = YamlHelper.ConvertFromJson(+ input,+ Indentation.FourSpaces,+ new MockILogger(),+ CancellationToken.None);++ actual.HasSucceeded.Should().BeFalse();+ actual.Data.Should().Be(expected);+ }++ [Fact(DisplayName = "Convert From Json with unsupported Indentation")]+ public void ConvertFromJsonWithUnsupportedIndentationShouldReturnEmptyString()+ {+ // prepare+ string input = "{}";+ string expected = string.Empty;++ // act+ ToolResult<string> actual = YamlHelper.ConvertFromJson(+ input,+ Indentation.Minified,+ new MockILogger(),+ CancellationToken.None);++ actual.HasSucceeded.Should().BeFalse();+ actual.Data.Should().Be(expected);+ }++ [Fact(DisplayName = "Convert From Json with unsupported Json")]+ public void ConvertFromJsonWithUnsupportedJsonShouldExceptionMessage()+ {+ // prepare+ string input = "-";+ string expected = "Expected a digit ('0'-'9'), but instead reached end of data. LineNumber: 0 | BytePositionInLine: 1.";++ // act+ ToolResult<string> actual = YamlHelper.ConvertFromJson(+ input,+ Indentation.Minified,+ new MockILogger(),+ CancellationToken.None);++ actual.HasSucceeded.Should().BeFalse();+ actual.Data.Should().Be(expected);+ }++ [Theory]+ [InlineData("{\r\n \"key\": \"value\"\r\n }", "key: value\r\n")]+ [InlineData("{\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }", "key: value\r\nkey2: 1\r\n")]+ public void ConvertFromJsonWithTwoSpaces(string input, string expectedResult)+ {+ ToolResult<string> result = YamlHelper.ConvertFromJson(+ input,+ Indentation.TwoSpaces,+ new MockILogger(),+ CancellationToken.None);+ result.Data.Should().Be(expectedResult);+ }++ [Theory]+ [InlineData("{\r\n \"key\": \"value\"\r\n }", "key: value\r\n")]+ [InlineData("{\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }", "key: value\r\nkey2: 1\r\n")]+ public void ConvertFromJsonWithFourSpaces(string input, string expectedResult)+ {+ ToolResult<string> result = YamlHelper.ConvertFromJson(+ input,+ Indentation.FourSpaces,+ new MockILogger(),+ CancellationToken.None);+ result.Data.Should().Be(expectedResult);+ }++ [Theory]+ [InlineData("[\r\n {\r\n \"key\": \"value\"\r\n }\r\n]", "- key: value\r\n")]+ [InlineData("[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]", "- key: value\r\n key2: 1\r\n")]+ public void ConvertFromJsonWithJsonRootArrayWithTwoSpaces(string input, string expectedResult)+ {+ ToolResult<string> result = YamlHelper.ConvertFromJson(+ input,+ Indentation.TwoSpaces,+ new MockILogger(),+ CancellationToken.None);+ result.Data.Should().Be(expectedResult);+ }++ [Theory]+ [InlineData("[\r\n {\r\n \"key\": \"value\"\r\n }\r\n]", "- key: value\r\n")]+ [InlineData("[\r\n {\r\n \"key\": \"value\",\r\n \"key2\": 1\r\n }\r\n]", "- key: value\r\n key2: 1\r\n")]+ public void ConvertFromJsonWithJsonRootArrayWithFourSpaces(string input, string expectedResult)+ {+ ToolResult<string> result = YamlHelper.ConvertFromJson(+ input,+ Indentation.FourSpaces,+ new MockILogger(),+ CancellationToken.None);+ result.Data.Should().Be(expectedResult);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonDataTypeDetectorTests.cs b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonDataTypeDetectorTests.csnew file mode 100644index 000000000..1f56c9da4--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/JsonDataTypeDetectorTests.cs@@ -0,0 +1,32 @@+using System.Diagnostics.CodeAnalysis;+using System.Threading.Tasks;+using DevToys.Tools.SmartDetection;+using Microsoft.Extensions.Logging;++namespace DevToys.UnitTests.Tools.SmartDetection;++[ExcludeFromCodeCoverage]+public class JsonDataTypeDetectorTests+{+ [Theory]+ [InlineData(null, false)]+ [InlineData("", false)]+ [InlineData(" ", false)]+ [InlineData("{ \"title\": \"example glossary\" }", true)]+ [InlineData("[ \"title\", \"example glossary\" ]", true)]+ [InlineData("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", false)]+ [InlineData("foo :\n bar :\n - boo: 1\n - rab: 2\n - plop: 3", false)]+ public async Task TryDetectDataAsync(string input, bool expectedResult)+ {+ LoggingExtensions.LoggerFactory ??= LoggerFactory.Create(builder => { });++ DataDetectionResult dataDetectionResult = new(false, input);+ JsonDataTypeDetector sut = new();+ DataDetectionResult result = await sut.TryDetectDataAsync(+ input,+ dataDetectionResult,+ default);++ result.Success.Should().Be(expectedResult);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/YamlDataTypeDetectorTests.cs b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/YamlDataTypeDetectorTests.csnew file mode 100644index 000000000..ac448de0d--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/SmartDetection/YamlDataTypeDetectorTests.cs@@ -0,0 +1,32 @@+using System.Diagnostics.CodeAnalysis;+using System.Threading.Tasks;+using DevToys.Tools.SmartDetection;+using Microsoft.Extensions.Logging;++namespace DevToys.UnitTests.Tools.SmartDetection;++[ExcludeFromCodeCoverage]+public class YamlDataTypeDetectorTests+{+ [Theory]+ [InlineData(null, false)]+ [InlineData("", false)]+ [InlineData(" ", false)]+ [InlineData("{ \"title\": \"example glossary\" }", false)]+ [InlineData("[ \"title\", \"example glossary\" ]", false)]+ [InlineData("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", false)]+ [InlineData("foo :\n bar :\n - boo: 1\n - rab: 2\n - plop: 3", true)]+ public async Task TryDetectDataAsync(string input, bool expectedResult)+ {+ LoggingExtensions.LoggerFactory ??= LoggerFactory.Create(builder => { });++ DataDetectionResult dataDetectionResult = new(false, input);+ YamlDataTypeDetector sut = new();+ DataDetectionResult result = await sut.TryDetectDataAsync(+ input,+ dataDetectionResult,+ default);++ result.Success.Should().Be(expectedResult);+ }+}diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/FourSpaces.json b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/FourSpaces.jsonnew file mode 100644index 000000000..5e8bbd019--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/FourSpaces.json@@ -0,0 +1,6 @@+{+ "foo": "bar",+ "fizz": [+ "wizz"+ ]+}\ No newline at end of filediff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/FourSpaces.yaml b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/FourSpaces.yamlnew file mode 100644index 000000000..1e945c7d2--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/FourSpaces.yaml@@ -0,0 +1,3 @@+foo: bar+fizz:+ - wizzdiff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/Invalid.json b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/Invalid.jsonnew file mode 100644index 000000000..93e11f8c1--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/Invalid.json@@ -0,0 +1 @@+ bar { "foo": 123 }\ No newline at end of filediff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/Invalid.yaml b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/Invalid.yamlnew file mode 100644index 000000000..74f93be2f--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/Invalid.yaml@@ -0,0 +1 @@+'L' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0\ No newline at end of filediff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/TwoSpaces.json b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/TwoSpaces.jsonnew file mode 100644index 000000000..f25709124--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/TwoSpaces.json@@ -0,0 +1,6 @@+{+ "foo": "bar",+ "fizz": [+ "wizz"+ ]+}\ No newline at end of filediff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/TwoSpaces.yaml b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/TwoSpaces.yamlnew file mode 100644index 000000000..b462c38e9--- /dev/null+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/JsonYamlConverter/TwoSpaces.yaml@@ -0,0 +1,3 @@+foo: bar+fizz:+ - wizzdiff --git a/src/spellcheckerexclusion.dic b/src/spellcheckerexclusion.dicindex 8a054922f..716339a7f 100644--- a/src/spellcheckerexclusion.dic+++ b/src/spellcheckerexclusion.dic@@ -11,3 +11,8 @@ monaconugetnuspecnupkg+yaml+deserializer+textarea+wizz+jtoken