// .NET C# cannot have types with same name in the Codenamespace. If that happens a digit is appended to the typename.
        // Eg. CoreComponents and UnqualifiedDataTypes both have "IdentifierType", one gets named "IdentifierType1" :-(
        // Solution: Prepend types in CoreComponents with "cctscct" and modify references in UnqualifiedComponents
        public static void ResolveTypeNameClashesByRenaming(XmlSchemaSet schemaSet)
        {
            string ccts_cctPrefix = "cctscct";
            XmlSchema coreCompSchema = schemaSet.Schemas(Constants.CoreComponentTypeSchemaModuleTargetNamespace).OfType<XmlSchema>().Single();
            XmlSchema unqualSchema = schemaSet.Schemas(Constants.UnqualifiedDataTypesTargetNamespace).OfType<XmlSchema>().Single();

            foreach (var complexType in coreCompSchema.Items.OfType<XmlSchemaComplexType>())
            {
                complexType.Name = ccts_cctPrefix + complexType.Name;
                complexType.IsAbstract = true; // Make it abstract as well. Ain't gonna use the base, only the one derived from this type.
            }

            foreach (var complexType in unqualSchema.Items.OfType<XmlSchemaComplexType>()
                            .Where(t => t.BaseXmlSchemaType.QualifiedName.Namespace.Equals(Constants.CoreComponentTypeSchemaModuleTargetNamespace)))
            {
                var name = new XmlQualifiedName(ccts_cctPrefix + complexType.BaseXmlSchemaType.QualifiedName.Name, complexType.BaseXmlSchemaType.QualifiedName.Namespace);
                var content = complexType.ContentModel as XmlSchemaSimpleContent;
                if (content.Content is XmlSchemaSimpleContentRestriction)
                {
                    (content.Content as XmlSchemaSimpleContentRestriction).BaseTypeName = name;
                }
                else if (content.Content is XmlSchemaSimpleContentExtension)
                {
                    (content.Content as XmlSchemaSimpleContentExtension).BaseTypeName = name;
                }
            }
            schemaSet.Reprocess(coreCompSchema);
            schemaSet.Reprocess(unqualSchema);
        }
Пример #2
0
 internal static void EnumerateDocumentedItems(XmlSchemaSet xmlSchemaSet, Dictionary<string, string> documentedItems)
 {
     foreach (XmlSchema schema in xmlSchemaSet.Schemas())
     {
         EnumerateDocumentedItems(schema.Items, documentedItems);
     }
 }
Пример #3
0
        private static bool Validate(String filename, XmlSchemaSet schemaSet)
        {
            Console.WriteLine("Validating XML file {0}...", filename.ToString());

            XmlSchema compiledSchema = null;

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

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add(compiledSchema);
            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
            settings.ValidationType = ValidationType.Schema;

            success = true;

            //Create the schema validating reader.
            XmlReader vreader = XmlReader.Create(filename, settings);

            while (vreader.Read()) { }

            //Close the reader.
            vreader.Close();
            return success;
        }
Пример #4
0
        protected override object CoreGetSourceObject(string sourceFilePath, IDictionary<string, IList<string>> properties)
        {
            XmlSchemaSet xmlSchemaSet;
            XmlSchema xmlSchema;
            ObjectConstruct objectConstruct00;

            if ((object)sourceFilePath == null)
                throw new ArgumentNullException("sourceFilePath");

            if ((object)properties == null)
                throw new ArgumentNullException("properties");

            if (DataType.IsWhiteSpace(sourceFilePath))
                throw new ArgumentOutOfRangeException("sourceFilePath");

            sourceFilePath = Path.GetFullPath(sourceFilePath);

            objectConstruct00 = new ObjectConstruct();

            using (Stream stream = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                xmlSchema = XmlSchema.Read(stream, ValidationCallback);

            xmlSchemaSet = new XmlSchemaSet();
            xmlSchemaSet.Add(xmlSchema);
            xmlSchemaSet.Compile();

            xmlSchema = xmlSchemaSet.Schemas().Cast<XmlSchema>().ToList()[0];

            EnumSchema(objectConstruct00, xmlSchema.Items);

            return objectConstruct00;
        }
        private void AddImportedSchemas(XmlSchema schema, XmlSchemaSet schemaSet, List<XmlSchema> importsList)
        {
            ModuleProc PROC = new ModuleProc(this.DYN_MODULE_NAME, "AddImportedSchemas");

            try
            {
                foreach (XmlSchemaImport import in schema.Includes)
                {
                    ICollection realSchemas = schemaSet.Schemas(import.Namespace);

                    foreach (XmlSchema ixsd in realSchemas)
                    {
                        if (!importsList.Contains(ixsd))
                        {
                            importsList.Add(ixsd);
                            AddImportedSchemas(ixsd, schemaSet, importsList);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Exception(PROC, ex);
            }
        }
Пример #6
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");
		}
Пример #7
0
        public bool ProcessSchema(string filePath)
        {
            if(String.IsNullOrWhiteSpace(filePath))
            {
                return false;
            }

            var schemaSet = new XmlSchemaSet();
            schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
            schemaSet.Add("urn:newrelic-config", filePath);
            schemaSet.Compile();

            XmlSchema schema = null;
            foreach (XmlSchema TempSchema in schemaSet.Schemas())
            {
                schema = TempSchema;
            }

            var configurationElement = schema.Items[0] as XmlSchemaElement;
            if (configurationElement != null)
            {
                ProcessElement(configurationElement, null);
                ConfigurationFile.Xsd.RootElement = true;
            }

            return true;
        }
 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;
 }
Пример #9
0
        /// <summary>
        /// Формируем XmlSchema для правильного отображения индикаторов группы в VGridControl
        /// </summary>
        /// <param name="elmList">названия всех по</param>
        /// <returns>Возвращаем поток в который записана XmlSchema</returns>
        public static MemoryStream CreateXmlSchemaForIndicatorsInGroup(List<string[]> elmList)
        {
            var xmlSchema = new XmlSchema();

            // <xs:element name="root">
            var elementRoot = new XmlSchemaElement();
            xmlSchema.Items.Add(elementRoot);
            elementRoot.Name = "root";
            // <xs:complexType>
            var complexType = new XmlSchemaComplexType();
            elementRoot.SchemaType = complexType;

            // <xs:choice minOccurs="0" maxOccurs="unbounded">
            var choice = new XmlSchemaChoice();
            complexType.Particle = choice;
            choice.MinOccurs = 0;
            choice.MaxOccursString = "unbounded";

            // <xs:element name="record">
            var elementRecord = new XmlSchemaElement();
            choice.Items.Add(elementRecord);
            elementRecord.Name = "record";
            // <xs:complexType>
            var complexType2 = new XmlSchemaComplexType();
            elementRecord.SchemaType = complexType2;

            // <xs:sequence>
            var sequence = new XmlSchemaSequence();
            complexType2.Particle = sequence;

            foreach (var el in elmList)
            {
                var element = new XmlSchemaElement();
                sequence.Items.Add(element);
                element.Name = el[0];
                element.SchemaTypeName = new XmlQualifiedName(el[1], "http://www.w3.org/2001/XMLSchema");
            }

            var schemaSet = new XmlSchemaSet();
            schemaSet.Add(xmlSchema);
            schemaSet.Compile();

            XmlSchema compiledSchema = null;

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

            var nsmgr = new XmlNamespaceManager(new NameTable());
            nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");

            var ms = new MemoryStream();
            if (compiledSchema != null) compiledSchema.Write(ms, nsmgr);
            ms.Position = 0;

            return ms;
        }
Пример #10
0
        public static XmlQualifiedName EnsureProbeMatchSchema(DiscoveryVersion discoveryVersion, XmlSchemaSet schemaSet)
        {
            Fx.Assert(schemaSet != null, "The schemaSet must be non null.");
            Fx.Assert(discoveryVersion != null, "The discoveryVersion must be non null.");

            // ensure that EPR is added to the schema.
            if (discoveryVersion == DiscoveryVersion.WSDiscoveryApril2005 || discoveryVersion == DiscoveryVersion.WSDiscoveryCD1)
            {
                EndpointAddressAugust2004.GetSchema(schemaSet);
            }
            else if (discoveryVersion == DiscoveryVersion.WSDiscovery11)
            {
                EndpointAddress10.GetSchema(schemaSet);
            }
            else
            {
                Fx.Assert("The discoveryVersion is not supported.");
            }

            // do not add/find Probe related schema items
            SchemaTypes typesFound = SchemaTypes.ProbeType | SchemaTypes.ResolveType;
            SchemaElements elementsFound = SchemaElements.None;         

            XmlSchema discoverySchema = null;
            ICollection discoverySchemas = schemaSet.Schemas(discoveryVersion.Namespace);
            if ((discoverySchemas == null) || (discoverySchemas.Count == 0))
            {
                discoverySchema = CreateSchema(discoveryVersion);
                AddImport(discoverySchema, discoveryVersion.Implementation.WsaNamespace);
                schemaSet.Add(discoverySchema);
            }
            else
            {                
                foreach (XmlSchema schema in discoverySchemas)
                {
                    discoverySchema = schema;
                    if (schema.SchemaTypes.Contains(discoveryVersion.Implementation.QualifiedNames.ProbeMatchType))
                    {
                        typesFound |= SchemaTypes.ProbeMatchType;
                        break;
                    }

                    LocateSchemaTypes(discoveryVersion, schema, ref typesFound);
                    LocateSchemaElements(discoveryVersion, schema, ref elementsFound);
                }
            }

            if ((typesFound & SchemaTypes.ProbeMatchType) != SchemaTypes.ProbeMatchType)
            {
                AddSchemaTypes(discoveryVersion, typesFound, discoverySchema);
                AddElements(discoveryVersion, elementsFound, discoverySchema);
                schemaSet.Reprocess(discoverySchema);
            }

            return discoveryVersion.Implementation.QualifiedNames.ProbeMatchType;
        }
Пример #11
0
        public void v2()
        {
            XmlSchemaSet sc = new XmlSchemaSet();

            //remove after compile
            XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
            sc.Compile();
            sc.RemoveRecursive(Schema1);
            CError.Compare(sc.Count, 0, "Count");
            ICollection Col = sc.Schemas();
            CError.Compare(Col.Count, 0, "ICollection.Count");

            //remove before compile
            Schema1 = sc.Add(null, TestData._XsdAuthor);
            sc.RemoveRecursive(Schema1);
            CError.Compare(sc.Count, 0, "Count");
            Col = sc.Schemas();
            CError.Compare(Col.Count, 0, "ICollection.Count"); return;
        }
Пример #12
0
		private XmlSchemaSet NewXmlSchemaSet ()
		{
			xss = new XmlSchemaSet ();
			foreach (MetadataSection section in metadata.MetadataSections)
				if (section.Metadata is XmlSchema)
					xss.Add (section.Metadata as XmlSchema);

			Assert.AreEqual (3, xss.Schemas ().Count, "#1");
			return xss;
		}
Пример #13
0
        public void v1()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            ICollection Col = sc.Schemas();

            CError.Compare(Col.Count, 0, "Count");
            CError.Compare(Col.IsSynchronized, false, "IsSynchronized");

            return;
        }
Пример #14
0
        public void v3()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            XmlSchema Schema1 = sc.Add(null, TestData._XsdNoNs);

            ICollection Col = sc.Schemas(null);

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

            return;
        }
Пример #15
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;
        }
Пример #16
0
 private void ShowHierarchy(XmlSchemaSet schemaSet, TextWriter writer)
 {
     var schema = schemaSet.Schemas(Constants.InvoiceTargetNamespace).Cast<XmlSchema>().Single();
     prefixLookup = schema.Namespaces.ToArray().Where(v => !string.IsNullOrEmpty(v.Name)).ToDictionary(k => k.Namespace, v => v.Name);
     PrintSchemaDetail(schema, writer);
     var prefixes = schemaSet.GetNamespacePrefixes();
     Console.WriteLine();
     foreach (var prefix in prefixes)
     {
         writer.WriteLine($"{prefix.Name,9}: -> \"{prefix.Namespace}\"");
     }
 }
Пример #17
0
        /// <summary>
        ///
        /// </summary>
        /// <remarks></remarks>
        /// <seealso cref=""/>        
        public void Read()
        {
            string path = Path.Combine(AppConfiguration.GetModuleWorkspacePath("DCM"), "Metadata", "schema.xsd");
            //string path = Path.Combine(AppConfiguration.GetModuleWorkspacePath("DCM"), "Metadata", "ABCD", "ABCD_2.06.XSD");
            //string path = Path.Combine(AppConfiguration.GetModuleWorkspacePath("DCM"), "Metadata", "eml", "eml.xsd");

            XmlTextReader xsd_file = new XmlTextReader(path);
            XmlSchema schema_file = new XmlSchema();
            schema_file = XmlSchema.Read(xsd_file, ValidationCallback);

            // Add the customer schema to a new XmlSchemaSet and compile it.
            // Any schema validation warnings and errors encountered reading or
            // compiling the schema are handled by the ValidationEventHandler delegate.
            XmlSchemaSet schemaSet = new XmlSchemaSet();
            schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
            schemaSet.Add(schema_file);
            schemaSet.Compile();

            // Retrieve the compiled XmlSchema object from the XmlSchemaSet
            // by iterating over the Schemas property.
            XmlSchema customerSchema = null;
            foreach (XmlSchema schema in schemaSet.Schemas())
            {
                customerSchema = schema;
            }

            // Iterate over each XmlSchemaElement in the Values collection
            // of the Elements property.
            foreach (XmlSchemaElement element in customerSchema.Elements.Values)
            {
                readXmlSchemaElement(element, null);
            }
            Debug.WriteLine("-------------------------------------------------");
            Debug.WriteLine("-------------metadataAttributeNames--------------");
            Debug.WriteLine("-------------------------------------------------");
            if (metadataAttributeNames.Count > 0)
            {
                metadataAttributeNames.ForEach(p => Debug.WriteLine(p));
            }

            Debug.WriteLine("-------------metadataPackageNames--------------");
            Debug.WriteLine("-------------------------------------------------");
            if (metadataPackageNames.Count > 0)
            {
                metadataPackageNames.ForEach(p => Debug.WriteLine(p));
            }
            Debug.WriteLine("-------------------------------------------------");
            Debug.WriteLine("Packages :" + packages);
            Debug.WriteLine("PackagesAsParents :" + metadataPackageNames.Count);
            Debug.WriteLine("Attributes :" + metadataAttributeNames.Count);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NativeEventTypeDefinition"/> class.
        /// </summary>
        /// <param name="schemaTypeName">Name of the schema type.</param>
        /// <param name="schemaSet">The schema set.</param>
        public NativeTypeDefinition(XmlQualifiedName schemaTypeName, XmlSchemaSet schemaSet)
        {
            SchemaTypeName = schemaTypeName;

            var schemaList = new List<string>();
            foreach(XmlSchema schema in schemaSet.Schemas())
            {
                var stringWriter = new StringWriter();
                schema.Write(stringWriter);
                schemaList.Add(stringWriter.ToString());
            }

            Schemas = schemaList.ToArray();
        }
Пример #19
0
 //static readonly Regex StripXmlDeclarationRegex = new Regex(@"/\<?xml.+?\>/g", RegexOptions.Compiled);
 //public static string StripXmlDeclaration(string xsd)
 //{
 //    return StripXmlDeclarationRegex.Replace(xsd, "");
 //}
 public static string GetXsd(XmlSchemaSet schemaSet)
 {
     var sb = new StringBuilder();
     using (var sw = new StringWriter(sb))
     {
         foreach (XmlSchema schema in schemaSet.Schemas())
         {
             if (schema.SchemaTypes.Count == 0) continue; //remove blank schemas
             schema.Write(sw);
         }
     }
     sb = sb.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", ""); //remove xml declaration
     return sb.ToString().Trim();
 }
Пример #20
0
        internal static XmlSchema GetSchema(string ns, XmlSchemaSet schemas)
        {
            if (ns == null) { ns = String.Empty; }

            ICollection currentSchemas = schemas.Schemas();
            foreach (XmlSchema schema in currentSchemas)
            {
                if ((schema.TargetNamespace == null && ns.Length == 0) || ns.Equals(schema.TargetNamespace))
                {
                    return schema;
                }
            }
            return CreateSchema(ns, schemas);
        }
Пример #21
0
        public void v2()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            sc.XmlResolver = new XmlUrlResolver();
            XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
            sc.Compile();
            sc.Remove(Schema1);

            CError.Compare(sc.Count, 0, "Count");
            ICollection Col = sc.Schemas();
            CError.Compare(Col.Count, 0, "ICollection.Count");

            return;
        }
    public XmlCompletionDataProvider(XmlSchemaSet schemaSet, string defaultNamespace
      , string prefix = null
      , Func<string> namespaceWriter = null
      , Func<XmlSchemaElement, bool> filter = null)
    {
      var def = schemaSet.Schemas(defaultNamespace).OfType<XmlSchema>().First();

      this.schemaCompletionDataItems = new XmlSchemaCompletionDataCollection();
      foreach (var schema in schemaSet.Schemas().OfType<XmlSchema>().Where(s => s != def))
      {
        this.schemaCompletionDataItems.Add(new XmlSchemaCompletionData(schema)
        {
          ElementFilter = filter
        });
      }
      this.defaultSchemaCompletionData = new XmlSchemaCompletionData(def)
      {
        RelatedSchemas = this.schemaCompletionDataItems,
        NamespaceWriter = namespaceWriter,
        ElementFilter = filter
      };
      this.defaultNamespacePrefix = prefix ?? string.Empty;
    }
 private void AddImportedSchemas(XmlSchema schema, XmlSchemaSet schemaSet, List<XmlSchema> importsList)
 {
     foreach (XmlSchemaImport import in schema.Includes)
     {
         ICollection realSchemas = schemaSet.Schemas(import.Namespace);
         foreach (XmlSchema ixsd in realSchemas)
         {
             if (!importsList.Contains(ixsd))
             {
                 importsList.Add(ixsd);
                 AddImportedSchemas(ixsd, schemaSet, importsList);
             }
         }
     }
 }
Пример #24
0
 //[Variation(Desc = "v2 - ICollection.CopyTo with array = null")]
 public void v2()
 {
     try
     {
         XmlSchemaSet sc = new XmlSchemaSet();
         sc.Add("xsdauthor", TestData._XsdAuthor);
         ICollection Col = sc.Schemas();
         Col.CopyTo(null, 0);
     }
     catch (ArgumentNullException)
     {
         // GLOBALIZATION
         return;
     }
     Assert.True(false);
 }
Пример #25
0
        // http://stackoverflow.com/questions/22835730/create-xsd-from-xml-in-code
        // https://msdn.microsoft.com/en-us/library/xz2797k1%28v=vs.110%29.aspx
        private static void GenerateXsdFromXml(string xmlPath, string xsdPath)
        {
            var reader = XmlReader.Create(xmlPath);
            var inference = new XmlSchemaInference();
            var schemaSet = new XmlSchemaSet();
            schemaSet = inference.InferSchema(reader);
            reader.Dispose();

            using (var writer = XmlWriter.Create(xsdPath))
            {
                foreach (XmlSchema schema in schemaSet.Schemas())
                {
                    schema.Write(writer);
                }
            }
        }
Пример #26
0
        public void v3()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            sc.XmlResolver = new XmlUrlResolver();
            XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
            XmlSchema Schema2 = sc.Add("test", TestData._XsdNoNs);
            sc.Compile();
            sc.Remove(Schema1);

            CError.Compare(sc.Count, 1, "Count");
            ICollection Col = sc.Schemas();
            CError.Compare(Col.Count, 1, "ICollection.Count");
            CError.Compare(sc.Contains("test"), true, "Contains");

            return;
        }
Пример #27
0
        public static void AnalyseSchema(XmlSchemaSet set)
        {
            // Retrieve the compiled XmlSchema object from the XmlSchemaSet
            // by iterating over the Schemas property.
            XmlSchema customerSchema = null;
            foreach (XmlSchema schema in set.Schemas())
            {
                customerSchema = schema;
            }

            // Iterate over each XmlSchemaElement in the Values collection
            // of the Elements property.
            foreach (XmlSchemaElement element in customerSchema.Elements.Values)
            {
                RecursiveElementAnalyser(" ", element);
            }

        }
Пример #28
0
 //[Variation(Desc = "v3 - ICollection.CopyTo with array smaller than source", Priority = 0)]
 public void v3()
 {
     XmlSchemaSet sc = new XmlSchemaSet();
     try
     {
         sc.Add("xsdauthor", TestData._XsdAuthor);
         sc.Add(null, TestData._XsdNoNs);
         ICollection Col = sc.Schemas();
         XmlSchema[] array = new XmlSchema[1];
         Col.CopyTo(array, 0);
     }
     catch (ArgumentException)
     {
         // GLOBALIZATION
         return;
     }
     Assert.True(false);
 }
Пример #29
0
        static internal XmlSchema GetSchema(string ns, XmlSchemaSet schemaSet)
        {
            if (ns == null) { ns = String.Empty; }

            ICollection schemas = schemaSet.Schemas();
            foreach (XmlSchema existingSchema in schemas)
            {
                if ((existingSchema.TargetNamespace == null && ns.Length == 0) || ns.Equals(existingSchema.TargetNamespace))
                    return existingSchema;
            }

            XmlSchema schema = new XmlSchema();
            schema.ElementFormDefault = XmlSchemaForm.Qualified;
            if (ns.Length > 0)
                schema.TargetNamespace = ns;
            schemaSet.Add(schema);
            return schema;
        }
Пример #30
0
 internal static XmlSchema GetSchemaWithType(SchemaObjectDictionary schemaInfo, XmlSchemaSet schemas, XmlQualifiedName typeName)
 {
     SchemaObjectInfo schemaObjectInfo;
     if (schemaInfo.TryGetValue(typeName, out schemaObjectInfo))
     {
         if (schemaObjectInfo.schema != null)
             return schemaObjectInfo.schema;
     }
     ICollection currentSchemas = schemas.Schemas();
     string ns = typeName.Namespace;
     foreach (XmlSchema schema in currentSchemas)
     {
         if (NamespacesEqual(ns, schema.TargetNamespace))
         {
             return schema;
         }
     }
     return null;
 }
Пример #31
0
        void ProcessExternal(ValidationEventHandler handler, List <CompiledSchemaMemo> handledUris, XmlResolver resolver, XmlSchemaExternal ext, XmlSchemaSet col)
        {
            if (ext == null)
            {
                error(handler, "Object is not valid in Includes Property of XmlSchema");
                return;
            }

            // The only case we want to handle where the SchemaLocation is null is if the external is an import.
            XmlSchemaImport import = ext as XmlSchemaImport;

            if (ext.SchemaLocation == null && import == null)
            {
                return;
            }

            XmlSchema includedSchema = null;

            if (ext.SchemaLocation != null)
            {
                Stream stream = null;
                string url    = null;
                if (resolver != null)
                {
                    url = GetResolvedUri(resolver, ext.SchemaLocation);
                    foreach (var i in handledUris)
                    {
                        if (i.SourceUri.Equals(url))
                        {
                            // This schema is already handled, so simply skip (otherwise, duplicate definition errrors occur.
                            return;
                        }
                    }
                    handledUris.Add(new CompiledSchemaMemo()
                    {
                        SourceUri = 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 = ext 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.");
                        }
                    }
                }

                if (stream == null)
                {
                    // It is missing schema components.
                    missedSubComponents = true;
                    return;
                }
                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*.
            if (import != null)
            {
                if (ext.Schema == null && ext.SchemaLocation == null)
                {
                    // if a schema location wasn't specified, check the other schemas we have to see if one of those
                    // is a match.
                    foreach (XmlSchema schema in col.Schemas())
                    {
                        if (schema.TargetNamespace == import.Namespace)
                        {
                            includedSchema         = schema;
                            includedSchema.schemas = schemas;
                            includedSchema.SetParent();
                            ext.Schema = includedSchema;
                            break;
                        }
                    }
                    // handle case where target namespace doesn't exist in schema collection - i.e can't find it at all
                    if (includedSchema == null)
                    {
                        return;
                    }
                }
                else if (includedSchema != null)
                {
                    if (TargetNamespace == includedSchema.TargetNamespace)
                    {
                        error(handler, "Target namespace must be different from that of included schema.");
                        return;
                    }
                    else if (includedSchema.TargetNamespace != import.Namespace)
                    {
                        error(handler, "Attribute namespace and its importing schema's target namespace must be the same.");
                        return;
                    }
                }
            }
            else if (includedSchema != null)
            {
                if (TargetNamespace == null &&
                    includedSchema.TargetNamespace != null)
                {
                    includedSchema.error(handler, String.Format("On {0} element, targetNamespace is required to include a schema which has its own target namespace", ext.GetType().Name));
                    return;
                }
                else if (TargetNamespace != null &&
                         includedSchema.TargetNamespace == null)
                {
                    includedSchema.TargetNamespace = TargetNamespace;
                }
            }

            // Do not compile included schema here.
            if (includedSchema != null)
            {
                AddExternalComponentsTo(includedSchema, compilationItems, handler, handledUris, resolver, col);
            }
        }
Пример #32
0
        /// <summary>
        /// Load the schema from an XSD into this XmlSchema object
        /// </summary>
        /// <param name="SchemaLocation">The location of the schema to import</param>
        public void Load()
        {
            // Load the schema into the schema set
            try
            {
                ss.Compile();

                // Iterate through types and create them
                int i = 0;
                namespaces.Clear(); // clear namespaces

                // Determine target namespace
                string targetNs = "";
                foreach (System.Xml.Schema.XmlSchema s in ss.Schemas())
                {
                    if (targetNs != s.TargetNamespace && s.TargetNamespace != null)
                    {
                        targetNs = s.TargetNamespace;
                        break;
                    }
                }

                targetNamespace = targetNs;

                foreach (Object o in ss.GlobalTypes.Values)
                {
                    if (o is System.Xml.Schema.XmlSchemaComplexType)
                    {
                        RegisterComplexType((System.Xml.Schema.XmlSchemaComplexType)o);
                    }
                    else if (o is System.Xml.Schema.XmlSchemaSimpleType)
                    {
                        RegisterSimpleType((System.Xml.Schema.XmlSchemaSimpleType)o);
                    }

                    // Alert for update
                    if (Loading != null)
                    {
                        Loading(this, ((float)i / ((float)ss.GlobalTypes.Count * 2)));
                    }
                    i++;
                }

                // Iterate through root elements and create them
                foreach (Object o in ss.GlobalElements.Values)
                {
                    if (o is System.Xml.Schema.XmlSchemaElement)
                    {
                        RegisterElement((System.Xml.Schema.XmlSchemaElement)o);
                    }
                }

                // Iterate through types and compile them
                for (int p = 0; p < Types.Count; p++)
                {
                    XmlSchemaType t = Types[p];

                    if (t is XmlSchemaComplexType)
                    {
                        (t as XmlSchemaComplexType).Compile();
                    }

                    // Alert for update
                    if (Loading != null)
                    {
                        Loading(this, ((float)i / ((float)Types.Count * 2)));
                    }
                    i++;
                }

                types.Sort(new XmlSchemaComparison());
            }
            catch (Exception e)
            {
                throw new System.Xml.Schema.XmlSchemaException(String.Format("Can not compile the schemas - {0}", e.Message), e);
            }
        }