Ejemplo n.º 1
0
        static void LoadOperationalTemplateSchemas(System.Xml.Schema.XmlSchemaSet xs)
        {
            if (!xs.Contains(RmXmlSerializer.OpenEhrNamespace))
            {
                System.Xml.Schema.XmlSchema baseTypesSchema = RmXmlSerializer.GetOpenEhrSchema("BaseTypes");

                System.Xml.Schema.XmlSchema resourceSchema = RmXmlSerializer.GetOpenEhrSchema("Resource");
                resourceSchema.Includes.Clear();
                System.Xml.Schema.XmlSchemaInclude include = new System.Xml.Schema.XmlSchemaInclude();
                include.Schema = baseTypesSchema;
                resourceSchema.Includes.Add(include);

                System.Xml.Schema.XmlSchema archetypeSchema = RmXmlSerializer.GetOpenEhrSchema("Archetype");
                archetypeSchema.Includes.Clear();
                include        = new System.Xml.Schema.XmlSchemaInclude();
                include.Schema = resourceSchema;
                archetypeSchema.Includes.Add(include);

                System.Xml.Schema.XmlSchema openEhrProfileSchema = RmXmlSerializer.GetOpenEhrSchema("OpenehrProfile");
                openEhrProfileSchema.Includes.Clear();
                include        = new System.Xml.Schema.XmlSchemaInclude();
                include.Schema = archetypeSchema;
                openEhrProfileSchema.Includes.Add(include);

                System.Xml.Schema.XmlSchema templateSchema = RmXmlSerializer.GetOpenEhrSchema("Template");
                templateSchema.Includes.Clear();
                include        = new System.Xml.Schema.XmlSchemaInclude();
                include.Schema = openEhrProfileSchema;
                templateSchema.Includes.Add(include);
                xs.Add(templateSchema);

                xs.Compile();
            }
        }
Ejemplo n.º 2
0
        private bool ValidateXML(XElement xml)
        {
            if (System.IO.File.Exists(tbXSD_Path.Text))
            {
                _SchemaSet.Add(null, tbXSD_Path.Text);
                XDocument doc = new XDocument(new XElement("Root",
                                                           new XElement("AuthData", new XElement("Login"), new XElement("Pass")),
                                                           xml
                                                           ));

                bool foundError = false;
                System.Xml.Schema.Extensions.Validate(doc, _SchemaSet, (sender, e) =>
                {
                    foundError = true;
                    MessageBox.Show(e.Message, "Ошибка в XML", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                });

                if (foundError && !SharedClasses.Utility.ShowChoiceMessageBox("Продолжить выгрузку данных?", "Выбор"))
                {
                    return(false);
                }
            }
            else
            {
                MessageBox.Show("Валидация пропущена: не найден файл схемы.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            return(true);
        }
Ejemplo n.º 3
0
        public static System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            OneTableDataSet ds = new OneTableDataSet();

            System.Xml.Schema.XmlSchemaComplexType type     = new System.Xml.Schema.XmlSchemaComplexType();
            System.Xml.Schema.XmlSchemaSequence    sequence = new System.Xml.Schema.XmlSchemaSequence();
            xs.Add(ds.GetSchemaSerializable());
            if (PublishLegacyWSDL())
            {
                System.Xml.Schema.XmlSchemaAny any = new System.Xml.Schema.XmlSchemaAny();
                any.Namespace = ds.Namespace;
                sequence.Items.Add(any);
            }
            else
            {
                System.Xml.Schema.XmlSchemaAny any1 = new System.Xml.Schema.XmlSchemaAny();
                any1.Namespace       = "http://www.w3.org/2001/XMLSchema";
                any1.MinOccurs       = new decimal(0);
                any1.ProcessContents = System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any1);
                System.Xml.Schema.XmlSchemaAny any2 = new System.Xml.Schema.XmlSchemaAny();
                any2.Namespace       = "urn:schemas-microsoft-com:xml-diffgram-v1";
                any2.MinOccurs       = new decimal(0);
                any2.ProcessContents = System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any2);
                sequence.MaxOccurs = decimal.MaxValue;
                System.Xml.Schema.XmlSchemaAttribute attribute = new System.Xml.Schema.XmlSchemaAttribute();
                attribute.Name       = "namespace";
                attribute.FixedValue = ds.Namespace;
                type.Attributes.Add(attribute);
            }
            type.Particle = sequence;
            return(type);
        }
Ejemplo n.º 4
0
            public static System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(System.Xml.Schema.XmlSchemaSet xs)
            {
                System.Xml.Schema.XmlSchemaComplexType type     = new System.Xml.Schema.XmlSchemaComplexType();
                System.Xml.Schema.XmlSchemaSequence    sequence = new System.Xml.Schema.XmlSchemaSequence();
                Dataset1 ds = new Dataset1();

                xs.Add(ds.GetSchemaSerializable());
                System.Xml.Schema.XmlSchemaAny any1 = new System.Xml.Schema.XmlSchemaAny();
                any1.Namespace       = "http://www.w3.org/2001/XMLSchema";
                any1.MinOccurs       = new decimal(0);
                any1.MaxOccurs       = decimal.MaxValue;
                any1.ProcessContents = System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any1);
                System.Xml.Schema.XmlSchemaAny any2 = new System.Xml.Schema.XmlSchemaAny();
                any2.Namespace       = "urn:schemas-microsoft-com:xml-diffgram-v1";
                any2.MinOccurs       = new decimal(1);
                any2.ProcessContents = System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any2);
                System.Xml.Schema.XmlSchemaAttribute attribute1 = new System.Xml.Schema.XmlSchemaAttribute();
                attribute1.Name       = "namespace";
                attribute1.FixedValue = ds.Namespace;
                type.Attributes.Add(attribute1);
                System.Xml.Schema.XmlSchemaAttribute attribute2 = new System.Xml.Schema.XmlSchemaAttribute();
                attribute2.Name       = "tableTypeName";
                attribute2.FixedValue = "CustomersDataTable";
                type.Attributes.Add(attribute2);
                type.Particle = sequence;
                return(type);
            }
Ejemplo n.º 5
0
        public bool IsValid(string xml, System.Xml.Schema.XmlSchema xd, bool reportWarnings = false)
        {
            // Create the schema object
            System.Xml.Schema.XmlSchemaSet sc = new System.Xml.Schema.XmlSchemaSet();
            _xml = xml;
            sc.Add(xd);
            // Create reader settings
            System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
            // Attach event handler whic will be fired when validation error occurs
            settings.ValidationEventHandler += XmlReader_ValidationCallBack;
            // Set validation type to schema
            settings.ValidationType = System.Xml.ValidationType.Schema;
            if (reportWarnings)
            {
                settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
            }
            //settings.ValidationFlags = settings.ValidationFlags Or System.Xml.Schema.XmlSchemaValidationFlags.ProcessInlineSchema
            //settings.ValidationFlags = settings.ValidationFlags Or System.Xml.Schema.XmlSchemaValidationFlags.ProcessSchemaLocation
            // Add to the collection of schemas in readerSettings
            settings.Schemas.Add(sc);
            //settings.ProhibitDtd = False
            // Create object of XmlReader using XmlReaderSettings
            System.IO.StringReader xmlMs = new System.IO.StringReader(xml);

            System.Xml.XmlReader reader = System.Xml.XmlReader.Create(xmlMs, settings);
            Exceptions = new List <System.Xml.Schema.XmlSchemaException>();

            // Parse the file.
            while (reader.Read())
            {
            }
            return(Exceptions.Count == 0);
        }
Ejemplo n.º 6
0
        private void LoadSqlPodXml()
        {
            //リソースからxsdファイルを読み込む
            Assembly myAssembly = Assembly.GetExecutingAssembly();
            Stream   xsdStream  = myAssembly.GetManifestResourceStream("SqlAccessor.XmlSchema.sqlPod.xsd");

            System.Xml.Schema.XmlSchema sqlPodSchema = System.Xml.Schema.XmlSchema.Read(xsdStream, null);

            //XMLの妥当性を検証するためのXML Schema
            System.Xml.Schema.XmlSchemaSet schemaSet = new System.Xml.Schema.XmlSchemaSet();
            schemaSet.Add(sqlPodSchema);

            //XMLの妥当性は検証する
            XmlReaderSettings readerSettings = new XmlReaderSettings();

            readerSettings.ValidationType = ValidationType.Schema;
            readerSettings.Schemas        = schemaSet;

            //コメント及び空白はスキップする
            readerSettings.IgnoreComments   = true;
            readerSettings.IgnoreWhitespace = true;

            XmlReader       aXmlReader      = XmlReader.Create(_sqlPodXml, readerSettings);
            XmlSimpleReader xmlSimpleReader = new XmlSimpleReader(aXmlReader);
            var             lookaheadReader = new LookaheadEnumerator <XmlSimpleReader.XmlElement>(xmlSimpleReader);

            using (lookaheadReader) {
                this.ParseSqlPodElement(lookaheadReader);
            }
        }
Ejemplo n.º 7
0
 public MmlReader()
 {
     string schemapath = System.Environment.CurrentDirectory + "\\MML23\\xsd";
     MmlSchemaSet = new System.Xml.Schema.XmlSchemaSet();
     foreach (string xsdfile in System.IO.Directory.GetFiles(schemapath)) {
         MmlSchemaSet.Add(null, xsdfile);
     }
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Resolve o esquema da consulta.
        /// </summary>
        /// <param name="xs"></param>
        public static void ResolveSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            var schema = Schema;

            if (!xs.Contains(schema))
            {
                xs.XmlResolver = new System.Xml.XmlUrlResolver();
                xs.Add(schema);
            }
        }
Ejemplo n.º 9
0
        public MmlReader()
        {
            string schemapath = System.Environment.CurrentDirectory + "\\MML23\\xsd";

            MmlSchemaSet = new System.Xml.Schema.XmlSchemaSet();
            foreach (string xsdfile in System.IO.Directory.GetFiles(schemapath))
            {
                MmlSchemaSet.Add(null, xsdfile);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Resolve o esquema da consulta.
        /// </summary>
        /// <param name="xs"></param>
        public static void ResolveRolePermissionSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            var querySchema = RolePermissionSchema;

            if (!xs.Contains(querySchema))
            {
                xs.XmlResolver = new System.Xml.XmlUrlResolver();
                xs.Add(querySchema);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Resolve o esquema da consulta.
        /// </summary>
        /// <param name="xs"></param>
        public static void ResolveQuerySchema(this System.Xml.Schema.XmlSchemaSet xs)
        {
            var querySchema = QuerySchema;

            if (!xs.Contains(querySchema))
            {
                xs.XmlResolver = new System.Xml.XmlUrlResolver();
                xs.Add(querySchema);
            }
        }
Ejemplo n.º 12
0
 public static System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(System.Xml.Schema.XmlSchemaSet xs) {
     DataSet1 ds = new DataSet1();
     System.Xml.Schema.XmlSchemaComplexType type = new System.Xml.Schema.XmlSchemaComplexType();
     System.Xml.Schema.XmlSchemaSequence sequence = new System.Xml.Schema.XmlSchemaSequence();
     xs.Add(ds.GetSchemaSerializable());
     System.Xml.Schema.XmlSchemaAny any = new System.Xml.Schema.XmlSchemaAny();
     any.Namespace = ds.Namespace;
     sequence.Items.Add(any);
     type.Particle = sequence;
     return type;
 }
Ejemplo n.º 13
0
        public static System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            CustomerAccountCCRMSchema ds = new CustomerAccountCCRMSchema();

            System.Xml.Schema.XmlSchemaComplexType type     = new System.Xml.Schema.XmlSchemaComplexType();
            System.Xml.Schema.XmlSchemaSequence    sequence = new System.Xml.Schema.XmlSchemaSequence();
            xs.Add(ds.GetSchemaSerializable());
            System.Xml.Schema.XmlSchemaAny any = new System.Xml.Schema.XmlSchemaAny();
            any.Namespace = ds.Namespace;
            sequence.Items.Add(any);
            type.Particle = sequence;
            return(type);
        }
        public static System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            F2010StateCodeSelectionData ds = new F2010StateCodeSelectionData();

            System.Xml.Schema.XmlSchemaComplexType type     = new System.Xml.Schema.XmlSchemaComplexType();
            System.Xml.Schema.XmlSchemaSequence    sequence = new System.Xml.Schema.XmlSchemaSequence();
            xs.Add(ds.GetSchemaSerializable());
            System.Xml.Schema.XmlSchemaAny any = new System.Xml.Schema.XmlSchemaAny();
            any.Namespace = ds.Namespace;
            sequence.Items.Add(any);
            type.Particle = sequence;
            return(type);
        }
        public static System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            ProjectFlowStatusProgressDs ds = new ProjectFlowStatusProgressDs();

            System.Xml.Schema.XmlSchemaComplexType type     = new System.Xml.Schema.XmlSchemaComplexType();
            System.Xml.Schema.XmlSchemaSequence    sequence = new System.Xml.Schema.XmlSchemaSequence();
            xs.Add(ds.GetSchemaSerializable());
            System.Xml.Schema.XmlSchemaAny any = new System.Xml.Schema.XmlSchemaAny();
            any.Namespace = ds.Namespace;
            sequence.Items.Add(any);
            type.Particle = sequence;
            return(type);
        }
Ejemplo n.º 16
0
        public static System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            View_Main_ReportsDataSet ds = new View_Main_ReportsDataSet();

            System.Xml.Schema.XmlSchemaComplexType type     = new System.Xml.Schema.XmlSchemaComplexType();
            System.Xml.Schema.XmlSchemaSequence    sequence = new System.Xml.Schema.XmlSchemaSequence();
            xs.Add(ds.GetSchemaSerializable());
            System.Xml.Schema.XmlSchemaAny any = new System.Xml.Schema.XmlSchemaAny();
            any.Namespace = ds.Namespace;
            sequence.Items.Add(any);
            type.Particle = sequence;
            return(type);
        }
        public static System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            RendererProviderConfig ds = new RendererProviderConfig();

            System.Xml.Schema.XmlSchemaComplexType type     = new System.Xml.Schema.XmlSchemaComplexType();
            System.Xml.Schema.XmlSchemaSequence    sequence = new System.Xml.Schema.XmlSchemaSequence();
            xs.Add(ds.GetSchemaSerializable());
            System.Xml.Schema.XmlSchemaAny any = new System.Xml.Schema.XmlSchemaAny();
            any.Namespace = ds.Namespace;
            sequence.Items.Add(any);
            type.Particle = sequence;
            return(type);
        }
Ejemplo n.º 18
0
        public static void ValidarXml(string xmlFilename, string schemaFilename)
        {
            var falhou        = false;
            var strValidation = new StringBuilder();

            // Define o tipo de validação
            var settings = new XmlReaderSettings();

            settings.ValidationType = ValidationType.Schema;
            // Carrega o arquivo de esquema
            var schemas = new System.Xml.Schema.XmlSchemaSet();

            settings.Schemas = schemas;
            // Quando carregar o eschema, especificar o namespace que ele valida
            // e a localização do arquivo
            schemas.Add(null, schemaFilename);
            // Especifica o tratamento de evento para os erros de validacao
            settings.ValidationEventHandler += (sender, args) =>
            {
                falhou = true;
                // Exibe o erro da validação
                strValidation.Append("Erros da validação : " + args.Message);
            };
            // cria um leitor para validação
            var validator = XmlReader.Create(xmlFilename, settings);

            try
            {
                // Faz a leitura de todos os dados XML
                while (validator.Read())
                {
                }
            }
            catch (XmlException err)
            {
                // Um erro ocorre se o documento XML inclui caracteres ilegais
                // ou tags que não estão aninhadas corretamente
                strValidation.Append("Ocorreu um erro critico durante a validacao XML.");
                strValidation.Append("Erros da validação : " + err.Message);
                falhou = true;
            }
            finally
            {
                validator.Close();
            }
            if (falhou)
            {
                throw new System.Exception(strValidation.ToString());
            }
        }
Ejemplo n.º 19
0
    public static XmlSchemaComplexType GetSchemaFile(
        System.Xml.Schema.XmlSchemaSet xs)
    {
        string xsdFile = Directory.GetCurrentDirectory() +
                         "\\Product.xsd";
        XmlSerializer schemaSerializer =
            new XmlSerializer(typeof(XmlSchema));
        XmlSchema schema =
            (XmlSchema)schemaSerializer.Deserialize(
                XmlReader.Create(xsdFile));

        xs.Add(schema);

        // target namespace
        string           tns  = "http://SchemaProvider.Example.org/Product.xsd";
        XmlQualifiedName name =
            new XmlQualifiedName("product_type", tns);
        XmlSchemaComplexType productType =
            (XmlSchemaComplexType)schema.SchemaTypes[name];

        return(productType);
    }
Ejemplo n.º 20
0
        public void TestLoadSaveXmlValidate()
        {
            // Load the schema

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

            xmlSchemaSet.XmlResolver = new Xml.XmlUrlResolver();

            string schemaPath = Path.Combine(
                TestContext.CurrentContext.TestDirectory,
                "Resources\\schemas\\xml\\AAS.xsd");

            xmlSchemaSet.Add(null, schemaPath);

            var schemaMessages = new List <string>();

            xmlSchemaSet.ValidationEventHandler +=
                (object sender, Xml.Schema.ValidationEventArgs e) => { schemaMessages.Add(e.Message); };
            xmlSchemaSet.Compile();

            if (schemaMessages.Count > 0)
            {
                var parts = new List <string> {
                    $"Failed to compile the schema: {schemaPath}"
                };
                parts.AddRange(schemaMessages);

                throw new InvalidOperationException(string.Join(Environment.NewLine, parts));
            }

            // Load-Save-Validate

            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))
                    {
                        string name    = Path.GetFileName(aasxPath);
                        string outPath = System.IO.Path.Combine(tmpDirPath, $"{name}.converted.xml");

                        package.SaveAs(outPath, writeFreshly: true);

                        var settings = new Xml.XmlReaderSettings();
                        settings.ValidationType = Xml.ValidationType.Schema;
                        settings.Schemas        = xmlSchemaSet;

                        var messages = new List <string>();
                        settings.ValidationEventHandler +=
                            (object sender, Xml.Schema.ValidationEventArgs e) =>
                        {
                            messages.Add(e.Message);
                        };

                        using (var reader = Xml.XmlReader.Create(outPath, settings))
                        {
                            while (reader.Read())
                            {
                                // Invoke callbacks
                            }
                            ;

                            if (messages.Count > 0)
                            {
                                var parts = new List <string>
                                {
                                    $"Failed to validate XML file exported from {aasxPath} to {outPath}:"
                                };
                                parts.AddRange(messages);

                                throw new AssertionException(string.Join(Environment.NewLine, parts));
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Generate the content files domains.xml and urls.xml for each category.
        /// </summary>
        private static void generateXmlFormatedContent()
        {
            // Set the currentOperation
            clsSettings.serviceSettings.currentOperation = operationList.generatingXmlFormatedContent;

            // Nombre del fichero donde está el contenido a convertir en XML.
            string indexFileName = "global_usage";
            // Nombre del directorio donde está el contenido a convertir en XML.
            string sourceFolderName = "BL";
            // Nombre del directorio donde crear los ficheros XML.
            string xmlDestinationFolderName = "BL_XML";

            // Full path to the index xml file created.
            string xmlIndexFilePath = string.Format("{0}{1}{2}{3}{4}", clsSettings.serviceSettings.dataDirectory,
                                                    xmlDestinationFolderName, System.IO.Path.DirectorySeparatorChar, indexFileName, ".xml");

            // Begin the content files processing.
            // Create the content files (domain.xml & url.xml files) for each category found in the categoryIndex file (xmlIndexFilePath)

            // Load the XML document containing the CategoryIndex.
            XDocument xDocumentIndex = XDocument.Load(xmlIndexFilePath);
            // Read only the Attribute name of each Category Element.
            IEnumerable <XAttribute> CategoryNames = from e in xDocumentIndex.Descendants("Category")
                                                     where ((string)e.Attribute("name")) != string.Empty
                                                     select e.Attribute("name");

            // Generate the schema files to validate the domains.xml and urls.xml files, respectively.
            System.Xml.Schema.XmlSchemaSet schemaSet = new System.Xml.Schema.XmlSchemaSet();

            // Generate domains.xsd
            string xsdFileFullPath = string.Format("{0}{1}", clsSettings.serviceSettings.dataDirectory, "domains.xsd");

            generateXsdDomainsFile(xsdFileFullPath);
            // Add the schema to the collection.
            schemaSet.Add(null, xsdFileFullPath);

            // Generate urls.xsd
            xsdFileFullPath = string.Format("{0}{1}", clsSettings.serviceSettings.dataDirectory, "urls.xsd");
            generateXsdUrlsFile(xsdFileFullPath);
            // Add the schema to the collection.
            schemaSet.Add(null, xsdFileFullPath);

            // Iterate on each CategoryName.
            foreach (XAttribute name in CategoryNames)
            {
                string CategoryFolderName = name.Value.Replace('/', Path.DirectorySeparatorChar);
                string workingDir         = string.Format("{0}{1}{2}{3}{4}", clsSettings.serviceSettings.dataDirectory,
                                                          sourceFolderName, Path.DirectorySeparatorChar,
                                                          CategoryFolderName, Path.DirectorySeparatorChar);
                if (Directory.Exists(workingDir))
                {
                    string destXmlFolderFullPath = string.Format("{0}{1}{2}{3}{4}", clsSettings.serviceSettings.dataDirectory, xmlDestinationFolderName,
                                                                 Path.DirectorySeparatorChar, CategoryFolderName, Path.DirectorySeparatorChar);

                    // Check if exist the domains file and process if so.
                    if (File.Exists(string.Format("{0}{1}", workingDir, "domains")))
                    {
                        StringBuilder sb = new StringBuilder();
                        sb = processBLFile(string.Format("{0}{1}", workingDir, "domains"), name.Value);
                        if (sb.Length != 0)
                        {
                            writeXmlBLFile(sb, destXmlFolderFullPath, "domains.xml");
                            // Validate according to generate xsd file domains.xsd
                            validateXmlFile(string.Format("{0}{1}", destXmlFolderFullPath, "domains.xml"), schemaSet);
                        }
                        // Do some Cleanup.
                        if (sb != null)
                        {
                            sb = null;
                        }
                    }

                    // Check if exist the urls file and process if so.
                    if (File.Exists(string.Format("{0}{1}", workingDir, "urls")))
                    {
                        StringBuilder sb = new StringBuilder();
                        sb = processBLFile(string.Format("{0}{1}", workingDir, "urls"), name.Value);
                        if (sb.Length != 0)
                        {
                            writeXmlBLFile(sb, destXmlFolderFullPath, "urls.xml");
                            // Validate according to generate xsd file urls.xsd
                            validateXmlFile(string.Format("{0}{1}", destXmlFolderFullPath, "urls.xml"), schemaSet);
                        }
                        // Do some Cleanup.
                        if (sb != null)
                        {
                            sb = null;
                        }
                    }
                }
            }

            // Do some Cleanup.
            if (xDocumentIndex != null)
            {
                xDocumentIndex = null;
            }
            if (schemaSet != null)
            {
                schemaSet = null;
            }
            if (CategoryNames != null)
            {
                CategoryNames = null;
            }

            return;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Create the file "global_usage.xml" from the original "global_usage" coming from the original file downloaded.
        /// </summary>
        private static void generateXmlFormatedIndex()
        {
            // Set the currentOperation
            clsSettings.serviceSettings.currentOperation = operationList.generatingXmlFormatedIndex;

            // Nombre del fichero donde está el contenido a convertir en XML.
            string indexFileName = "global_usage";
            // Nombre del directorio donde está el contenido a convertir en XML.
            string sourceFolderName = "BL";
            // Nombre del directorio donde crear los ficheros XML.
            string xmlDestinationFolderName = "BL_XML";

            // Read the text file: 'global_usage'
            StreamReader streamOriginalIndexContent = new StreamReader(string.Format("{0}{1}{2}{3}", clsSettings.serviceSettings.dataDirectory,
                                                                                     sourceFolderName, System.IO.Path.DirectorySeparatorChar, indexFileName));

            // Variable for the generated XML.
            System.Text.StringBuilder sbXmlResult = new StringBuilder();

            // XML file Header.
            sbXmlResult.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            // xmlns=\"urn:CategoryIndex-schema\"
            sbXmlResult.AppendLine(string.Format("<CategoryIndex DateCreated=\"{0}\" source=\"{1}\">", clsSettings.serviceSettings.downloadedFileLastModifiedDate.ToString("o"), clsSettings.serviceSettings.downloadUri));

            while (!streamOriginalIndexContent.EndOfStream)
            {
                string textLine = streamOriginalIndexContent.ReadLine();
                // Si es una línea de comentario.
                if (textLine.StartsWith("#"))
                {
                    continue;
                }

                // Si es una línea en blanco.
                if (string.IsNullOrEmpty(textLine))
                {
                    continue;
                }

                Categoria Category = new Categoria();
                while (!string.IsNullOrEmpty(textLine))
                {
                    // Sólo tomar los campos que me interesan.
                    // NAME:
                    if (textLine.StartsWith("NAME:", true, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        Category.name = textLine.Replace("NAME:", string.Empty);
                        textLine      = streamOriginalIndexContent.ReadLine();
                        continue;
                    }
                    // DEFAULT_TYPE:
                    if (textLine.StartsWith("DEFAULT_TYPE:", true, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        Category.defaualt_type = textLine.Replace("DEFAULT_TYPE:", string.Empty);
                        textLine = streamOriginalIndexContent.ReadLine();
                        continue;
                    }
                    // DESC EN:
                    if (textLine.StartsWith("DESC EN:", true, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        Category.desc_en = textLine.Replace("DESC EN:", string.Empty);
                        textLine         = streamOriginalIndexContent.ReadLine();
                        continue;
                    }
                    // DESC ES:
                    if (textLine.StartsWith("DESC ES:", true, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        Category.desc_es = textLine.Replace("DESC ES:", string.Empty);
                        textLine         = streamOriginalIndexContent.ReadLine();
                        continue;
                    }
                    // NAME EN:
                    if (textLine.StartsWith("NAME EN:", true, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        Category.name_en = textLine.Replace("NAME EN:", string.Empty);
                        textLine         = streamOriginalIndexContent.ReadLine();
                        continue;
                    }
                    // NAME ES:
                    if (textLine.StartsWith("NAME ES:", true, System.Globalization.CultureInfo.CurrentCulture))
                    {
                        Category.name_es = textLine.Replace("NAME ES:", string.Empty);
                        textLine         = streamOriginalIndexContent.ReadLine();
                        continue;
                    }

                    textLine = streamOriginalIndexContent.ReadLine();
                }

                //Procesar el contenido de la variable cat
                sbXmlResult.AppendLine(string.Format(" <Category name=\"{0}\">", string.IsNullOrEmpty(Category.name) ? string.Empty : Category.name.Trim()));
                //DEFAULT_TYPE:
                sbXmlResult.AppendLine(string.Format("  <default-type>{0}</default-type>", string.IsNullOrEmpty(Category.defaualt_type) ? string.Empty : Category.defaualt_type.Trim()));
                //DESC EN:
                sbXmlResult.AppendLine(string.Format("  <desc-en>{0}</desc-en>", string.IsNullOrEmpty(Category.desc_en) ? string.Empty : Category.desc_en.Trim()));
                //DESC ES:
                sbXmlResult.AppendLine(string.Format("  <desc-es>{0}</desc-es>", string.IsNullOrEmpty(Category.desc_es) ? string.Empty : Category.desc_es.Trim()));
                //NAME EN:
                sbXmlResult.AppendLine(string.Format("  <name-en>{0}</name-en>", string.IsNullOrEmpty(Category.name_en) ? string.Empty : Category.name_en.Trim()));
                //NAME ES:
                sbXmlResult.AppendLine(string.Format("  <name-es>{0}</name-es>", string.IsNullOrEmpty(Category.name_es) ? string.Empty : Category.name_es.Trim()));
                // Cerrar la categoría actual.
                sbXmlResult.AppendLine(" </Category>");
            }

            // Do some cleanup.
            if (streamOriginalIndexContent != null)
            {
                streamOriginalIndexContent.Close();
                streamOriginalIndexContent = null;
            }

            // End of que categories's catalog.
            sbXmlResult.Append("</CategoryIndex>");

            // Make sure exist the BL_XML folder.
            if (!Directory.Exists(string.Format("{0}{1}", clsSettings.serviceSettings.dataDirectory, xmlDestinationFolderName)))
            {
                clsSettings.serviceSettings.dataDirectory.CreateSubdirectory(xmlDestinationFolderName);
            }

            // Full path of the xml file to create.
            string xmlIndexFilePath = string.Format("{0}{1}{2}{3}{4}", clsSettings.serviceSettings.dataDirectory,
                                                    xmlDestinationFolderName, Path.DirectorySeparatorChar, indexFileName, ".xml");

            // Delete the xml file if this exists.
            if (File.Exists(xmlIndexFilePath))
            {
                File.Delete(xmlIndexFilePath);
            }

            // Create the xml file with the new content.
            File.AppendAllText(xmlIndexFilePath, sbXmlResult.ToString());

            // Validate the xml generated file.
            // Generate the schema for the Xml file.
            string xsdGlobalUsageFileFullPath = string.Format("{0}{1}{2}", clsSettings.serviceSettings.dataDirectory, indexFileName, ".xsd");

            generateXsdGlobalUsage(xsdGlobalUsageFileFullPath);

            // Create the XmlSchemaSet class.
            System.Xml.Schema.XmlSchemaSet schemaSet = new System.Xml.Schema.XmlSchemaSet();

            // Add the schema to the collection. "urn:CategoryIndex-schema"
            schemaSet.Add(null, xsdGlobalUsageFileFullPath);

            validateXmlFile(xmlIndexFilePath, schemaSet);

            // Do some cleanup.
            if (schemaSet != null)
            {
                schemaSet = null;
            }
        }         // Fin de generateXmlFomatedIndex()
        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);
        }