Ejemplo n.º 1
0
    static void Main()
    {
        XmlSchemaSet schemas = new XmlSchemaSet();
        schemas.Add("", "../../16. Catalog.xsd");

        XDocument doc = XDocument.Load("../../../1. Catalog.xml"); // you can try to change the xml file to see the warnings
        string msg = "";
        doc.Validate(schemas, (o, e) =>
        {
            msg = e.Message;
        });
        Console.WriteLine(msg == "" ? "Document is valid" : "Document invalid: " + msg);
    }
    static void Main()
    {
        var xmlScheme = new XmlSchemaSet();
        xmlScheme.Add(string.Empty, @"..\..\..\catalogue.xsd");

        XDocument doc = XDocument.Load(@"..\..\..\catalogue.xml");
        XDocument notValidDoc = XDocument.Load(@"..\..\..\notValidCatalogue.xml");

        Console.WriteLine("The valid catalogue XML result:");
        Validate(doc, xmlScheme);
        Console.WriteLine("The notValidCatalogue XML result:");
        Validate(notValidDoc, xmlScheme);
    }
Ejemplo n.º 3
0
Archivo: test.cs Proyecto: mono/gert
	static void Test2 ()
	{
		XmlSchemaSet schemaSet = new XmlSchemaSet ();
		schemaSet.Add (null, "test.xsd");

		XmlReaderSettings settings = new XmlReaderSettings ();
		settings.ValidationType = ValidationType.Schema;
		settings.CloseInput = true;
		settings.Schemas.Add (schemaSet);

		XmlReader r = XmlReader.Create ("test.xml", settings);
		XPathDocument d = new XPathDocument (r);
		d.CreateNavigator ();
	}
Ejemplo n.º 4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string booksSchemaFile = Server.MapPath("books.xsd");
        string booksFile = Server.MapPath("books.xml");

        XmlSchemaSet schemas = new XmlSchemaSet();
        schemas.Add(null, XmlReader.Create(booksSchemaFile));
        XDocument booksXML = XDocument.Load(booksFile);
        booksXML.Validate(schemas, (senderParam, eParam) =>
                                   {
                                     Response.Write(eParam.Message);
                                   }, true);

        XNamespace ns = "http://example.books.com";
        var books = from book in booksXML.Descendants(ns + "book")
                    select book.Element(ns + "title").Value;
        Response.Write(String.Format("Found {0} books!", books.Count()));
    }
Ejemplo n.º 5
0
Archivo: test.cs Proyecto: mono/gert
	static int Main ()
	{
		XmlSchema schema = XmlSchema.Read (new XmlTextReader ("schema.xsd"), null);

#if NET_2_0
		XmlReaderSettings settings = new XmlReaderSettings ();
		settings.ValidationType = ValidationType.None;

		XmlSchemaSet schemaSet = new XmlSchemaSet();
		schemaSet.Add(schema);

		XmlReader reader = XmlReader.Create (new StringReader (xml), settings);

		XmlNamespaceManager manager = new XmlNamespaceManager (reader.NameTable);
		XmlSchemaValidator validator = new XmlSchemaValidator (reader.NameTable,
			schemaSet, manager, XmlSchemaValidationFlags.None);
		validator.Initialize ();
		validator.ValidateElement ("test", string.Empty, null);
		try {
			validator.ValidateAttribute ("mode", string.Empty, "NOT A ENUMERATION VALUE", null);
			return 1;
		} catch (XmlSchemaValidationException) {
		} finally {
			reader.Close ();
		}
#else
		XmlValidatingReader validator = new XmlValidatingReader (xml, XmlNodeType.Document, null);
		validator.ValidationType = ValidationType.Schema;
		validator.Schemas.Add (schema);
		try {
			while (validator.Read ()) ;
			return 1;
		} catch (XmlSchemaException) {
		} finally {
			validator.Close ();
		}
#endif

		return 0;
	}
Ejemplo n.º 6
0
        private void ValidateSchema(Stream schema, Stream stream)
        {
            // Load the template into an XDocument
            XDocument xml = XDocument.Load(stream);

            using (var schemaReader = XmlReader.Create(schema))
            {
                // Prepare the XML Schema Set
                XmlSchemaSet schemas = new XmlSchemaSet();
                schemas.Add(SharePointConstants.PageTransformationSchema, schemaReader);

                // Set stream back to start
                stream.Seek(0, SeekOrigin.Begin);

                xml.Validate(schemas, (o, e) =>
                {
                    var errorMessage = string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                     SharePointTransformationResources.Error_WebPartMappingSchemaValidation, e.Message);
                    this.logger.LogError(e.Exception, errorMessage
                                         .CorrelateString(this.taskId));
                    throw new ApplicationException(errorMessage);
                });
            }
        }
        private List <string> ValidateAuftrag(DigitalisierungsAuftrag auftrag)
        {
            var data = auftrag.Serialize();

            var    schemas = new XmlSchemaSet();
            string schema;
            var    assembly     = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CMI.Contract.Common.dll"));
            var    resourceName = "CMI.Contract.Common.Digitalisierungsauftrag.xsd";

            using (var stream = assembly.GetManifestResourceStream(resourceName))
                using (var reader = new StreamReader(stream ?? throw new InvalidOperationException()))
                {
                    schema = reader.ReadToEnd();
                }

            schemas.Add("", XmlReader.Create(new StringReader(schema)));

            var xmlDoc = XDocument.Parse(data);
            var errors = new List <string>();

            xmlDoc.Validate(schemas, (o, e) => { errors.Add(e.Message); });

            return(errors);
        }
Ejemplo n.º 8
0
        private static XmlSchema ReadAndCompileSchema(string filename)
        {
            var tr = new XmlTextReader(filename,
                                       new NameTable());

            // The Read method will throw errors encountered
            // on parsing the schema
            XmlSchema schema = XmlSchema.Read(tr,
                                              new ValidationEventHandler(ValidationCallbackOne));

            tr.Close();

            XmlSchemaSet xset = new XmlSchemaSet();

            xset.Add(schema);

            xset.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);

            // The Compile method will throw errors
            // encountered on compiling the schema
            xset.Compile();

            return(schema);
        }
Ejemplo n.º 9
0
        public void saveData(MailData Data, String Filepath)
        {
            XDocument XMLFile;
            //Chargement du schéma
            String       Schema = File.ReadAllText("BulkMail.xsd");
            XmlSchemaSet schema = new XmlSchemaSet();

            schema.Add("", XmlReader.Create(new StringReader(Schema)));
            //Base du XML
            XElement Nom      = new XElement("nom", Data.Nom);
            XElement MailList = new XElement("mailList", Data.EmailList.Select(e => e + " "));

            //Création de l'élement Email
            XElement Objet         = new XElement("objet", Data.Email[0]);
            XElement Expediteur    = new XElement("expediteur", Data.Email[1]);
            XElement Corps         = new XElement("corps", Data.Email[2]);
            XElement PiecesJointes = new XElement("piecesJointes", Data.PiecesJointes.Select(e => e + " "));
            XElement Email         = new XElement("email", Objet, Expediteur, Corps, PiecesJointes);

            //Mise en place complète du XML
            XElement Root = new XElement("campagne", Nom, MailList, Email);

            XMLFile = new XDocument(Root);

            //On valide le schéma (normalement pas nécessaire, mais sait-on jamais)
            bool errors = false;

            XMLFile.Validate(schema, (o, e) =>
            {
                Console.WriteLine("{0}", e.Message);
                errors = true;
            });
            Console.WriteLine("{0}", errors? "did not validate" : "validated");

            XMLFile.Save(Filepath);
        }
Ejemplo n.º 10
0
            public void InvalidXMLUnitTest()
            {
                Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);

                if (m_eventDialogSchema == null)
                {
                    Console.WriteLine("Loading XSD schema for dialog event package, takes a while...");

                    m_eventDialogSchema = new XmlSchemaSet();
                    XmlReader schemaReader = new XmlTextReader(SIPSorcery.SIP.Properties.Resources.EventDialogSchema, XmlNodeType.Document, null);
                    m_eventDialogSchema.Add(m_dialogXMLNS, schemaReader);
                }

                // The mandatory version attribue on dialog-info is missing.
                string invalidDialogInfoXMLStr =
                    "<?xml version='1.0' encoding='utf-16'?>" +
                    "<dialog-info state='full' entity='sip:[email protected]' xmlns='urn:ietf:params:xml:ns:dialog-info'>" +
                    " <dialog id='as7d900as8' call-id='a84b4c76e66710' local-tag='1928301774' direction='initiator'>" +
                    "  <state event='rejected' code='486'>terminated</state>" +
                    " </dialog>" +
                    "</dialog-info>";

                XDocument eventDialogDoc = XDocument.Parse(invalidDialogInfoXMLStr);

                eventDialogDoc.Validate(m_eventDialogSchema, (o, e) =>
                {
                    Console.WriteLine("XSD validation " + e.Severity + " event: " + e.Message);

                    if (e.Severity == XmlSeverityType.Error)
                    {
                        throw e.Exception;
                    }
                });

                Console.WriteLine("-----------------------------------------");
            }
Ejemplo n.º 11
0
    public string verification(string xmlUri, string xsdUri)
    {
        errorMessage = "";
        XmlSchemaSet schemaSet = new XmlSchemaSet();

        schemaSet.Add(null, xsdUri);
        XmlReaderSettings readerSetting = new XmlReaderSettings();

        readerSetting.ValidationType          = ValidationType.Schema;
        readerSetting.Schemas                 = schemaSet;
        readerSetting.ValidationEventHandler += new ValidationEventHandler(validationCallBack);
        XmlReader reader = XmlReader.Create(xmlUri, readerSetting);

        anyError = false;
        while (reader.Read())
        {
            ;
        }
        if (anyError == false)
        {
            return("No error");
        }
        return(errorMessage);
    }
Ejemplo n.º 12
0
        [Test]         // bug #502115
        public void ExtensionRedefineAttribute2()
        {
            const string xml = "<Bar xmlns='foo'/>";

            XmlSchema schema = GetSchema("Test/XmlFiles/xsd/extension-attr-redefine-2.xsd");

            XmlSchemaSet xss = new XmlSchemaSet();

            xss.Add(schema);
            xss.Compile();

            StringReader sr = new StringReader(xml);

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ValidationType = ValidationType.Schema;
            settings.Schemas        = xss;
            XmlReader vr = XmlReader.Create(sr, settings);

            while (vr.Read())
            {
                ;
            }
        }
Ejemplo n.º 13
0
        [Test]         // bug #502115
        public void ExtensionRedefineAttribute3()
        {
            const string xml = "<Bar xmlns='foo'/>";

            XmlSchema schema = GetSchema("Test/XmlFiles/xsd/extension-attr-redefine-3.xsd");

            XmlSchemaSet xss = new XmlSchemaSet();

            xss.Add(schema);
            if (StrictMsCompliant)
            {
                xss.Compile();
            }
            else
            {
                try {
                    xss.Compile();
                    Assert.Fail();
                } catch (XmlSchemaException) {
                }
                return;
            }

            StringReader sr = new StringReader("<Bar xmlns='foo'/>");

            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ValidationType = ValidationType.Schema;
            settings.Schemas        = xss;
            XmlReader vr = XmlReader.Create(sr, settings);

            while (vr.Read())
            {
                ;
            }
        }
        public static XmlQualifiedName GetSchema(XmlSchemaSet schemaSet)
        {
            String baseFieldValueSchemaString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                                "<xsd:schema targetNamespace=\"http://schemas.dev.office.com/PnP/2015/12/ProvisioningSchema\" " +
                                                "elementFormDefault=\"qualified\" " +
                                                "xmlns=\"http://schemas.dev.office.com/PnP/2015/12/ProvisioningSchema\" " +
                                                "xmlns:pnp=\"http://schemas.dev.office.com/PnP/2015/12/ProvisioningSchema\" " +
                                                "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
                                                "<xsd:complexType name=\"BaseFieldValue\">" +
                                                "<xsd:simpleContent>" +
                                                "<xsd:extension base=\"xsd:string\">" +
                                                "<xsd:attribute name=\"FieldName\" use=\"required\" type=\"xsd:string\"/>" +
                                                "</xsd:extension>" +
                                                "</xsd:simpleContent>" +
                                                "</xsd:complexType>" +
                                                "</xsd:schema>";

            XmlSchema baseFieldValueSchema = XmlSchema.Read(new StringReader(baseFieldValueSchemaString), null);

            schemaSet.XmlResolver = new XmlUrlResolver();
            schemaSet.Add(baseFieldValueSchema);

            return(new XmlQualifiedName("BaseFieldValue", XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_12));
        }
Ejemplo n.º 15
0
        public void v1()
        {
            XmlSchemaSet sc = new XmlSchemaSet();

            try
            {
                sc.Add((XmlSchema)null);
            }
            catch (ArgumentNullException)
            {
                try
                {
                    Assert.Equal(sc.Count, 0);
                    Assert.Equal(sc.Contains((XmlSchema)null), false);
                }
                catch (ArgumentNullException)
                {
                    Assert.Equal(sc.Contains((string)null), false);
                    Assert.Equal(sc.IsCompiled, false);
                    return;
                }
            }
            Assert.True(false);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Verifica se o xml está seguindo o schema xsd
        /// </summary>
        /// <param name="xml">Leitor do XML</param>
        /// <param name="xsdFile">Caminho do arquivo xsd</param>
        /// <returns>Um erro por linha</returns>
        public static string CheckXSD(XmlReader xml, string xsdFile)
        {
            // Valida o xsd
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.ValidationType = ValidationType.Schema;
            settings.DtdProcessing  = DtdProcessing.Prohibit; // Por padrão já é proibido, mas como é uma questão de segurança, estou deixando essa opção explícita
            var schemas = new XmlSchemaSet();

            settings.Schemas = schemas;
            // Quando carregar o eschema, especificar o namespace que ele valida e a localização do arquivo
            schemas.Add(null, xsdFile);
            // Especifica o tratamento de evento para os erros de validacao
            string msg = null;

            settings.ValidationEventHandler += (object sender, ValidationEventArgs args) => {
                if (msg == null)
                {
                    msg = "";
                }
                if (msg.Length > 0)
                {
                    msg += "\n";
                }
                msg += args.Message;
            };

            // Cria um leitor para validação e faz a leitura de todos os dados XML
            using var validator = XmlReader.Create(xml, settings);
            while (validator.Read())
            {
                ;
            }

            return(msg);
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("expect xml file name");
                return;
            }
            string       fileName     = args[0];
            XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();

            XmlTextReader xsdReader = new XmlTextReader(new StringReader(Resources.CommonDocument));

            xmlSchemaSet.Add(null, xsdReader);
            xmlSchemaSet.Compile();
            foreach (XmlSchema schema in xmlSchemaSet.Schemas())
            {
                Console.Write("Schema with target namespace {0}", schema.TargetNamespace);
                Console.WriteLine(" contains {0} elements", schema.Elements.Count);
            }

            XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();

            xmlReaderSettings.Schemas.Add(xmlSchemaSet);
            xmlReaderSettings.ValidationType          = ValidationType.Schema;
            xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(xmlReaderSettings_ValidationEventHandler);

            XmlReader xmlReader = XmlReader.Create(fileName, xmlReaderSettings);

            while (xmlReader.Read())
            {
            }
            ;

            Console.WriteLine("Validation complete");
            Console.ReadLine();
        }
Ejemplo n.º 18
0
        public void v5(object param0, object param1)
        {
            Initialize();
            XmlSchemaSet xss = new XmlSchemaSet();

            xss.XmlResolver             = new XmlUrlResolver();
            xss.ValidationEventHandler += ValidationCallback;
            XmlSchema schema = XmlSchema.Read(new StreamReader(new FileStream(Path.Combine(TestData._Root, param0.ToString()), FileMode.Open, FileAccess.Read)), ValidationCallback);

#pragma warning disable 0618
            schema.Compile(ValidationCallback, new XmlUrlResolver());
#pragma warning restore 0618
            try
            {
                xss.Add(schema);
            }
            catch (XmlException)
            {
                Assert.True(false); //expect a validation warning for unresolvable schema location
            }
            CError.Compare(warningCount, (int)param1, "Warning Count mismatch");
            CError.Compare(errorCount, 0, "Error Count mismatch");
            return;
        }
        public ValidationResult GetValidationResults(Stream template)
        {
            var exceptions = new List <Exception>();

            if (template == null)
            {
                throw new ArgumentNullException(nameof(template));
            }

            // Load the template into an XDocument
            XDocument xml = XDocument.Load(template);

            // Load the XSD embedded resource
            Stream stream = typeof(XMLPnPSchemaV201503Formatter)
                            .Assembly
                            .GetManifestResourceStream("PnP.Framework.Provisioning.Providers.Xml.ProvisioningSchema-2015-03.xsd");

            // Prepare the XML Schema Set
            XmlSchemaSet schemas = new XmlSchemaSet();

            schemas.Add(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_03,
                        new XmlTextReader(stream));

            Boolean result = true;

            xml.Validate(schemas, (o, e) =>
            {
                exceptions.Add(e.Exception);
                Diagnostics.Log.Error(e.Exception, "SchemaFormatter", "Template is not valid: {0}", e.Message);
                result = false;
            });

            return(new ValidationResult {
                IsValid = result, Exceptions = exceptions
            });
        }
Ejemplo n.º 20
0
        public void v23()
        {
            Initialize();
            XmlSchemaSet xss = new XmlSchemaSet();

            xss.ValidationEventHandler += ValidationCallback;
            xss.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd"));

            try
            {
                XmlReader r1 = CreateReader(Path.Combine(TestData._Root, "bug356711_1.xml"), true);
                XmlReader r2 = CreateReader(r1, xss, false);
                while (r2.Read())
                {
                    ;
                }
            }
            catch (XmlException)
            {
                Assert.True(false);
            }
            CError.Compare(errorCount, 0, "ProhibitDTD did not work with schemaLocation");
            return;
        }
Ejemplo n.º 21
0
        public void v22(object param0)
        {
            Initialize();
            XmlSchemaSet xss = new XmlSchemaSet();

            xss.XmlResolver             = new XmlUrlResolver();
            xss.ValidationEventHandler += ValidationCallback;
            xss.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd"));

            try
            {
                XmlReader reader = CreateReader(Path.Combine(TestData._Root, param0.ToString()), xss, false);
                while (reader.Read())
                {
                    ;
                }
            }
            catch (XmlException)
            {
                Assert.True(false);
            }
            CError.Compare(errorCount, 0, "ProhibitDTD did not work with schemaLocation");
            return;
        }
Ejemplo n.º 22
0
        public void v13(object param0)
        {
            Initialize();
            XmlSchemaSet xss = new XmlSchemaSet();

            xss.XmlResolver             = new XmlUrlResolver();
            xss.ValidationEventHandler += ValidationCallback;

            XmlReader r  = CreateReader(Path.Combine(TestData._Root, param0.ToString()), false);
            XmlReader r2 = CreateReader(r, true);

            try
            {
                xss.Add(null, r2);
            }
            catch (XmlException)
            {
                Assert.True(false); //expect a validation warning for unresolvable schema location
            }

            _output.WriteLine("Count: " + xss.Count);
            CError.Compare(warningCount, 1, "Warning Count mismatch");
            return;
        }
Ejemplo n.º 23
0
        private void IntegrateNewSchema(XmlSchema schema)
        {
            Contract.Requires(schema != null);

            if (schema.TargetNamespace == QueryStorage.QuerySpace ||
                schema.TargetNamespace == RegistrationStorage.Dataspace)
            {
                throw new InvalidOperationException("Нельзя добавить схему с данным пространством имен");
            }
            if (_allSchemas == null)
            {
                Initialize();
            }

            Debug.Assert(_allSchemas != null);
            var presentSchema = _allSchemas.Schemas(schema.TargetNamespace).OfType <XmlSchema>().FirstOrDefault();

            if (presentSchema != null)
            {
                _allSchemas.Remove(presentSchema);
            }
            _allSchemas.Add(schema);
            _allSchemas.Compile();
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            XmlSchemaSet schema = new XmlSchemaSet();

            schema.Add("https://maitinimas.lt", @"C:\Users\Paulius\Documents\GitHub\xmlValidation\XmlValidate\XMLSchema.xsd");

            XDocument xmlDocument      = XDocument.Load(@"C:\Users\Paulius\Documents\GitHub\xmlValidation\XmlValidate\Food.xml");
            bool      validationErrors = false;

            xmlDocument.Validate(schema, (s, e) =>
            {
                Console.WriteLine(e.Message);
                validationErrors = true;
            });

            if (validationErrors)
            {
                Console.WriteLine("Validation failed");
            }
            else
            {
                Console.WriteLine("Validation succeeded");
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Validates xml against a given schema. Returns true if xml is valid, throws <see cref="XmlException"/> otherwise.
        /// </summary>
        /// <param name="xml">Xml string.</param>
        /// <param name="schema">Xsd string.</param>
        public static bool Validate(string xml, string schema)
        {
//			string schema = Properties.Resources.schema;
//			Console.WriteLine(schema);

            if (string.IsNullOrEmpty(xml) || string.IsNullOrEmpty(schema))
            {
                throw new ArgumentException();
            }

            XmlSchemaSet schemaSet = new XmlSchemaSet();

            schemaSet.Add(null, XmlReader.Create(new StringReader(schema)));

            XmlDocument document = new XmlDocument
            {
                Schemas = schemaSet
            };

            document.LoadXml(xml);
            document.Validate((o, e) => throw new XmlException(e.Message));

            return(true);
        }
        public static XmlSchemaSet GetManifestSchemaSet(string schemaNamespace)
        {
            return(_manifestSchemaSetCache.GetOrAdd(schemaNamespace, schema =>
            {
                const string schemaResourceName = "NuGetPe.Authoring.nuspec.xsd";

                string formattedContent;

                // Update the xsd with the right schema namespace
                var assembly = typeof(Manifest).Assembly;
                using (var reader = new StreamReader(assembly.GetManifestResourceStream(schemaResourceName)))
                {
                    string content = reader.ReadToEnd();
                    formattedContent = String.Format(CultureInfo.InvariantCulture, content, schema);
                }

                using (var reader = new StringReader(formattedContent))
                {
                    var schemaSet = new XmlSchemaSet();
                    schemaSet.Add(schema, XmlReader.Create(reader));
                    return schemaSet;
                }
            }));
        }
Ejemplo n.º 27
0
        public void ProvideInvalidXsiType()
        {
            XmlSchemaValidator  val;
            XmlSchemaInfo       info    = new XmlSchemaInfo();
            XmlNamespaceManager ns      = new XmlNamespaceManager(new NameTable());
            XmlSchemaSet        schemas = new XmlSchemaSet();

            schemas.Add("uri:tempuri", Path.Combine(TestData, XSDFILE_TARGET_NAMESPACE));
            val = CreateValidator(schemas, ns, 0);
            ns.AddNamespace("t", "uri:tempuri");

            val.Initialize();

            try
            {
                val.ValidateElement("foo", "uri:tempuri", null, "type1", null, null, null);
            }
            catch (XmlSchemaValidationException e)
            {
                _exVerifier.IsExceptionOk(e, "Sch_XsiTypeNotFound", new string[] { "type1" });
                return;
            }
            Assert.True(false);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Wrapper To perform XmlValidation
        /// </summary>
        /// <param name="docSpec">The Document NameSpec derieved for the message</param>
        /// <param name="maxErrorCount">maximum number of Schema validation errors to be captured</param>
        /// <param name="stream">Stream representation of the incoming message</param>
        /// <param name="messageType">Message Type of the incoming message</param>
        /// <param name="messageId">Id of the incoming message</param>
        public void ValidationWrapper(IDocumentSpec docSpec, int maxErrorCount, VirtualStream stream, string messageType, string messageId)
        {
            XmlSchemaSet schemas = new XmlSchemaSet();

            try
            {
                foreach (var schema in docSpec.GetSchemaCollection())
                {
                    schemas.Add(schema);
                }
            }
            catch (XmlSchemaException ex)
            {
                string errorDescription = string.Format("An error occured while loading the schemas. Error Message: {0} \r\nLine: {1}, Position: {2} \r\n", ex.Message, ex.LineNumber, ex.LinePosition);

                throw new Exception(errorDescription);
            }
            catch (Exception sysEx)
            {
                throw new Exception("An error occured while loading the schemas. Error detail: " + sysEx.ToString());
            }

            Validate(stream, schemas, maxErrorCount, messageType, messageId);
        }
Ejemplo n.º 29
0
 /// <summary>
 /// The validate schema.
 /// </summary>
 /// <param name="schema">
 /// The schema.
 /// </param>
 /// <param name="xmlData">
 /// The xml_data.
 /// </param>
 private static void ValidateSchema(string schema, string xmlData)
 {
     try
     {
         var xmlTextReader = new XmlTextReader(new StringReader(schema));
         var xmlSchemaSet  = new XmlSchemaSet();
         xmlSchemaSet.Add(null, xmlTextReader);
         var xmlReaderSettings = new XmlReaderSettings
         {
             Schemas         = xmlSchemaSet,
             ValidationFlags = XmlSchemaValidationFlags.AllowXmlAttributes,
             ValidationType  = ValidationType.Schema
         };
         var xmlReader = XmlReader.Create(new StringReader(xmlData), xmlReaderSettings);
         do
         {
         }while (xmlReader.Read());
         xmlReader.Close();
     }
     catch (Exception ex)
     {
         throw new BarcodeConverterException("Ошибка проверки документа по схеме XSD", ex);
     }
 }
        public void Load(XmlReader reader)
        {
            ValidateArg.NotNull(reader, nameof(reader));

            var schemaSet    = new XmlSchemaSet();
            var schemaStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("TestPropertySettings.xsd");

            schemaSet.Add(null, XmlReader.Create(schemaStream));

            var settings = new XmlReaderSettings
            {
                Schemas         = schemaSet,
                ValidationType  = ValidationType.Schema,
                ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings
            };

            settings.ValidationEventHandler += (object o, ValidationEventArgs e) => throw e.Exception;

            using (var newReader = XmlReader.Create(reader, settings))
            {
                try
                {
                    if (newReader.Read() && newReader.Name.Equals(this.Name))
                    {
                        XmlSerializer deserializer = new XmlSerializer(typeof(TestPropertySettingsContainer));
                        this.TestPropertySettings = deserializer.Deserialize(newReader) as TestPropertySettingsContainer;
                    }
                }
                catch (InvalidOperationException e) when(e.InnerException is XmlSchemaValidationException)
                {
                    throw new InvalidRunSettingsException(
                              String.Format(Resources.Invalid, GoogleTestConstants.TestPropertySettingsName),
                              e.InnerException);
                }
            }
        }
Ejemplo n.º 31
0
        public void SetSchemaSetTo_Empty_NotCompiled_Compiled(string schemaSetStatus)
        {
            XmlSchemaValidator val;
            XmlSchemaSet       sch = new XmlSchemaSet();

            if (schemaSetStatus != "empty")
            {
                sch.Add("", Path.Combine(TestData, XSDFILE_NO_TARGET_NAMESPACE));
                if (schemaSetStatus == "compiled")
                {
                    sch.Compile();
                }
            }

            val = new XmlSchemaValidator(new NameTable(), sch, new XmlNamespaceManager(new NameTable()), AllFlags);
            Assert.NotNull(val);

            val.Initialize();
            val.ValidateElement("elem1", "", null);
            val.SkipToEndElement(null);
            val.EndValidation();

            return;
        }
        public void v12()
        {
            bWarningCallback = false;
            bErrorCallback   = false;

            XmlSchemaSet sc = new XmlSchemaSet();

            sc.XmlResolver = new XmlUrlResolver();

            sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
            XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, "include_v1_a.xsd"));

            CError.Compare(sc.Count, 1, "Count after add");
            CError.Compare(sc.Contains(Schema1), true, "Contains after add");

            sc.Compile();
            CError.Compare(sc.Count, 1, "Count after add/comp");
            CError.Compare(sc.Contains(Schema1), true, "Contains after add/comp");
            ///edit
            XmlSchemaInclude inc = new XmlSchemaInclude();

            inc.SchemaLocation = "include_v2.xsd";
            Schema1.Includes.Add(inc);

            sc.Reprocess(Schema1);
            ValidateSchemaSet(sc, 1, false, 1, 0, 0, "Validation after edit/reprocess");
            CError.Compare(bWarningCallback, false, "Warning repr");
            CError.Compare(bErrorCallback, true, "Error repr");

            sc.Compile();
            ValidateSchemaSet(sc, 1, false, 1, 0, 0, "Validation after comp/reprocess");
            CError.Compare(bWarningCallback, false, "Warning comp");
            CError.Compare(bErrorCallback, true, "Error comp");
            CError.Compare(Schema1.IsCompiled, false, "IsCompiled on SOM");
            return;
        }
        public static ValidationResponse Validate(this BaseUblDocument doc, string xsdLocation)
        {
            var response = new ValidationResponse {
                IsValid = true, Errors = ""
            };

            var schemas = new XmlSchemaSet();

            using (var xr = new XmlTextReader(xsdLocation))
            {
                schemas.Add(XmlSchema.Read(xr, null));
            }

            var xmlReader = XmlReader.Create(new StringReader(doc.ToXml()));
            var xDoc      = XDocument.Load(xmlReader);

            xDoc.Validate(schemas, (o, e) =>
            {
                response.Errors += e.Message + Environment.NewLine;
                response.IsValid = false;
            });

            return(response);
        }
Ejemplo n.º 34
0
        private static XmlSchemaSet compileValidationSchemas()
        {
            var resolver = ZipArtifactSource.CreateValidationSource();

            XmlSchemaSet schemas = new XmlSchemaSet();

            foreach (var schemaName in minimalSchemas)
            {
                using (var schema = resolver.LoadArtifactByName(schemaName))
                {
                    if (schema == null)
                    {
                        throw new FileNotFoundException("Cannot find manifest resources that represent the minimal set of schemas required for validation");
                    }

                    schemas.Add(null, XmlReader.Create(schema));   // null = use schema namespace as specified in schema file
                    schema.Dispose();
                }
            }

            schemas.Compile();

            return(schemas);
        }
Ejemplo n.º 35
0
        private void Validate()
        {
            this.LogTaskMessage(!string.IsNullOrEmpty(this.XmlFile) ? string.Format(CultureInfo.CurrentCulture, "Validating: {0}", this.XmlFile) : "Validating Xml");
            XmlSchemaSet schemas = new XmlSchemaSet();

            foreach (ITaskItem i in this.SchemaFiles)
            {
                this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loading SchemaFile: {0}", i.ItemSpec));
                schemas.Add(this.TargetNamespace, i.ItemSpec);
            }

            bool errorEncountered = false;

            this.xmlDoc.Validate(
                schemas,
                (o, e) =>
            {
                this.Output += e.Message;
                this.LogTaskWarning(string.Format(CultureInfo.InvariantCulture, "{0}", e.Message));
                errorEncountered = true;
            });

            this.IsValid = errorEncountered ? false : true;
        }
 private static void Load_SDMX_Schemas(XmlSchemaSet Schemas)
 {
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.xml)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXCommon)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXMessage)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXStructure)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXGenericData)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXUtilityData)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXCompactData)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXCrossSectionalData)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXGenericMetadata)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXMetadataReport)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXRegistry)));
     Schemas.Add(null, XmlReader.Create(new StringReader(SDMXApi_2_0.Schemas.SDMXQuery)));
 }
            public static XmlQualifiedName WaterMLSchema(XmlSchemaSet xs)
            {
                //// This method is called by the framework to get the schema for this type.
                //// We return an existing schema from disk.
                Assembly asmb = Assembly.GetExecutingAssembly();
                string[] names = asmb.GetManifestResourceNames();
                Stream stream = asmb.GetManifestResourceStream("WaterOneFlowImpl.JustVariableValue.xsd");
                //string text =   new StreamReader(stream).ReadToEnd();
                //   stream.Position = 0;
                XmlSchema vsvSchema = XmlSchema.Read(stream, null);

                xs.Add(vsvSchema);

                //XmlNameTable xmlNameTable = new NameTable();
                //XmlSchemaSet xmlSchemaSet = new XmlSchemaSet(xmlNameTable);
                //xmlSchemaSet.Add(vsvSchema);

                //vsvSchema.Namespaces.Add("wtr10", "http://www.cuahsi.org/waterML/1.0/");

                //XmlQualifiedName xmlQualifiedName = new XmlQualifiedName(TypeName, "http://www.cuahsi.org/waterML/1.0/");

                ////  XmlSchemaObject vsv = vsvSchema.Elements[xmlQualifiedName];
                //XmlSchemaObject vsv = vsvSchema.SchemaTypes[xmlQualifiedName];

                ////XmlSchema vsvSchema2 = new XmlSchema();
                //vsvSchema2.Items.Add(vsv);
                //foreach (string VARIABLE in new String[]
                //                             {
                //                                 "CensorCodeEnum",
                //                                 "QualityControlLevelEnum",

                //                             })
                //{
                //    XmlQualifiedName qn = new XmlQualifiedName(VARIABLE, "http://www.cuahsi.org/waterML/1.0/");

                //    vsvSchema2.Items.Add(vsvSchema.SchemaTypes[qn]);

                //  }
                //foreach (var VARIABLE in new String[]
                //                             {

                //                                 "ValueAttr","DbIdentifiers","offsetAttr"

                //                             })
                //{
                //    XmlQualifiedName qn = new XmlQualifiedName(VARIABLE, "http://www.cuahsi.org/waterML/1.0/");

                //    vsvSchema2.Items.Add(vsvSchema.AttributeGroups[qn]);
                //}

                //vsvSchema2.Namespaces.Add("", "http://www.cuahsi.org/waterML/1.0/");

                //xs.XmlResolver = new XmlUrlResolver();
                //xs.Add(vsvSchema2);

                return new XmlQualifiedName(TypeName, "http://www.cuahsi.org/waterML/1.0/");
            }
Ejemplo n.º 38
0
 protected internal static void AddSchemas(XmlSchemaSet schemas) {
     schemas.Add(schemaSet);
 }