Example #1
0
        /*
         * TODO (mristin, 2020-10-05): This test has been temporary disabled so that we can merge in the branch
         * MIHO/EnhanceDocumentShelf. The test should be fixed in a future pull request and we will then re-enable it
         * again.
         *
         * Please do not forget to remove the Resharper directive at the top of this class.
         *
         * [Test]
         *
         * dead-csharp ignore this comment
         */
        public void TestLoadSaveXmlValidate()
        {
            var validator = AasSchemaValidation.NewXmlValidator();

            List <string> aasxPaths = SamplesAasxDir.ListAasxPaths();

            using (var tmpDir = new TemporaryDirectory())
            {
                string tmpDirPath = tmpDir.Path;

                foreach (string aasxPath in aasxPaths)
                {
                    using (var package = new AdminShellPackageEnv(aasxPath))
                    {
                        /*
                         * TODO (mristin, 2020-09-17): Remove autofix once XSD and Aasx library in sync
                         *
                         * Package has been loaded, now we need to do an automatic check & fix.
                         *
                         * This is necessary as Aasx library is still not conform with the XSD AASX schema and breaks
                         * certain constraints (*e.g.*, the cardinality of langString = 1..*).
                         */
                        var recs = package.AasEnv.ValidateAll();
                        if (recs != null)
                        {
                            package.AasEnv.AutoFix(recs);
                        }

                        // Save as XML
                        string name    = Path.GetFileName(aasxPath);
                        string outPath = System.IO.Path.Combine(tmpDirPath, $"{name}.converted.xml");
                        package.SaveAs(outPath, writeFreshly: true);

                        using (var fileStream = System.IO.File.OpenRead(outPath))
                        {
                            var records = new AasValidationRecordList();
                            validator.Validate(records, fileStream);
                            if (records.Count != 0)
                            {
                                var parts = new List <string>
                                {
                                    $"Failed to validate XML file exported from {aasxPath} to {outPath}:"
                                };
                                parts.AddRange(records.Select((r) => r.Message));
                                throw new AssertionException(string.Join(Environment.NewLine, parts));
                            }
                        }
                    }
                }
            }
        }
Example #2
0
        public void TestSuccess()
        {
            string successDir = Path.Combine(
                TestContext.CurrentContext.TestDirectory,
                "TestResources\\XmlValidation\\expectedOk");

            if (!System.IO.Directory.Exists(successDir))
            {
                throw new InvalidOperationException(
                          $"The directory containing the valid AAS XML files does not exist or is not a directory: " +
                          successDir);
            }

            var paths = System.IO.Directory.GetFiles(successDir)
                        .Where(p => System.IO.Path.GetExtension(p) == ".xml")
                        .ToList();

            if (paths.Count == 0)
            {
                throw new InvalidOperationException(
                          $"No *.xml files were found in the directory expected to contain the valid XML files: " +
                          successDir);
            }

            var validator = AasSchemaValidation.NewXmlValidator();

            foreach (string path in paths)
            {
                using (var fileStream = System.IO.File.OpenRead(path))
                {
                    var records = new AasValidationRecordList();
                    validator.Validate(records, fileStream);
                    if (records.Count != 0)
                    {
                        var parts = new List <string>
                        {
                            $"Failed to validate XML file {path}:"
                        };
                        parts.AddRange(records.Select((r) => r.Message));
                        throw new AssertionException(string.Join(Environment.NewLine, parts));
                    }
                }
            }
        }
        /// <summary>
        /// validates the given XML content and stores the results in the <paramref name="recs"/>.
        /// </summary>
        /// <param name="recs">Validation records</param>
        /// <param name="xmlContent">Content to be validated</param>
        public void Validate(AasValidationRecordList recs, Stream xmlContent)
        {
            if (recs == null)
            {
                throw new ArgumentException($"Unexpected null {nameof(recs)}");
            }

            if (xmlContent == null)
            {
                throw new ArgumentException($"Unexpected null {nameof(xmlContent)}");
            }

            // load/ validate on same records
            var settings = new System.Xml.XmlReaderSettings();

            settings.ValidationType = System.Xml.ValidationType.Schema;
            settings.Schemas        = xmlSchemaSet;

            settings.ValidationEventHandler +=
                (object sender, System.Xml.Schema.ValidationEventArgs e) =>
            {
                recs.Add(
                    new AasValidationRecord(
                        AasValidationSeverity.Serialization, null,
                        $"XML: {e?.Exception?.LineNumber}, {e?.Exception?.LinePosition}: {e?.Message}"));
            };

            // use the xml stream
            using (var reader = System.Xml.XmlReader.Create(xmlContent, settings))
            {
                while (reader.Read())
                {
                    // Invoke callbacks
                }
                ;
            }
        }
        public static int ValidateJSONAlternative(AasValidationRecordList recs, Stream jsonContent)
        {
            // see: https://github.com/RicoSuter/NJsonSchema/wiki/JsonSchemaValidator
            var newRecs = new AasValidationRecordList();

            // access
            if (recs == null || jsonContent == null)
            {
                return(-1);
            }

            // Load the schema files
            // right now: exactly ONE schema file
            var files = GetSchemaResources(SerializationFormat.JSON);

            if (files == null || files.Length != 1)
            {
                return(-1);
            }

            NJsonSchema.JsonSchema schema = null;

            try
            {
                Assembly myAssembly = Assembly.GetExecutingAssembly();
                foreach (var schemaFn in files)
                {
                    using (Stream schemaStream = myAssembly.GetManifestResourceStream(schemaFn))
                    {
                        using (var streamReader = new StreamReader(schemaStream))
                        {
                            var allTxt = streamReader.ReadToEnd();
                            schema = NJsonSchema.JsonSchema.FromJsonAsync(allTxt).GetAwaiter().GetResult();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new FileNotFoundException("ValidateJSON: Error loading schema: " +
                                                ex.Message);
            }

            if (schema == null)
            {
                throw new FileNotFoundException("ValidateJSON: Schema not found properly.");
            }

            // create validator
            var validator = new NJsonSchema.Validation.JsonSchemaValidator();

            // load the JSON content
            string jsonTxt = null;

            try
            {
                using (var streamReader = new StreamReader(jsonContent))
                {
                    jsonTxt = streamReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("ValidateJSON: Error loading JSON content: " +
                                                    ex.Message);
            }

            if (jsonTxt == null || jsonTxt == "")
            {
                throw new InvalidOperationException("ValidateJSON: Error loading JSON content gave null.");
            }

            // validate
            ICollection <NJsonSchema.Validation.ValidationError> errors;

            try
            {
                errors = validator.Validate(jsonTxt, schema);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("ValidateJSON: Error when validating: " +
                                                    ex.Message);
            }

            // re-format messages
            if (errors != null)
            {
                foreach (var ve in errors)
                {
                    var msg = ("" + ve.ToString());
                    msg = Regex.Replace(msg, @"\s+", " ");
                    newRecs.Add(new AasValidationRecord(AasValidationSeverity.Serialization, null,
                                                        $"JSON: {ve.LineNumber,5},{ve.LinePosition:3}: {msg}"));
                }
            }

            // result
            recs.AddRange(newRecs);
            return(newRecs.Count);
        }
        /// <summary>
        /// creates an XML validator and applies it on the given content.
        ///
        /// If you repeatedly need to validate XML against a schema, re-use an instance of
        /// <see cref="XmlValidator"/> produced with <see cref="NewXmlValidator"/>.
        /// </summary>
        /// <param name="recs">Validation records</param>
        /// <param name="xmlContent">Content to be validated</param>
        public static void ValidateXML(AasValidationRecordList recs, Stream xmlContent)
        {
            var validator = NewXmlValidator();

            validator.Validate(recs, xmlContent);
        }
        /// <summary>
        /// produces a validator which validates XML AASX files.
        /// </summary>
        /// <returns>initialized validator</returns>
        public static XmlValidator NewXmlValidator()
        {
            // Load the schema files
            var files = GetSchemaResources(SerializationFormat.XML);

            if (files == null)
            {
                throw new InvalidOperationException("No XML schema files could be found in the resources.");
            }

            var xmlSchemaSet = new System.Xml.Schema.XmlSchemaSet();

            xmlSchemaSet.XmlResolver = new System.Xml.XmlUrlResolver();

            try
            {
                Assembly myAssembly = Assembly.GetExecutingAssembly();
                foreach (var schemaFn in files)
                {
                    using (Stream schemaStream = myAssembly.GetManifestResourceStream(schemaFn))
                    {
                        using (XmlReader schemaReader = XmlReader.Create(schemaStream))
                        {
                            xmlSchemaSet.Add(null, schemaReader);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new FileNotFoundException(
                          $"Error accessing embedded resource schema files: {ex.Message}");
            }

            var newRecs = new AasValidationRecordList();

            // set up messages
            xmlSchemaSet.ValidationEventHandler += (object sender, System.Xml.Schema.ValidationEventArgs e) =>
            {
                newRecs.Add(
                    new AasValidationRecord(
                        AasValidationSeverity.Serialization, null,
                        $"{e?.Exception?.LineNumber}, {e?.Exception?.LinePosition}: {e?.Message}"));
            };

            // compile
            try
            {
                xmlSchemaSet.Compile();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(
                          $"Error compiling schema files: {ex.Message}");
            }

            if (newRecs.Count > 0)
            {
                var parts = new List <string> {
                    $"Failed to compile the schema files:"
                };
                parts.AddRange(newRecs.Select <AasValidationRecord, string>((r) => r.Message));
                throw new InvalidOperationException(string.Join(Environment.NewLine, parts));
            }

            return(new XmlValidator(xmlSchemaSet));
        }
        public static int ValidateXML(AasValidationRecordList recs, Stream xmlContent)
        {
            // see: AasxCsharpLibrary.Tests/TestLoadSave.cs
            var newRecs = new AasValidationRecordList();

            // access
            if (recs == null || xmlContent == null)
            {
                return(-1);
            }

            // Load the schema files
            var files = GetSchemaResources(SerializationFormat.XML);

            if (files == null)
            {
                return(-1);
            }

            var xmlSchemaSet = new System.Xml.Schema.XmlSchemaSet();

            xmlSchemaSet.XmlResolver = new System.Xml.XmlUrlResolver();

            try
            {
                Assembly myAssembly = Assembly.GetExecutingAssembly();
                foreach (var schemaFn in files)
                {
                    using (Stream schemaStream = myAssembly.GetManifestResourceStream(schemaFn))
                    {
                        using (XmlReader schemaReader = XmlReader.Create(schemaStream))
                        {
                            xmlSchemaSet.Add(null, schemaReader);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new FileNotFoundException("ValidateXML: Error accessing embedded resource schema files: " +
                                                ex.Message);
            }

            // set up messages
            xmlSchemaSet.ValidationEventHandler += (object sender, System.Xml.Schema.ValidationEventArgs e) =>
            {
                newRecs.Add(new AasValidationRecord(AasValidationSeverity.Serialization, null,
                                                    "" + e?.Exception?.LineNumber + ", " + e?.Exception?.LinePosition + ": " + e?.Message));
            };

            // compile
            try
            {
                xmlSchemaSet.Compile();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("ValidateXML: Error compiling schema files: " +
                                                    ex.Message);
            }

            if (newRecs.Count > 0)
            {
                var parts = new List <string> {
                    $"Failed to compile the schema files:"
                };
                parts.AddRange(newRecs.Select <AasValidationRecord, string>((r) => r.Message));
                throw new InvalidOperationException(string.Join(Environment.NewLine, parts));
            }

            // load/ validate on same records
            var settings = new System.Xml.XmlReaderSettings();

            settings.ValidationType = System.Xml.ValidationType.Schema;
            settings.Schemas        = xmlSchemaSet;

            settings.ValidationEventHandler +=
                (object sender, System.Xml.Schema.ValidationEventArgs e) =>
            {
                newRecs.Add(new AasValidationRecord(AasValidationSeverity.Serialization, null,
                                                    "XML: " + e?.Exception?.LineNumber + ", " + e?.Exception?.LinePosition + ": " + e?.Message));
            };

            // use the xml stream
            using (var reader = System.Xml.XmlReader.Create(xmlContent, settings))
            {
                while (reader.Read())
                {
                    // Invoke callbacks
                }
                ;
            }

            // result
            recs.AddRange(newRecs);
            return(newRecs.Count);
        }