Inheritance: XmlSchemaObject
示例#1
0
        protected void ExportStreamBody(Message message, string wrapperName, string wrapperNs, string partName, string partNs, bool isRpc, bool skipSchemaExport)
        {
            XmlSchemaSet generatedXmlSchemas = this.exporter.GeneratedXmlSchemas;

            System.Xml.Schema.XmlSchema schema = System.ServiceModel.Description.SchemaHelper.GetSchema(DataContractSerializerMessageContractImporter.StreamBodyTypeName.Namespace, generatedXmlSchemas);
            if (!schema.SchemaTypes.Contains(DataContractSerializerMessageContractImporter.StreamBodyTypeName))
            {
                XmlSchemaSimpleType type = new XmlSchemaSimpleType {
                    Name = DataContractSerializerMessageContractImporter.StreamBodyTypeName.Name
                };
                XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction {
                    BaseTypeName = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Base64Binary).QualifiedName
                };
                type.Content = restriction;
                System.ServiceModel.Description.SchemaHelper.AddTypeToSchema(type, schema, generatedXmlSchemas);
            }
            XmlSchemaSequence wrapperSequence = null;

            if (!isRpc && (wrapperName != null))
            {
                wrapperSequence = this.ExportWrappedPart(message, wrapperName, wrapperNs, generatedXmlSchemas, skipSchemaExport);
            }
            MessagePartDescription part = new MessagePartDescription(partName, partNs);

            this.ExportMessagePart(message, part, DataContractSerializerMessageContractImporter.StreamBodyTypeName, null, false, false, skipSchemaExport, !isRpc, wrapperNs, wrapperSequence, generatedXmlSchemas);
        }
示例#2
0
 internal static void AddElementForm(XmlSchemaElement element, System.Xml.Schema.XmlSchema schema)
 {
     if (schema.ElementFormDefault != XmlSchemaForm.Qualified)
     {
         element.Form = XmlSchemaForm.Qualified;
     }
 }
示例#3
0
        private void ExportAnyMessage(Message message, MessagePartDescription part)
        {
            XmlSchemaSet generatedXmlSchemas = this.exporter.GeneratedXmlSchemas;

            System.Xml.Schema.XmlSchema schema = System.ServiceModel.Description.SchemaHelper.GetSchema(DataContractSerializerMessageContractImporter.GenericMessageTypeName.Namespace, generatedXmlSchemas);
            if (!schema.SchemaTypes.Contains(DataContractSerializerMessageContractImporter.GenericMessageTypeName))
            {
                XmlSchemaComplexType type = new XmlSchemaComplexType {
                    Name = DataContractSerializerMessageContractImporter.GenericMessageTypeName.Name
                };
                XmlSchemaSequence sequence = new XmlSchemaSequence();
                type.Particle = sequence;
                XmlSchemaAny item = new XmlSchemaAny {
                    MinOccurs = 0M,
                    MaxOccurs = 79228162514264337593543950335M,
                    Namespace = "##any"
                };
                sequence.Items.Add(item);
                System.ServiceModel.Description.SchemaHelper.AddTypeToSchema(type, schema, generatedXmlSchemas);
            }
            string      partName = string.IsNullOrEmpty(part.UniquePartName) ? part.Name : part.UniquePartName;
            MessagePart part2    = AddMessagePart(message, partName, XmlQualifiedName.Empty, DataContractSerializerMessageContractImporter.GenericMessageTypeName);

            part.UniquePartName = part2.Name;
        }
        public bool Execute(XmlSchema schema, string targetNamespace, bool loadExternals, XmlSchemaCollection xsc) {
            this.schema = schema;
            Xmlns = NameTable.Add("xmlns");

            Cleanup(schema);
            if (loadExternals && xmlResolver != null) {
                schemaLocations = new Hashtable(); //new Dictionary<Uri, Uri>();
                if (schema.BaseUri != null) {
                    schemaLocations.Add(schema.BaseUri, schema.BaseUri);
                }
                LoadExternals(schema, xsc);
            }
            ValidateIdAttribute(schema);
            Preprocess(schema, targetNamespace, Compositor.Root);
            if (!HasErrors) {
                schema.IsPreprocessed = true;
                for (int i = 0; i < schema.Includes.Count; ++i) {
                    XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
                    if (include.Schema != null) {
                        include.Schema.IsPreprocessed = true;
                    }
                }
            }
            return !HasErrors;
        }
 private void BuildRefNamespaces(XmlSchema schema)
 {
     this.referenceNamespaces.Clear();
     this.referenceNamespaces.Add("http://www.w3.org/2001/XMLSchema", "http://www.w3.org/2001/XMLSchema");
     for (int i = 0; i < schema.Includes.Count; i++)
     {
         XmlSchemaExternal external = (XmlSchemaExternal) schema.Includes[i];
         if (external is XmlSchemaImport)
         {
             XmlSchemaImport import = external as XmlSchemaImport;
             string key = import.Namespace;
             if (key == null)
             {
                 key = string.Empty;
             }
             if (this.referenceNamespaces[key] == null)
             {
                 this.referenceNamespaces.Add(key, key);
             }
         }
     }
     string targetNamespace = schema.TargetNamespace;
     if (targetNamespace == null)
     {
         targetNamespace = string.Empty;
     }
     if (this.referenceNamespaces[targetNamespace] == null)
     {
         this.referenceNamespaces.Add(targetNamespace, targetNamespace);
     }
 }
        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);
            }
        }
示例#7
0
 private Microsoft.Expression.DesignSurface.UserInterface.DataPane.XmlSchema GetXmlSchemaFromSchemaFile(Uri schemaFile, DocumentNode dataSource, out string errorMessage)
 {
     errorMessage = string.Empty;
     Microsoft.Expression.DesignSurface.UserInterface.DataPane.XmlSchema xmlSchema = (Microsoft.Expression.DesignSurface.UserInterface.DataPane.XmlSchema)null;
     try
     {
         bool isSchemaValid = true;
         using (XmlReader reader = XmlReader.Create(schemaFile.ToString()))
         {
             System.Xml.Schema.XmlSchema schema = System.Xml.Schema.XmlSchema.Read(reader, (ValidationEventHandler)((sender, e) => isSchemaValid = false));
             if (schema != null)
             {
                 if (isSchemaValid)
                 {
                     XmlSchemaSet schemaSet = new XmlSchemaSet();
                     schemaSet.Add(schema);
                     schemaSet.Compile();
                     xmlSchema = new Microsoft.Expression.DesignSurface.UserInterface.DataPane.XmlSchema(schemaSet, dataSource);
                 }
             }
         }
     }
     finally
     {
         if (xmlSchema == null)
         {
             errorMessage = StringTable.XmlDataSourceSchemaReadError;
         }
     }
     return(xmlSchema);
 }
        private void AddDocumentToSet(MetadataSet metadataSet, object document)
        {
            System.Web.Services.Description.ServiceDescription serviceDescription = document as System.Web.Services.Description.ServiceDescription;
            System.Xml.Schema.XmlSchema schema = document as System.Xml.Schema.XmlSchema;
            XmlElement policy = document as XmlElement;

            if (serviceDescription != null)
            {
                metadataSet.MetadataSections.Add(MetadataSection.CreateFromServiceDescription(serviceDescription));
            }
            else if (schema != null)
            {
                metadataSet.MetadataSections.Add(MetadataSection.CreateFromSchema(schema));
            }
            else if ((policy != null) && MetadataSection.IsPolicyElement(policy))
            {
                metadataSet.MetadataSections.Add(MetadataSection.CreateFromPolicy(policy, null));
            }
            else
            {
                MetadataSection item = new MetadataSection {
                    Metadata = document
                };
                metadataSet.MetadataSections.Add(item);
            }
        }
 private string GetXml(XmlSchema schema)
 {
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.LoadXml(SerializeObjectToXml(schema));
     return @"<?xml version=""1.0"" encoding=""utf-8""?>"
         + xmlDoc.DocumentElement.OuterXml;
 }
示例#10
0
        /// <summary>
        /// Check the contents of an XML file against a XSD stored in a Stream
        /// (the Stream may be stored as resource or may be stored somewhere else...)
        /// </summary>
        /// <param name="sXMLPath">PathFilename to XML file</param>
        /// <param name="streamXSD">Stream constructed from XSD (resource) file.</param>
        /// <param name="settings">Optional settings to determine level of detail to check</param>
        public void CheckXML_XSD(string sXMLPath,
                                 Stream streamXSD,
                                 XmlReaderSettings settings = null)
        {
            StreamReader strmrStreamReader = new StreamReader(streamXSD);

            System.Xml.Schema.XmlSchema xSchema = new System.Xml.Schema.XmlSchema();
            xSchema = XmlSchema.Read(strmrStreamReader, null);

            // Set the validation settings.
            if (settings == null)
            {
                settings = new XmlReaderSettings();
                settings.Schemas.Add(xSchema);
                settings.ValidationType   = ValidationType.Schema;
                settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
                settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
                settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
            }

            settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

            using (XmlReader reader = XmlReader.Create(sXMLPath, settings))
            {
                // XmlReader reader = XmlReader.Create("SampleXML/DBRestore.xml", settings);
                // Parse the file.
                while (reader.Read())
                {
                }
            }
        }
 internal SchemaObjectInfo(XmlSchemaType type, XmlSchemaElement element, XmlSchema schema, List<XmlSchemaType> knownTypes)
 {
     this.type = type;
     this.element = element;
     this.schema = schema;
     this.knownTypes = knownTypes;
 }
 internal static void AddElementForm(XmlSchemaElement element, XmlSchema schema)
 {
     if (schema.ElementFormDefault != XmlSchemaForm.Qualified)
     {
         element.Form = XmlSchemaForm.Qualified;
     }
 }
示例#13
0
		public void Bug360541 ()
		{
			XmlSchemaComplexType stype = GetStype ();
			
			XmlSchemaElement selem1 = new XmlSchemaElement ();
			selem1.Name = "schema";
			selem1.SchemaType = stype;

			XmlSchema schema = new XmlSchema ();
			schema.Items.Add (selem1);

			XmlSchemas xs = new XmlSchemas ();
			xs.Add (schema);

			xs.Find (XmlQualifiedName.Empty, typeof (XmlSchemaElement));

			selem1 = new XmlSchemaElement ();
			selem1.Name = "schema1";
			selem1.SchemaType = stype;

			schema = new XmlSchema ();
			schema.Items.Add (selem1);

			xs = new XmlSchemas ();
			xs.Add (schema);
			xs.Find (XmlQualifiedName.Empty, typeof (XmlSchemaElement));
		}
		public void TestAdd ()
		{
			XmlSchemaCollection col = new XmlSchemaCollection ();
			XmlSchema schema = new XmlSchema ();
			XmlSchemaElement elem = new XmlSchemaElement ();
			elem.Name = "foo";
			schema.Items.Add (elem);
			schema.TargetNamespace = "urn:foo";
			col.Add (schema);
			col.Add (schema);	// No problem !?

			XmlSchema schema2 = new XmlSchema ();
			schema2.Items.Add (elem);
			schema2.TargetNamespace = "urn:foo";
			col.Add (schema2);	// No problem !!

			schema.Compile (null);
			col.Add (schema);
			col.Add (schema);	// Still no problem !!!

			schema2.Compile (null);
			col.Add (schema2);

			schema = GetSchema ("Test/XmlFiles/xsd/3.xsd");
			schema.Compile (null);
			col.Add (schema);

			schema2 = GetSchema ("Test/XmlFiles/xsd/3.xsd");
			schema2.Compile (null);
			col.Add (schema2);
		}
示例#15
0
        /// <summary>Called when extension shall processs generated CodeDOM</summary>
        /// <param name="code">Object tree representing generated CodeDOM</param>
        /// <param name="schema">Input XML schema</param>
        /// <param name="provider">CodeDOM provider (the language)</param>
        /// <version version="1.5.3">Added documentation</version>
        /// <version version="1.5.3">Parameter <c>Provider</c> renamed to <c>provider</c></version>
        public void Process(CodeNamespace code, XmlSchema schema, CodeDomProvider provider)
        {
            // Copy as we will be adding types.
            CodeTypeDeclaration[] types =
                new CodeTypeDeclaration[code.Types.Count];
            code.Types.CopyTo(types, 0);

            foreach (CodeTypeDeclaration type in types) {
                if (type.IsClass || type.IsStruct) {
                    foreach (CodeTypeMember member in type.Members) {
                        if (member is CodeMemberField && ((CodeMemberField)member).Type.ArrayElementType != null) {
                            CodeMemberField field = (CodeMemberField)member;
                            // Change field type to collection.
                            field.Type = GetCollection(field.Type.ArrayElementType);
                            field.InitExpression = new CodeObjectCreateExpression(field.Type);
                            if (field.Name.EndsWith("Field"))
                                field.Comments.Add(new CodeCommentStatement(string.Format("<summary>Contains value of the <see cref='{0}'/> property</summary>", field.Name.Substring(0, field.Name.Length - "field".Length)), true));
                        } else if (member is CodeMemberProperty && ((CodeMemberProperty)member).Type.ArrayElementType != null) {
                            CodeMemberProperty Property = (CodeMemberProperty)member;
                            Property.Type = GetCollection(Property.Type.ArrayElementType);
                            Property.HasSet = false;
                        }
                    }
                }
            }
        }
示例#16
0
        public static List<XmlSchemaElement> extractElements(XmlSchema schema)
        {
            List<XmlSchemaElement> elements = new List<XmlSchemaElement>();
            foreach (object item in schema.Elements)
            {
                if (item is DictionaryEntry)
                {
                    DictionaryEntry entry = (DictionaryEntry)item;
                    XmlSchemaElement element = entry.Value as XmlSchemaElement;
                    if (element != null)
                    {
                        elements.Add(element);
                    }
                }
            }
            foreach (object item in schema.Items)
            {
                if (item is XmlSchemaElement)
                {
                    XmlSchemaElement element = item as XmlSchemaElement;
                    if( !elements.Exists(el => el == element ))
                        elements.Add(element);
                }
            }

            return elements;
        }
示例#17
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();
            }
        }
        internal void Add(XmlDocument schemaDoc, XmlSchema schema, string typeName, string namespaceUri)
        {
            XmlSchemaSimpleType simpleType = schema.SchemaTypes[new XmlQualifiedName(typeName, namespaceUri)] as XmlSchemaSimpleType;
            XmlSchemaSimpleTypeRestriction typeRestriction = simpleType.Content as XmlSchemaSimpleTypeRestriction;
            XmlSchemaPatternFacet pattern = typeRestriction.Facets[0] as XmlSchemaPatternFacet;
            Regex re = new Regex(pattern.Value);

            XmlNodeList attributeNameNodes = schemaDoc.SelectNodes("//*[@type='" + typeName + "']/@name");
            for (int i = 0; i < attributeNameNodes.Count; i++)
            {
                string attrName = attributeNameNodes.Item(i).Value;
                if (RegexForAttrName[attrName] != null)
                {
                    continue;
                }
                else
                {
                    RegexForAttrName[attrName] = re;
                    if (XPathPredicateOfAttributes == null)
                    {
                        XPathPredicateOfAttributes = "";
                    }
                    else
                    {
                        XPathPredicateOfAttributes += " or ";
                    }
                    XPathPredicateOfAttributes += "local-name() = '" + attrName + "'";
                }
            }
        }
示例#19
0
        //gen new xsd base on selected tables and columns which generated by OSQL.
        private string CreateXsd()
        {
            xmlschema = new sch.XmlSchema();

            //Create the PdeData element
            sch.XmlSchemaElement rootElement = new sch.XmlSchemaElement();
            rootElement.Name = "PdeData";
            xmlschema.Items.Add(rootElement);
            sch.XmlSchemaComplexType rootType = new sch.XmlSchemaComplexType();
            rootType.IsMixed = false;
            sch.XmlSchemaAll rootAll = new sch.XmlSchemaAll();
            rootType.Particle      = rootAll;
            rootElement.SchemaType = rootType;

            for (int i = 0; i < selectedTables.Count; i++)
            {
                rootAll = GenOneTabElement(rootAll, selectedTables[i], selectedColumns[i], tabColsType[i]);
            }

            xmlschema.Compile(new sch.ValidationEventHandler(ValidationEventHandler));
            FileStream stream = new FileStream("e:\\temp.xsd", FileMode.Create);

            //Write the file
            xmlschema.Write(stream);
            stream.Close();

            return("e:\\temp.xsd");
        }
 public void LoadSettings_StandardSettingsValidateToSchema_ValidateSuccessfully()
 {
     using (StreamReader schemaReader = new StreamReader("../../slksettings.xsd"))
     {
         System.Xml.Schema.XmlSchema xmlSchema = XmlSchema.Read(schemaReader,
                                                                delegate(object sender2, ValidationEventArgs e2)
         {
             XmlSchemaException schemaException = e2.Exception;
             string messageFormat = "[{0}:{1}] {2}";
             string message       = string.Format(CultureInfo.InvariantCulture, messageFormat, schemaException.LineNumber, schemaException.LinePosition, schemaException.Message);
             throw new InvalidOperationException(message);
         });
         using (StreamReader stringReader = new StreamReader("../../slksettings.xml"))
         {
             XmlReaderSettings xmlSettings = new XmlReaderSettings();
             xmlSettings.Schemas.Add(xmlSchema);
             xmlSettings.ValidationType = ValidationType.Schema;
             using (XmlReader reader = XmlReader.Create(stringReader, xmlSettings))
             {
                 while (reader.Read())
                 {
                 }
             }
         }
     }
 }
示例#21
0
        private void addElements(XmlSchema schema, string targetNamespaceUri)
        {
            debug("adding elements: " + schema.Elements.Count);
            debug("adding elements items: " + schema.Items.Count);

            foreach (XmlSchemaObject item in schema.Items)
            {
                var element = item as XmlSchemaElement;
                if (element != null && element.SchemaType is XmlSchemaComplexType)
                {
                    processComplexType(targetNamespaceUri, element.SchemaType as XmlSchemaComplexType, element.Name, Elements);
                }

            }
            foreach (XmlSchemaElement element in schema.Elements.Values)
            {
                if (element.SchemaType is XmlSchemaComplexType)
                {
                    processComplexType(targetNamespaceUri, element.SchemaType as XmlSchemaComplexType, element.Name, Elements);
                }
            }

            debug("Elements Found: " + Elements.Count);
            foreach (var elems in Elements)
            {
                debug("Elem: " + elems.Key + ":" + elems.Value.Name);
                debug(string.Join(", ", elems.Value.Properties.Select(_ => _.Name + ":" + _.Type).ToArray()));
            }
        }
		public static void ValidateSpecification(XmlElement containingNode, XmlSchema schema)
		{
			// We must parse the XML to get the schema validation to work.  So, we write
			// the xml out to a string, and read it back in with Schema Validation enabled
			var sw = new StringWriter();

			var xmlWriterSettings = new XmlWriterSettings
			{
				Encoding = Encoding.UTF8,
				ConformanceLevel = ConformanceLevel.Fragment,
				Indent = false,
				NewLineOnAttributes = false,
				IndentChars = ""
			};

			var xmlWriter = XmlWriter.Create(sw, xmlWriterSettings);
			foreach (XmlNode node in containingNode.ChildNodes)
				node.WriteTo(xmlWriter);
			xmlWriter.Close();

			var xmlReaderSettings = new XmlReaderSettings
			{
				ValidationType = ValidationType.Schema,
				ConformanceLevel = ConformanceLevel.Fragment,
				Schemas = new XmlSchemaSet()
			};
			xmlReaderSettings.Schemas.Add(schema);

			var xmlReader = XmlTextReader.Create(new StringReader(sw.ToString()), xmlReaderSettings);
			while (xmlReader.Read()) ;
			xmlReader.Close();
		}
示例#23
0
 internal static System.Xml.Schema.XmlSchema GetSchema(string ns, XmlSchemaSet schemaSet)
 {
     if (ns == null)
     {
         ns = string.Empty;
     }
     foreach (System.Xml.Schema.XmlSchema schema in schemaSet.Schemas())
     {
         if ((schema.TargetNamespace == null) && (ns.Length == 0))
         {
             return(schema);
         }
         if (ns.Equals(schema.TargetNamespace))
         {
             return(schema);
         }
     }
     System.Xml.Schema.XmlSchema schema2 = new System.Xml.Schema.XmlSchema {
         ElementFormDefault = XmlSchemaForm.Qualified
     };
     if (ns.Length > 0)
     {
         schema2.TargetNamespace = ns;
     }
     schemaSet.Add(schema2);
     return(schema2);
 }
示例#24
0
        /// <summary>
        /// Check XML file against an XSD accessible via Stream object.
        /// </summary>
        /// <param name="xmlPathFileName">PathFilename to XML file</param>
        /// <param name="xsdStream">Stream constructed from XSD (resource) file.</param>
        /// <param name="xmlSettings">Optional settings to determine level of detail to check</param>
        public void CheckXML_XSD(string xmlPathFileName,
                                 Stream xsdStream,
                                 XmlReaderSettings xmlSettings = null)
        {
            StreamReader strmrStreamReader = new StreamReader(xsdStream);

            System.Xml.Schema.XmlSchema xSchema = new System.Xml.Schema.XmlSchema();
            xSchema = XmlSchema.Read(strmrStreamReader, null);

            // Set the validation settings.
            if (xmlSettings == null)
            {
                xmlSettings = new XmlReaderSettings();
                xmlSettings.Schemas.Add(xSchema);
                xmlSettings.ValidationType   = ValidationType.Schema;
                xmlSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
                xmlSettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
                xmlSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
            }

            xmlSettings.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallBack);

            using (XmlReader reader = XmlReader.Create(xmlPathFileName, xmlSettings))
            {
                while (reader.Read())
                {
                }
            }
        }
示例#25
0
		internal override int Compile(ValidationEventHandler h, XmlSchema schema)
		{
			// If this is already compiled this time, simply skip.
			if (CompilationId == schema.CompilationId)
				return 0;

			XmlSchemaUtil.CompileID(Id, this, schema.IDCollection, h);
			CompileOccurence (h, schema);

			if (Items.Count == 0)
				this.warn (h, "Empty choice is unsatisfiable if minOccurs not equals to 0");

			foreach(XmlSchemaObject obj in Items)
			{
				if(obj is XmlSchemaElement ||
					obj is XmlSchemaGroupRef ||
					obj is XmlSchemaChoice ||
					obj is XmlSchemaSequence ||
					obj is XmlSchemaAny)
				{
					errorCount += obj.Compile(h,schema);
				}
				else
					error(h, "Invalid schema object was specified in the particles of the choice model group.");
			}
			this.CompilationId = schema.CompilationId;
			return errorCount;
		}
示例#26
0
        public void StartParsing(XmlReader reader, string targetNamespace) {
            this.reader = reader;
            positionInfo = PositionInfo.GetPositionInfo(reader);
            namespaceManager = reader.NamespaceManager;
            if (namespaceManager == null) {
                namespaceManager = new XmlNamespaceManager(nameTable);
                isProcessNamespaces = true;
            } 
            else {
                isProcessNamespaces = false;
            }
            while (reader.NodeType != XmlNodeType.Element && reader.Read()) {}

            markupDepth = int.MaxValue;
            schemaXmlDepth = reader.Depth;
            SchemaType rootType = schemaNames.SchemaTypeFromRoot(reader.LocalName, reader.NamespaceURI);
            
            string code;
            if (!CheckSchemaRoot(rootType, out code)) {
                throw new XmlSchemaException(code, reader.BaseURI, positionInfo.LineNumber, positionInfo.LinePosition);
            }
            
            if (schemaType == SchemaType.XSD) {
                schema = new XmlSchema();
                schema.BaseUri = new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute);
                builder = new XsdBuilder(reader, namespaceManager, schema, nameTable, schemaNames, eventHandler);
            }
            else {  
                Debug.Assert(schemaType == SchemaType.XDR);
                xdrSchema = new SchemaInfo();
                xdrSchema.SchemaType = SchemaType.XDR;
                builder = new XdrBuilder(reader, namespaceManager, xdrSchema, targetNamespace, nameTable, schemaNames, eventHandler);
                ((XdrBuilder)builder).XmlResolver = xmlResolver;
            }
        }
示例#27
0
        public void v2()
        {
            XmlSchemaSet sc = new XmlSchemaSet();
            sc.XmlResolver = new XmlUrlResolver();
            XmlSchema schema = new XmlSchema();
            sc.Add(null, TestData._XsdNoNs);
            CError.Compare(sc.Count, 1, "AddCount");
            CError.Compare(sc.IsCompiled, false, "AddIsCompiled");

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

            try
            {
                schema = sc.Add(null, Path.Combine(TestData._Root, "include_v2.xsd"));
            }
            catch (XmlSchemaException)
            {
                // no schema should be addded to the set.
                CError.Compare(sc.Count, 1, "Count");
                CError.Compare(sc.IsCompiled, true, "IsCompiled");
                return;
            }
            Assert.True(false);
        }
        /// <summary>
        ///  TODO: Create new XmlSchema instead of DeepCopy
        /// </summary>
        /// <param name="templateSchema">Arbitrary maindoc schema used as a template for our new base class schema</param>
        /// <param name="sharedElementCount">Number of elements that shoud be copied over to the new base class schema complex type</param>
        /// <returns></returns>
        private static XmlSchema CreateAbstractBaseSchemaFromMaindocSchema(XmlSchema templateSchema, int sharedElementCount)
        {
            XmlSchema abstractBaseSchema = DeepCopy(templateSchema);
            var abstractBaseElement = abstractBaseSchema.Items.OfType<XmlSchemaElement>().Single();          // Single. There can only be one
            var abstractBaseComplexType = abstractBaseSchema.Items.OfType<XmlSchemaComplexType>().Single();  // Christopher Lambert again

            // overwrite template props
            abstractBaseSchema.TargetNamespace = abstractBaseSchema.TargetNamespace.Replace(abstractBaseElement.Name, Constants.abstractBaseSchemaName);
            abstractBaseSchema.Namespaces.Add("", abstractBaseSchema.TargetNamespace);
            abstractBaseSchema.SourceUri = templateSchema.SourceUri.Replace(abstractBaseElement.Name, Constants.abstractBaseSchemaName);

            abstractBaseComplexType.IsAbstract = true;
            abstractBaseComplexType.Annotation.Items.Clear();
            XmlSchemaDocumentation doc = new XmlSchemaDocumentation();
            var nodeCreaterDoc = new XmlDocument();
            doc.Markup = new XmlNode[] { nodeCreaterDoc.CreateTextNode("This is a custom generated class that holds all the props/fields common to all UBL maindocs."),
                                         nodeCreaterDoc.CreateTextNode("You won't find a matching xsd file where it originates from.") };
            abstractBaseComplexType.Annotation.Items.Add(doc);
            abstractBaseComplexType.Name = Constants.abstractBaseSchemaComplexTypeName;

            // remove non-shared tailing elements.
            XmlSchemaObjectCollection elementCollection = (abstractBaseComplexType.Particle as XmlSchemaSequence).Items;
            while (sharedElementCount < elementCollection.Count) elementCollection.RemoveAt(sharedElementCount);

            abstractBaseElement.Name = Constants.abstarctBaseSchemaElementName;
            abstractBaseElement.SchemaTypeName = new XmlQualifiedName(Constants.abstractBaseSchemaComplexTypeName, abstractBaseSchema.TargetNamespace);

            // Don't need schemaLocation for loaded schemas. Will generate schemasetcompile warnings if not removed
            foreach (var baseSchemaImports in abstractBaseSchema.Includes.OfType<XmlSchemaImport>()) baseSchemaImports.SchemaLocation = null;

            return abstractBaseSchema;
        }
示例#29
0
        /// <summary>
        /// Processes the class.
        /// </summary>
        /// <param name="codeNamespace">The code namespace.</param>
        /// <param name="schema">The input XSD schema.</param>
        /// <param name="type">Represents a type declaration for a class, structure, interface, or enumeration</param>
        protected override void ProcessClass(CodeNamespace codeNamespace, XmlSchema schema, CodeTypeDeclaration type)
        {
            this.autoPropertyListField.Clear();
            this.fieldListToRemoveField.Clear();
            this.fieldWithAssignementInCtorListField.Clear();

            // looks for properties that can not become automatic property
            CodeConstructor ctor = null;
            foreach (CodeTypeMember member in type.Members)
            {
                if (member is CodeConstructor)
                    ctor = member as CodeConstructor;
            }

            if (ctor != null)
            {
                foreach (var statement in ctor.Statements)
                {
                    var codeAssignStatement = statement as CodeAssignStatement;
                    if (codeAssignStatement == null) continue;
                    var code = codeAssignStatement.Left as CodeFieldReferenceExpression;
                    if (code != null)
                    {
                        this.fieldWithAssignementInCtorListField.Add(code.FieldName);
                    }
                }
            }

            base.ProcessClass(codeNamespace, schema, type);

            // generate automatic properties
            this.GenerateAutomaticProperties(type);
        }
示例#30
0
		///<remarks>
		/// 1. Content must be present and one of restriction or extention
		///</remarks>
		internal override int Compile(ValidationEventHandler h, XmlSchema schema)
		{
			// If this is already compiled this time, simply skip.
			if (CompilationId == schema.CompilationId)
				return 0;

			if(Content == null)
			{
				error(h, "Content must be present in a simpleContent");
			}
			else
			{
				if(Content is XmlSchemaSimpleContentRestriction)
				{
					XmlSchemaSimpleContentRestriction xscr = (XmlSchemaSimpleContentRestriction) Content;
					errorCount += xscr.Compile(h, schema);
				}
				else if(Content is XmlSchemaSimpleContentExtension)
				{
					XmlSchemaSimpleContentExtension xsce = (XmlSchemaSimpleContentExtension) Content;
					errorCount += xsce.Compile(h, schema);
				}
				else
					error(h,"simpleContent can't have any value other than restriction or extention");
			}
			
			XmlSchemaUtil.CompileID(Id,this, schema.IDCollection,h);
			this.CompilationId = schema.CompilationId;
			return errorCount;
		}
		/// <summary>
		/// Customizes the generated code to better conform to the NHibernate's coding conventions.
		/// </summary>
		/// <param name="code">The customizable code DOM.</param>
		/// <param name="sourceSchema">The source XML Schema.</param>
		protected override void CustomizeGeneratedCode(CodeNamespace code, XmlSchema sourceSchema)
		{
			new ImproveHbmTypeNamesCommand(code).Execute();
			new ImproveEnumFieldsCommand(code).Execute();

			// TODO: Rename class fields?
		}
        private void Cleanup(XmlSchema schema) {
            if (schema.IsProcessing) {
                return;
            }
            schema.IsProcessing = true;

            for (int i = 0; i < schema.Includes.Count; ++i) {
                XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];

                if (include.Schema != null) {
                    Cleanup(include.Schema);
                }

                if (include is XmlSchemaRedefine) {
                    XmlSchemaRedefine rdef = include as XmlSchemaRedefine;
                    rdef.AttributeGroups.Clear();
                    rdef.Groups.Clear();
                    rdef.SchemaTypes.Clear();
                }
                
            }

            schema.Attributes.Clear();
            schema.AttributeGroups.Clear();
            schema.SchemaTypes.Clear();
            schema.Elements.Clear();
            schema.Groups.Clear();
            schema.Notations.Clear();
            schema.Ids.Clear();
            schema.IdentityConstraints.Clear();

            schema.IsProcessing = false;
        }
示例#33
0
 private static XmlReaderSettings CreateXmlReaderSettings(XmlSchema xmlSchema)
 {
     XmlReaderSettings settings = new XmlReaderSettings();
     settings.ValidationType = ValidationType.Schema;
     settings.Schemas.Add(xmlSchema);
     return settings;
 }
 public void JumpToDoesNothingWhenFileNameIsEmptyString()
 {
     XmlSchema schemaObject = new XmlSchema();
     schemaObject.SourceUri = String.Empty;
     DerivedXmlSchemaObjectLocation location = new DerivedXmlSchemaObjectLocation(schemaObject);
     Assert.IsFalse(location.IsDerivedJumpToFilePositionMethodCalled);
 }
示例#35
0
 public static bool Validate(XmlDocument document, XmlSchema schema)
 {
     succes = true;
     document.Schemas.Add(schema);
     document.Validate(new ValidationEventHandler(ValidationCallBack));
     return succes;
 }
示例#36
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);
            }
        }
示例#37
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();
            }
        }
示例#38
0
        /// <summary>
        /// Constructs a schema from the contents of an XML specification.
        /// </summary>
        /// <param name="fileContents">The contents of a file that specifies the schema in XML.</param>
        public DataModelSchema(string fileContents)
        {
            // Initialize the object
            this.VolatileStoreName = "ADO Data Model";
            this.DurableStoreName  = "SQL Data Model";

            // Create a string reader from the input string (which contains the source of the original file).  Read this data into
            // an XmlSchema object.
            XmlTextReader xmlTextReader = new XmlTextReader(new StringReader(fileContents));

            this.xmlSchema = XmlSchema.Read(xmlTextReader, new ValidationEventHandler(ValidationCallback));

            // Compiling the Schema is critical for qualified name resolution.
            XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();

            xmlSchemaSet.Add(this.xmlSchema);
            xmlSchemaSet.Compile();

            // The namespace manager is used to create qualified names from the XPath specifications.
            this.XmlNamespaceManager = new XmlNamespaceManager(new NameTable());
            foreach (XmlQualifiedName xmlQualifiedName in this.xmlSchema.Namespaces.ToArray())
            {
                this.XmlNamespaceManager.AddNamespace(xmlQualifiedName.Name, xmlQualifiedName.Namespace);
            }
        }
		public void TestSimpleValidation ()
		{
			string xml = "<root/>";
			xvr = PrepareXmlReader (xml);
			Assert.AreEqual (ValidationType.Auto, xvr.ValidationType);
			XmlSchema schema = new XmlSchema ();
			XmlSchemaElement elem = new XmlSchemaElement ();
			elem.Name = "root";
			schema.Items.Add (elem);
			xvr.Schemas.Add (schema);
			xvr.Read ();	// root
			Assert.AreEqual (ValidationType.Auto, xvr.ValidationType);
			xvr.Read ();	// EOF

			xml = "<hoge/>";
			xvr = PrepareXmlReader (xml);
			xvr.Schemas.Add (schema);
			try {
				xvr.Read ();
				Assert.Fail ("element mismatch is incorrectly allowed");
			} catch (XmlSchemaException) {
			}

			xml = "<hoge xmlns='urn:foo' />";
			xvr = PrepareXmlReader (xml);
			xvr.Schemas.Add (schema);
			try {
				xvr.Read ();
				Assert.Fail ("Element in different namespace is incorrectly allowed.");
			} catch (XmlSchemaException) {
			}
		}
示例#40
0
        private void LoadSchema(string schemaUri)
        {
            //string fullSchemaURI = @"http://local.bbc.co.uk:8081/schemas/" + schemaUri;
            //string fullSchemaURI = @"http://dnadev.national.core.bbc.co.uk/bbc.dna/schemas/" + schemaUri;


            if (_cachedSchemas.ContainsKey(schemaUri))
            {
                //Retrieve shema from cache.
                _xmlSchema = _cachedSchemas[schemaUri];
            }
            else
            {
                //Get Local Path of schema file.
                // Make sure that you specify the Schema directory name is Case correct.

                using (var iis = IIsInitialise.GetIIsInitialise())
                {
                    String path = iis.GetVDirPath("h2g2UnitTesting", "Schemas");
                    path = Path.Combine(path, schemaUri);

                    _xmlSchema = new XmlSchema();
                    //Uri ourUri = new Uri(fullSchemaURI);
                    //WebRequest request = WebRequest.Create(ourUri);
                    //request.Proxy = null;
                    //WebResponse response = request.GetResponse();

                    //Read Schema from local path. This allows relative includes within the schema files to be resolved correctly.
                    _xmlSchema = XmlSchema.Read(new XmlTextReader(path), new ValidationEventHandler(xmlReaderSettingsValidationEventHandler));
                }

                //Cache it.
                _cachedSchemas[schemaUri] = _xmlSchema;
            }
        }
        static ConfigurationFileSchemaTests()
        {
            const string helperSchemaString =
                @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                @"<xs:schema attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">"
                +
                @"    <xs:element name=""providers"" type=""ProviderList_Type"" />" +
                @"    <xs:element name=""provider"" type=""Provider_Type"" />" +
                @"    <xs:element name=""contexts"" type=""ContextList_Type"" />" +
                @"    <xs:element name=""context"" type=""Context_Type"" />" +
                @"    <xs:element name=""interceptors"" type=""InterceptorList_Type"" />" +
                @"    <xs:element name=""interceptor"" type=""ElementWithTypeAndParameters_Type"" />" +
                @"    <xs:element name=""parameters"" type=""ParameterList_Type"" />" +
                @"    <xs:element name=""parameter"" type=""Parameter_Type"" />" +
                @"    <xs:element name=""elementWithTypeAndParameters"" type=""ElementWithTypeAndParameters_Type"" />" +
                @"</xs:schema>";

            const string fakeXmlDocumentTransformSchemaString =
                @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                @"<xs:schema targetNamespace=""http://schemas.microsoft.com/XML-Document-Transform"" " +
                @"      elementFormDefault=""qualified"" attributeFormDefault=""unqualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">"
                +
                @"    <xs:attribute name=""Transform"" type=""xs:string"" />" +
                @"</xs:schema>";

            using (var reader = XmlReader.Create(EntityFrameworkConfigSchemaName))
            {
                ConfigurationFileSchema = XmlSchema.Read(reader, null);
            }

            HelperSchema = XmlSchema.Read(XmlReader.Create(new StringReader(helperSchemaString)), null);
            FakeXmlDocumentTransformationSchema = XmlSchema.Read(
                XmlReader.Create(new StringReader(fakeXmlDocumentTransformSchemaString)), null);
        }
示例#42
0
 public virtual void VisitSchema(XmlSchema xmlSchema)
 {
     foreach (XmlSchemaObject o in xmlSchema.Items)
     {
         Dispatch(o);
     }
 }
示例#43
0
文件: parser.cs 项目: ArildF/masters
        internal void StartParsing(XmlReader reader, string targetNamespace, SchemaInfo schemaInfo) {
            this.reader = reader;
            positionInfo = PositionInfo.GetPositionInfo(reader);
            this.namespaceManager = reader.NamespaceManager;
            if (this.namespaceManager == null) {
                this.namespaceManager = new XmlNamespaceManager(this.nameTable);
                this.isProcessNamespaces = true;
            } 
            else {
                this.isProcessNamespaces = false;
            }
            while (this.reader.NodeType != XmlNodeType.Element && this.reader.Read()) {}

            this.markupDepth = int.MaxValue;
			this.schemaXmlDepth = reader.Depth;
            XmlQualifiedName qname = new XmlQualifiedName(this.reader.LocalName, XmlSchemaDatatype.XdrCanonizeUri(this.reader.NamespaceURI, this.nameTable, this.schemaNames));
            if (this.schemaNames.IsXDRRoot(qname)) {
                Debug.Assert(schemaInfo != null);
                schemaInfo.SchemaType = SchemaType.XDR;
                this.schema = null;
                this.builder = new XdrBuilder(reader, this.namespaceManager, schemaInfo, targetNamespace, this.nameTable, this.schemaNames, this.validationEventHandler);
            }
            else if (this.schemaNames.IsXSDRoot(qname)) {
                if (schemaInfo != null) {
                    schemaInfo.SchemaType = SchemaType.XSD;
                }
                this.schema = new XmlSchema();
                this.schema.BaseUri = reader.BaseURI;
                this.builder = new XsdBuilder(reader, this.namespaceManager, this.schema, this.nameTable, this.schemaNames, this.validationEventHandler);
            }
            else { 
                throw new XmlSchemaException(Res.Sch_SchemaRootExpected, reader.BaseURI, positionInfo.LineNumber, positionInfo.LinePosition);
            }
                
        }
示例#44
0
    private void CreateSimpletypeLength(string length, string minLength, string maxLength, bool expected) {
      passed = true;

      XmlSchema schema = new XmlSchema();

      XmlSchemaSimpleType testType = new XmlSchemaSimpleType();
      testType.Name = "TestType";

      XmlSchemaSimpleTypeRestriction testTypeRestriction = new XmlSchemaSimpleTypeRestriction();
      testTypeRestriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

      if (length != "-") {
        XmlSchemaLengthFacet _length = new XmlSchemaLengthFacet();
        _length.Value = length;
        testTypeRestriction.Facets.Add(_length);
      }
      if (minLength != "-") {
        XmlSchemaMinLengthFacet _minLength = new XmlSchemaMinLengthFacet();
        _minLength.Value = minLength;
        testTypeRestriction.Facets.Add(_minLength);
      }
      if (maxLength != "-") {
        XmlSchemaMaxLengthFacet _maxLength = new XmlSchemaMaxLengthFacet();
        _maxLength.Value = maxLength;
        testTypeRestriction.Facets.Add(_maxLength);
      }

      testType.Content = testTypeRestriction;
      schema.Items.Add(testType);
      schema.Compile(new ValidationEventHandler(ValidationCallbackOne));

      Assert.IsTrue (expected == passed, (passed ? "Test passed, should have failed" : "Test failed, should have passed") + ": " + length + " " + minLength + " " + maxLength);
      
    }
示例#45
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));
        }
示例#46
0
        private string genExpXsd()
        {
            sch.XmlSchema expSchema = new sch.XmlSchema();

            //Create the PdeData element
            sch.XmlSchemaElement rootElement = new sch.XmlSchemaElement();
            rootElement.Name = ROOT_ELEMENT;
            expSchema.Items.Add(rootElement);
            sch.XmlSchemaComplexType rootType = new sch.XmlSchemaComplexType();
            rootType.IsMixed = false;
            sch.XmlSchemaSequence rootSequence = new sch.XmlSchemaSequence();
            rootType.Particle      = rootSequence;
            rootElement.SchemaType = rootType;

            foreach (ExportItemMap itemMap in exportItems)
            {
                if (itemMap.mapType == ProntoDoc.Framework.CoreObject.MapType.singleCell)
                {
                    sch.XmlSchemaElement item = new sch.XmlSchemaElement();
                    item.Name           = itemMap.treeNodeName;
                    item.SchemaTypeName = new XmlQualifiedName(itemMap.dataType, ns);
                    rootSequence.Items.Add(item);
                }
                else
                {
                    sch.XmlSchemaElement tabElement = new sch.XmlSchemaElement();
                    tabElement.MinOccurs       = 0;
                    tabElement.MaxOccursString = "unbounded";
                    tabElement.Name            = itemMap.treeNodeName;
                    rootSequence.Items.Add(tabElement);

                    sch.XmlSchemaComplexType tabType = new sch.XmlSchemaComplexType();
                    tabType.IsMixed = false;
                    sch.XmlSchemaAll tabAll = new sch.XmlSchemaAll();
                    tabType.Particle      = tabAll;
                    tabElement.SchemaType = tabType;

                    //generate children node
                    foreach (TableColumnMap col in itemMap.tabCols)
                    {
                        sch.XmlSchemaElement item = new sch.XmlSchemaElement();
                        item.Name           = col.treeNodeName;
                        item.SchemaTypeName = new XmlQualifiedName(col.dataType, ns);
                        tabAll.Items.Add(item);
                    }
                }
            }

            expSchema.Compile(new sch.ValidationEventHandler(ValidationEventHandler));
            FileStream stream = new FileStream("e:\\tempout.xsd", FileMode.Create);

            //Write the file
            expSchema.Write(stream);
            stream.Close();

            return("e:\\tempout.xsd");
        }
 public static MetadataSection CreateFromSchema(System.Xml.Schema.XmlSchema schema)
 {
     if (schema == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("schema");
     }
     return(new MetadataSection {
         Dialect = XmlSchemaDialect, Identifier = schema.TargetNamespace, Metadata = schema
     });
 }
示例#48
0
        private XsdDatatypeProvider()
        {
            if (table != null)
            {
                return;
            }

            table = new Hashtable();

            // TODO: fill all type names.
            string [] names = new string []
            {
                "anySimpleType",
                "string",
                "normalizedString",
                "token",
                "language",
                "NMTOKEN", "NMTOKENS",
                "Name", "NCName",
                "ID", "IDREF", "IDREFS",
                "ENTITY", "ENTITIES", //"NOTATION",
                "decimal",
                "integer", "long", "int", "short", "byte",
                "nonPositiveInteger", "negativeInteger",
                "nonNegativeInteger", "positiveInteger",
                "unsignedLong", "unsignedInt",
                "unsignedShort", "unsignedByte",
                "double", "float",
                "base64Binary", "hexBinary",
                "boolean",
                "anyURI",
                "duration", "dateTime", "date", "time",
//				"QName",
                "gYearMonth", "gMonthDay",
                "gYear", "gMonth", "gDay",
            };

            StringBuilder sb = new StringBuilder();

            sb.Append("<xs:schema xmlns:xs='" + XSchema.Namespace + "'>");
            foreach (string name in names)
            {
                sb.Append("<xs:element name='" + name + "' type='xs:" + name + "'/>");
            }
            sb.Append("</xs:schema>");
            XSchema schema = XSchema.Read(new XmlTextReader(sb.ToString(), XmlNodeType.Document, null), null);

            schema.Compile(null);
            foreach (XmlSchemaElement el in schema.Elements.Values)
            {
                table.Add(el.Name, new XsdPrimitiveType(el.Name, el.ElementType as XmlSchemaDatatype));
            }
        }
示例#49
0
        /// <summary>
        /// This function basically reproduces the functionality that WSDL.exe provides and generates
        /// a CSharp class that is a proxy to the Web service specified at the provided WSDL URL.
        /// Returns the string for the generated C# code file
        /// </summary>
        private string GenerateWsdlProxyClass(string wsdl)
        {
            // get the WSDL content into a service description
            StringReader       sWsdl = new StringReader(wsdl);
            ServiceDescription sd    = null;

            sd = ServiceDescription.Read(sWsdl);

            // create an importer and associate with the ServiceDescription
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

            importer.ProtocolName          = "SOAP";
            importer.CodeGenerationOptions = CodeGenerationOptions.None;
            importer.AddServiceDescription(sd, null, null);

            // Download and inject any imported schemas (ie. WCF generated WSDL)
            foreach (XmlSchema wsdlSchema in sd.Types.Schemas)
            {
                // Loop through all detected imports in the main schema
                foreach (XmlSchemaObject externalSchema in wsdlSchema.Includes)
                {
                    WebClient http = new WebClient();
                    // Read each external schema into a schema object and add to importer
                    if (externalSchema is XmlSchemaImport)
                    {
                        Uri    schemaUri    = new Uri(((XmlSchemaExternal)externalSchema).SchemaLocation);
                        Stream schemaStream = http.OpenRead(schemaUri);
                        System.Xml.Schema.XmlSchema schema = XmlSchema.Read(schemaStream, null);
                        importer.Schemas.Add(schema);
                    }
                }
            }

            // set up for code generation by creating a namespace and adding to importer
            CodeNamespace   ns  = new CodeNamespace(LocalAssembly + LocalCount);
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.Namespaces.Add(ns);
            importer.Import(ns, ccu);

            // final code generation in specified language
            CSharpCodeProvider provider = new CSharpCodeProvider();
            StringWriter       sw       = new StringWriter();

            provider.GenerateCodeFromCompileUnit(ccu, sw, new CodeGeneratorOptions());

            sw.Flush();
            string code = sw.ToString();

            sw.Close();

            return(code);
        }
示例#50
0
        /// <summary>
        /// Initializes the traversing with the XmlSchema.
        /// </summary>
        /// <param name="sourceFile">The schema file to traverse.</param>
        /// <returns>An <c>IVisitableComponent</c> containing all the visitable nodes.</returns>
        public IVisitableComponent Traverse(string sourceFile)
        {
            try
            {
                Validator val = new Validator();
                using (FileStream fs = new FileStream(sourceFile, FileMode.Open))
                    _context = System.Xml.Schema.XmlSchema.Read(fs, new ValidationEventHandler(val.OnValidation));
                if (val.HasErrors)
                {
                    throw new ArgumentException("There were errors in the schema "
                                                + sourceFile + Environment.NewLine + val.Errors);
                }
            }
            catch (Exception ex)
            {
                throw new ArgumentException("The schema couldn't be loaded: "
                                            + sourceFile + Environment.NewLine + ex.Message, ex);
            }

            // Retrieve the current configuration from the Host.
            IConfigurationRetriever retriever =
                (IConfigurationRetriever)Host.GetService(typeof(IConfigurationRetriever));

            if (retriever == null)
            {
                GeneratorHost.ThrowInvalidHostResponse(typeof(IConfigurationRetriever));
            }

            _config = retriever.GetConfig("generator") as GeneratorSection;
            if (_config == null)
            {
                GeneratorHost.ThrowInvalidHostResponse("No <generator> section retrieved.");
            }

            if (!_context.IsCompiled)
            {
                _context.Compile(null);
            }
            XmlDocument doc = new XmlDocument();

            doc.Load(sourceFile);
            VisitableSchemaRoot result = new VisitableSchemaRoot(_context, doc, _context.Id);

            foreach (XmlSchemaObject item in _context.Items)
            {
                if (item is XmlSchemaElement)
                {
                    result.Add(Build(item as XmlSchemaElement, result));
                }
            }

            return(result);
        }
示例#51
0
        private Schema.XmlSchemaSequence CreateSequenceElement(Schema.XmlSchema parent, string name)
        {
            Schema.XmlSchemaElement element = new Schema.XmlSchemaElement();
            element.Name = name;
            parent.Items.Add(element);
            Schema.XmlSchemaComplexType type = new Schema.XmlSchemaComplexType();
            type.IsMixed = false;
            Schema.XmlSchemaSequence sequence = new Schema.XmlSchemaSequence();
            type.Particle      = sequence;
            element.SchemaType = type;

            return(sequence);
        }
示例#52
0
        /// <summary>
        /// Initializes schema set for a service definition
        /// </summary>
        private void initSchemaSet()
        {
            if (null == schemaSet)
            {
                List <string> parameters = new List <string>();
                Types         types      = serviceDescription.Types;

                System.Xml.Schema.XmlSchema xmlSchema = types.Schemas[0];
                schemaSet = new XmlSchemaSet();
                schemaSet.Add(xmlSchema);
                schemaSet.Compile();
            }
        }
示例#53
0
        private static bool EsCFDIXmlValido(List <String> PathsXSD, System.IO.StringReader XMLPath, out List <string> Errores)
        {
            try
            {
                // 0- Initialize variables...
                _IsValid  = true;
                Resultado = new List <string>();


                // 1- Read XML file content
                Reader = new System.Xml.XmlTextReader(XMLPath);

                // 3- Create a new instance of XmlSchema object
                System.Xml.Schema.XmlSchema  Schema         = new System.Xml.Schema.XmlSchema();
                System.Xml.XmlReaderSettings ReaderSettings = new System.Xml.XmlReaderSettings();

                // 2- Read Schema file content
                foreach (String XSD in PathsXSD)
                {
                    StreamReader SR = new StreamReader(XSD);
                    Schema = System.Xml.Schema.XmlSchema.Read(SR, new System.Xml.Schema.ValidationEventHandler(ReaderSettings_ValidationEventHandler));
                    ReaderSettings.ValidationType = System.Xml.ValidationType.Schema;
                    ReaderSettings.Schemas.Add(Schema);
                }
                // 8- Add your ValidationEventHandler address to
                // XmlReaderSettings ValidationEventHandler
                ReaderSettings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ReaderSettings_ValidationEventHandler);

                // 9- Create a new instance of XmlReader object
                System.Xml.XmlReader objXmlReader = System.Xml.XmlReader.Create(Reader, ReaderSettings);

                // 10- Read XML content in a loop
                while (objXmlReader.Read())
                {
                    // empty loop
                }

                // Se cierra el validador
                objXmlReader.Close();
                Errores = Resultado;
                return(_IsValid);
            }
            catch (Exception ex)
            {
                Errores = new List <string>();
                Errores.Add("Error de validacion del XML Error:" + ex.ToString());
                return(true);
            }
        }
示例#54
0
        public static MetadataSection CreateFromSchema(XsdNS.XmlSchema schema)
        {
            if (schema == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("schema");
            }

            MetadataSection section = new MetadataSection();

            section.Dialect    = MetadataSection.XmlSchemaDialect;
            section.Identifier = schema.TargetNamespace;
            section.Metadata   = schema;

            return(section);
        }
示例#55
0
        public static Row Deserialize(string input, System.Xml.Schema.XmlSchema schema)
        {
            if ((string.IsNullOrEmpty(input) == true))
            {
                throw new System.ArgumentNullException("input");
            }
            if ((schema == null))
            {
                throw new System.ArgumentNullException("schema");
            }
            Row output = null;

            output = Microsoft.Rapid.Client.Core.SerializerUtil.Deserialize <Row>(input, schema);
            return(output);
        }
示例#56
0
        public static DataRoot Deserialize(System.Uri input, System.Xml.Schema.XmlSchema schema)
        {
            if ((input == null))
            {
                throw new System.ArgumentNullException("input");
            }
            if ((schema == null))
            {
                throw new System.ArgumentNullException("schema");
            }
            DataRoot output = null;

            output = Microsoft.Rapid.Client.Core.SerializerUtil.Deserialize <DataRoot>(input, schema);
            return(output);
        }
示例#57
0
        public static Collated Deserialize(System.Xml.XmlReader input, System.Xml.Schema.XmlSchema schema)
        {
            if ((input == null))
            {
                throw new System.ArgumentNullException("input");
            }
            if ((schema == null))
            {
                throw new System.ArgumentNullException("schema");
            }
            Collated output = null;

            output = Microsoft.Rapid.Client.Core.SerializerUtil.Deserialize <Collated>(input, schema);
            return(output);
        }
 protected override void Compile()
 {
     System.Xml.Schema.XmlSchema schema  = StockSchemas.CreateWsdl();
     System.Xml.Schema.XmlSchema schema2 = StockSchemas.CreateSoap();
     System.Xml.Schema.XmlSchema schema3 = StockSchemas.CreateSoapEncoding();
     System.Xml.Schema.XmlSchema schema4 = StockSchemas.CreateFakeXsdSchema();
     base.SchemaSet.Add(schema);
     base.SchemaSet.Add(schema2);
     base.SchemaSet.Add(schema3);
     base.SchemaSet.Add(schema4);
     base.Compile();
     base.SchemaSet.Remove(schema);
     base.SchemaSet.Remove(schema2);
     base.SchemaSet.Remove(schema3);
     base.SchemaSet.Remove(schema4);
 }
示例#59
0
        internal static void AddTypeToSchema(XmlSchemaType type, System.Xml.Schema.XmlSchema schema, XmlSchemaSet schemaSet)
        {
            XmlSchemaType type2 = (XmlSchemaType)schema.SchemaTypes[new XmlQualifiedName(type.Name, schema.TargetNamespace)];

            if (type2 != null)
            {
                if (type2 != type)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxConflictingGlobalType", new object[] { type.Name, schema.TargetNamespace })));
                }
            }
            else
            {
                schema.Items.Add(type);
                schemaSet.Reprocess(schema);
            }
        }
示例#60
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);
     }
 }