Skip to content

A Swiss Army knife for developers.

Ported XML Validator to DevToys 2.0 (#1011)

Etienne BAUDOUX76b6203d1624
diff --git a/src/app/dev/DevToys.Api/Core/ResultInfo.cs b/src/app/dev/DevToys.Api/Core/ResultInfo.cs
index 779b3b38f..a6e02d45e 100644
--- a/src/app/dev/DevToys.Api/Core/ResultInfo.cs
+++ b/src/app/dev/DevToys.Api/Core/ResultInfo.cs
@@ -7,3 +7,12 @@
/// <param name="Data">The resulting data or the task</param>
/// <param name="HasSucceeded">Whether the task succeeded</param>
public record ResultInfo<T>(T Data, bool HasSucceeded = true);
+
+/// <summary>
+/// Record to contain both whether the task was a success and the resulting data
+/// </summary>
+/// <typeparam name="T">Type of the result</typeparam>
+/// <typeparam name="U">Type of the severity</typeparam>
+/// <param name="Data">The resulting data or the task</param>
+/// <param name="Severity">The severity of the result</param>
+public record ResultInfo<T, U>(T Data, U Severity);
diff --git a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
index 1218ffa1f..de3ab80dd 100644
--- a/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
+++ b/src/app/dev/DevToys.Api/Tool/SmartDetection/PredefinedCommonDataTypeNames.cs
@@ -7,6 +7,7 @@ public static class PredefinedCommonDataTypeNames
public const string JsonArray = "jsonArray";
public const string Yaml = "yaml";
public const string Xml = "xml";
+ public const string Xsd = "xsd";
public const string Base64Text = "base64Text";
public const string Base64Image = "base64Image";
public const string Image = "image";
diff --git a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
index 8d0dece8a..6c3865ab2 100644
--- a/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
+++ b/src/app/dev/DevToys.Tools/DevToys.Tools.csproj
@@ -168,6 +168,11 @@
<AutoGen>True</AutoGen>
<DependentUpon>Text.resx</DependentUpon>
</Compile>
+ <Compile Update="Tools\Text\XMLValidator\XMLValidator.Designer.cs">
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ <DependentUpon>XMLValidator.resx</DependentUpon>
+ </Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Strings\GlobalStrings\GlobalStrings.resx">
@@ -278,6 +283,10 @@
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Text.Designer.cs</LastGenOutput>
</EmbeddedResource>
+ <EmbeddedResource Update="Tools\Text\XMLValidator\XMLValidator.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>XMLValidator.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
</ItemGroup>
<ItemGroup>
diff --git a/src/app/dev/DevToys.Tools/Helpers/XsdHelper.cs b/src/app/dev/DevToys.Tools/Helpers/XsdHelper.cs
new file mode 100644
index 000000000..fca2f7b13
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Helpers/XsdHelper.cs
@@ -0,0 +1,219 @@
+using System.Text;
+using System.Xml;
+using System.Xml.Linq;
+using System.Xml.Schema;
+using System.Xml.XPath;
+using DevToys.Tools.Models;
+using DevToys.Tools.Tools.Text.XMLValidator;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.Tools.Helpers;
+
+internal static class XsdHelper
+{
+ /// <summary>
+ /// Detects whether the given string is a valid XSD or not.
+ /// </summary>
+ internal static bool IsValid(string? input, ILogger logger)
+ {
+ try
+ {
+ using StringReader reader = new(input!);
+ var xmlSchema = XmlSchema.Read(reader, null);
+ return xmlSchema is not null;
+ }
+ catch (Exception ex) when (ex is XmlException || ex is XmlSchemaException)
+ {
+ return false;
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Invalid data detected.");
+ return false;
+ }
+ }
+
+ internal static ResultInfo<string, XmlValidatorResultSeverity> ValidateXmlAgainstXsd(string xsd, string xml, ILogger logger, CancellationToken cancellationToken)
+ {
+ Guard.IsNotNullOrWhiteSpace(xsd);
+ Guard.IsNotNullOrWhiteSpace(xml);
+
+ try
+ {
+ XmlValidatorResultSeverity hasSucceeded = XmlValidatorResultSeverity.Success;
+ var errors = new StringBuilder();
+ void ValidationErrorCallBack(object? sender, ValidationEventArgs e)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ hasSucceeded = e.Severity == XmlSeverityType.Warning ? XmlValidatorResultSeverity.Warning : XmlValidatorResultSeverity.Error;
+ errors.AppendLine(e.Message);
+ }
+
+ // Load XSD document.
+ using StringReader reader = new(xsd!);
+ var xmlSchema = XmlSchema.Read(reader, ValidationErrorCallBack);
+
+ if (xmlSchema is not null)
+ {
+ XmlSchemaSet xmlSchemaSet = new();
+ xmlSchemaSet.Add(xmlSchema);
+
+ // Load XML document.
+ XDocument xmlDocument;
+ try
+ {
+ xmlDocument = XDocument.Parse(xml);
+ }
+ catch (XmlException ex)
+ {
+ return new ResultInfo<string, XmlValidatorResultSeverity>($"XML: {ex.Message}", XmlValidatorResultSeverity.Error);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ // Validate XML against the XSD.
+ xmlDocument.Validate(xmlSchemaSet, ValidationErrorCallBack);
+
+ if (hasSucceeded == XmlValidatorResultSeverity.Success)
+ {
+ // XML will always be valid if it doesn't define a namespace. Let's verify that namespaces aren't missing.
+ var xsdDocument = XDocument.Parse(xsd);
+ IEnumerable<XmlNamespace> xsdNamespaces = GetAllNamespaces(xsdDocument);
+ IEnumerable<XmlNamespace> xmlNamespaces = GetAllNamespaces(xmlDocument);
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ IEnumerable<XmlNamespace> namespacesMissingInXsd
+ = GetMissingNamespacesInXsd(xsdNamespaces, xmlSchema.TargetNamespace, xmlNamespaces);
+
+ bool areAllNamespacesDefinedInXsd = !namespacesMissingInXsd.Any();
+ if (!areAllNamespacesDefinedInXsd)
+ {
+ string missingNamespacesFormatted = FormatNamespaces(namespacesMissingInXsd);
+ return new ResultInfo<string, XmlValidatorResultSeverity>(string.Format(XMLValidator.XsdNamespacesInconsistentMsg, missingNamespacesFormatted), XmlValidatorResultSeverity.Warning);
+ }
+
+ bool isTargetNamespaceReferenceMissingInXml
+ = DetectMissingTargetNamespaceInXml(xmlSchema.TargetNamespace, xmlNamespaces, out string? missingTargetNamespaceUri);
+ if (isTargetNamespaceReferenceMissingInXml)
+ {
+ return new ResultInfo<string, XmlValidatorResultSeverity>(string.Format(XMLValidator.TargetNamespaceNotDefinedInXml, missingTargetNamespaceUri), XmlValidatorResultSeverity.Warning);
+ }
+
+ IEnumerable<XmlNamespace> namespacesMissingInXml
+ = GetMissingNamespacesInXml(xsdNamespaces, xmlNamespaces);
+
+ bool areAllNamespacesDefinedInXml = !namespacesMissingInXml.Any();
+ if (!areAllNamespacesDefinedInXml)
+ {
+ string missingNamespacesFormatted = FormatNamespaces(namespacesMissingInXml);
+ return new ResultInfo<string, XmlValidatorResultSeverity>(string.Format(XMLValidator.XmlNamespacesInconsistentMsg, missingNamespacesFormatted), XmlValidatorResultSeverity.Warning);
+ }
+ }
+ }
+
+ return new ResultInfo<string, XmlValidatorResultSeverity>(errors.ToString(), hasSucceeded);
+ }
+ catch (Exception ex) when (ex is XmlException || ex is XmlSchemaException)
+ {
+ return new ResultInfo<string, XmlValidatorResultSeverity>($"XSD: {ex.Message}", XmlValidatorResultSeverity.Error);
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Error while validation XML against XSD.");
+ }
+
+ return new ResultInfo<string, XmlValidatorResultSeverity>(string.Empty, XmlValidatorResultSeverity.Error);
+ }
+
+ /// <summary>
+ /// Identifies namespaces used within the XML data but not defined in the XSD schema.
+ /// </summary>
+ /// <param name="xsdParsingResult">XSD parsing result</param>
+ /// <param name="xmlParsingResult">XML parsing result</param>
+ /// <returns>The missing namespaces.</returns>
+ private static IEnumerable<XmlNamespace> GetMissingNamespacesInXsd(
+ IEnumerable<XmlNamespace> xsdNamespaces,
+ string? targetNamespace,
+ IEnumerable<XmlNamespace> xmlNamespaces)
+ {
+ IEnumerable<XmlNamespace> clearedXdsNamespaces = GetNamespacesFromXsd(xsdNamespaces);
+
+ // filter targetNamespace
+ if (targetNamespace is not null)
+ {
+ xmlNamespaces = xmlNamespaces.Where(xns => !string.Equals(xns.Uri, targetNamespace, StringComparison.InvariantCultureIgnoreCase));
+ }
+
+ return xmlNamespaces.Where(ns => clearedXdsNamespaces.Contains(ns) == false);
+ }
+
+ /// <summary>
+ /// Identifies namespaces defined within the XSD schema but not used in the XML data.
+ /// </summary>
+ /// <param name="xsdParsingResult">XSD parsing result</param>
+ /// <param name="xmlParsingResult">XML parsing result</param>
+ /// <returns>The missing namespaces</returns>
+ private static IEnumerable<XmlNamespace> GetMissingNamespacesInXml(IEnumerable<XmlNamespace> xsdNamespaces, IEnumerable<XmlNamespace> xmlNamespaces)
+ {
+ IEnumerable<XmlNamespace> clearedXdsNamespaces = GetNamespacesFromXsd(xsdNamespaces);
+
+ return clearedXdsNamespaces.Where(ns => xmlNamespaces.Contains(ns) == false);
+ }
+
+ private static bool DetectMissingTargetNamespaceInXml(string? targetNamespace, IEnumerable<XmlNamespace> xmlNamespaces, out string? missingTargetNamespaceUri)
+ {
+ bool isTargetNamespaceDefinedInXml = xmlNamespaces.Select(ns => ns.Uri).Any(uri => string.Equals(uri, targetNamespace));
+ if (isTargetNamespaceDefinedInXml)
+ {
+ missingTargetNamespaceUri = null;
+ return false;
+ }
+
+ missingTargetNamespaceUri = targetNamespace;
+ return true;
+ }
+
+ private static IEnumerable<XmlNamespace> GetNamespacesFromXsd(IEnumerable<XmlNamespace> xsdNamespaces)
+ {
+ static bool IsDefaultXsdNamespace(XmlNamespace xmlNamespace) => xmlNamespace.Prefix.StartsWith("xs", StringComparison.InvariantCultureIgnoreCase);
+
+ // return namespaces without default XSD namespace (xmlns:xs="http://www.w3.org/2001/XMLSchema")
+ return xsdNamespaces.Where(xns => !IsDefaultXsdNamespace(xns));
+ }
+
+ /// <summary>
+ /// Extracts all <c>xmlns</c> namespaces from a given <paramref name="xmlDocument"/>.
+ /// </summary>
+ /// <param name="xmlDocument">XML document containing namespaces.</param>
+ /// <returns></returns>
+ private static IEnumerable<XmlNamespace> GetAllNamespaces(XDocument xmlDocument)
+ {
+ XPathNavigator? navigator = xmlDocument.CreateNavigator();
+ navigator.MoveToFollowing(XPathNodeType.Element);
+
+ IDictionary<string, string> namespaces = navigator.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml) ?? new Dictionary<string, string>();
+ return namespaces.Select(pair => new XmlNamespace(pair.Key, pair.Value)).ToList();
+ }
+
+ private static string FormatNamespaces(IEnumerable<XmlNamespace> namespaces)
+ {
+ List<string> missingNamespaces = new();
+ foreach (XmlNamespace ns in namespaces)
+ {
+ string formattedPrefix;
+ if (string.Equals(ns.Prefix, string.Empty))
+ {
+ formattedPrefix = "xmlns";
+ }
+ else
+ {
+ formattedPrefix = $"xmlns:{ns.Prefix}";
+ }
+
+ missingNamespaces.Add(formattedPrefix + $"=\"{ns.Uri}\"");
+ }
+
+ return string.Join(", ", missingNamespaces);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Models/XmlNamespace.cs b/src/app/dev/DevToys.Tools/Models/XmlNamespace.cs
new file mode 100644
index 000000000..8b0672885
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Models/XmlNamespace.cs
@@ -0,0 +1,5 @@
+namespace DevToys.Tools.Models;
+
+internal record XmlNamespace(string Prefix, string Uri)
+{
+}
diff --git a/src/app/dev/DevToys.Tools/Models/XmlValidatorResultSeverity.cs b/src/app/dev/DevToys.Tools/Models/XmlValidatorResultSeverity.cs
new file mode 100644
index 000000000..2fa4df2d5
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Models/XmlValidatorResultSeverity.cs
@@ -0,0 +1,8 @@
+namespace DevToys.Tools.Models;
+
+internal enum XmlValidatorResultSeverity
+{
+ Success,
+ Warning,
+ Error
+}
diff --git a/src/app/dev/DevToys.Tools/SmartDetection/XsdDataTypeDetector.cs b/src/app/dev/DevToys.Tools/SmartDetection/XsdDataTypeDetector.cs
new file mode 100644
index 000000000..a8afd012f
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/SmartDetection/XsdDataTypeDetector.cs
@@ -0,0 +1,34 @@
+using DevToys.Tools.Helpers;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.Tools.SmartDetection;
+
+[Export(typeof(IDataTypeDetector))]
+[DataTypeName(PredefinedCommonDataTypeNames.Xsd, baseName: PredefinedCommonDataTypeNames.Xml)]
+internal sealed partial class XsdDataTypeDetector : IDataTypeDetector
+{
+ private readonly ILogger _logger;
+
+ [ImportingConstructor]
+ public XsdDataTypeDetector()
+ {
+ _logger = this.Log();
+ }
+
+ public ValueTask<DataDetectionResult> TryDetectDataAsync(
+ object data,
+ DataDetectionResult? resultFromBaseDetector,
+ CancellationToken cancellationToken)
+ {
+ if (resultFromBaseDetector is not null
+ && resultFromBaseDetector.Data is string dataString)
+ {
+ if (XsdHelper.IsValid(dataString, _logger))
+ {
+ return ValueTask.FromResult(new DataDetectionResult(Success: true, Data: dataString));
+ }
+ }
+
+ return ValueTask.FromResult(DataDetectionResult.Unsuccessful);
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.Designer.cs b/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.Designer.cs
new file mode 100644
index 000000000..699102e50
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.Designer.cs
@@ -0,0 +1,234 @@
+//------------------------------------------------------------------------------
+// <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.Text.XMLValidator {
+ 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 XMLValidator {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal XMLValidator() {
+ }
+
+ /// <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.Text.XMLValidator.XMLValidator", typeof(XMLValidator).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 Xml Validator tool.
+ /// </summary>
+ internal static string AccessibleName {
+ get {
+ return ResourceManager.GetString("AccessibleName", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Validate XML data via an XSD scheme..
+ /// </summary>
+ internal static string Description {
+ get {
+ return ResourceManager.GetString("Description", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Please specify an input XML.
+ /// </summary>
+ internal static string InvalidXmlOrFileCommand {
+ get {
+ return ResourceManager.GetString("InvalidXmlOrFileCommand", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Please specify an input XSD.
+ /// </summary>
+ internal static string InvalidXsdOrFileCommand {
+ get {
+ return ResourceManager.GetString("InvalidXsdOrFileCommand", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XML Validator.
+ /// </summary>
+ internal static string LongDisplayTitle {
+ get {
+ return ResourceManager.GetString("LongDisplayTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XSD.
+ /// </summary>
+ internal static string SearchKeywords {
+ get {
+ return ResourceManager.GetString("SearchKeywords", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XML Validator.
+ /// </summary>
+ internal static string ShortDisplayTitle {
+ get {
+ return ResourceManager.GetString("ShortDisplayTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Validation result will potentially always be &apos;valid&apos; since the XML does not reference the following &quot;targetNamespace&quot; defined in the XSD: {0}.
+ /// </summary>
+ internal static string TargetNamespaceNotDefinedInXml {
+ get {
+ return ResourceManager.GetString("TargetNamespaceNotDefinedInXml", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XML and XSD content must be set in order to perform a validation..
+ /// </summary>
+ internal static string ValidationImpossibleMsg {
+ get {
+ return ResourceManager.GetString("ValidationImpossibleMsg", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XML.
+ /// </summary>
+ internal static string XmlData {
+ get {
+ return ResourceManager.GetString("XmlData", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XML file selected doesn&apos;t exist..
+ /// </summary>
+ internal static string XmlFileNotFound {
+ get {
+ return ResourceManager.GetString("XmlFileNotFound", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Validation failed for an unknown reason..
+ /// </summary>
+ internal static string XmlInvalidMessage {
+ get {
+ return ResourceManager.GetString("XmlInvalidMessage", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Validation result will always be &apos;valid&apos; since the XML does not define these namespace(s) defined in the XSD: {0}.
+ /// </summary>
+ internal static string XmlNamespacesInconsistentMsg {
+ get {
+ return ResourceManager.GetString("XmlNamespacesInconsistentMsg", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Text or path to a XML file to treat..
+ /// </summary>
+ internal static string XmlOptionDescription {
+ get {
+ return ResourceManager.GetString("XmlOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XML is compliant to the defined XSD scheme..
+ /// </summary>
+ internal static string XmlValidMessage {
+ get {
+ return ResourceManager.GetString("XmlValidMessage", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XSD file selected doesn&apos;t exist..
+ /// </summary>
+ internal static string XsdFileNotFound {
+ get {
+ return ResourceManager.GetString("XsdFileNotFound", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Validation result will always be &apos;valid&apos; since the XSD does not define these namespace(s) defined in the XML: {0}.
+ /// </summary>
+ internal static string XsdNamespacesInconsistentMsg {
+ get {
+ return ResourceManager.GetString("XsdNamespacesInconsistentMsg", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Text or path to a XSD file to treat..
+ /// </summary>
+ internal static string XsdOptionDescription {
+ get {
+ return ResourceManager.GetString("XsdOptionDescription", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to XSD.
+ /// </summary>
+ internal static string XsdScheme {
+ get {
+ return ResourceManager.GetString("XsdScheme", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.resx b/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.resx
new file mode 100644
index 000000000..b05cd3008
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidator.resx
@@ -0,0 +1,177 @@
+<?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>Xml Validator tool</value>
+ </data>
+ <data name="Description" xml:space="preserve">
+ <value>Validate XML data via an XSD scheme.</value>
+ </data>
+ <data name="LongDisplayTitle" xml:space="preserve">
+ <value>XML Validator</value>
+ </data>
+ <data name="SearchKeywords" xml:space="preserve">
+ <value>XSD</value>
+ </data>
+ <data name="ShortDisplayTitle" xml:space="preserve">
+ <value>XML Validator</value>
+ </data>
+ <data name="XsdScheme" xml:space="preserve">
+ <value>XSD</value>
+ </data>
+ <data name="XmlData" xml:space="preserve">
+ <value>XML</value>
+ </data>
+ <data name="TargetNamespaceNotDefinedInXml" xml:space="preserve">
+ <value>Validation result will potentially always be 'valid' since the XML does not reference the following "targetNamespace" defined in the XSD: {0}</value>
+ </data>
+ <data name="ValidationImpossibleMsg" xml:space="preserve">
+ <value>XML and XSD content must be set in order to perform a validation.</value>
+ </data>
+ <data name="XmlInvalidMessage" xml:space="preserve">
+ <value>Validation failed for an unknown reason.</value>
+ </data>
+ <data name="XmlNamespacesInconsistentMsg" xml:space="preserve">
+ <value>Validation result will always be 'valid' since the XML does not define these namespace(s) defined in the XSD: {0}</value>
+ </data>
+ <data name="XmlValidMessage" xml:space="preserve">
+ <value>XML is compliant to the defined XSD scheme.</value>
+ </data>
+ <data name="XsdNamespacesInconsistentMsg" xml:space="preserve">
+ <value>Validation result will always be 'valid' since the XSD does not define these namespace(s) defined in the XML: {0}</value>
+ </data>
+ <data name="InvalidXmlOrFileCommand" xml:space="preserve">
+ <value>Please specify an input XML</value>
+ </data>
+ <data name="InvalidXsdOrFileCommand" xml:space="preserve">
+ <value>Please specify an input XSD</value>
+ </data>
+ <data name="XmlFileNotFound" xml:space="preserve">
+ <value>XML file selected doesn't exist.</value>
+ </data>
+ <data name="XmlOptionDescription" xml:space="preserve">
+ <value>Text or path to a XML file to treat.</value>
+ </data>
+ <data name="XsdFileNotFound" xml:space="preserve">
+ <value>XSD file selected doesn't exist.</value>
+ </data>
+ <data name="XsdOptionDescription" xml:space="preserve">
+ <value>Text or path to a XSD file to treat.</value>
+ </data>
+</root>
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorCommandLineTool.cs b/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorCommandLineTool.cs
new file mode 100644
index 000000000..7f5f59782
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorCommandLineTool.cs
@@ -0,0 +1,93 @@
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+using Microsoft.Extensions.Logging;
+using OneOf;
+
+namespace DevToys.Tools.Tools.Text.XMLValidator;
+
+[Export(typeof(ICommandLineTool))]
+[Name("XMLValidator")]
+[CommandName(
+ Name = "xmlvalidator",
+ Alias = "xsd",
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Text.XMLValidator.XMLValidator",
+ DescriptionResourceName = nameof(XMLValidator.Description))]
+internal sealed class XMLValidatorCommandLineTool : ICommandLineTool
+{
+#pragma warning disable IDE0044 // Add readonly modifier
+ [Import]
+ private IFileStorage _fileStorage = null!;
+#pragma warning restore IDE0044 // Add readonly modifier
+
+ [CommandLineOption(
+ Name = "xsd",
+ Alias = "s",
+ IsRequired = true,
+ DescriptionResourceName = nameof(XMLValidator.XsdOptionDescription))]
+ private OneOf<FileInfo, string>? XsdFile { get; set; }
+
+ [CommandLineOption(
+ Name = "xml",
+ Alias = "x",
+ IsRequired = true,
+ DescriptionResourceName = nameof(XMLValidator.XmlOptionDescription))]
+ private OneOf<FileInfo, string>? XmlFile { get; set; }
+
+ public async ValueTask<int> InvokeAsync(ILogger logger, CancellationToken cancellationToken)
+ {
+ if (!XsdFile.HasValue)
+ {
+ Console.Error.WriteLine(XMLValidator.InvalidXsdOrFileCommand);
+ return -1;
+ }
+
+ ResultInfo<string> xsd = await XsdFile.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
+ if (!xsd.HasSucceeded)
+ {
+ Console.Error.WriteLine(XMLValidator.XsdFileNotFound);
+ return -1;
+ }
+
+ if (!XmlFile.HasValue)
+ {
+ Console.Error.WriteLine(XMLValidator.InvalidXmlOrFileCommand);
+ return -1;
+ }
+
+ ResultInfo<string> xml = await XmlFile.Value.ReadAllTextAsync(_fileStorage, cancellationToken);
+ if (!xml.HasSucceeded)
+ {
+ Console.Error.WriteLine(XMLValidator.XmlFileNotFound);
+ return -1;
+ }
+
+ ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsd.Data, xml.Data, logger, cancellationToken);
+
+ switch (result.Severity)
+ {
+ case XmlValidatorResultSeverity.Success:
+ return 0;
+
+ case XmlValidatorResultSeverity.Warning:
+ Console.Error.WriteLine(result.Data);
+ return -1;
+
+ case XmlValidatorResultSeverity.Error:
+ string errorDescription;
+ if (string.IsNullOrWhiteSpace(result.Data))
+ {
+ errorDescription = XMLValidator.XmlInvalidMessage;
+ }
+ else
+ {
+ errorDescription = result.Data;
+ }
+
+ Console.Error.WriteLine(errorDescription);
+ return -1;
+
+ default:
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorGuiTool.cs b/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorGuiTool.cs
new file mode 100644
index 000000000..e0c6a5a2a
--- /dev/null
+++ b/src/app/dev/DevToys.Tools/Tools/Text/XMLValidator/XMLValidatorGuiTool.cs
@@ -0,0 +1,172 @@
+using DevToys.Tools.Helpers;
+using DevToys.Tools.Models;
+using Microsoft.Extensions.Logging;
+
+namespace DevToys.Tools.Tools.Text.XMLValidator;
+
+[Export(typeof(IGuiTool))]
+[Name("XMLValidator")]
+[ToolDisplayInformation(
+ IconFontName = "DevToys-Tools-Icons",
+ IconGlyph = '\u0116',
+ GroupName = PredefinedCommonToolGroupNames.Text,
+ ResourceManagerAssemblyIdentifier = nameof(DevToysToolsResourceManagerAssemblyIdentifier),
+ ResourceManagerBaseName = "DevToys.Tools.Tools.Text.XMLValidator.XMLValidator",
+ ShortDisplayTitleResourceName = nameof(XMLValidator.ShortDisplayTitle),
+ LongDisplayTitleResourceName = nameof(XMLValidator.LongDisplayTitle),
+ DescriptionResourceName = nameof(XMLValidator.Description),
+ AccessibleNameResourceName = nameof(XMLValidator.AccessibleName),
+ SearchKeywordsResourceName = nameof(XMLValidator.SearchKeywords))]
+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Xml)]
+[AcceptedDataTypeName(PredefinedCommonDataTypeNames.Xsd)]
+internal sealed class XMLValidatorGuiTool : IGuiTool, IDisposable
+{
+ private enum GridRows
+ {
+ TopStretch,
+ BottomAuto,
+ }
+
+ private enum GridColumns
+ {
+ Stretch
+ }
+
+ private readonly ILogger _logger;
+ private readonly DisposableSemaphore _semaphore = new();
+ private readonly IUIMultiLineTextInput _xsdInputText = MultilineTextInput();
+ private readonly IUIMultiLineTextInput _xmlInputText = MultilineTextInput();
+ private readonly IUIInfoBar _infoBar = InfoBar();
+
+ private CancellationTokenSource? _cancellationTokenSource;
+
+ [ImportingConstructor]
+ internal XMLValidatorGuiTool()
+ {
+ _logger = this.Log();
+ }
+
+ // For unit tests.
+ internal Task? WorkTask { get; private set; }
+
+ public UIToolView View
+ => new(
+ isScrollable: false,
+ Grid()
+ .ColumnMediumSpacing()
+
+ .Rows(
+ (GridRows.TopStretch, new UIGridLength(1, UIGridUnitType.Fraction)),
+ (GridRows.BottomAuto, Auto))
+
+ .Columns(
+ (GridColumns.Stretch, new UIGridLength(1, UIGridUnitType.Fraction)))
+
+ .Cells(
+ Cell(
+ GridRows.TopStretch,
+ GridColumns.Stretch,
+
+ SplitGrid()
+ .Vertical()
+ .WithLeftPaneChild(
+ _xsdInputText
+ .Title(XMLValidator.XsdScheme)
+ .Language("xml")
+ .CanCopyWhenEditable()
+ .Extendable()
+ .OnTextChanged(OnInputChanged))
+
+ .WithRightPaneChild(
+ _xmlInputText
+ .Title(XMLValidator.XmlData)
+ .Language("xml")
+ .CanCopyWhenEditable()
+ .Extendable()
+ .OnTextChanged(OnInputChanged))),
+
+ Cell(
+ GridRows.BottomAuto,
+ GridColumns.Stretch,
+
+ _infoBar
+ .NonClosable()
+ .Open())));
+
+ public void Dispose()
+ {
+ _cancellationTokenSource?.Cancel();
+ _cancellationTokenSource?.Dispose();
+ _semaphore.Dispose();
+ }
+
+ public void OnDataReceived(string dataTypeName, object? parsedData)
+ {
+ if (dataTypeName == PredefinedCommonDataTypeNames.Xml && parsedData is string xml)
+ {
+ _xmlInputText.Text(xml);
+ }
+ else if (dataTypeName == PredefinedCommonDataTypeNames.Xsd && parsedData is string xsd)
+ {
+ _xsdInputText.Text(xsd);
+ }
+ }
+
+ private void OnInputChanged(string _)
+ {
+ _cancellationTokenSource?.Cancel();
+ _cancellationTokenSource?.Dispose();
+ _cancellationTokenSource = new CancellationTokenSource();
+
+ WorkTask = ValidateAsync(_xsdInputText.Text, _xmlInputText.Text, _cancellationTokenSource.Token);
+ }
+
+ private async Task ValidateAsync(string xsd, string xml, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrWhiteSpace(xsd) || string.IsNullOrWhiteSpace(xml))
+ {
+ _infoBar
+ .Description(XMLValidator.ValidationImpossibleMsg)
+ .Informational();
+ return;
+ }
+
+ await TaskSchedulerAwaiter.SwitchOffMainThreadAsync(cancellationToken);
+
+ ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsd, xml, _logger, cancellationToken);
+
+ switch (result.Severity)
+ {
+ case XmlValidatorResultSeverity.Success:
+ _infoBar
+ .Description(XMLValidator.XmlValidMessage)
+ .Success();
+ break;
+
+ case XmlValidatorResultSeverity.Warning:
+ _infoBar
+ .Description(result.Data)
+ .Warning();
+ break;
+
+ case XmlValidatorResultSeverity.Error:
+ string errorDescription;
+ if (string.IsNullOrWhiteSpace(result.Data))
+ {
+ errorDescription = XMLValidator.XmlInvalidMessage;
+ }
+ else
+ {
+ errorDescription = result.Data;
+ }
+
+ _infoBar
+ .Description(errorDescription)
+ .Error();
+ break;
+
+ default:
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj
index 7cec6444c..cda81f693 100644
--- a/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj
+++ b/src/app/tests/DevToys.UnitTests/DevToys.UnitTests.csproj
@@ -6,18 +6,66 @@
</PropertyGroup>
<ItemGroup>
- <Content Include="Tools\TestData\*\*.*">
- <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+ <Content Include="Tools\TestData\Base64ImageEncoderDecoder\PNG_transparency_demonstration_1.png">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\Base64ImageEncoderDecoder\Png_transparency_demonstration_1_base64.txt">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\HashAndChecksumGenerator\Checksum.txt">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\HashAndChecksumGenerator\File.txt">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\JsonYamlConverter\FourSpaces.json">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\JsonYamlConverter\FourSpaces.yaml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\JsonYamlConverter\Invalid.json">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\JsonYamlConverter\Invalid.yaml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\JsonYamlConverter\TwoSpaces.json">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\JsonYamlConverter\TwoSpaces.yaml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\XmlFormatter\FourSpaces.xml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\XmlFormatter\Minified.xml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\XmlFormatter\NewLineOnAttributes.xml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\XmlFormatter\OneTab.xml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\XmlFormatter\TwoSpaces.xml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
+ <Content Include="Tools\TestData\XmlFormatter\ValidXml.xml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
- <None Remove="Tools\TestData\XmlFormatter\FourSpaces.xml" />
- <None Remove="Tools\TestData\XmlFormatter\Minified.xml" />
- <None Remove="Tools\TestData\XmlFormatter\NewLineOnAttributes.xml" />
- <None Remove="Tools\TestData\XmlFormatter\OneTab.xml" />
- <None Remove="Tools\TestData\XmlFormatter\TwoSpaces.xml" />
- <None Remove="Tools\TestData\XmlFormatter\ValidXml.xml" />
+ <EmbeddedResource Include="Tools\TestData\XmlValidator\InvalidXml.xml" />
+ <EmbeddedResource Include="Tools\TestData\XmlValidator\InvalidXsd.xml" />
+ <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXml.xml" />
+ <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXmlWithNamespace.xml" />
+ <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXmlWithoutNamespace.xml" />
+ <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXsd.xml" />
+ <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXsdOnlyWithTargetNamespace.xml" />
+ <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXsdWithNamespace.xml" />
+ <EmbeddedResource Include="Tools\TestData\XmlValidator\ValidXsdWithoutNamespace.xml" />
</ItemGroup>
<ItemGroup>
diff --git a/src/app/tests/DevToys.UnitTests/Tools/Helpers/XsdHelperTests.cs b/src/app/tests/DevToys.UnitTests/Tools/Helpers/XsdHelperTests.cs
new file mode 100644
index 000000000..a03a4aa1c
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/Helpers/XsdHelperTests.cs
@@ -0,0 +1,98 @@
+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 XsdHelperTests
+{
+ [Fact]
+ public async Task ValidateXml_InvalidXmlFile()
+ {
+ string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsd.xml");
+ string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.InvalidXml.xml");
+
+ ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);
+
+ result.Severity.Should().Be(XmlValidatorResultSeverity.Error);
+ }
+
+ [Fact]
+ public async Task ValidateXml_ValidXmlSchema()
+ {
+ string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsd.xml");
+ string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXml.xml");
+
+ ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);
+
+ result.Severity.Should().Be(XmlValidatorResultSeverity.Success);
+ }
+
+ [Fact]
+ public async Task ValidateXml_InvalidXsdSchema()
+ {
+ string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.InvalidXsd.xml");
+ string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXml.xml");
+
+ ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);
+
+ result.Severity.Should().Be(XmlValidatorResultSeverity.Error);
+ }
+
+ [Fact]
+ public async Task ValidateXml_NoNamespacesMissing()
+ {
+ string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsdWithNamespace.xml");
+ string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXmlWithNamespace.xml");
+
+ ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);
+
+ result.Severity.Should().Be(XmlValidatorResultSeverity.Success);
+ }
+
+ [Fact]
+ public async Task ValidateXml_XsdTargetNamespaceIsNotPredefinedElsewhereInXsdHeader()
+ {
+ string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsd.xml");
+ string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXml.xml");
+
+ ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);
+
+ result.Severity.Should().Be(XmlValidatorResultSeverity.Success);
+ }
+
+ [Fact]
+ public async Task ValidateXml_NamespacesMissingInXml()
+ {
+ string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsdWithNamespace.xml");
+ string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXmlWithoutNamespace.xml");
+
+ ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);
+
+ result.Severity.Should().Be(XmlValidatorResultSeverity.Warning);
+ }
+
+ [Fact]
+ public async Task ValidateXml_NamespacesMissingInXsd()
+ {
+ string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsdWithoutNamespace.xml");
+ string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXmlWithNamespace.xml");
+
+ ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);
+
+ result.Severity.Should().Be(XmlValidatorResultSeverity.Warning);
+ }
+
+ [Fact]
+ public async Task ValidateXml_XmlIsMissingTargetedNamespace()
+ {
+ string xsdSchemaString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXsdOnlyWithTargetNamespace.xml");
+ string xmlDataString = await TestDataProvider.GetFileContent("DevToys.UnitTests.Tools.TestData.XmlValidator.ValidXmlWithoutNamespace.xml");
+
+ ResultInfo<string, XmlValidatorResultSeverity> result = XsdHelper.ValidateXmlAgainstXsd(xsdSchemaString, xmlDataString, new MockILogger(), CancellationToken.None);
+
+ result.Severity.Should().Be(XmlValidatorResultSeverity.Warning);
+ }
+}
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/InvalidXml.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/InvalidXml.xml
new file mode 100644
index 000000000..f6ded868a
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/InvalidXml.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<bookstore xmlns="http://www.contoso.com/books">
+ <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
+ <title>The Autobiography of Benjamin Franklin</title>
+ <author>
+ <first-name>Benjamin</first-name>
+ <last-name>Franklin</last-name>
+ </author>
+ <price>8.99</price>
+ </book>
+
+ I am an invalid XML file!!!!!!!!!!!
+
+ <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2"/>/
+ <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
+ <title>The Gorgias</title>
+ <author>
+ <name>Plato</name>
+ </author>
+ <price>9.99</price>
+ </book>
+</bookstore>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/InvalidXsd.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/InvalidXsd.xml
new file mode 100644
index 000000000..1acddcf94
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/InvalidXsd.xml
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.contoso.com/books" xmlns:xs="http://www.w3.org/2001/XMLSchema">-->
+
+ THIS BEAUTIFUL XSD FILE SHOULD NOT COMPILE!!!!!!!!!!!!
+
+ <xs:element name="bookstore">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element maxOccurs="unbounded" name="book">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="title" type="xs:string" />
+ <xs:element name="author">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element minOccurs="0" name="name" type="xs:string" />
+ <xs:element minOccurs="0" name="first-name" type="xs:string" />
+ <xs:element minOccurs="0" name="last-name" type="xs:string" />
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+ <xs:element name="price" type="xs:decimal" />
+ </xs:sequence>
+ <xs:attribute name="genre" type="xs:string" use="required" />
+ <xs:attribute name="publicationdate" type="xs:date" use="required" />
+ <xs:attribute name="ISBN" type="xs:string" use="required" />
+ </xs:complexType>
+ </xs:element>
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+</xs:schema>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXml.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXml.xml
new file mode 100644
index 000000000..c33dd4dec
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXml.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<bookstore xmlns="http://www.contoso.com/books">
+ <book genre="autobiography" publicationdate="1981-03-22" ISBN="1-861003-11-0">
+ <title>The Autobiography of Benjamin Franklin</title>
+ <author>
+ <first-name>Benjamin</first-name>
+ <last-name>Franklin</last-name>
+ </author>
+ <price>8.99</price>
+ </book>
+ <book genre="novel" publicationdate="1967-11-17" ISBN="0-201-63361-2">
+ <title>The Confidence Man</title>
+ <author>
+ <first-name>Herman</first-name>
+ <last-name>Melville</last-name>
+ </author>
+ <price>11.99</price>
+ </book>
+ <book genre="philosophy" publicationdate="1991-02-15" ISBN="1-861001-57-6">
+ <title>The Gorgias</title>
+ <author>
+ <name>Plato</name>
+ </author>
+ <price>9.99</price>
+ </book>
+</bookstore>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXmlWithNamespace.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXmlWithNamespace.xml
new file mode 100644
index 000000000..b6462fdd9
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXmlWithNamespace.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0"?>
+<note xmlns="https://www.w3schools.com">
+ <to>Tove</to>
+ <from>Jani</from>
+ <heading>Reminder</heading>
+ <body>Don't forget me this weekend!</body>
+</note>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXmlWithoutNamespace.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXmlWithoutNamespace.xml
new file mode 100644
index 000000000..e6b3ff6a5
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXmlWithoutNamespace.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0"?>
+<note>
+ <to>Tove</to>
+ <from>Jani</from>
+ <heading>Reminder</heading>
+ <body>Don't forget me this weekend!</body>
+</note>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsd.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsd.xml
new file mode 100644
index 000000000..d9ecaf7ef
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsd.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.contoso.com/books" xmlns:xs="http://www.w3.org/2001/XMLSchema">
+ <xs:element name="bookstore">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element maxOccurs="unbounded" name="book">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="title" type="xs:string" />
+ <xs:element name="author">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element minOccurs="0" name="name" type="xs:string" />
+ <xs:element minOccurs="0" name="first-name" type="xs:string" />
+ <xs:element minOccurs="0" name="last-name" type="xs:string" />
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+ <xs:element name="price" type="xs:decimal" />
+ </xs:sequence>
+ <xs:attribute name="genre" type="xs:string" use="required" />
+ <xs:attribute name="publicationdate" type="xs:date" use="required" />
+ <xs:attribute name="ISBN" type="xs:string" use="required" />
+ </xs:complexType>
+ </xs:element>
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+</xs:schema>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdOnlyWithTargetNamespace.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdOnlyWithTargetNamespace.xml
new file mode 100644
index 000000000..30e05557f
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdOnlyWithTargetNamespace.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+targetNamespace="https://www.w3schools.com"
+elementFormDefault="qualified">
+ <xs:element name="note">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="to" type="xs:string"/>
+ <xs:element name="from" type="xs:string"/>
+ <xs:element name="heading" type="xs:string"/>
+ <xs:element name="body" type="xs:string"/>
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+</xs:schema>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdWithNamespace.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdWithNamespace.xml
new file mode 100644
index 000000000..33a941876
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdWithNamespace.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
+targetNamespace="https://www.w3schools.com"
+xmlns="https://www.w3schools.com"
+elementFormDefault="qualified">
+ <xs:element name="note">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="to" type="xs:string"/>
+ <xs:element name="from" type="xs:string"/>
+ <xs:element name="heading" type="xs:string"/>
+ <xs:element name="body" type="xs:string"/>
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+</xs:schema>
\ No newline at end of file
diff --git a/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdWithoutNamespace.xml b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdWithoutNamespace.xml
new file mode 100644
index 000000000..f8a4d0598
--- /dev/null
+++ b/src/app/tests/DevToys.UnitTests/Tools/TestData/XmlValidator/ValidXsdWithoutNamespace.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
+ <xs:element name="note">
+ <xs:complexType>
+ <xs:sequence>
+ <xs:element name="to" type="xs:string"/>
+ <xs:element name="from" type="xs:string"/>
+ <xs:element name="heading" type="xs:string"/>
+ <xs:element name="body" type="xs:string"/>
+ </xs:sequence>
+ </xs:complexType>
+ </xs:element>
+</xs:schema>
\ No newline at end of file