Пример #1
1
        public string GetXml(bool validate)
        {
            XNamespace ns = "http://sd.ic.gc.ca/SLDR_Schema_Definition_en";

            var spectrum_licences = getLicences();

            XDocument doc = new XDocument(new XElement("spectrum_licence_data_registry", spectrum_licences));

            foreach (XElement e in doc.Root.DescendantsAndSelf())
            {
                if (e.Name.Namespace == "")
                    e.Name = ns + e.Name.LocalName;
            }

            var errors = new StringBuilder();

            if (validate)
            {
                XmlSchemaSet set = new XmlSchemaSet();
                var schema = getMainSchema();
                set.Add(null, schema);

                doc.Validate(set, (sender, args) => { errors.AppendLine(args.Message); });
            }

            //return errors.Length > 0 ? errors.ToString() : doc.ToString();
            var  result = errors.Length > 0 ? "Validation Errors: " + errors.ToString() : getDocumentAsString(doc);
            return result;
        }
		void IWsdlImportExtension.ImportContract (WsdlImporter importer,
			WsdlContractConversionContext context)
		{
			if (!enabled)
				return;

			if (importer == null)
				throw new ArgumentNullException ("importer");
			if (context == null)
				throw new ArgumentNullException ("context");
			if (this.importer != null || this.context != null)
				throw new SystemException ("INTERNAL ERROR: unexpected recursion of ImportContract method call");

#if USE_DATA_CONTRACT_IMPORTER
			dc_importer = new XsdDataContractImporter ();
			schema_set_in_use = new XmlSchemaSet ();
			schema_set_in_use.Add (importer.XmlSchemas);
			foreach (WSDL wsdl in importer.WsdlDocuments)
				foreach (XmlSchema xs in wsdl.Types.Schemas)
					schema_set_in_use.Add (xs);
			dc_importer.Import (schema_set_in_use);
#endif

			this.importer = importer;
			this.context = context;
			try {
				DoImportContract ();
			} finally {
				this.importer = null;
				this.context = null;
			}
		}
Пример #3
0
        public void v2()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            sc.XmlResolver = new XmlUrlResolver();
            XmlSchema schema = new XmlSchema();
            sc.Add(null, TestData._XsdNoNs);
            CError.Compare(sc.Count, 1, "AddCount");
            CError.Compare(sc.IsCompiled, false, "AddIsCompiled");

            sc.Compile();
            CError.Compare(sc.IsCompiled, true, "IsCompiled");
            CError.Compare(sc.Count, 1, "Count");

            try
            {
                schema = sc.Add(null, Path.Combine(TestData._Root, "include_v2.xsd"));
            }
            catch (XmlSchemaException)
            {
                // no schema should be addded to the set.
                CError.Compare(sc.Count, 1, "Count");
                CError.Compare(sc.IsCompiled, true, "IsCompiled");
                return;
            }
            Assert.True(false);
        }
Пример #4
0
		public void Add ()
		{
			XmlSchemaSet ss = new XmlSchemaSet ();
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml ("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' />");
			ss.Add (null, new XmlNodeReader (doc)); // null targetNamespace
			ss.Compile ();

			// same document, different targetNamespace
			ss.Add ("ab", new XmlNodeReader (doc));

			// Add(null, xmlReader) -> targetNamespace in the schema
			doc.LoadXml ("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='urn:foo' />");
			ss.Add (null, new XmlNodeReader (doc));

			Assert.AreEqual (3, ss.Count);

			bool chameleon = false;
			bool ab = false;
			bool urnfoo = false;

			foreach (XmlSchema schema in ss.Schemas ()) {
				if (schema.TargetNamespace == null)
					chameleon = true;
				else if (schema.TargetNamespace == "ab")
					ab = true;
				else if (schema.TargetNamespace == "urn:foo")
					urnfoo = true;
			}
			Assert.IsTrue (chameleon, "chameleon schema missing");
			Assert.IsTrue (ab, "target-remapped schema missing");
			Assert.IsTrue (urnfoo, "target specified in the schema ignored");
		}
Пример #5
0
        internal static bool IsValidMessage(XDocument doc, XDocument schema)
        {
            var schemas = new XmlSchemaSet();

            schemas.Add("http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message",
                GetPath("lib\\SDMXMessage.xsd"));


            if (schema != null)
            {
                using (var reader = schema.CreateReader())
                {
                    schemas.Add(null, reader);
                }
            }

            bool isValid = true;

            doc.Validate(schemas, (s, args) =>
            {
                isValid = false;
                if (args.Severity == XmlSeverityType.Warning)

                    Console.WriteLine("\tWarning: " + args.Message);
                else
                    Console.WriteLine("\tError: " + args.Message);
            });

            return isValid;
        }
		void IWsdlImportExtension.ImportContract (WsdlImporter importer,
			WsdlContractConversionContext context)
		{
			if (!enabled)
				return;

			if (importer == null)
				throw new ArgumentNullException ("importer");
			if (context == null)
				throw new ArgumentNullException ("context");
			if (this.importer != null || this.context != null)
				throw new SystemException ("INTERNAL ERROR: unexpected recursion of ImportContract method call");

			dc_importer = new XsdDataContractImporter ();
			schema_set_in_use = new XmlSchemaSet ();
			schema_set_in_use.Add (importer.XmlSchemas);
			foreach (WSDL wsdl in importer.WsdlDocuments)
				foreach (XmlSchema xs in wsdl.Types.Schemas)
					schema_set_in_use.Add (xs);

			// commenting out this import operation, but might be required (I guess not).
			//dc_importer.Import (schema_set_in_use);
			schema_set_in_use.Compile ();

			this.importer = importer;
			this.context = context;
			try {
				DoImportContract ();
			} finally {
				this.importer = null;
				this.context = null;
			}
		}
Пример #7
0
        public void v3(object param0, object param1, object param2, object param3, object param4)
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            sc.XmlResolver = new XmlUrlResolver();

            sc.Add((string)param3, TestData._Root + param1.ToString());
            CError.Compare(sc.Count, 1, "AddCount");
            CError.Compare(sc.IsCompiled, false, "AddIsCompiled");

            sc.Compile();
            CError.Compare(sc.Count, 1, "CompileCount");
            CError.Compare(sc.IsCompiled, true, "CompileIsCompiled");

            XmlSchema parent = sc.Add(null, TestData._Root + param0.ToString());

            CError.Compare(sc.Count, param2, "Add2Count");
            CError.Compare(sc.IsCompiled, false, "Add2IsCompiled");

            // check that schema is present in parent.Includes and its NS correct.
            foreach (XmlSchemaImport imp in parent.Includes)
                if (imp.SchemaLocation.Equals(param1.ToString()) && imp.Schema.TargetNamespace == (string)param4)
                    return;

            Assert.True(false);
        }
		public void AddTwice ()
		{
			XmlSchemaSet ss = new XmlSchemaSet ();
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml ("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' />");
			ss.Add ("ab", new XmlNodeReader (doc));
			ss.Add ("ab", new XmlNodeReader (doc));
		}
Пример #9
0
        public void v3()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            sc.Add("xsdauthor", TestData._XsdAuthor);
            sc.Add(null, TestData._Root + "xsdbookexternal.xsd");

            CError.Compare(sc.Count, 2, "Count");

            return;
        }
Пример #10
0
 /// <summary>
 /// Prevents a default instance of the <see cref="SchemaCache"/> class from being created. 
 /// Initialize a new instance of the <see cref="SchemaCache"/> class
 /// </summary>
 private SchemaCache()
 {
     var schemaSet = new XmlSchemaSet();
     schemaSet.ValidationEventHandler -= this.SchemaSetValidationEventHandler;
     schemaSet.ValidationEventHandler += this.SchemaSetValidationEventHandler;
     schemaSet.Add(this.LoadXsdFromResource(GetSoapXsdLocation(SoapProtocolVersion.Soap11)));
     schemaSet.Add(this.LoadXsdFromResource(GetSoapXsdLocation(SoapProtocolVersion.Soap12)));
     this._soapSchema = schemaSet;
     this._soapSchema.Compile();
 }
Пример #11
0
		public void AddSchemaThenReader ()
		{
			XmlSchemaSet ss = new XmlSchemaSet ();
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml ("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' />");
			XmlSchema xs = new XmlSchema ();
			xs.TargetNamespace = "ab";
			ss.Add (xs);
			ss.Add ("ab", new XmlNodeReader (doc));
		}
Пример #12
0
        public void v2()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            sc.Add("xsdauthor", TestData._XsdNoNs);
            sc.Add("xsdauthor", TestData._XsdAuthor);

            CError.Compare(sc.Count, 2, "Count");

            return;
        }
        //[Variation(Desc = "v4 - sc = self", Priority = 0)]
        public void v4()
        {
            XmlSchemaSet sc = new XmlSchemaSet();

            sc.Add("xsdauthor", TestData._XsdAuthor);
            sc.Add(sc);

            Assert.Equal(sc.Count, 1);

            return;
        }
Пример #14
0
        public void v2()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            XmlSchema Schema1 = sc.Add("xsdauthor1", TestData._XsdNoNs);
            XmlSchema Schema2 = sc.Add("xsdauthor", TestData._XsdAuthor);
            ICollection Col = sc.Schemas();

            CError.Compare(Col.Count, 2, "Count");

            return;
        }
Пример #15
0
        public void Adding2ReadersOnSchemaWithNoNamespacesAddWithDiffNamespace()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            XmlTextReader Reader1 = new XmlTextReader(TestData._XsdNoNs);
            XmlTextReader Reader2 = new XmlTextReader(TestData._XsdNoNs);
            XmlSchema Schema1 = sc.Add("xsdauthor1", Reader1);
            XmlSchema Schema2 = sc.Add("xsdauthor2", Reader2);

            Assert.Equal(2, sc.Count);
            Assert.NotNull(Schema1);
            Assert.NotEqual(Schema1, Schema2);
        }
Пример #16
0
        public void v3()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            sc.Add("xsdauthor1", TestData._XsdNoNs);
            XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor);
            sc.Compile();
            sc.Remove(Schema1);

            CError.Compare(sc.IsCompiled, false, "IsCompiled after compiled and remove");

            return;
        }
Пример #17
0
 public static XmlSchemaSet SchemasFromDescrip(IEnumerable<ServiceDescription> descriptions)
 {
   var schemaSet = new XmlSchemaSet();
   var soap = new StringReader(string.Format(Properties.Resources.SoapSchema, descriptions.First().TargetNamespace));
   schemaSet.Add(XmlSchema.Read(soap, new ValidationEventHandler(Validation)));
   foreach (var schema in descriptions.SelectMany(d => d.Types.Schemas.OfType<XmlSchema>()))
   {
     schemaSet.Add(schema);
   }
   schemaSet.Compile();
   return schemaSet;
 }
        //[Variation(Desc = "v3 - sc = non empty SchemaSet, add with duplicate schemas", Priority = 0)]
        public void v3()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            XmlSchemaSet scnew = new XmlSchemaSet();

            sc.Add("xsdauthor", TestData._XsdAuthor);
            scnew.Add("xsdauthor", TestData._XsdAuthor);

            sc.Add(scnew);
            // adding schemaset with same schema should be ignored
            Assert.Equal(sc.Count, 1);
            return;
        }
Пример #19
0
 private void LoadSchemas(string schemaPath)
 {
     theSchemas = new XmlSchemaSet();
     theSchemas.XmlResolver = new SimpleXmlResolver(schemaPath);
     theSchemas.Add("http://schemas.openxmlformats.org/wordprocessingml/2006/main", XmlReader.Create(
         File.Open(schemaPath + "\\wml.xsd", FileMode.Open, FileAccess.Read, FileShare.Read), new XmlReaderSettings()));
     theSchemas.Add("http://schemas.openxmlformats.org/drawingml/2006/main", XmlReader.Create(
         File.Open(schemaPath + "\\dml-stylesheet.xsd", FileMode.Open, FileAccess.Read, FileShare.Read), new XmlReaderSettings()));
     //theSchemas.Add("http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", XmlReader.Create(
     //    File.Open(schemaPath + "\\wml.xsd", FileMode.Open, FileAccess.Read, FileShare.Read), new XmlReaderSettings()));
     theSchemas.Add("urn:schemas-microsoft-com:office:office", XmlReader.Create(
       File.Open(schemaPath + "\\vml-officeDrawing.xsd", FileMode.Open, FileAccess.Read, FileShare.Read), new XmlReaderSettings()));
 }
Пример #20
0
        private static XmlSchemaSet compileXhtmlSchema()
        {
            var assembly = typeof(XHtml).Assembly;
            XmlSchemaSet schemas = new XmlSchemaSet();

            var schema = new StringReader(Properties.Resources.fhir_xhtml);
            schemas.Add(null, XmlReader.Create(schema));   // null = use schema namespace as specified in schema file
            schema = new StringReader(Properties.Resources.xml);
            schemas.Add(null, XmlReader.Create(schema));   // null = use schema namespace as specified in schema file

            schemas.Compile();

            return schemas;
        }
Пример #21
0
        //[Variation(Desc = "v4 - Contains for 2 existing schemas, Remove one, Contains again", Priority = 0)]
        public void v4()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            XmlSchema Schema1 = sc.Add("xsdauthor", TestData._XsdAuthor);
            XmlSchema Schema2 = sc.Add("xsdauthor", TestData._XsdNoNs);

            Assert.Equal(sc.Contains("xsdauthor"), true);

            sc.Remove(Schema1);

            Assert.Equal(sc.Contains("xsdauthor"), true);

            return;
        }
        public void Validate(Stream XMLDoc)
        {
            try
            {
                // Declare local objects
                XmlReader tr = null;
                XmlSchemaSet xsc = null;

                // Text reader object

                xsc = new XmlSchemaSet();
                xsc.Add("http://www.cuahsi.org/waterML/1.1/", "cuahsiTimeSeries_v1_1.xsd");
                xsc.Add("http://www.cuahsi.org/waterML/1.0/", "cuahsiTimeSeries_v1_0.xsd");

                // XML validator object

                // Set the validation settings.
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationType = ValidationType.Schema;
                settings.Schemas = xsc;

                // Add validation event handler

                settings.ValidationType = ValidationType.Schema;
                settings.ValidationEventHandler +=
                         new ValidationEventHandler(ValidationHandler);

                // Validate XML data
                tr = XmlReader.Create(XMLDoc, settings);

                while (tr.Read()) ;

                tr.Close();

                // Raise exception, if XML validation fails
                if (ErrorsCount > 0)
                {
                    throw new Exception(ErrorMessage);
                }

                // XML Validation succeeded
                Console.WriteLine("XML validation succeeded.\r\n");
            }
            catch (Exception error)
            {
                // XML Validation failed
                Console.WriteLine("XML validation failed." + "\r\n" +
                "Error Message: " + error.Message);
            }
        }
        private static XmlSchemaSet compileXhtmlSchema()
        {
            var assembly = typeof(NarrativeXhtmlPatternAttribute).Assembly;
            XmlSchemaSet schemas = new XmlSchemaSet();

            Stream schema = assembly.GetManifestResourceStream("Hl7.Fhir.Validation.xhtml.fhir-xhtml.xsd"); 
            schemas.Add(null, XmlReader.Create(schema));   // null = use schema namespace as specified in schema file
            schema = assembly.GetManifestResourceStream("Hl7.Fhir.Validation.xhtml.xml.xsd"); 
            schemas.Add(null, XmlReader.Create(schema));   // null = use schema namespace as specified in schema file

            schemas.Compile();

            return schemas;
        }
Пример #24
0
 /// <summary>
 /// Add a schema to this schema loader
 /// </summary>
 /// <param name="SchemaLocation">The schemalocation to load</param>
 public void Add(String SchemaLocation)
 {
     try
     {
         XmlReaderSettings set = new XmlReaderSettings()
         {
             ProhibitDtd = false
         };
         ss.Add(null, XmlReader.Create(SchemaLocation, set));
     }
     catch (Exception e)
     {
         throw new System.Xml.Schema.XmlSchemaException(String.Format("Can not load the schema '{0}' - {1}", SchemaLocation, e.Message), e);
     }
 }
        public void v3()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
            _ValidationErrors.Clear();
            sc.Add("xsderror", TestData._XsdError);
            sc.Add("xsderror", TestData._XsdError2);

            // should only be one error before compile()
            CError.Compare(_ValidationErrors.Count, 1, "err count");
            sc.Compile();
            // should be two errors before compile()
            CError.Compare(_ValidationErrors.Count, 2, "err count");
            return;
        }
Пример #26
0
        private void ValidateMODS()
        {
            ValidationEventHandler validationHandler = new ValidationEventHandler(XmlValidationError);
            XmlNameTable nameTable = new NameTable();

            XmlDocument xDoc = new XmlDocument(nameTable);
            xDoc.LoadXml(xml);

            XmlSchemaSet validationSchemas = new XmlSchemaSet();
            Assembly assembly = Assembly.GetExecutingAssembly();

            // following schemas edited to remove any external schemaLocation attributes in <import tags
            Stream stream = assembly.GetManifestResourceStream("uk.ac.hull.repository.hydranet.xlink.xsd");
            validationSchemas.Add("http://www.w3.org/1999/xlink", XmlReader.Create(new StreamReader(stream)));
            stream = assembly.GetManifestResourceStream("uk.ac.hull.repository.hydranet.mods-3-3.xsd");
            validationSchemas.Add("http://www.loc.gov/mods/v3", XmlReader.Create(new StreamReader(stream)));

            XPathNavigator xNavMain = xDoc.CreateNavigator();
            xNavMain.CheckValidity(validationSchemas,validationHandler);

            XmlNamespaceManager xNameSpaceMgr =
               new XmlNamespaceManager(new NameTable());

            xNameSpaceMgr.AddNamespace("valMODS", "http://www.loc.gov/mods/v3");
            xNameSpaceMgr.AddNamespace("valXlinq", "http://www.w3.org/1999/xlink");

            string fieldName = "";
            try
            {
                fieldName = "version";
                MandatoryValues.Add(fieldName, xNavMain.SelectSingleNode(
                   "valMODS:modsCollection/valMODS:mods/@valMODS:version | valMODS:modsCollection/valMODS:mods/@version", xNameSpaceMgr).ToString());

                fieldName = "title/titleInfo";
                MandatoryValues.Add(fieldName, xNavMain.SelectSingleNode("valMODS:modsCollection/valMODS:mods/valMODS:titleInfo/valMODS:title", xNameSpaceMgr).ToString());

            }
            catch (Exception)
            {
                throw new XmlSchemaValidationException(String.Format("Missing mandatory field '{0}' in MODS metadata",fieldName));
            }

            foreach (DictionaryEntry entry in MandatoryValues)
            {
                if (entry.Value.ToString().Trim() == "")
                    throw new XmlSchemaValidationException(String.Format("Missing mandatory field '{0}' in MODS metadata", entry.Key.ToString()));
            }
        }
Пример #27
0
 public static XmlQualifiedName GetSchema(XmlSchemaSet xmlSchemaSet)
 {
     if (xmlSchemaSet == null)
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("xmlSchemaSet");
     XmlQualifiedName eprType = EprType;
     XmlSchema eprSchema = GetEprSchema();
     ICollection schemas = xmlSchemaSet.Schemas(Addressing200408Strings.Namespace);
     if (schemas == null || schemas.Count == 0)
         xmlSchemaSet.Add(eprSchema);
     else
     {
         XmlSchema schemaToAdd = null;
         foreach (XmlSchema xmlSchema in schemas)
         {
             if (xmlSchema.SchemaTypes.Contains(eprType))
             {
                 schemaToAdd = null;
                 break;
             }
             else
                 schemaToAdd = xmlSchema;
         }
         if (schemaToAdd != null)
         {
             foreach (XmlQualifiedName prefixNsPair in eprSchema.Namespaces.ToArray())
                 schemaToAdd.Namespaces.Add(prefixNsPair.Name, prefixNsPair.Namespace);
             foreach (XmlSchemaObject schemaObject in eprSchema.Items)
                 schemaToAdd.Items.Add(schemaObject);
             xmlSchemaSet.Reprocess(schemaToAdd);
         }
     }
     return eprType;
 }
        public static XmlQualifiedName GetSchema(XmlSchemaSet schemaSet)
        {
            String wikiPageWebPartSchemaString = "<?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=\"WikiPageWebPart\">" +
                        "<xsd:all>" +
                            "<xsd:element name=\"Contents\" minOccurs=\"1\" maxOccurs=\"1\">" +
                                "<xsd:complexType>" +
                                    "<xsd:sequence>" +
                                        "<xsd:any processContents=\"lax\" namespace=\"##any\" minOccurs=\"0\" />" +
                                    "</xsd:sequence>" +
                                "</xsd:complexType>" +
                            "</xsd:element>" +
                        "</xsd:all>" +
                        "<xsd:attribute name=\"Title\" type=\"xsd:string\" use=\"required\" />" +
                        "<xsd:attribute name=\"Row\" type=\"xsd:int\" use=\"required\" />" +
                        "<xsd:attribute name=\"Column\" type=\"xsd:int\" use=\"required\" />" +
                    "</xsd:complexType>" +
                "</xsd:schema>";

            XmlSchema webPartSchema = XmlSchema.Read(new StringReader(wikiPageWebPartSchemaString), null);
            schemaSet.XmlResolver = new XmlUrlResolver();
            schemaSet.Add(webPartSchema);

            return (new XmlQualifiedName("WikiPageWebPart", XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_12));
        }
Пример #29
0
        public static bool IsXmlValid(string schemaFile, string xmlFile)
        {
            try
            {
                var valid = true;
                var sc = new XmlSchemaSet();
                sc.Add(string.Empty, schemaFile);
                var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = sc };
                settings.ValidationEventHandler += delegate { valid = false; };
                settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
                settings.IgnoreWhitespace = true;
                var reader = XmlReader.Create(xmlFile, settings);

                try
                {
                    while (reader.Read()) {}
                }
                catch (XmlException xmlException)
                {
                    Console.WriteLine(xmlException);
                }
                return valid;
            }
            catch
            {
                return false;
            }
        }
Пример #30
0
 private static XmlSchemaSet LoadSchema(Stream xsd)
 {
     var reader = XmlReader.Create(xsd);
     var set = new XmlSchemaSet();
     set.Add(null, reader);
     return set;
 }
Пример #31
0
        public void v2()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            try
            {
                XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
                CError.Compare(sc.Count, 1, "AddCount");
                CError.Compare(sc.Contains(Schema1), true, "AddContains");
                CError.Compare(sc.IsCompiled, false, "AddIsCompiled");

                XmlSchema Schema2 = XmlSchema.Read(new StreamReader(new FileStream(TestData._XsdNoNs, FileMode.Open, FileAccess.Read)), null);

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

                sc.Reprocess(Schema2);
                CError.Compare(sc.Count, 1, "Reprocess");
                CError.Compare(sc.Contains(Schema2), true, "Contains");
            }
            catch (ArgumentException e)
            {
                _output.WriteLine(e.ToString());
                CError.Compare(sc.Count, 1, "AE");
                return;
            }
            Assert.True(false);
        }
Пример #32
0
        public static void LoadStructureSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            if (!xs.Contains(OpenEhrNamespace))
            {
                if (structureSchema == null)
                {
                    lock (structureSchemaLock)
                    {
                        if (structureSchema == null)
                        {
                            System.Xml.Schema.XmlSchema tempSchema = GetOpenEhrSchema("Structure");
                            tempSchema.Includes.RemoveAt(0);

                            System.Xml.Schema.XmlSchema includeSchema = GetOpenEhrSchema("BaseTypes");

                            foreach (System.Xml.Schema.XmlSchemaObject item in includeSchema.Items)
                            {
                                tempSchema.Items.Add(item);
                            }

                            structureSchema = tempSchema;
                        }
                    }
                }
                xs.Add(structureSchema);
            }
        }
Пример #33
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();
            Products ds = new Products();

            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 = "ProductDataTable";
            type.Attributes.Add(attribute2);
            type.Particle = sequence;
            return(type);
        }
Пример #34
0
        public static void LoadEhrStatusSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            if (!xs.Contains(OpenEhrNamespace))
            {
                System.Xml.Schema.XmlSchema ehrStatusSchema = GetOpenEhrSchema("EhrStatus");
                ehrStatusSchema.Includes.RemoveAt(0);

                System.Xml.Schema.XmlSchema structureSchema = GetOpenEhrSchema("Structure");

                foreach (System.Xml.Schema.XmlSchemaObject item in structureSchema.Items)
                {
                    ehrStatusSchema.Items.Add(item);
                }

                System.Xml.Schema.XmlSchema baseTypesSchema = GetOpenEhrSchema("BaseTypes");

                foreach (System.Xml.Schema.XmlSchemaObject item in baseTypesSchema.Items)
                {
                    ehrStatusSchema.Items.Add(item);
                }

                xs.Add(ehrStatusSchema);

                xs.Compile();
            }
        }
Пример #35
0
        public static void LoadCompositionSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            if (!xs.Contains(OpenEhrNamespace))
            {
                System.Xml.Schema.XmlSchema compositionSchema = GetOpenEhrSchema("Composition");

                System.Xml.Schema.XmlSchema contentSchema = GetOpenEhrSchema("Content");
                compositionSchema.Includes.RemoveAt(0);

                foreach (System.Xml.Schema.XmlSchemaObject item in contentSchema.Items)
                {
                    compositionSchema.Items.Add(item);
                }

                System.Xml.Schema.XmlSchema structureSchema = GetOpenEhrSchema("Structure");

                foreach (System.Xml.Schema.XmlSchemaObject item in structureSchema.Items)
                {
                    compositionSchema.Items.Add(item);
                }

                System.Xml.Schema.XmlSchema baseTypesSchema = GetOpenEhrSchema("BaseTypes");

                foreach (System.Xml.Schema.XmlSchemaObject item in baseTypesSchema.Items)
                {
                    compositionSchema.Items.Add(item);
                }

                xs.Add(compositionSchema);

                xs.Compile();
            }
        }
Пример #36
0
        public static System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(System.Xml.Schema.XmlSchemaSet xs)
        {
            TypedDataSet ds = new TypedDataSet();

            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 System.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 System.Decimal(0);
                any2.ProcessContents = System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any2);
                sequence.MaxOccurs = System.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);
        }
Пример #37
0
        public bool IsValid(string xml, System.Xml.Schema.XmlSchema xd, bool reportWarnings = false)
        {
            // Create the schema object
            var sc = new System.Xml.Schema.XmlSchemaSet();

            sc.Add(xd);
            return(IsValid(xml, sc, reportWarnings));
        }
Пример #38
0
        public MmlWriter()
        {
            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);
            }
        }
Пример #39
0
    public static System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(System.Xml.Schema.XmlSchemaSet xs)
    {
        Products ds = new Products();

        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);
    }
Пример #40
0
 /// <summary>
 /// Validates an XML document against Exchange.xsd schema
 /// </summary>
 /// <param name="doc2validate">XML document to be validated</param>
 public static void AgainstScheme(XmlDocument doc2validate)
 {
     System.Xml.Schema.XmlSchemaSet schemas = new System.Xml.Schema.XmlSchemaSet();
     schemas.Add(null, System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Scheme\Exchange.xsd"));
     try
     {
         XDocument doc = XDocument.Parse(doc2validate.InnerXml);
         doc.Validate(schemas, (o, e) =>
         {
             throw new Exception(e.Message);
         });
     }
     catch (Exception ex)
     {
         throw new Exception("XML could not be validated! It is not well-formed or does not comply with XSD.", ex);
     }
 }
Пример #41
0
 public static void LoadBaseTypesSchema(System.Xml.Schema.XmlSchemaSet xs)
 {
     if (!xs.Contains(OpenEhrNamespace))
     {
         if (baseTypesSchema == null)
         {
             lock (baseTypesSchemaLock)
             {
                 if (baseTypesSchema == null)
                 {
                     baseTypesSchema = GetOpenEhrSchema("BaseTypes");
                 }
             }
         }
         xs.Add(baseTypesSchema);
     }
 }
Пример #42
0
        /// <summary>
        /// Validate an Xml According to the passed schema
        /// </summary>
        /// <param name="xmlSchema">XsdSchema</param>
        public virtual void Validate(string xmlSchema)
        {
            var xml = _currentXmlBag.GetRawXml();

            if (string.IsNullOrEmpty(xml))
            {
                throw new InvalidOperationException("Non è possibile validare un xml vuoto");
            }

            if (string.IsNullOrEmpty(xmlSchema))
            {
                throw new ArgumentNullException(nameof(xmlSchema));
            }

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

            schemas.Add(string.Empty, System.Xml.XmlReader.Create(new System.IO.StringReader(xmlSchema)));

            var doc = XDocument.Parse(xml);

            var validationErrors = new List <XsdValidationInfo>();

            var errors = false;

            doc.Validate(
                schemas,
                (o, e) =>
            {
                validationErrors.Add(new XsdValidationInfo(e.Message, e.Exception));
                errors = true;
            });

            if (errors)
            {
                throw new XsdValidationException(validationErrors);
            }
        }
Пример #43
0
        void DoCompile(ValidationEventHandler handler, Hashtable handledUris, XmlSchemaSet col, XmlResolver resolver)
        {
            SetParent();
            CompilationId = col.CompilationId;
            schemas       = col;
            if (!schemas.Contains(this))              // e.g. xs:import
            {
                schemas.Add(this);
            }

            attributeGroups.Clear();
            attributes.Clear();
            elements.Clear();
            groups.Clear();
            notations.Clear();
            schemaTypes.Clear();

            //1. Union and List are not allowed in block default
            if (BlockDefault != XmlSchemaDerivationMethod.All)
            {
                if ((BlockDefault & XmlSchemaDerivationMethod.List) != 0)
                {
                    error(handler, "list is not allowed in blockDefault attribute");
                }
                if ((BlockDefault & XmlSchemaDerivationMethod.Union) != 0)
                {
                    error(handler, "union is not allowed in blockDefault attribute");
                }
            }

            //2. Substitution is not allowed in finaldefault.
            if (FinalDefault != XmlSchemaDerivationMethod.All)
            {
                if ((FinalDefault & XmlSchemaDerivationMethod.Substitution) != 0)
                {
                    error(handler, "substitution is not allowed in finalDefault attribute");
                }
            }

            //3. id must be of type ID
            XmlSchemaUtil.CompileID(Id, this, col.IDCollection, handler);

            //4. targetNamespace should be of type anyURI or absent
            if (TargetNamespace != null)
            {
                if (TargetNamespace.Length == 0)
                {
                    error(handler, "The targetNamespace attribute cannot have have empty string as its value.");
                }

                if (!XmlSchemaUtil.CheckAnyUri(TargetNamespace))
                {
                    error(handler, TargetNamespace + " is not a valid value for targetNamespace attribute of schema");
                }
            }

            //5. version should be of type normalizedString
            if (!XmlSchemaUtil.CheckNormalizedString(Version))
            {
                error(handler, Version + "is not a valid value for version attribute of schema");
            }

            // Compile the content of this schema

            compilationItems = new XmlSchemaObjectCollection();
            for (int i = 0; i < Items.Count; i++)
            {
                compilationItems.Add(Items [i]);
            }

            // First, we run into inclusion schemas to collect
            // compilation target items into compiledItems.
            for (int i = 0; i < Includes.Count; i++)
            {
                XmlSchemaExternal ext = Includes [i] as XmlSchemaExternal;
                if (ext == null)
                {
                    error(handler, String.Format("Object of Type {0} is not valid in Includes Property of XmlSchema", Includes [i].GetType().Name));
                    continue;
                }

                if (ext.SchemaLocation == null)
                {
                    continue;
                }

                Stream stream = null;
                string url    = null;
                if (resolver != null)
                {
                    url = GetResolvedUri(resolver, ext.SchemaLocation);
                    if (handledUris.Contains(url))
                    {
                        // This schema is already handled, so simply skip (otherwise, duplicate definition errrors occur.
                        continue;
                    }
                    handledUris.Add(url, url);
                    try {
                        stream = resolver.GetEntity(new Uri(url), null, typeof(Stream)) as Stream;
                    } catch (Exception) {
                        // LAMESPEC: This is not good way to handle errors, but since we cannot know what kind of XmlResolver will come, so there are no mean to avoid this ugly catch.
                        warn(handler, "Could not resolve schema location URI: " + url);
                        stream = null;
                    }
                }

                // Process redefinition children in advance.
                XmlSchemaRedefine redefine = Includes [i] as XmlSchemaRedefine;
                if (redefine != null)
                {
                    for (int j = 0; j < redefine.Items.Count; j++)
                    {
                        XmlSchemaObject redefinedObj = redefine.Items [j];
                        redefinedObj.isRedefinedComponent = true;
                        redefinedObj.isRedefineChild      = true;
                        if (redefinedObj is XmlSchemaType ||
                            redefinedObj is XmlSchemaGroup ||
                            redefinedObj is XmlSchemaAttributeGroup)
                        {
                            compilationItems.Add(redefinedObj);
                        }
                        else
                        {
                            error(handler, "Redefinition is only allowed to simpleType, complexType, group and attributeGroup.");
                        }
                    }
                }

                XmlSchema includedSchema = null;
                if (stream == null)
                {
                    // It is missing schema components.
                    missedSubComponents = true;
                    continue;
                }
                else
                {
                    XmlTextReader xtr = null;
                    try {
                        xtr            = new XmlTextReader(url, stream, nameTable);
                        includedSchema = XmlSchema.Read(xtr, handler);
                    } finally {
                        if (xtr != null)
                        {
                            xtr.Close();
                        }
                    }
                    includedSchema.schemas = schemas;
                }
                includedSchema.SetParent();
                ext.Schema = includedSchema;

                // Set - actual - target namespace for the included schema * before compilation*.
                XmlSchemaImport import = ext as XmlSchemaImport;
                if (import != null)
                {
                    if (TargetNamespace == includedSchema.TargetNamespace)
                    {
                        error(handler, "Target namespace must be different from that of included schema.");
                        continue;
                    }
                    else if (includedSchema.TargetNamespace != import.Namespace)
                    {
                        error(handler, "Attribute namespace and its importing schema's target namespace must be the same.");
                        continue;
                    }
                }
                else
                {
                    if (TargetNamespace == null &&
                        includedSchema.TargetNamespace != null)
                    {
                        error(handler, "Target namespace is required to include a schema which has its own target namespace");
                        continue;
                    }
                    else if (TargetNamespace != null &&
                             includedSchema.TargetNamespace == null)
                    {
                        includedSchema.TargetNamespace = TargetNamespace;
                    }
                }

                // Do not compile included schema here.

                AddExternalComponentsTo(includedSchema, compilationItems);
            }

            // Compilation phase.
            // At least each Compile() must give unique (qualified) name for each component.
            // It also checks self-resolvable properties correctness.
            // Post compilation schema information contribution is not done here.
            // It should be done by Validate().
            for (int i = 0; i < compilationItems.Count; i++)
            {
                XmlSchemaObject obj = compilationItems [i];
                if (obj is XmlSchemaAnnotation)
                {
                    int numerr = ((XmlSchemaAnnotation)obj).Compile(handler, this);
                    errorCount += numerr;
                }
                else if (obj is XmlSchemaAttribute)
                {
                    XmlSchemaAttribute attr = (XmlSchemaAttribute)obj;
                    int numerr = attr.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(Attributes, attr, attr.QualifiedName, handler);
                    }
                }
                else if (obj is XmlSchemaAttributeGroup)
                {
                    XmlSchemaAttributeGroup attrgrp = (XmlSchemaAttributeGroup)obj;
                    int numerr = attrgrp.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            AttributeGroups,
                            attrgrp,
                            attrgrp.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaComplexType)
                {
                    XmlSchemaComplexType ctype = (XmlSchemaComplexType)obj;
                    int numerr = ctype.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            schemaTypes,
                            ctype,
                            ctype.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaSimpleType)
                {
                    XmlSchemaSimpleType stype = (XmlSchemaSimpleType)obj;
                    stype.islocal = false;                     //This simple type is toplevel
                    int numerr = stype.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            SchemaTypes,
                            stype,
                            stype.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaElement)
                {
                    XmlSchemaElement elem = (XmlSchemaElement)obj;
                    elem.parentIsSchema = true;
                    int numerr = elem.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Elements,
                            elem,
                            elem.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaGroup)
                {
                    XmlSchemaGroup grp    = (XmlSchemaGroup)obj;
                    int            numerr = grp.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Groups,
                            grp,
                            grp.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaNotation)
                {
                    XmlSchemaNotation ntn = (XmlSchemaNotation)obj;
                    int numerr            = ntn.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Notations,
                            ntn,
                            ntn.QualifiedName,
                            handler);
                    }
                }
                else
                {
                    ValidationHandler.RaiseValidationEvent(
                        handler,
                        null,
                        String.Format("Object of Type {0} is not valid in Item Property of Schema", obj.GetType().Name),
                        null,
                        this,
                        null,
                        XmlSeverityType.Error);
                }
            }
        }
Пример #44
0
    public string CheckXmlFile(string xmlFile, string xsdFile)
    {
        //FileStream LogFile = new FileStream("ComtecXml.ini", FileMode.Create, FileAccess.Write);
        //StreamWriter sw = new StreamWriter(LogFile);
        var pSw = new Stopwatch();

        pSw.Start();
        try
        {
            var pXml = new FileStream(xmlFile, FileMode.Open, FileAccess.Read);
            var pXsd = new System.Xml.Schema.XmlSchemaSet();
            pXsd.Add("", xsdFile);
            {
                //SnpXmlValidatingReader:
                var reader = new SnpXmlValidatingReader {
                    ValidatingType = EVsaxValidateType.SaxSchematronUsch
                };
                string StateValidate;
                StateValidate = reader.Validate(pXml, Path.GetFileName(xmlFile), pXsd)
                    ? "1"
                    : "0";
                if (StateValidate == "0")
                {
                    pXml.Close();
                    return("-1");
                }
                if (StateValidate == "1")
                {
                    var errors = reader.ErrorHandler;
                    if (errors.Errors.Count == 0)
                    {
                        pXml.Close();
                        return("1");
                    }
                    else
                    {
                        string ErrorsToComtec = "Всего ошибок: " + errors.Errors.Count.ToString() + "\r\n";
                        int    i = 0000;
                        foreach (var e in errors.Errors)
                        {
                            i++;
                            ErrorsToComtec = ErrorsToComtec + i.ToString() + ". " + e.ErrorText.Replace("зрения", "точки зрения") + "\r\n";
                        }
                        reader.Close();
                        pXml.Close();
                        return(ErrorsToComtec);
                    }
                }
            }
        }
        catch (System.Xml.XmlException e)
        {
            return("-1");
        }
        catch (System.Xml.Schema.XmlSchemaException e)
        {
            return("-1");
        }
        catch (FileNotFoundException ioEx)
        {
            return("-1");
        }
        catch (Exception e)
        {
            return("-1");
        }
        return("-1");
    }
Пример #45
0
        void DoCompile(ValidationEventHandler handler, List <CompiledSchemaMemo> handledUris, XmlSchemaSet col, XmlResolver resolver)
        {
            SetParent();
            CompilationId = col.CompilationId;
            schemas       = col;
            if (!schemas.Contains(this))              // e.g. xs:import
            {
                schemas.Add(this);
            }

            attributeGroups.Clear();
            attributes.Clear();
            elements.Clear();
            groups.Clear();
            notations.Clear();
            schemaTypes.Clear();
            named_identities.Clear();
            ids.Clear();
            compilationItems.Clear();

            //1. Union and List are not allowed in block default
            if (BlockDefault != XmlSchemaDerivationMethod.All)
            {
                if ((BlockDefault & XmlSchemaDerivationMethod.List) != 0)
                {
                    error(handler, "list is not allowed in blockDefault attribute");
                }
                if ((BlockDefault & XmlSchemaDerivationMethod.Union) != 0)
                {
                    error(handler, "union is not allowed in blockDefault attribute");
                }
            }

            //2. Substitution is not allowed in finaldefault.
            if (FinalDefault != XmlSchemaDerivationMethod.All)
            {
                if ((FinalDefault & XmlSchemaDerivationMethod.Substitution) != 0)
                {
                    error(handler, "substitution is not allowed in finalDefault attribute");
                }
            }

            //3. id must be of type ID
            XmlSchemaUtil.CompileID(Id, this, IDCollection, handler);

            //4. targetNamespace should be of type anyURI or absent
            if (TargetNamespace != null)
            {
                if (TargetNamespace.Length == 0)
                {
                    error(handler, "The targetNamespace attribute cannot have have empty string as its value.");
                }

                if (!XmlSchemaUtil.CheckAnyUri(TargetNamespace))
                {
                    error(handler, TargetNamespace + " is not a valid value for targetNamespace attribute of schema");
                }
            }

            //5. version should be of type normalizedString
            if (!XmlSchemaUtil.CheckNormalizedString(Version))
            {
                error(handler, Version + "is not a valid value for version attribute of schema");
            }

            // Compile the content of this schema

            for (int i = 0; i < Items.Count; i++)
            {
                compilationItems.Add(Items [i]);
            }

            // First, we run into inclusion schemas to collect
            // compilation target items into compiledItems.
            for (int i = 0; i < Includes.Count; i++)
            {
                ProcessExternal(handler, handledUris, resolver, Includes [i] as XmlSchemaExternal, col);
            }

            // Compilation phase.
            // At least each Compile() must give unique (qualified) name for each component.
            // It also checks self-resolvable properties correctness.
            // Post compilation schema information contribution is not done here.
            // It should be done by Validate().
            for (int i = 0; i < compilationItems.Count; i++)
            {
                XmlSchemaObject obj = compilationItems [i];
                if (obj is XmlSchemaAnnotation)
                {
                    int numerr = ((XmlSchemaAnnotation)obj).Compile(handler, this);
                    errorCount += numerr;
                }
                else if (obj is XmlSchemaAttribute)
                {
                    XmlSchemaAttribute attr = (XmlSchemaAttribute)obj;
                    int numerr = attr.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(Attributes, attr, attr.QualifiedName, handler);
                    }
                }
                else if (obj is XmlSchemaAttributeGroup)
                {
                    XmlSchemaAttributeGroup attrgrp = (XmlSchemaAttributeGroup)obj;
                    int numerr = attrgrp.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            AttributeGroups,
                            attrgrp,
                            attrgrp.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaComplexType)
                {
                    XmlSchemaComplexType ctype = (XmlSchemaComplexType)obj;
                    int numerr = ctype.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            schemaTypes,
                            ctype,
                            ctype.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaSimpleType)
                {
                    XmlSchemaSimpleType stype = (XmlSchemaSimpleType)obj;
                    stype.islocal = false;                     //This simple type is toplevel
                    int numerr = stype.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            SchemaTypes,
                            stype,
                            stype.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaElement)
                {
                    XmlSchemaElement elem = (XmlSchemaElement)obj;
                    elem.parentIsSchema = true;
                    int numerr = elem.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Elements,
                            elem,
                            elem.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaGroup)
                {
                    XmlSchemaGroup grp    = (XmlSchemaGroup)obj;
                    int            numerr = grp.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Groups,
                            grp,
                            grp.QualifiedName,
                            handler);
                    }
                }
                else if (obj is XmlSchemaNotation)
                {
                    XmlSchemaNotation ntn = (XmlSchemaNotation)obj;
                    int numerr            = ntn.Compile(handler, this);
                    errorCount += numerr;
                    if (numerr == 0)
                    {
                        XmlSchemaUtil.AddToTable(
                            Notations,
                            ntn,
                            ntn.QualifiedName,
                            handler);
                    }
                }
                else
                {
                    ValidationHandler.RaiseValidationEvent(
                        handler,
                        null,
                        String.Format("Object of Type {0} is not valid in Item Property of Schema", obj.GetType().Name),
                        null,
                        this,
                        null,
                        XmlSeverityType.Error);
                }
            }
        }
    public static IEnumerable fnWebSendXMLDataKFHHomeSearch(
        SqlString PostURL,
        SqlString Method,
        SqlString ContentType,
        SqlXml XMLData,
        SqlString P12CertPath,
        SqlString P12CertPass,
        SqlInt32 Timeout,
        SqlString SchemaURI,
        SqlString RootName,
        SqlString SuccessNode,
        SqlString SuccessValue,
        SqlBoolean UniqueNodeValues,
        SqlString XPathReturnValue
        )
    {
        // creates a collection to store the row values ( might have to make this a scalar row rather then multi-rowed )
        ArrayList resultCollection = new ArrayList();

        // logs the time the row had begun processing
        SqlDateTime _StartedTS = DateTime.Now;

        // stores the URL of the request and stores any xml input as bytes
        Uri URL = null;

        byte[] postBytes = null;

        // if the required fields post url and method are not provided then...
        if (PostURL.IsNull || PostURL.Value == "" || Method.IsNull)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [Post URL] was missing or the [Method] was missing.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // if the methods are not correctly set to the only valid values then...
        if (Method.Value != "POST" && Method.Value != "GET")
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [Method] provided was not either POST or GET.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // check to see if the url is correctly formed otherwise...
        if (Uri.TryCreate(PostURL.Value, UriKind.RelativeOrAbsolute, out URL) == false)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [URL] provided was incorrectly formatted.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // if xml schema has been specified but no xml has been passed then...
        if (!SchemaURI.IsNull && XMLData.IsNull)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [Schema URI] was provided but [XML Data] was not.", STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection);
        }

        // check to see if we can access the schema .xsd file otherwise...
        if (!SchemaURI.IsNull && System.IO.File.Exists(SchemaURI.Value) == false)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [Schema URI] was provided but could not be loaded because it could not be found.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // if xml specific fields are available but no xml has been passed then...
        if ((!RootName.IsNull || !SuccessNode.IsNull || !SuccessValue.IsNull) && XMLData.IsNull)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [Root Name] or [Success Node] or [Success Value] was provided but the [XML Data] was missing.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // if certificate pass is specified but no certificate file has then...
        if (!P12CertPass.IsNull && P12CertPath.IsNull)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [P12 Cert Pass] was provided but the [P12 Cert Path] is missing.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // check to see if we can access the certificate file otherwise...
        if (!P12CertPath.IsNull && System.IO.File.Exists(P12CertPath.Value) == false)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [P12 Cert Path] was provided but could not be loaded because it could not be found.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // check that the certificate provided can be opened before performing major code...
        if (!P12CertPath.IsNull)
        {
            try
            {
                if (!P12CertPass.IsNull)
                {
                    new X509Certificate2(P12CertPath.Value, P12CertPass.Value);
                }
                else
                {
                    new X509Certificate2(P12CertPath.Value);
                }
            }
            catch (Exception ex)
            {
                resultCollection.Add(new PostResult(null, null, false, true, String.Format("Certificate exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace), STATUS_CODES.FAILED_VALIDATION, null));
                return(resultCollection);
            }
        }

        // check if any xml data has been passed to the clr
        using (var stringWriter = new StringWriter())
        {
            if (!XMLData.IsNull)
            {
                // prepare xml variable
                XmlDocument2 xDoc = new XmlDocument2();

                try
                {
                    // rename root node if applicable
                    if (!RootName.IsNull)
                    {
                        XmlDocument2 _xDoc = new XmlDocument2();
                        _xDoc.LoadXml(XMLData.Value);
                        XmlElement _xDocNewRoot = xDoc.CreateElement(RootName.Value);
                        xDoc.AppendChild(_xDocNewRoot);
                        _xDocNewRoot.InnerXml = _xDoc.DocumentElement.InnerXml;
                    }
                    else
                    {
                        // otherwise just load the xml exactly as provided
                        xDoc.LoadXml(XMLData.Value);
                    }

                    // add the xml declaration if it doesn't exist
                    if (xDoc.FirstChild.NodeType != XmlNodeType.XmlDeclaration)
                    {
                        XmlDeclaration xmlDec = xDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                        XmlElement     root   = xDoc.DocumentElement;
                        xDoc.InsertBefore(xmlDec, root);
                    }

                    // if the schema file has been specified then validate otherwise skip
                    if (!SchemaURI.IsNull)
                    {
                        System.Xml.Schema.XmlSchemaSet schemas = new System.Xml.Schema.XmlSchemaSet();
                        schemas.Add("", SchemaURI.Value);
                        xDoc.Schemas.Add(schemas);
                        if (!UniqueNodeValues.IsNull)
                        {
                            xDoc.UniqueNodeValues = UniqueNodeValues.Value;
                        }
                        xDoc.Validate(ValidationEventHandler);
                    }

                    // adds any validation errors to the output rows and stops processing if errors were found
                    if (xDoc.ValidationErrors.Count > 0)
                    {
                        resultCollection.AddRange(xDoc.ValidationErrors);
                        return(resultCollection);
                    }

                    // Save the xml as a string
                    using (var xmlTextWriter = XmlWriter.Create(stringWriter))
                    {
                        xDoc.WriteTo(xmlTextWriter);
                        xmlTextWriter.Flush();
                    }

                    // get the bytes for the xml document
                    //postBytes = Encoding.UTF8.GetBytes(xDoc.OuterXml);
                    UTF8Encoding encoding = new UTF8Encoding();
                    postBytes = encoding.GetBytes(xDoc.InnerXml);

                    //Revisions:

                    //json String Variable
                    // byte[] byteData = new System.Text.ASCIIEncoding().GetBytes(json);
                }
                catch (Exception ex)
                {
                    string errorMsg = String.Format("XML Parse exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                    resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.XML_ERROR, null, _StartedTS));
                    return(resultCollection);
                }
            }

            if (Timeout.IsNull)
            {
                Timeout = 20;
            }
            if (ContentType.IsNull)
            {
                ContentType = "*/*";
            }


            // Set the SecurityProtocol

            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;


            // create the web request object after validation succeeds
            HttpWebRequest webRequest;
            try
            {
                // create the http request
                webRequest = (HttpWebRequest)HttpWebRequest.Create(URL);

                // setup the connection settings
                webRequest.Method      = Method.Value;
                webRequest.ContentType = ContentType.Value;
                webRequest.Accept      = ContentType.Value;
                webRequest.Timeout     = (Timeout.Value * 1000);
                webRequest.SendChunked = true;
                webRequest.KeepAlive   = false;
            }
            catch (Exception ex)
            {
                string errorMsg = String.Format("WebRequest Create exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE, null, _StartedTS));
                return(resultCollection);
            }

            try
            {
                // add the P12 certificate to the request if specified
                if (!P12CertPath.IsNull)
                {
                    // load with password if specified
                    if (!P12CertPass.IsNull)
                    {
                        webRequest.ClientCertificates.Add(new X509Certificate2(P12CertPath.Value, P12CertPass.Value));
                    }
                    else
                    {
                        webRequest.ClientCertificates.Add(new X509Certificate2(P12CertPath.Value));
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMsg = String.Format("Certificate exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.CERTIFICATE_ERROR, null, _StartedTS));
                return(resultCollection);
            }

            // post the request
            if (Method.Value == "POST")
            {
                try
                {
                    using (StreamWriter postStream = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
                    {
                        try
                        {
                            // post the data as bytes to the request stream
                            if (postBytes != null)
                            {
                                postStream.Write(System.Text.Encoding.UTF8.GetString(postBytes));
                                postStream.Flush();
                                //postStream.BaseStream.Write(postBytes, 0, postBytes.Length);
                            }
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = String.Format("StreamWriter exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                            resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.GET_REQUEST_STREAM, null, _StartedTS, DateTime.Now));
                            return(resultCollection);
                        }
                        finally
                        {
                            postStream.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    string errorMsg = String.Format("Web request exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                    resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.GET_REQUEST_STREAM, null, _StartedTS, DateTime.Now));
                    return(resultCollection);
                }
            }

            string          response    = string.Empty;
            HttpWebResponse objResponse = null;

            // get the response (also used for GET)
            try
            {
                objResponse = (HttpWebResponse)webRequest.GetResponse();
                if (webRequest.HaveResponse == true)
                {
                    using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
                    {
                        try
                        {
                            // get the result of the post
                            response = responseStream.ReadToEnd();

                            // see if the response is in xml format or not
                            XmlDocument doc = null;
                            if (response.IndexOf("<", 0) <= 2)
                            {
                                doc = new XmlDocument();
                                try { doc.LoadXml(response); }
                                catch (Exception) { doc = null; }
                            }

                            // if the response is expected in xml format
                            if (doc != null)
                            {
                                // check for a success value and node if specified...
                                if (!SuccessNode.IsNull && !SuccessValue.IsNull)
                                {
                                    try
                                    {
                                        // use the response xml and get the success node(s) specified in the xpath
                                        XmlNodeList nodeSuccess = doc.SelectNodes(SuccessNode.Value);

                                        using (XmlNodeReader xnr = new XmlNodeReader(doc))
                                        {
                                            if (nodeSuccess.Count == 0)
                                            {
                                                resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), false, false, null, STATUS_CODES.XML_XPATH_RESULT_NODE_MISSING,
                                                                                    ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                                            }
                                            else
                                            {
                                                // loop through each node we need to validate and get the value
                                                IEnumerator EN = nodeSuccess.GetEnumerator();
                                                while (EN.MoveNext() == true)
                                                {
                                                    if (((XmlNode)EN.Current).InnerText == SuccessValue.Value)
                                                    {
                                                        resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), true, false, null, STATUS_CODES.SUCCESS,
                                                                                            ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                                                    }
                                                    else
                                                    {
                                                        resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), false, true, null, STATUS_CODES.FAILURE,
                                                                                            ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        string errorMsg = String.Format("XML reader exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                                        resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE,
                                                                            ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                                        return(resultCollection);
                                    }
                                }
                                else
                                {
                                    // if we're not checking for a success node then just return the xml response
                                    using (XmlNodeReader xnr = new XmlNodeReader(doc))
                                    {
                                        resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), true, false, null, STATUS_CODES.SUCCESS,
                                                                            ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                                    }
                                }
                            }
                            else
                            {
                                // all other requests return in plain text in the additional info column
                                resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, true, false, response, STATUS_CODES.SUCCESS,
                                                                    ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                            }
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = String.Format("StreamWriter exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                            resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE, null, _StartedTS, DateTime.Now));
                            return(resultCollection);
                        }
                        finally
                        {
                            responseStream.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMsg = String.Format("Web response exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE, null, _StartedTS, DateTime.Now));
                return(resultCollection);
            }
            finally
            {
                if (objResponse != null)
                {
                    objResponse.Close();
                }
            }
        }

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

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

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

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

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

            var newRecs = new AasValidationRecordList();

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

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

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

            return(new XmlValidator(xmlSchemaSet));
        }