Read() public static method

public static Read ( Stream stream, ValidationEventHandler validationEventHandler ) : XmlSchema
stream Stream
validationEventHandler ValidationEventHandler
return XmlSchema
        /// <summary>
        /// Adds an <see cref="XmlSchema"/> instance for this type to the supplied <see cref="XmlSchemaSet"/>.
        /// </summary>
        /// <param name="xs">The <see cref="XmlSchemaSet"/> to add an <see cref="XmlSchema"/> to.</param>
        /// <returns>An <see cref="XmlQualifiedName"/> for the current object.</returns>
        public static XmlQualifiedName AcquireSchema(XmlSchemaSet xs)
        {
            if (xs == null)
            {
                throw new ArgumentNullException("xs");
            }

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("CommonContracts.WsEventing.GetStatusResponse.xsd"))
            {
                Debug.Assert(stream != null, "Resource Stream 'CommonContracts.WsEventing.GetStatusResponse.xsd' was not able to be opened");

                var schema = XmlSchema.Read(stream, null);

                var imports = new XmlSchemaSet();
                Expires.AcquireSchema(imports);
                SubscriptionManager.AcquireSchema(imports);

                foreach (var includeSchema in imports.Schemas().Cast <XmlSchema>())
                {
                    if (includeSchema.TargetNamespace == Constants.WsEventing.Namespace)
                    {
                        XmlSchemaInclude include = new XmlSchemaInclude();
                        include.Schema = includeSchema;
                        schema.Includes.Add(include);
                    }
                }

                xs.Add(schema);
            }

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("CommonContracts.WsEventing.WsAddressing.xsd"))
            {
                Debug.Assert(stream != null, "Resource Stream 'CommonContracts.WsEventing.WsAddressing.xsd' was not able to be opened");

                var schema = XmlSchema.Read(stream, null);
                xs.Add(schema);
            }

            return(new XmlQualifiedName("GetStatusResponseType", Constants.WsEventing.Namespace));
        }
Beispiel #2
0
        /// <summary>
        /// Validates an instance against the schema.
        /// </summary>
        public virtual ValidationResult ValidateInstance(ISource instance)
        {
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ValidationType  = language;
            settings.ValidationFlags =
                XmlSchemaValidationFlags.ProcessIdentityConstraints
                | XmlSchemaValidationFlags.ReportValidationWarnings;
            if (language == ValidationType.Schema && (SchemaSources != null || Schema != null))
            {
                if (Schema != null)
                {
                    settings.Schemas.Add(Schema);
                }
                else
                {
                    foreach (ISource loc in SchemaSources)
                    {
                        try {
                            XmlSchema s = XmlSchema.Read(loc.Reader, ThrowOnError);
                            settings.Schemas.Add(s);
                        } catch (IOException ex) {
                            throw new XMLUnitException("Schema is not readable",
                                                       ex);
                        }
                    }
                }
            }
            List <ValidationProblem> problems = new List <ValidationProblem>();

            settings.ValidationEventHandler += CollectProblems(problems);
            using (XmlReader r = XmlReader.Create(instance.Reader,
                                                  settings)) {
                while (r.Read())
                {
                    ;
                }
            }
            return(new ValidationResult(problems.Count == 0, problems));
        }
        internal static CodeNamespaceResult CreateCodeNamespace(PhysicalSchema schema, string targetNamespace)
        {
            XmlSchemaSet xset = new XmlSchemaSet();

            foreach (var file in schema.Files)
            {
                var sr = new StringReader(file.Content);
                xset.Add(XmlSchema.Read(sr, null));
            }

            xset.Compile();
            XmlSchemas schemas = new XmlSchemas();

            foreach (XmlSchema xmlSchema in xset.Schemas())
            {
                schemas.Add(xmlSchema);
            }

            XmlSchemaImporter importer = new XmlSchemaImporter(schemas);

            var ns       = new CodeNamespace(targetNamespace);
            var exporter = new XmlCodeExporter(ns);

            var result = new CodeNamespaceResult();

            foreach (XmlSchemaElement element in xset.GlobalElements.Values)
            {
                XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName);

                if (string.IsNullOrEmpty(result.RootElementName))
                {
                    result.RootElementName = mapping.TypeName;
                }

                exporter.ExportTypeMapping(mapping);
            }

            result.Code = ns;
            return(result);
        }
        private void CreateMockDocument(Dictionary <string, string> cells, string path, bool breakit = false)
        {
            XmlDocument document = new XmlDocument();
            //Setup xml document with UTF-8 encoding and specified Schema.
            XmlTextReader reader = new XmlTextReader("Spreadsheet.xsd");

            XmlDeclaration xmlDeclaration = document.CreateXmlDeclaration("1.0", "UTF-8", null);
            XmlElement     root           = document.DocumentElement;

            document.InsertBefore(xmlDeclaration, root);

            XmlSchema myschema = XmlSchema.Read(reader, ValidationCallback);

            document.Schemas.Add(myschema);

            //Create the spreadsheet element.
            XmlElement spreadsheet = document.CreateElement("spreadsheet");

            spreadsheet.SetAttribute("IsValid", ".*");

            foreach (var cell in cells)
            {
                XmlElement element = document.CreateElement("cell");
                if (!breakit)
                {
                    element.SetAttribute("name", cell.Key);
                }
                element.SetAttribute("contents", cell.Value);
                spreadsheet.AppendChild(element);
            }

            document.AppendChild(spreadsheet);

            //Create the xml.
            TextWriter writer = File.CreateText(path);

            //Assert that the document is valid with the schema.
            document.Save(writer);
            writer.Close(); // Close the writer to avoid open collision errors.
        }
Beispiel #5
0
        static XmlReaderSettings GetXmlReaderSettings()
        {
            var asm = typeof(IEntityExtensions).Assembly;

            var schemas = new string[] {
                "Common.xsd",
                "Authorization.xsd",
                "Environments.xsd",
                "Session.xsd"
            };

            var resNames = schemas.Select(s => asm.GetManifestResourceNames().Single(rn => rn.EndsWith(s, StringComparison.OrdinalIgnoreCase)));

            var xrs = new XmlReaderSettings();

            xrs.ValidationType          = ValidationType.Schema;
            xrs.ValidationEventHandler += (s, e) => {
                var xr = (XmlReader)s;

                var message = $"{xr.NodeType} '{xr.Name}' at ({e.Exception.LineNumber},{e.Exception.LinePosition})";

                if (e.Severity == XmlSeverityType.Warning)
                {
                    logger.Warn(e.Exception, message);
                    return;
                }

                throw new ValidationException(message, e.Exception);
            };

            foreach (var rn in resNames)
            {
                using (var rs = asm.GetManifestResourceStream(rn)) {
                    var xs = XmlSchema.Read(rs, null);
                    xrs.Schemas.Add(xs);
                }
            }

            return(xrs);
        }
        [Test] // bug #78220
        public void TestCompile()
        {
            string schemaFragment1 = string.Format(CultureInfo.InvariantCulture,
                                                   "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" +
                                                   "<xs:schema xmlns:tns=\"NSDate\" elementFormDefault=\"qualified\" targetNamespace=\"NSDate\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" +
                                                   "  <xs:import namespace=\"NSStatus\" />{0}" +
                                                   "  <xs:element name=\"trans\" type=\"tns:TranslationStatus\" />{0}" +
                                                   "  <xs:complexType name=\"TranslationStatus\">{0}" +
                                                   "    <xs:simpleContent>{0}" +
                                                   "      <xs:extension xmlns:q1=\"NSStatus\" base=\"q1:StatusType\">{0}" +
                                                   "        <xs:attribute name=\"Language\" type=\"xs:int\" use=\"required\" />{0}" +
                                                   "      </xs:extension>{0}" +
                                                   "    </xs:simpleContent>{0}" +
                                                   "  </xs:complexType>{0}" +
                                                   "</xs:schema>", Environment.NewLine);

            string schemaFragment2 = string.Format(CultureInfo.InvariantCulture,
                                                   "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" +
                                                   "<xs:schema xmlns:tns=\"NSStatus\" elementFormDefault=\"qualified\" targetNamespace=\"NSStatus\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" +
                                                   "  <xs:simpleType name=\"StatusType\">{0}" +
                                                   "    <xs:restriction base=\"xs:string\">{0}" +
                                                   "      <xs:enumeration value=\"Untouched\" />{0}" +
                                                   "      <xs:enumeration value=\"Touched\" />{0}" +
                                                   "      <xs:enumeration value=\"Complete\" />{0}" +
                                                   "      <xs:enumeration value=\"None\" />{0}" +
                                                   "    </xs:restriction>{0}" +
                                                   "  </xs:simpleType>{0}" +
                                                   "</xs:schema>", Environment.NewLine);

            XmlSchema schema1 = XmlSchema.Read(new StringReader(schemaFragment1), null);
            XmlSchema schema2 = XmlSchema.Read(new StringReader(schemaFragment2), null);

            XmlSchemaCollection schemas = new XmlSchemaCollection();

            schemas.Add(schema2);
            schemas.Add(schema1);

            Assert("#1", schema1.IsCompiled);
            Assert("#2", schema2.IsCompiled);
        }
Beispiel #7
0
        private void InitializeHighlighters()
        {
            var       xsd          = Application.GetResourceStream(new Uri("pack://application:,,,/AurelienRibon.Ui.SyntaxHighlightBox;component/resources/syntax.xsd"));
            var       schemaStream = xsd.Stream;
            XmlSchema schema       = XmlSchema.Read(schemaStream, (s, e) =>
            {
                Debug.WriteLine("Xml schema validation error : " + e.Message);
            });

            XmlReaderSettings readerSettings = new XmlReaderSettings();

            readerSettings.Schemas.Add(schema);
            readerSettings.ValidationType = ValidationType.Schema;

            foreach (var res in GetResources("resources/(.+?)[.]xml"))
            {
                XDocument xmldoc = null;
                try
                {
                    XmlReader reader = XmlReader.Create(res.Value, readerSettings);
                    xmldoc = XDocument.Load(reader);
                }
                catch (XmlSchemaValidationException ex)
                {
                    Debug.WriteLine("Xml validation error at line " + ex.LineNumber + " for " + res.Key + " :");
                    Debug.WriteLine("Warning : if you cannot find the issue in the xml file, verify the xsd file.");
                    Debug.WriteLine(ex.Message);
                    return;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    return;
                }

                XElement root = xmldoc.Root;
                String   name = root.Attribute("name").Value.Trim();
                HighlighterManager.Instance.Highlighters.Add(name, new XmlHighlighter(root));
            }
        }
Beispiel #8
0
    public bool ValidateXml(string xmlFileLocation)
    {
        isValid = true;
        try {
            string xml = "";
            using (StreamReader rdr = File.OpenText(xmlFileLocation)) {
                xml = rdr.ReadToEnd();
            }

            // build XSD schema
            StringReader _XsdStream = new StringReader(xsdString);

            XmlSchema _XmlSchema = XmlSchema.Read(_XsdStream, null);

            // build settings (this replaces XmlValidatingReader)
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(_XmlSchema);
            settings.IgnoreComments = true;
            settings.IgnoreProcessingInstructions = true;
            settings.IgnoreWhitespace             = true;
            settings.ValidationEventHandler      += new ValidationEventHandler(ValidationCallBack);

            // build XML reader
            StringReader _XmlStream = new StringReader(xml);

            XmlReader _XmlReader = XmlReader.Create(_XmlStream, settings);

            // validate
            using (_XmlReader) {
                while (_XmlReader.Read())
                {
                    ;
                }
            }
        } catch {
            isValid = false;
        }
        return(isValid);
    }
Beispiel #9
0
        public void v1(string testDir, string testFile, int expCount, int expCountGT, int expCountGE, int expCountGA)
        {
            Initialize();
            string xsd = Path.Combine(path, testDir, testFile);

            XmlSchemaSet ss     = new XmlSchemaSet();
            XmlSchema    Schema = XmlSchema.Read(XmlReader.Create(xsd), ValidationCallback);

            ss.XmlResolver = new XmlUrlResolver();

            ss.Add(Schema);
            ValidateSchemaSet(ss, expCount, false, 0, 0, 0, "Validation after add");
            ValidateWithSchemaInfo(ss);

            ss.Compile();
            ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, expCountGA, "Validation after add/comp");
            ValidateWithSchemaInfo(ss);

            foreach (XmlSchema schema in ss.Schemas())
            {
                ss.Reprocess(schema);
            }

            ValidateSchemaSet(ss, expCount, false, 1, 0, 0, "Validation after repr");
            ValidateWithSchemaInfo(ss);

            ss.Compile();
            ValidateSchemaSet(ss, expCount, true, expCountGT, expCountGE, expCountGA, "Validation after repr/comp");
            ValidateWithSchemaInfo(ss);

            Assert.True(ss.RemoveRecursive(Schema));
            ValidateSchemaSet(ss, 0, false, 1, 0, 0, "Validation after remRec");
            ValidateWithSchemaInfo(ss);

            ss.Compile();
            ValidateSchemaSet(ss, 0, true, 0, 0, 0, "Validation after remRec/comp");
            ValidateWithSchemaInfo(ss);

            return;
        }
Beispiel #10
0
        public void v6(object param0)
        {
            Initialize();
            XmlSchemaSet xss = new XmlSchemaSet();

            xss.XmlResolver             = new XmlUrlResolver();
            xss.ValidationEventHandler += ValidationCallback;
            var reader = new XmlTextReader(Path.Combine(TestData._Root, param0.ToString()));

            reader.XmlResolver = new XmlUrlResolver();
            XmlSchema schema = XmlSchema.Read(reader, ValidationCallback);

#pragma warning disable 0618
            schema.Compile(ValidationCallback);
#pragma warning restore 0618

            xss.Add(schema);

            // expect a validation warning for unresolvable schema location
            CError.Compare(warningCount, 0, "Warning Count mismatch");
            CError.Compare(errorCount, 0, "Error Count mismatch");
        }
Beispiel #11
0
        public int CreateTables(Dictionary <string, Dictionary <int, VersionsList> > TablesList, Dictionary <string, List <string> > ParentChildren)
        {
            if (File.Exists("Version.txt"))
            {
                using (StreamReader stream = new StreamReader("Version.txt"))
                {
                    if (!Int32.TryParse(stream.ReadLine(), out Version))
                    {
                        WriteVersion(Version);
                    }
                }
            }
            else
            {
                WriteVersion(Version);
            }

            ParentChildren.Add("Item", new List <string>());

            // reading from .xsd file
            XmlSchema myschema;

            try
            {
                XmlTextReader reader = new XmlTextReader("Model.xsd");
                myschema = XmlSchema.Read(reader, ValidationCallback);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.InnerException);
                Console.WriteLine(e.StackTrace);
                myschema = null;
            }

            CreateTableFrame(TablesList, ParentChildren, myschema);
            TableFill(TablesList);

            return(Version);
        }
Beispiel #12
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="readerStream"></param>
        /// <returns></returns>
        public XmlDocument Parse( Stream readerStream ) {
            XmlDocument doc = new XmlDocument();

            ArrayList[] schemas = dbf.GetAttributes();
            if (schemas != null && schemas[0] != null) {
                for (int i = 0; i < schemas[0].Count; i++) {
                    String schema_uri = (String)schemas[1][i];
                    if (schema_uri.IndexOf(".xsd") == -1)
                        schema_uri += ".xsd";

                    XmlTextReader schema_reader = new XmlTextReader(schema_uri);
                    try {
                        XmlSchema schema = XmlSchema.Read(schema_reader, null);
                        doc.Schemas.Add(schema);
                    } catch (Exception e) {
                        Console.WriteLine("Failed to add schema definition (XSD):" + e);
                    }
                }
            }

            doc.Load(readerStream);

            if (dbf.GetValidating()) {
                //  Need to validate XML...
                //  
                ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationEventHandler);
                try {
                    doc.Validate(eventHandler);
                } catch (XmlSchemaException e) {
                    if (ihandler != null) {
                        SAXParseException saxe = new SAXParseException("SAXParseException parsing " + readerStream + " - " + e.Message, e);
                        saxe.LineNumber = e.LineNumber;
                        saxe.ColumnNumber = e.LinePosition;
                    }
                }
            }

            return doc;
        }
Beispiel #13
0
        protected XmlReader GetXmlInputReader(XmlTextReader xmlReader, string xsdResourceName)
        {
            XmlReader sourceReader;

            if (xsdResourceName != null)
            {
                // we validate against a well defined schema
                sourceReader = new XmlValidatingReader(xmlReader);
                ((XmlValidatingReader)sourceReader).ValidationType = ValidationType.Schema;
                ((XmlValidatingReader)sourceReader).Schemas.Add(XmlSchema.Read(Assembly
                                                                               .GetExecutingAssembly()
                                                                               .GetManifestResourceStream(xsdResourceName),
                                                                               null));
            }
            else
            {
                // it is easier to by default be lax if no internal XSD resource has been given
                sourceReader = xmlReader;
            }

            return(sourceReader);
        }
Beispiel #14
0
        public void RegressionTest1()
        {
            XmlSchemaSet sc = new XmlSchemaSet();

            //first schema
            XmlSchema schema = XmlSchema.Read(new StringReader(@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='bar'><xsd:element name='author1' type='xsd:string'/></xsd:schema>"), null);

            Assert.Equal("bar", sc.Add(schema).TargetNamespace);
            Assert.Equal(1, sc.Count);

            //second schema
            XmlDocument doc = new XmlDocument();

            doc.LoadXml("<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='foo'><xsd:element name='author2' type='xsd:boolean'/></xsd:schema>");

            XmlNode       root   = doc.FirstChild;
            XmlNodeReader reader = new XmlNodeReader(root);

            Assert.Equal("foo", sc.Add(null, reader).TargetNamespace);
            sc.Compile();
            Assert.Equal(2, sc.Count);
        }
Beispiel #15
0
    public static int Main()
    {
        FileStream fs;
        XmlSchema  schema;

        try
        {
            fs     = new FileStream("example.xsd", FileMode.Open);
            schema = XmlSchema.Read(fs, new ValidationEventHandler(ShowCompileError));

            XmlSchemaSet schemaSet = new XmlSchemaSet();
            schemaSet.ValidationEventHandler += new ValidationEventHandler(ShowCompileError);
            schemaSet.Add(schema);
            schemaSet.Compile();

            XmlSchema compiledSchema = null;

            foreach (XmlSchema schema1 in schemaSet.Schemas())
            {
                compiledSchema = schema1;
            }

            schema = compiledSchema;

            if (schema.IsCompiled)
            {
                // Schema is successfully compiled.
                // Do something with it here.
            }
            return(0);
        }
        catch (XmlSchemaException e)
        {
            Console.WriteLine("LineNumber = {0}", e.LineNumber);
            Console.WriteLine("LinePosition = {0}", e.LinePosition);
            Console.WriteLine("Message = {0}", e.Message);
            return(-1);
        }
    }
Beispiel #16
0
        /// <summary>
        /// Instantiate a new VSCompiler.
        /// </summary>
        public VSCompiler()
        {
            Assembly  assembly     = Assembly.GetExecutingAssembly();
            XmlReader schemaReader = null;

            // load the schema extensions
            try
            {
                schemaReader   = GetXmlFromEmbeddedStream(assembly, "Microsoft.Tools.WindowsInstallerXml.Extensions.Xsd.vs.xsd");
                this.xmlSchema = XmlSchema.Read(schemaReader, null);
            }
            finally
            {
                if (null != schemaReader)
                {
                    schemaReader.Close();
                }
            }

            // load the table definition extensions
            this.tableDefinitionCollection = GetTableDefinitions();
        }
Beispiel #17
0
        public bool XmlValidate(string filePath)
        {
            bool isValid = true;

            try
            {
                XmlReader   reader        = new XmlTextReader(@"C:\Users\Priyanka\Downloads\XMLParserConsoleTester\XMLParserConsoleTester\XMLParsing_UTest\XMLJobSchema.xsd"); // Change in filepath as to where schema is stored in the user's PC
                XmlSchema   myXmlSchema   = XmlSchema.Read(reader, null);
                XmlDocument myXmlDocument = new XmlDocument();
                myXmlDocument.Load(filePath);
                XmlValidatorTestHelper xmlSchemaValidator = new XmlValidatorTestHelper();
                xmlSchemaValidator.ValidXmlDoc(myXmlDocument, myXmlSchema);
            }

            catch (Exception e)
            {
                Console.WriteLine(e);
                isValid = false;
            }

            return(isValid);
        }
Beispiel #18
0
        public IEnumerable <LibraryItem> Read(Stream xmlStream)
        {
            if (xmlStream == null)
            {
                throw new ArgumentNullException(nameof(xmlStream));
            }

            var settings = new XmlReaderSettings
            {
                IgnoreComments = true,
                IgnoreProcessingInstructions = true,
                IgnoreWhitespace             = true,
                ValidationType = ValidationType.Schema,
            };
            var schemaStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(BooksXml.SchemaResourcePath);

            settings.Schemas.Add(XmlSchema.Read(schemaStream, null));

            var reader = XmlReader.Create(xmlStream, settings);

            return(new XmlBookRepositoryEnumerator(reader));
        }
        /// <summary>
        /// Overload:  Validates an xmldocument according to the xmlschema
        /// </summary>
        /// <param name="xmlRaw"></param>
        /// <param name="sXslSchemaPath"></param>
        /// <returns></returns>
        public static bool Validate(XmlDocument xmlRaw, string sXslSchemaPath)
        {
            XmlSchema xmlSchema = null;

            try
            {
                // if schema file is empty, just return true (this is for types that cannot be validated)
                if (FileUtilities.ReadFileContents(sXslSchemaPath).Trim().Length < 20)
                {
                    return(true);
                }

                XmlTextReader xmlReader = new XmlTextReader(sXslSchemaPath);
                xmlSchema = XmlSchema.Read(xmlReader, new ValidationEventHandler(SchemaReadError));
            }
            catch (Exception ex)
            {
                throw new Exception("Validate:LoadSchema", ex);
            }

            return(Validate(xmlRaw, xmlSchema));
        }
Beispiel #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SchemaValidationHandler"/> class.
        /// </summary>
        /// <param name="toValidate">To validate.</param>
        /// <param name="mainXsdLocation">The main XSD location.</param>
        /// <param name="helperXsdLocations">The helper XSD locations.</param>
        private SchemaValidationHandler(object toValidate, String mainXsdLocation, List <String> helperXsdLocations)
        {
            if (toValidate == null || String.IsNullOrEmpty(mainXsdLocation))
            {
                throw new ArgumentException(string.Format("Cannot validate without an object:{0} or schema:{1}", toValidate, mainXsdLocation));
            }

            // reset stuff
            InitSchemaValidationHandler();

            // get the schema
            List <XmlSchema> schemas = new List <XmlSchema>();

            schemas.Add(XmlSchema.Read(new XmlTextReader(mainXsdLocation), ValidationEvent));
            foreach (string schemaFile in helperXsdLocations)
            {
                // get the schema
                XmlSchema xmlSchema = XmlSchema.Read(new XmlTextReader(schemaFile), ValidationEvent);
                schemas.Add(xmlSchema);
            }
            ValidateToSchema(toValidate, schemas);
        }
        public static CodeNamespace Process(string xsdSchema, string modelsNamespace)
        {
            // Load the XmlSchema and its collection.
            XmlSchema xsd;

            using (var fs = new StringReader(xsdSchema))
            {
                xsd = XmlSchema.Read(fs, null);
                xsd.Compile(null);
            }
            XmlSchemas schemas = new XmlSchemas();

            schemas.Add(xsd);
            // Create the importer for these schemas.
            XmlSchemaImporter importer = new XmlSchemaImporter(schemas);
            // System.CodeDom namespace for the XmlCodeExporter to put classes in.
            CodeNamespace   ns       = new CodeNamespace(modelsNamespace);
            XmlCodeExporter exporter = new XmlCodeExporter(ns);

            // Iterate schema top-level elements and export code for each.
            foreach (XmlSchemaElement element in xsd.Elements.Values)
            {
                // Import the mapping first.
                XmlTypeMapping mapping = importer.ImportTypeMapping(
                    element.QualifiedName);
                // Export the code finally.
                exporter.ExportTypeMapping(mapping);
            }

            // execute extensions

            //var collectionsExt = new ArraysToCollectionsExtension();
            //collectionsExt.Process(ns, xsd);

            //var filedsExt = new FieldsToPropertiesExtension();
            //filedsExt.Process(ns, xsd);

            return(ns);
        }
Beispiel #22
0
        private static IEnumerable <Backstory> LoadResourceBackstoriesRegular(string resourcesDirectory)
        {
            XmlSchemaSet backstoriesSchemaSet = new XmlSchemaSet();

            backstoriesSchemaSet.Add(XmlSchema.Read(new StringReader(Properties.Resources.BackstoriesSchema), ValidateSchema));

            foreach (string resourceFileName in Directory.EnumerateFiles(resourcesDirectory, "*.xml", SearchOption.TopDirectoryOnly))
            {
                XDocument doc = XDocument.Load(resourceFileName, LoadOptions.None);
                if (XmlHelper.IsValid(doc, backstoriesSchemaSet))
                {
                    string category = Path.GetFileNameWithoutExtension(resourceFileName);

                    foreach (XElement element in doc.Root.Elements())
                    {
                        Backstory backstory = XmlHelper.ReadBackstoryElementResource(element);
                        backstory.Category = category;
                        yield return(backstory);
                    }
                }
            }
        }
Beispiel #23
0
        public void SchemasWithNoSourceURIOneLoadedFromXmlSchemaReadOtherFromDOMDiffTNS()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            //first schema
            XmlSchema schema = XmlSchema.Read(new StringReader(@"<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='bar'><xsd:element name='author1' type='xsd:string'/></xsd:schema>"), null);
            XmlSchema temp   = sc.Add(schema);

            Assert.Equal("bar", temp.TargetNamespace);

            //second schema
            XmlDocument doc = new XmlDocument();

            doc.LoadXml("<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='foo'><xsd:element name='author2' type='xsd:boolean'/></xsd:schema>");
            XmlNode       root   = doc.FirstChild;
            XmlNodeReader reader = new XmlNodeReader(root);

            temp = sc.Add(null, reader);
            Assert.Equal("foo", temp.TargetNamespace);
            Assert.Equal(2, sc.Count);

            sc.Compile();
        }
Beispiel #24
0
        public bool XmlValidate(string filePath)
        {
            bool isValid = true;

            try
            {
                XmlReader   reader        = new XmlTextReader(@"C:\Users\z0045tam\source\repos\XMLParserConsoleApplicationFinal\XMLJobSchema.xsd");
                XmlSchema   myXmlSchema   = XmlSchema.Read(reader, null);
                XmlDocument myXmlDocument = new XmlDocument();
                myXmlDocument.Load(filePath);
                XmlValidatorTestHelper xmlSchemaValidator = new XmlValidatorTestHelper();
                xmlSchemaValidator.ValidXmlDoc(myXmlDocument, myXmlSchema);
            }

            catch (Exception e)
            {
                Console.WriteLine(e);
                isValid = false;
            }

            return(isValid);
        }
Beispiel #25
0
        public Byte[] CreateXml()
        {
            void eventHandler(Object sender, ValidationEventArgs e)
            {
                if (e.Exception != null)
                {
                    _validationErrors.Add(e.Exception.Message);
                }
            }

            foreach (var f in _schemaPathes)
            {
                using (var textReader = XmlReader.Create(f))
                {
                    XmlSchema sc = XmlSchema.Read(textReader, eventHandler);
                    _schemaSet.Add(sc);
                }
            }

            _schemaSet.Compile();
            return(CreateXmlFromSchema());
        }
Beispiel #26
0
        public DiagnosticsHandler(ILanguageServer router, BufferManager bufferManager)
        {
            _router        = router;
            _bufferManager = bufferManager;
            _schemaSet     = new XmlSchemaSet();
            using (var xsd = typeof(DiagnosticsHandler).Assembly.GetManifestResourceStream("NuSpec.Server.nuspec.xsd"))
                using (var sr = new StreamReader(xsd))
                {
                    var schemaContent = string.Format(sr.ReadToEnd(), "http://schemas.microsoft.com/packaging/2015/06/nuspec.xsd");

                    using (var ms = new MemoryStream())
                        using (var sw = new StreamWriter(ms))
                        {
                            sw.Write(schemaContent);
                            sw.Flush();
                            ms.Position = 0;

                            var schema = XmlSchema.Read(ms, (sender, args) => {});
                            _schemaSet.Add(schema);
                        }
                }
        }
Beispiel #27
0
        VsTemplate.Template GetWizardData(XmlNode wizardData)
        {
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ValidationType   = ValidationType.Schema;
            settings.ConformanceLevel = ConformanceLevel.Auto;

            // Pull the XSD from the config assembly (it's an embedded resource).
            using (Stream xsdstream = typeof(VsTemplate.Template).Assembly.GetManifestResourceStream(
                       VsTemplate.Template.SchemaResourceName))
            {
                Debug.Assert(xsdstream != null, "XSD not embedded in config assembly");
                // If the schema is not valid (we must check that at design-time), this will throw.
                XmlSchema xsd = XmlSchema.Read(xsdstream, null);
                settings.Schemas.Add(xsd);
            }
            using (XmlReader xr = XmlReader.Create(new XmlNodeReader(wizardData), settings))
            {
                VsTemplate.Template template = (VsTemplate.Template) new VsTemplate.TemplateSerializer().Deserialize(xr);
                return(template);
            }
        }
Beispiel #28
0
        public void v12a()
        {
            using (XmlReader r = XmlReader.Create(Path.Combine(TestData._Root, @"bug264908_v1.xsd")))
            {
                XmlSchema s = XmlSchema.Read(r, null);
                using (XmlReader r2 = XmlReader.Create(Path.Combine(TestData._Root, @"bug264908_v1a.xsd")))
                {
                    XmlSchema    s2  = XmlSchema.Read(r2, null);
                    XmlSchemaSet set = new XmlSchemaSet();

                    set.XmlResolver = null;
                    set.Add(s);
                    set.Add(s2);
                    set.Compile();

                    foreach (XmlSchema schema in set.Schemas())
                    {
                        set.Reprocess(schema);
                    }
                }
            }
        }
Beispiel #29
0
public void VerifyProxyDef()
{
    var libAss   = Assembly.GetAssembly(typeof(Paths));
    var proxyxsd = libAss.GetManifestResourceNames().FirstOrDefault(x => x.Contains("CardGenerator.xsd"));

    if (proxyxsd == null)
    {
        throw new UserMessageException("Shits f****d bro.");
    }
    var schemas = new XmlSchemaSet();
    var schema  = XmlSchema.Read(libAss.GetManifestResourceStream(proxyxsd), (sender, args) => { throw args.Exception; });

    schemas.Add(schema);

    XmlSerializer serializer = new XmlSerializer(typeof(game));
    var           fs         = File.Open(Directory.GetFiles().First(x => x.Name == "definition.xml").FullName, FileMode.Open);
    var           game       = (game)serializer.Deserialize(fs);

    fs.Close();

    if (game.proxygen == null)
    {
        throw new UserMessageException("You must have a ProxyGen element defined.");
    }

    var fileName = Path.Combine(Directory.FullName, game.proxygen.definitionsrc);

    XDocument doc = XDocument.Load(fileName);
    string    msg = "";

    doc.Validate(schemas, (o, e) =>
            {
                msg = e.Message;
            });
    if (!string.IsNullOrWhiteSpace(msg))
    {
        throw new UserMessageException(msg);
    }
}
Beispiel #30
0
        /// <summary>
        /// Validates the schema.
        /// </summary>
        public static async Task <List <BuildError> > ValidateSchema(string xml, string filename, CancellationToken token)
        {
            var errors   = new List <BuildError> ();
            var settings = new XmlReaderSettings {
                XmlResolver = new LocalOnlyXmlResolver()
            };

            void validationCallback(object _, ValidationEventArgs args)
            {
                errors.Add(CreateBuildError(args, filename));
            }

            try {
                XmlSchema schema;
                using (var xmlReader = XmlReader.Create(new StringReader(xml))) {
                    schema = XmlSchema.Read(xmlReader, validationCallback);
                }

                var sset = new XmlSchemaSet();
                sset.ValidationEventHandler += validationCallback;

                foreach (XmlSchema s in (await XmlSchemaManager.GetSchemaSet(token)).Schemas())
                {
                    if (s.TargetNamespace != schema.TargetNamespace)
                    {
                        sset.Add(schema);
                    }
                }
                sset.Compile();
            }
            catch (XmlSchemaException ex) {
                errors.Add(CreateBuildError(ex, filename));
            }
            catch (XmlException ex) {
                errors.Add(CreateBuildError(ex, filename));
            }

            return(errors);
        }