void AddElementToSchema(XmlSchemaElement element, string elementNs, XmlSchemaSet schemaSet)
        {
            OperationDescription parentOperation = this.operation;
            if (parentOperation.OperationMethod != null)
            {
                XmlQualifiedName qname = new XmlQualifiedName(element.Name, elementNs);

                OperationElement existingElement;
                if (ExportedMessages.ElementTypes.TryGetValue(qname, out existingElement))
                {
                    if (existingElement.Operation.OperationMethod == parentOperation.OperationMethod)
                        return;
                    if (!SchemaHelper.IsMatch(element, existingElement.Element))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CannotHaveTwoOperationsWithTheSameElement5, parentOperation.OperationMethod.DeclaringType, parentOperation.OperationMethod.Name, qname, existingElement.Operation.OperationMethod.DeclaringType, existingElement.Operation.Name)));
                    }
                    return;
                }
                else
                {
                    ExportedMessages.ElementTypes.Add(qname, new OperationElement(element, parentOperation));
                }
            }
            SchemaHelper.AddElementToSchema(element, SchemaHelper.GetSchema(elementNs, schemaSet), schemaSet);
        }
        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;
        }
        public void Import(XmlSchemaSet schemas)
        {
            if (schemas == null)
                throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("schemas"));

            InternalImport(schemas, null, null, null);
        }
示例#4
0
 private static XmlSchemaSet LoadSchema(Stream xsd)
 {
     var reader = XmlReader.Create(xsd);
     var set = new XmlSchemaSet();
     set.Add(null, reader);
     return set;
 }
 private string Validate(string path)
 {
     var sc = new XmlSchemaSet();
     string dir = @"..\..\..\..\Schemas\Collada\";
     sc.Add("http://www.collada.org/2008/03/COLLADASchema", dir + "collada_schema_1_5.xsd");
     return Validate(path, sc);
 }
        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);
        }
        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));
        }
        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);
        }
        static void Main()
        {
            XmlSchemaSet schemas = new XmlSchemaSet();
            schemas.Add("", "../../../Content/catalog.xsd");

            var document = XDocument.Load("../../catalog.xml");

            Console.WriteLine("Validating XML file...");
            bool errors = false;
            document.Validate(schemas, (o, e) =>
            {
                Console.WriteLine("{0}", e.Message);
                errors = true;
            });
            Console.WriteLine("XML file {0}", errors ? "did not validate" : "validated");

            Console.WriteLine(new string('*', 40));
            Console.WriteLine("Add something incorrect in \"catalog.xml\" like deleting the <year> tag");
            document.Root.Elements("album").Elements("year").Remove();
            //Console.WriteLine(document);

            Console.WriteLine("Validating XML file...");
            errors = false;
            document.Validate(schemas, (o, e) =>
            {
                Console.WriteLine("{0}", e.Message);
                errors = true;
            });
        }
示例#10
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;
            }
        }
 //[Variation(Desc = "v2 - Contains with non existing ns", Priority = 0)]
 public void v2()
 {
     XmlSchemaSet sc = new XmlSchemaSet();
     sc.Add("xsdauthor", TestData._XsdAuthor);
     Assert.Equal(sc.Contains("test"), false);
     return;
 }
 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 XmlSchemaValidator(XmlNameTable nameTable, XmlSchemaSet schemas, IXmlNamespaceResolver namespaceResolver, XmlSchemaValidationFlags validationFlags)
 {
     if (nameTable == null)
     {
         throw new ArgumentNullException("nameTable");
     }
     if (schemas == null)
     {
         throw new ArgumentNullException("schemas");
     }
     if (namespaceResolver == null)
     {
         throw new ArgumentNullException("namespaceResolver");
     }
     this.nameTable = nameTable;
     this.nsResolver = namespaceResolver;
     this.validationFlags = validationFlags;
     if (((validationFlags & XmlSchemaValidationFlags.ProcessInlineSchema) != XmlSchemaValidationFlags.None) || ((validationFlags & XmlSchemaValidationFlags.ProcessSchemaLocation) != XmlSchemaValidationFlags.None))
     {
         this.schemaSet = new XmlSchemaSet(nameTable);
         this.schemaSet.ValidationEventHandler += schemas.GetEventHandler();
         this.schemaSet.CompilationSettings = schemas.CompilationSettings;
         this.schemaSet.XmlResolver = schemas.GetResolver();
         this.schemaSet.Add(schemas);
         this.validatedNamespaces = new Hashtable();
     }
     else
     {
         this.schemaSet = schemas;
     }
     this.Init();
 }
示例#14
0
        public ClrMappingInfo GenerateMapping(XmlSchemaSet schemas)
        {
            if (schemas == null)
            {
                throw new ArgumentNullException("schemas");
            }
            schemas.ValidationEventHandler += new ValidationEventHandler(Validationcallback);
            schemas.Compile();

            this.schemas = schemas;
            if (schemaErrorCount > 0)
            {
                Console.WriteLine("Schema cannot be compiled. Class generation aborted");
                return null;
            }

            // Execute transformations
            try
            {
                Xml.Fxt.FxtLinq2XsdInterpreter.Run(schemas, configSettings.trafo);
            }
            catch (Xml.Fxt.FxtException)
            {
                Console.WriteLine("Schema cannot be transformed. Class generation aborted");
                return null;
            }
            return GenerateMetaModel();
        }
        //[Variation(Desc = "v1 - Contains with null")]
        public void v1()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            Assert.Equal(sc.Contains((String)null), false);

            return;
        }
        public DatabaseVersionSetup Load(TextReader reader)
        {
            var versionSetup = new DatabaseVersionSetup();

            var shemas = new XmlSchemaSet();
            Assembly assem = typeof(DatabaseVersionSetup).Assembly;
            using (Stream stream = assem.GetManifestResourceStream("DatabaseVersionControl.Core.Xsd.DVCSchema.xsd"))
            {
                if (stream != null){
                    shemas.Add("", XmlReader.Create(stream));
                }
                else{
                    throw new Exception("Could not load embedded resource Xsd.DVCSchema.xsd");
                }
            }
            XDocument element = XDocument.Load(reader);
            element.Validate(shemas, (sender, e) =>
                                         { if (_exception != null) _exception(e); }, true);
            var profiles = element.XPathSelectElements("//profiles/profile");
            versionSetup.DefaultProfile = element.Root.Attribute("defaultProfile").Value;
            LoadProfiles(versionSetup, profiles);
            var databases = element.XPathSelectElements("//repositories/repository");
            LoadRepositories(versionSetup, databases);
            return versionSetup;
        }
示例#17
0
 private static void ValidateXml(XDocument document, XmlSchemaSet schema)
 {
     document.Validate(schema, (obj, ev) =>
         {
             Console.WriteLine("{0}", ev.Message);
         });
 }
 public static bool DeepEqualsWithNormalization(XDocument doc1, XDocument doc2,
     XmlSchemaSet schemaSet)
 {
     XDocument d1 = Normalize(doc1, schemaSet);
     XDocument d2 = Normalize(doc2, schemaSet);
     return XNode.DeepEquals(d1, d2);
 }
示例#19
0
        public bool validate()
        {

            try
            {
                XmlSchemaSet sc = new XmlSchemaSet();
                // Add the schema to the collection.

                sc.Add("urn:mites-schema", this.xsdFile);
                // Set the validation settings.    
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.ValidationType = ValidationType.Schema;
                settings.Schemas = sc;
                settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
                // Create the XmlReader object.
                XmlReader reader = XmlReader.Create(this.xmlFile, settings);
                // Parse the file. 
                while (reader.Read())
                {
                    ;
                }
                return true;
            }
            catch (Exception e)
            {
                throw new Exception("Error in (SXML.ConfigurationReader,validate):" + e.ToString());
            }

        }
示例#20
0
        private static void LoadAndValidateInvoice(string xmlFilename, XmlSchemaSet invoiceSchemaSet)
        {
            UblLarsen.Ubl2.InvoiceType invoice = null;
            using (FileStream fs = File.OpenRead(xmlFilename))
            {
                Console.WriteLine($"Processing {xmlFilename} ...");
                // XDocument can contain any valid xml, don't know if it is an ubl invoice yet
                XDocument xmlInvoice = XDocument.Load(fs);
                if (!ValidateUblInvoiceDocument(xmlInvoice, invoiceSchemaSet))
                {
                    Console.WriteLine("Invalid ubl invoice document, but I will try and read it anyway...");
                }

                // Reuse filestream and load into an InvoiceType instance by using XmlSerializer
                fs.Position = 0;
                XmlSerializer xs = new XmlSerializer(typeof(UblLarsen.Ubl2.InvoiceType));
                try
                {
                    invoice = (UblLarsen.Ubl2.InvoiceType)xs.Deserialize(fs);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Deserialize: " + ex.Message);
                }
            }

            if (invoice != null)
            {
                ShowInvoice(invoice);
            }
        }
        public bool IsValid(Stream template)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

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

            // Load the XSD embedded resource
            Stream stream = typeof(XMLPnPSchemaV201508Formatter)
                .Assembly
                .GetManifestResourceStream("OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.ProvisioningSchema-2015-08.xsd");

            // Prepare the XML Schema Set
            XmlSchemaSet schemas = new XmlSchemaSet();
            schemas.Add(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_08,
                new XmlTextReader(stream));

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

            return (result);
        }
示例#22
0
        public static void Main()
        {
            XmlSchemaSet schemas = new XmlSchemaSet();
            schemas.Add("urn:catalogue", "..//..//xml/catalogue.xsd");

            XDocument XmlDocument = XDocument.Load("..//..//xml/catalogue.xml");

            List<string> errorMessages = new List<string>();

            XmlDocument.Validate(schemas, (obj, error) =>
            {
                errorMessages.Add(error.Message);
            });

            IPrinter printer = new ConsolePrinter();

            if (errorMessages.Count == 0)
            {
                printer.Print("Valid catalogue.xml");
            }
            else
            {
                printer.Print(errorMessages);
            }
        }
示例#23
0
        public void ValidateSave()
        {
            WorldEntity world = createTestWorld();

            XElement xElement = WorldTransformer.Instance.ToXElement(world, TransformerSettings.WorldNamespace + "World");

            xElement.Save("unittestsave.xml", SaveOptions.OmitDuplicateNamespaces);

            XmlSchemaSet schemaSet = new XmlSchemaSet();

            schemaSet.Add(null, "WorldSchema1.xsd");

            XDocument xDocument = new XDocument(xElement);
            xDocument.AddAnnotation(SaveOptions.OmitDuplicateNamespaces);
            xDocument.Save("unittest2.xml", SaveOptions.OmitDuplicateNamespaces);

            XElement x1 = new XElement(TransformerSettings.WorldNamespace + "Outer");
            x1.Add(new XElement(TransformerSettings.WorldNamespace + "Inner"));
            x1.Save("unittest3.xml", SaveOptions.OmitDuplicateNamespaces);
            string val = "";
            xDocument.Validate(schemaSet, (o, vea) => {
                val += o.GetType().Name + "\n";
                val += vea.Message + "\n";
            }, true);

            Assert.AreEqual("", val);
        }
示例#24
0
        public bool ValidateXml(string inputXML, string xsdUri)
        {
            stringBuilder = new StringBuilder();

            bool validated = false;

            // Create the XmlSchemaSet class.
            XmlSchemaSet sc = new XmlSchemaSet();

            // Add the schema to the collection.
            sc.Add(null, xsdUri);

            // Set the validation settings.
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas = sc;
            settings.ConformanceLevel = ConformanceLevel.Auto;
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

            XmlTextReader reader = new XmlTextReader(new StringReader(inputXML));
            while (reader.Read())
            { }

            if (stringBuilder.ToString() == String.Empty)
                validated = true;

            return validated;
        }
        /// <summary>
        /// Load an Schema From A File Location
        /// </summary>
        /// <param name="SchemaFileLocation">Schema File Location</param>
        /// <param name="TargetNamespace">Default Namespace - Could be a blank string</param>
        /// <returns>XmlSchemaSet Object</returns>
        public static XmlSchemaSet LoadSchemaSetFromFileLocation(string SchemaFileLocation, string TargetNamespace)
        {
            //Make sure the file is there
            if (!File.Exists(SchemaFileLocation))
            {
                throw new FileNotFoundException("Can't Find Schema File In: " + SchemaFileLocation);
            }

            //Make sure its a .xsd file
            if (!string.Equals(new FileInfo(SchemaFileLocation).Extension, ".xsd", StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidDataException("Schema File Must Be Of Extension .xsd");
            }

            //*************Done with validation*************
            //Schema To Load
            var SchemaSet = new XmlSchemaSet();

            //Add the file xsd file to the path
            SchemaSet.Add(TargetNamespace, SchemaFileLocation);

            //Compile The Schema
            SchemaSet.Compile();

            //Return the XMLSchemaSet
            return SchemaSet;
        }
        private static XmlSchemaSet LoadXsdFile(string xsdPath)
        {
            XmlSchemaSet xsdSchema = new XmlSchemaSet();
            xsdSchema.Add(string.Empty, xsdPath);

            return xsdSchema;
        }
 private static void PrintValidationResult(XDocument doc, XmlSchemaSet schema, string file)
 {
     doc.Validate(schema, (obj, ev) =>
     {
         Console.WriteLine("* {0} * {1}",file, ev.Message);
     });
 }
示例#28
0
 public void UnitTestValidate()
 {
     XmlSchemaSet schemas = new XmlSchemaSet();
     schemas.Add(Resource.GetXmlSchema("StealFocus.Core.Tests", "StealFocus.Core.Tests.Xml.Resources.Schema.xsd"));
     XmlDocument xmlDocument = Resource.GetXmlDocument("StealFocus.Core.Tests", "StealFocus.Core.Tests.Xml.Resources.Document.xml");
     XmlValidator.Validate(xmlDocument, schemas);
 }
示例#29
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");
		}
    public SoapEditorProxy(Connections.ConnectionData connData, ServiceDescription description, XmlSchemaSet schemas)
    {
      _connData = connData;
      _descrip = description;
      _schemas = schemas;
      _helper = new XmlCompletionDataProvider(schemas, "http://schemas.xmlsoap.org/soap/envelope/"
        , "soapenv", () => "xmlns:soap=\"" + description.TargetNamespace + "\""
        , e => (e.Name == "Envelope" && e.QualifiedName.Namespace == "http://schemas.xmlsoap.org/soap/envelope/")
          || TypeMatchesAction(e.QualifiedName, this.Action));

      _baseUrl = new Uri(_connData.Url).GetLeftPart(UriPartial.Path);
      switch (_connData.Authentication)
      {
        case Connections.Authentication.Windows:
          _cred = CredentialCache.DefaultNetworkCredentials;
          break;
        case Connections.Authentication.Explicit:
          _cred = new NetworkCredential(_connData.UserName, _connData.Password);
          break;
      }

      _actionUrls = _descrip.Services.OfType<Service>()
        .SelectMany(s => s.Ports.OfType<Port>().Where(SoapPort))
        .SelectMany(p => _descrip.Bindings[p.Binding.Name].Operations.OfType<OperationBinding>())
        .Select(o => new { Name = o.Name, Address = o.Extensions.OfType<SoapOperationBinding>().First().SoapAction })
        .Distinct()
        .ToDictionary(a => a.Name, a => a.Address);
    }
示例#31
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();
            }
        }
示例#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 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();
            }
        }
示例#34
0
        public SchemaValidator(string schemaNamespace, string schemaPath)
        {
            if (schemaNamespace == null)
            {
                throw new ArgumentNullException("schemaNamespace");
            }

            if (schemaNamespace.Length == 0)
            {
                throw new ArgumentException("schema namespace cannot be zero length!");
            }

            if (schemaPath == null)
            {
                throw new ArgumentNullException("schemaPath");
            }

            if (schemaPath.Length == 0)
            {
                throw new ArgumentException("schemaPath cannot be of zero length!");
            }

            if (!File.Exists(schemaPath))
            {
                throw new ArgumentException("Schema: " + schemaPath + " cannot be located!");
            }

            schemaSet = new XmlSchemaSet();
            schemaSet.Add(schemaNamespace, schemaPath);
            schemaSet.Compile();
        }
示例#35
0
 public bool IsValid(string xml, System.Xml.Schema.XmlSchemaSet sc, bool reportWarnings = false)
 {
     _xml = xml;
     // Create reader settings
     System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings();
     // Attach event handler whic will be fired when validation error occurs
     settings.ValidationEventHandler += XmlReader_ValidationCallBack;
     // Set validation type to schema
     settings.ValidationType = System.Xml.ValidationType.Schema;
     if (reportWarnings)
     {
         settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings;
     }
     //settings.ValidationFlags = settings.ValidationFlags Or System.Xml.Schema.XmlSchemaValidationFlags.ProcessInlineSchema
     //settings.ValidationFlags = settings.ValidationFlags Or System.Xml.Schema.XmlSchemaValidationFlags.ProcessSchemaLocation
     // Add to the collection of schemas in readerSettings
     settings.Schemas = sc;
     //settings.ProhibitDtd = False
     // Create object of XmlReader using XmlReaderSettings
     System.IO.StringReader xmlMs  = new System.IO.StringReader(xml);
     System.Xml.XmlReader   reader = System.Xml.XmlReader.Create(xmlMs, settings);
     Exceptions = new List <System.Xml.Schema.XmlSchemaException>();
     // Parse the file.
     while (reader.Read())
     {
     }
     return(Exceptions.Count == 0);
 }
示例#36
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));
        }
示例#37
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);
            }
        }
示例#38
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);
     }
 }
示例#39
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);
     }
 }
示例#40
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);
            }
        }
    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);
    }
        public override ArrayList ExpectedParticles(ValidationState context, bool isRequiredOnly, XmlSchemaSet schemaSet)
        {
            ArrayList particles = new ArrayList();

            int[] numArray = this.transitionTable[context.CurrentState.State];
            if (numArray != null)
            {
                for (int i = 0; i < (numArray.Length - 1); i++)
                {
                    if (numArray[i] != -1)
                    {
                        XmlSchemaParticle p = (XmlSchemaParticle)this.symbols.GetParticle(i);
                        if (p != null)
                        {
                            ContentValidator.AddParticleToExpected(p, schemaSet, particles);
                        }
                    }
                }
            }
            return(particles);
        }
示例#43
0
        public override ArrayList ExpectedParticles(ValidationState context, bool isRequiredOnly, XmlSchemaSet schemaSet)
        {
            ArrayList particles = new ArrayList();
            BitSet    set       = context.CurPos[context.CurrentState.CurPosIndex];

            for (int i = set.NextSet(-1); i != -1; i = set.NextSet(i))
            {
                XmlSchemaParticle p = (XmlSchemaParticle)this.positions[i].particle;
                if (p != null)
                {
                    ContentValidator.AddParticleToExpected(p, schemaSet, particles);
                }
            }
            return(particles);
        }
示例#44
0
 public static System.Xml.XmlQualifiedName ProvideSchema(System.Xml.Schema.XmlSchemaSet xs)
 {
     return(new System.Xml.XmlQualifiedName("time", "http://www.w3.org/2001/XMLSchema"));
 }
示例#45
0
 /// <summary>
 /// Validate a <see cref="XAttribute"/>
 /// </summary>
 /// <param name="source">Extension point</param>
 /// <param name="partialValidationType">An <see cref="XmlSchemaAttribute"/> or
 /// <see cref="XmlSchemaType"/> object used to initialize the partial validation
 /// context</param>
 /// <param name="schemas">The <see cref="XmlSchemaSet"/> used for validation</param>
 /// <param name="validationEventHandler">The <see cref="ValidationEventHandler"/> that
 /// receives schema validation warnings and errors encountered during schema
 /// validation</param>
 public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler?validationEventHandler)
 {
     source.Validate(partialValidationType, schemas, validationEventHandler, false);
 }
示例#46
0
 /// <summary>
 /// Validate a <see cref="XAttribute"/>
 /// </summary>
 /// <param name="source">Extension point</param>
 /// <param name="partialValidationType">An <see cref="XmlSchemaAttribute"/> or
 /// <see cref="XmlSchemaType"/> object used to initialize the partial validation
 /// context</param>
 /// <param name="schemas">The <see cref="XmlSchemaSet"/> used for validation</param>
 /// <param name="validationEventHandler">The <see cref="ValidationEventHandler"/> that
 /// receives schema validation warnings and errors encountered during schema
 /// validation</param>
 /// <param name="addSchemaInfo">If enabled the <see cref="XAttribute"/> is augmented with PSVI
 /// in the form of <see cref="IXmlSchemaInfo"/> annotations, default attributes and
 /// default element values</param>
 public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler?validationEventHandler, bool addSchemaInfo)
 {
     if (source == null)
     {
         throw new ArgumentNullException(nameof(source));
     }
     if (partialValidationType == null)
     {
         throw new ArgumentNullException(nameof(partialValidationType));
     }
     if (schemas == null)
     {
         throw new ArgumentNullException(nameof(schemas));
     }
     new XNodeValidator(schemas, validationEventHandler).Validate(source, partialValidationType, addSchemaInfo);
 }
        /// <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));
        }
示例#48
0
 /// <summary>
 /// Validate a <see cref="XDocument"/>
 /// </summary>
 /// <param name="source">Extension point</param>
 /// <param name="schemas">The <see cref="XmlSchemaSet"/> used for validation</param>
 /// <param name="validationEventHandler">The <see cref="ValidationEventHandler"/>
 /// that receives schema validation warnings and errors encountered during schema
 /// validation</param>
 public static void Validate(this XDocument source, XmlSchemaSet schemas, ValidationEventHandler?validationEventHandler)
 {
     source.Validate(schemas, validationEventHandler, false);
 }
示例#49
0
 private static System.Xml.XmlQualifiedName GetSchema(System.Xml.Schema.XmlSchemaSet xs)
 {
     xs.ResolveQuerySchema();
     return(new System.Xml.XmlQualifiedName("RecordDescriptor", Namespaces.Query));
 }
示例#50
0
 internal XmlSchemaCollection(XmlSchemaSet schemaSet)
 {
     this.schemaSet = schemaSet;
 }
示例#51
0
 public static void Validate(this XDocument document, XmlSchemaSet schemas, ValidationEventHandler handler, bool addSchemaInfo)
 {
     throw new NotImplementedException();
 }
示例#52
0
 public static System.Xml.XmlQualifiedName ExportSchema(System.Xml.Schema.XmlSchemaSet schemas)
 {
     System.Runtime.Serialization.XmlSerializableServices.AddDefaultSchema(schemas, typeName);
     return(typeName);
 }
 internal XmlValidator(XmlSchemaSet xmlSchemaSet)
 {
     this.xmlSchemaSet = xmlSchemaSet;
 }
示例#54
0
        internal void CopyFromCompiledSet(XmlSchemaSet otherSet)
        {
            SortedList sortedSchemas = otherSet.SortedSchemas;
            bool       flag          = this.schemas.Count == 0;
            ArrayList  list2         = new ArrayList();
            SchemaInfo info          = new SchemaInfo();

            for (int i = 0; i < sortedSchemas.Count; i++)
            {
                XmlSchema byIndex = (XmlSchema)sortedSchemas.GetByIndex(i);
                Uri       baseUri = byIndex.BaseUri;
                if (this.schemas.ContainsKey(byIndex.SchemaId) || (((baseUri != null) && (baseUri.OriginalString.Length != 0)) && (this.schemaLocations[baseUri] != null)))
                {
                    list2.Add(byIndex);
                }
                else
                {
                    this.schemas.Add(byIndex.SchemaId, byIndex);
                    if ((baseUri != null) && (baseUri.OriginalString.Length != 0))
                    {
                        this.schemaLocations.Add(baseUri, byIndex);
                    }
                    string targetNamespace = this.GetTargetNamespace(byIndex);
                    if (this.targetNamespaces[targetNamespace] == null)
                    {
                        this.targetNamespaces.Add(targetNamespace, targetNamespace);
                    }
                }
            }
            this.VerifyTables();
            foreach (XmlSchemaElement element in otherSet.GlobalElements.Values)
            {
                if (!this.AddToTable(this.elements, element.QualifiedName, element))
                {
                    goto Label_026E;
                }
            }
            foreach (XmlSchemaAttribute attribute in otherSet.GlobalAttributes.Values)
            {
                if (!this.AddToTable(this.attributes, attribute.QualifiedName, attribute))
                {
                    goto Label_026E;
                }
            }
            foreach (XmlSchemaType type in otherSet.GlobalTypes.Values)
            {
                if (!this.AddToTable(this.schemaTypes, type.QualifiedName, type))
                {
                    goto Label_026E;
                }
            }
            this.ProcessNewSubstitutionGroups(otherSet.SubstitutionGroups, false);
            info.Add(this.cachedCompiledInfo, this.eventHandler);
            info.Add(otherSet.CompiledInfo, this.eventHandler);
            this.cachedCompiledInfo = info;
            if (flag)
            {
                this.isCompiled = true;
                this.compileAll = false;
            }
            return;

Label_026E:
            foreach (XmlSchema schema2 in sortedSchemas.Values)
            {
                if (!list2.Contains(schema2))
                {
                    this.Remove(schema2, false);
                }
            }
            foreach (XmlSchemaElement element2 in otherSet.GlobalElements.Values)
            {
                if (!list2.Contains((XmlSchema)element2.Parent))
                {
                    this.elements.Remove(element2.QualifiedName);
                }
            }
            foreach (XmlSchemaAttribute attribute2 in otherSet.GlobalAttributes.Values)
            {
                if (!list2.Contains((XmlSchema)attribute2.Parent))
                {
                    this.attributes.Remove(attribute2.QualifiedName);
                }
            }
            foreach (XmlSchemaType type2 in otherSet.GlobalTypes.Values)
            {
                if (!list2.Contains((XmlSchema)type2.Parent))
                {
                    this.schemaTypes.Remove(type2.QualifiedName);
                }
            }
        }
示例#55
0
        /// <summary>
        /// Validate a <see cref="XAttribute"/>
        /// </summary>
        /// <param name="source">Extension point</param>
        /// <param name="partialValidationType">An <see cref="XmlSchemaAttribute"/> or
        /// <see cref="XmlSchemaType"/> object used to initialize the partial validation
        /// context</param>
        /// <param name="schemas">The <see cref="XmlSchemaSet"/> used for validation</param>
        /// <param name="validationEventHandler">The <see cref="ValidationEventHandler"/> that
        /// receives schema validation warnings and errors encountered during schema
        /// validation</param>
        /// <param name="addSchemaInfo">If enabled the <see cref="XAttribute"/> is augmented with PSVI
        /// in the form of <see cref="IXmlSchemaInfo"/> annotations, default attributes and
        /// default element values</param>
        public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler?validationEventHandler, bool addSchemaInfo)
        {
            ArgumentNullException.ThrowIfNull(source);
            ArgumentNullException.ThrowIfNull(partialValidationType);
            ArgumentNullException.ThrowIfNull(schemas);

            new XNodeValidator(schemas, validationEventHandler).Validate(source, partialValidationType, addSchemaInfo);
        }
示例#56
0
        public void Add(XmlSchemaSet schemas)
        {
            if (schemas == null)
            {
                throw new ArgumentNullException("schemas");
            }
            if (this != schemas)
            {
                bool lockTaken = false;
                bool flag2     = false;
                try
                {
Label_0017:
                    Monitor.TryEnter(this.InternalSyncObject, ref lockTaken);
                    if (!lockTaken)
                    {
                        goto Label_0017;
                    }
                    Monitor.TryEnter(schemas.InternalSyncObject, ref flag2);
                    if (!flag2)
                    {
                        Monitor.Exit(this.InternalSyncObject);
                        lockTaken = false;
                        Thread.Yield();
                        goto Label_0017;
                    }
                    if (schemas.IsCompiled)
                    {
                        this.CopyFromCompiledSet(schemas);
                    }
                    else
                    {
                        bool   flag3 = false;
                        string ns    = null;
                        foreach (XmlSchema schema2 in schemas.SortedSchemas.Values)
                        {
                            ns = schema2.TargetNamespace;
                            if (ns == null)
                            {
                                ns = string.Empty;
                            }
                            if ((!this.schemas.ContainsKey(schema2.SchemaId) && (this.FindSchemaByNSAndUrl(schema2.BaseUri, ns, null) == null)) && (this.Add(schema2.TargetNamespace, schema2) == null))
                            {
                                flag3 = true;
                                break;
                            }
                        }
                        if (flag3)
                        {
                            foreach (XmlSchema schema3 in schemas.SortedSchemas.Values)
                            {
                                this.schemas.Remove(schema3.SchemaId);
                                this.schemaLocations.Remove(schema3.BaseUri);
                            }
                        }
                    }
                }
                finally
                {
                    if (lockTaken)
                    {
                        Monitor.Exit(this.InternalSyncObject);
                    }
                    if (flag2)
                    {
                        Monitor.Exit(schemas.InternalSyncObject);
                    }
                }
            }
        }
示例#57
0
 public static void Validate(this XAttribute attribute, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler handler)
 {
     throw new NotImplementedException();
 }
示例#58
0
        public bool SendFilledDocument(int compilationRequestId, string username, string service, string token, string dataStr)
        {
            XmlDocument data = new XmlDocument();

            data.LoadXml(dataStr);

            Storage.StorageManager     manager            = new Storage.StorageManager();
            Storage.CompilationRequest compilationRequest = manager.getEntityByID <Storage.CompilationRequest>(compilationRequestId);
            if (compilationRequest == null)
            {
                return(false);
            }
            Storage.Publication publication = compilationRequest.Publication;

            IComputableWorkflow cw;

            if (publication.isPublic)
            {
                //pubblico
                cw = (IComputableWorkflow)manager.getWorkflowByPublication(publication);
            }
            else
            {
                //privato
                if (token == null || !compilationRequest.token.Equals(token))
                {
                    return(false);
                }
                Storage.Contact contact = compilationRequest.Contact;
                if (username == null || service == null ||
                    !(contact.externalUserID.Equals(username) && (contact.Service.nameService.Equals(service))))
                {
                    return(false);
                }
                if (compilationRequest.compiled)
                {
                    return(false);
                }
                cw = (IComputableWorkflow)manager.getWorkflowByPublication(publication);
            }
            cw.setWFname(publication.namePublication);

            System.Xml.Schema.XmlSchemaSet schema = cw.GetCollectedDocumentSchemas();
            data.Schemas = schema;
            try
            {
                data.Validate(null);
            }
            catch (XmlSchemaValidationException)
            {
                return(false);
            }
            Storage.Result           res          = null;
            System.Xml.Linq.XElement dataXElement = Storage.StorageManager.xmlDocumentToXElement(data);
            res = (Storage.Result)manager.addResult(compilationRequest.compilReqID, dataXElement);
            if (res == null)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
示例#59
0
        public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, bool addSchemaInfo)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (schemas == null)
            {
                throw new ArgumentNullException("schemas");
            }
            var nsmgr = new XmlNamespaceManager(new NameTable());
            var v     = new XmlSchemaValidator(nsmgr.NameTable, schemas, nsmgr, XmlSchemaValidationFlags.None);

            if (validationEventHandler != null)
            {
                v.ValidationEventHandler += validationEventHandler;
            }
            if (partialValidationType != null)
            {
                v.Initialize(partialValidationType);
            }
            else
            {
                v.Initialize();
            }
            var xi = addSchemaInfo ? new XmlSchemaInfo() : null;

            v.ValidateAttribute(source.Name.LocalName, source.Name.NamespaceName, source.Value, xi);
        }
示例#60
0
 public static void Validate(this XElement element, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler handler, bool addSchemaInfo)
 {
     throw new NotImplementedException();
 }