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);
		}
Esempio n. 2
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);
      
    }
        internal XmlSchema Add(string ns, SchemaInfo schemaInfo, XmlSchema schema, bool compile)
        {
            int errorCount = 0;

            if (schema != null)
            {
                if (schema.ErrorCount == 0 && compile)
                {
                    schema.Compile(this, nameTable, schemaNames, validationEventHandler, ns, schemaInfo, true);
                    ns = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace;
                }
                errorCount += schema.ErrorCount;
            }
            else
            {
                errorCount += schemaInfo.ErrorCount;
                ns          = NameTable.Add(ns);
            }
            if (errorCount == 0)
            {
                XmlSchemaCollectionNode node = new XmlSchemaCollectionNode();
                node.NamespaceURI = ns;
                node.SchemaInfo   = schemaInfo;
                node.Schema       = schema;
                Add(ns, node);
                return(schema);
            }
            return(null);
        }
Esempio n. 4
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 SetUpFixture()
 {
     string relativePath = "../../../TestFiles/log4net.xsd";
     Assert.IsTrue(File.Exists(relativePath), string.Format("File does not exist {0}", relativePath));
     xmlSchema = XmlSchema.Read(new XmlTextReader(relativePath), null);
     xmlSchema.Compile(null);
     provider = new SchemaParameterDescriptorProvider(xmlSchema);
 }
Esempio n. 6
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");
        }
Esempio n. 7
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));
            }
        }
Esempio n. 8
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);
        }
 private static XmlSchema LoadSchema()
 {
   var schema = new XmlSchema();
   using (var stream = typeof(XmlCompletionDataProvider).Assembly.GetManifestResourceStream("InnovatorAdmin.Editor.xslt.xsd"))
   {
     using (var reader = XmlReader.Create(stream))
     {
       schema = XmlSchema.Read(reader, new ValidationEventHandler(SchemaValidation));
       schema.Compile(new ValidationEventHandler(SchemaValidation));
     }
   }
   return schema;
 }
Esempio n. 10
0
        static void ValidateXsd(string [] args)
        {
            XmlTextReader schemaxml = new XmlTextReader(args [1]);
            XSchema       xsd       = XSchema.Read(schemaxml, null);

            schemaxml.Close();
            xsd.Compile(null);
            for (int i = 2; i < args.Length; i++)
            {
                XmlTextReader       xtr = new XmlTextReader(args [i]);
                XmlValidatingReader xvr = new XmlValidatingReader(xtr);
                xvr.Schemas.Add(xsd);
                while (!xvr.EOF)
                {
                    xvr.Read();
                }
                xvr.Close();
            }
        }
    /* Takes a type name, and a valid example of that type, 
       Creates a schema consisting of a single element of that
       type, and validates a bit of xml containing the valid 
       value, with whitespace against that schema.
     
FIXME: Really we want to test the value of whitespace more
       directly that by creating a schema then parsing a string.
     
     */

    public void WhiteSpaceTest(string type, string valid) {
      passed = true;
      XmlSchema schema = new XmlSchema();

      schema.TargetNamespace= "http://example.com/testCase";
      XmlSchemaElement element = new XmlSchemaElement();
      element.Name = "a";
      element.SchemaTypeName = new XmlQualifiedName(type, "http://www.w3.org/2001/XMLSchema");
      schema.Items.Add(element);
      schema.Compile(new ValidationEventHandler(ValidationCallbackOne));

      XmlValidatingReader vr = new XmlValidatingReader(new XmlTextReader(new StringReader("<a xmlns='http://example.com/testCase'>\n\n"+valid+"\n\n</a>" )));
      vr.Schemas.Add(schema);
      vr.ValidationType = ValidationType.Schema;
//      vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
      while(vr.Read()) { };
      vr.Close();
      
      Assert(type + " doesn't collapse whitespace: " + (errorInfo != null ? errorInfo.Message : null), passed);
    }
Esempio n. 12
0
		public static void Main (string[] args)
		{
			if (args.Length < 2) {
				PrintUsage ();
			}

			Stream s = null;

			switch (args[0]) {
				case "ecma":
					s = Assembly.GetExecutingAssembly ().GetManifestResourceStream ("monodoc-ecma.xsd");
					break;
				default:
					Console.WriteLine ("Unknown provider: {0}", args[0]);
					Environment.Exit (0);
					break;
			}

			if (s == null) {
				Console.WriteLine ("ERROR: schema for {0} was not found", args[0]);
				Environment.Exit (1);
			}

			schema = XmlSchema.Read (s, null);
			schema.Compile (null);

			// skip args[0] because it is the provider name
			for (int i = 1; i < args.Length; i++) {
				string arg = args[i];
				if (IsMonodocFile (arg))
					ValidateFile (arg);

				if (Directory.Exists (arg))
				{
					RecurseDirectory (arg);
				}
			}

			Console.WriteLine ("Total validation errors: {0}", errors);
		}
Esempio n. 13
0
        internal XssFilterInfo(string schemaLocation)
        {
            XmlDocument schemaDoc = GetSchemaDoc(schemaLocation);
            XmlReader schemaReader = new XmlNodeReader(schemaDoc);
            try
            {
                Schema = XmlSchema.Read(schemaReader, null);
            }
            finally
            {
                schemaReader.Close();
            }

            Schema.Compile(null);
            if (Type.GetType("Mono.Runtime", false) != null)
            {
                UriAndStyleValidator = new AttributeValueValidator();
                UriAndStyleValidator.Add(schemaDoc, Schema, "URI", Schema.TargetNamespace);
                UriAndStyleValidator.Add(schemaDoc, Schema, "InlineStyle", Schema.TargetNamespace);
                // NOTE: We don't bother with attributes of type "URIs" (plural) because only <object> has such an
                // attribute and we don't allow that element.
            }
        }
Esempio n. 14
0
		public void TestCompile_ZeroLength_TargetNamespace ()
		{
			XmlSchema schema = new XmlSchema ();
			schema.TargetNamespace = string.Empty;
			Assert.IsTrue (!schema.IsCompiled);

			// MS.NET 1.x: The Namespace '' is an invalid URI.
			// MS.NET 2.0: The targetNamespace attribute cannot have empty string as its value.
			schema.Compile (null);
		}
		// .ctor()

		public XmlSchemaDataImporter (DataSet dataset, XmlReader reader)
		{
			this.dataset = dataset;
			dataset.DataSetName = "NewDataSet"; // Initialize always
			schema = XmlSchema.Read (reader, null);
			if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "schema" && reader.NamespaceURI == XmlSchema.Namespace)
				reader.ReadEndElement ();
			schema.Compile (null);
		}
		static XmlSchemaDataImporter ()
		{
			XmlSchema s = new XmlSchema ();
			XmlSchemaAttribute a = new XmlSchemaAttribute ();
			a.Name = "foo";
			a.SchemaTypeName = new XmlQualifiedName ("integer", XmlSchema.Namespace);
			s.Items.Add (a);
			XmlSchemaAttribute b = new XmlSchemaAttribute ();
			b.Name = "bar";
			b.SchemaTypeName = new XmlQualifiedName ("decimal", XmlSchema.Namespace);
			s.Items.Add (b);
			XmlSchemaElement e = new XmlSchemaElement ();
			e.Name = "bar";
			s.Items.Add (e);
			s.Compile (null);
			schemaIntegerType = a.AttributeType as XmlSchemaDatatype;
			schemaDecimalType = b.AttributeType as XmlSchemaDatatype;
			schemaAnyType = e.ElementType as XmlSchemaComplexType;
		}
Esempio n. 17
0
		object Find (XmlSchema schema, XmlQualifiedName name, Type type)
		{
			if (!schema.IsCompiled) {
				schema.Compile (null);
			}

			XmlSchemaObjectTable tbl = null;

			if (type == typeof (XmlSchemaSimpleType) || type == typeof (XmlSchemaComplexType))
				tbl = schema.SchemaTypes;
			else if (type == typeof (XmlSchemaAttribute))
				tbl = schema.Attributes;
			else if (type == typeof (XmlSchemaAttributeGroup))
				tbl = schema.AttributeGroups;
			else if (type == typeof (XmlSchemaElement))
				tbl = schema.Elements;
			else if (type == typeof (XmlSchemaGroup))
				tbl = schema.Groups;
			else if (type == typeof (XmlSchemaNotation))
				tbl = schema.Notations;

			object res = (tbl != null) ? tbl [name] : null;
			if (res != null && res.GetType () != type) return null;
			else return res;
		}
Esempio n. 18
0
        /// <summary>
        /// Generates strongly typed serialization classes for the given schema document
        /// under the given namespace and generates a code compile unit.
        /// </summary>
        /// <param name="xmlSchema">Schema document to generate classes for.</param>
        /// <param name="generateNamespace">Namespace to be used for the generated code.</param>
        /// <param name="commonNamespace">Namespace in which to find common classes and interfaces, 
        /// like ISchemaElement.</param>
        /// <returns>A fully populated CodeCompileUnit, which can be serialized in the language of choice.</returns>
        public static CodeCompileUnit Generate(XmlSchema xmlSchema, string generateNamespace, string commonNamespace)
        {
            if (xmlSchema == null)
            {
                throw new ArgumentNullException("xmlSchema");
            }
            if (generateNamespace == null)
            {
                throw new ArgumentNullException("generateNamespace");
            }

            simpleTypeNamesToClrTypeNames = new Hashtable();
            typeNamesToEnumDeclarations = new Dictionary<string,EnumDeclaration>();
            refToAttributeGroups = new Dictionary<string, XmlSchemaAttributeGroup>();
            enumsToParseMethodClasses = new Dictionary<EnumDeclaration, CodeTypeDeclaration>();

            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            CodeNamespace codeNamespace = new CodeNamespace(generateNamespace);
            codeCompileUnit.Namespaces.Add(codeNamespace);
            codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.CodeDom.Compiler")); // for GeneratedCodeAttribute
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Diagnostics.CodeAnalysis"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Globalization"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Xml"));
            if (commonNamespace != null)
            {
                codeNamespace.Imports.Add(new CodeNamespaceImport(commonNamespace));
            }

            // NOTE: This hash table serves double duty so be sure to have the XSD
            //       type name mapped to the CLR type name *and* the CLR type name
            //       mapped to the same CLR type name.  Look at long and bool for
            //       examples below (and before you ask, no I don't know why DateTime
            //       just works).
            simpleTypeNamesToClrTypeNames.Add("dateTime", "DateTime");
            simpleTypeNamesToClrTypeNames.Add("integer", "int");
            simpleTypeNamesToClrTypeNames.Add("int", "int");
            simpleTypeNamesToClrTypeNames.Add("NMTOKEN", "string");
            simpleTypeNamesToClrTypeNames.Add("string", "string");
            simpleTypeNamesToClrTypeNames.Add("nonNegativeInteger", "long");
            simpleTypeNamesToClrTypeNames.Add("long", "long");
            simpleTypeNamesToClrTypeNames.Add("boolean", "bool");
            simpleTypeNamesToClrTypeNames.Add("bool", "bool");

            xmlSchema.Compile(null);

            foreach (XmlSchemaAttributeGroup schemaAttributeGroup in xmlSchema.AttributeGroups.Values)
            {
                refToAttributeGroups.Add(schemaAttributeGroup.Name, schemaAttributeGroup);
            }

            foreach (XmlSchemaObject schemaObject in xmlSchema.SchemaTypes.Values)
            {
                XmlSchemaSimpleType schemaSimpleType = schemaObject as XmlSchemaSimpleType;
                if (schemaSimpleType != null)
                {
                    ProcessSimpleType(schemaSimpleType, codeNamespace);
                }
            }

            foreach (XmlSchemaObject schemaObject in xmlSchema.SchemaTypes.Values)
            {
                XmlSchemaComplexType schemaComplexType = schemaObject as XmlSchemaComplexType;
                if (schemaComplexType != null)
                {
                    ProcessComplexType(schemaComplexType, codeNamespace);
                }
            }

            foreach (XmlSchemaObject schemaObject in xmlSchema.Elements.Values)
            {
                XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement;
                if (schemaElement != null)
                {
                    ProcessElement(schemaElement, codeNamespace);
                }
            }

            return codeCompileUnit;
        }
		/// <summary>
		/// Loads the schema.
		/// </summary>
		void ReadSchema(XmlReader reader)
		{
			try	{
				schema = XmlSchema.Read(reader, new ValidationEventHandler(SchemaValidation));
				schema.Compile(new ValidationEventHandler(SchemaValidation));
			
				namespaceUri = schema.TargetNamespace;
			} finally {
				reader.Close();
			}
		}
Esempio n. 20
0
		public XsdSimpleRestrictionType (RelaxngDatatype primitive, RelaxngParamList parameters)
		{
			type = new XmlSchemaSimpleType ();
			XmlSchemaSimpleTypeRestriction r =
				new XmlSchemaSimpleTypeRestriction ();
			type.Content = r;
			string ns = primitive.NamespaceURI;
			// Remap XML Schema datatypes namespace -> XML Schema namespace.
			if (ns == "http://www.w3.org/2001/XMLSchema-datatypes")
				ns = XSchema.Namespace;
			r.BaseTypeName = new XmlQualifiedName (primitive.Name, ns);
			foreach (RelaxngParam p in parameters) {
				XmlSchemaFacet f = null;
				string value = p.Value;
				switch (p.Name) {
				case "maxExclusive":
					f = new XmlSchemaMaxExclusiveFacet ();
					break;
				case "maxInclusive":
					f = new XmlSchemaMaxInclusiveFacet ();
					break;
				case "minExclusive":
					f = new XmlSchemaMinExclusiveFacet ();
					break;
				case "minInclusive":
					f = new XmlSchemaMinInclusiveFacet ();
					break;
				case "pattern":
					f = new XmlSchemaPatternFacet ();
					// .NET/Mono Regex has a bug that it does not support "IsLatin-1Supplement"
					// (it somehow breaks at '-').
					value = value.Replace ("\\p{IsLatin-1Supplement}", "[\\x80-\\xFF]");
					break;
				case "whiteSpace":
					f = new XmlSchemaWhiteSpaceFacet ();
					break;
				case "length":
					f = new XmlSchemaLengthFacet ();
					break;
				case "maxLength":
					f = new XmlSchemaMaxLengthFacet ();
					break;
				case "minLength":
					f = new XmlSchemaMinLengthFacet ();
					break;
				case "fractionDigits":
					f = new XmlSchemaFractionDigitsFacet ();
					break;
				case "totalDigits":
					f = new XmlSchemaTotalDigitsFacet ();
					break;
				default:
					throw new RelaxngException (String.Format ("XML Schema facet {0} is not recognized or not supported.", p.Name));
				}
				f.Value = value;
				r.Facets.Add (f);
			}

			// Now we create XmlSchema to handle simple-type
			// based validation (since there is no other way, 
			// because of sucky XmlSchemaSimpleType design).
			schema = new XSchema ();
			XmlSchemaElement el = new XmlSchemaElement ();
			el.Name = "root";
			el.SchemaType = type;
			schema.Items.Add (el);
			schema.Compile (null);
		}
 /// <summary>
 /// Compiles a schema object.
 /// </summary>
 void ReadSchema(XmlSchema newSchema)
 {
     schema = newSchema;
       if (!schema.IsCompiled) schema.Compile(new ValidationEventHandler(SchemaValidation));
       namespaceUri = schema.TargetNamespace;
 }
        /// <summary>
        /// Generates strongly typed serialization classes for the given schema document
        /// under the given namespace and generates a code compile unit.
        /// </summary>
        /// <param name="xmlSchema">Schema document to generate classes for.</param>
        /// <param name="generateNamespace">Namespace to be used for the generated code.</param>
        /// <returns>A fully populated CodeCompileUnit, which can be serialized in the language of choice.</returns>
        public static CodeCompileUnit Generate(XmlSchema xmlSchema, string generateNamespace)
        {
            if (xmlSchema == null)
            {
                throw new ArgumentNullException("xmlSchema");
            }
            if (generateNamespace == null)
            {
                throw new ArgumentNullException("generateNamespace");
            }

            simpleTypeNamesToClrTypeNames = new Hashtable();
            typeNamesToEnumDeclarations = new Hashtable();

            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            CodeNamespace codeNamespace = new CodeNamespace(generateNamespace);
            codeCompileUnit.Namespaces.Add(codeNamespace);
            codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Xml"));

            simpleTypeNamesToClrTypeNames.Add("dateTime", "DateTime");
            simpleTypeNamesToClrTypeNames.Add("uint", "uint");
            simpleTypeNamesToClrTypeNames.Add("int", "int");
            simpleTypeNamesToClrTypeNames.Add("integer", "int");
            simpleTypeNamesToClrTypeNames.Add("NMTOKEN", "string");
            simpleTypeNamesToClrTypeNames.Add("nonNegativeInteger", "uint");
            simpleTypeNamesToClrTypeNames.Add("string", "string");

            xmlSchema.Compile(null);

            foreach (XmlSchemaObject schemaObject in xmlSchema.SchemaTypes.Values)
            {
                XmlSchemaComplexType schemaComplexType = schemaObject as XmlSchemaComplexType;
                if (schemaComplexType != null)
                {
                    ProcessComplexType(schemaComplexType, codeNamespace);
                }

                XmlSchemaSimpleType schemaSimpleType = schemaObject as XmlSchemaSimpleType;
                if (schemaSimpleType != null)
                {
                    ProcessSimpleType(schemaSimpleType, codeNamespace);
                }
            }

            foreach (XmlSchemaObject schemaObject in xmlSchema.Elements.Values)
            {
                XmlSchemaElement schemaElement = schemaObject as XmlSchemaElement;
                if (schemaElement != null)
                {
                    ProcessElement(schemaElement, codeNamespace);
                }
            }

            return codeCompileUnit;
        }
Esempio n. 23
0
		public void AddRollbackIsCompiled ()
		{
			XmlSchemaSet ss = new XmlSchemaSet ();
			ss.Add (new XmlSchema ());
			ss.Compile ();
			Assert.IsTrue (ss.IsCompiled, "#1");
			XmlSchema sc = new XmlSchema (); // compiled one
			sc.Compile (null);
			ss.Add (sc);
			Assert.IsFalse (ss.IsCompiled, "#2");
			ss.Add (new XmlSchema ()); // not-compiled one
			Assert.IsFalse (ss.IsCompiled, "#3");
			XmlSchema s;

			s = new XmlSchema ();
			s.TargetNamespace = "urn:foo";
			XmlSchemaElement el;
			el = new XmlSchemaElement ();
			el.Name = "root";
			s.Items.Add (el);
			ss.Add (s);

			s = new XmlSchema ();
			s.TargetNamespace = "urn:foo";
			el = new XmlSchemaElement ();
			el.Name = "foo";
			s.Items.Add (el);
			ss.Add (s);
			ss.Compile ();
			Assert.IsTrue (ss.IsCompiled, "#4");
			ss.RemoveRecursive (s);
			Assert.IsTrue (ss.IsCompiled, "#5");
		}
Esempio n. 24
0
        public XsdSimpleRestrictionType(RelaxngDatatype primitive, RelaxngParamList parameters)
        {
            type = new XmlSchemaSimpleType();
            XmlSchemaSimpleTypeRestriction r =
                new XmlSchemaSimpleTypeRestriction();

            type.Content = r;
            string ns = primitive.NamespaceURI;

            // Remap XML Schema datatypes namespace -> XML Schema namespace.
            if (ns == "http://www.w3.org/2001/XMLSchema-datatypes")
            {
                ns = XSchema.Namespace;
            }
            r.BaseTypeName = new XmlQualifiedName(primitive.Name, ns);
            foreach (RelaxngParam p in parameters)
            {
                XmlSchemaFacet f     = null;
                string         value = p.Value;
                switch (p.Name)
                {
                case "maxExclusive":
                    f = new XmlSchemaMaxExclusiveFacet();
                    break;

                case "maxInclusive":
                    f = new XmlSchemaMaxInclusiveFacet();
                    break;

                case "minExclusive":
                    f = new XmlSchemaMinExclusiveFacet();
                    break;

                case "minInclusive":
                    f = new XmlSchemaMinInclusiveFacet();
                    break;

                case "pattern":
                    f = new XmlSchemaPatternFacet();
                    // .NET/Mono Regex has a bug that it does not support "IsLatin-1Supplement"
                    // (it somehow breaks at '-').
                    value = value.Replace("\\p{IsLatin-1Supplement}", "[\\x80-\\xFF]");
                    break;

                case "whiteSpace":
                    f = new XmlSchemaWhiteSpaceFacet();
                    break;

                case "length":
                    f = new XmlSchemaLengthFacet();
                    break;

                case "maxLength":
                    f = new XmlSchemaMaxLengthFacet();
                    break;

                case "minLength":
                    f = new XmlSchemaMinLengthFacet();
                    break;

                case "fractionDigits":
                    f = new XmlSchemaFractionDigitsFacet();
                    break;

                case "totalDigits":
                    f = new XmlSchemaTotalDigitsFacet();
                    break;

                default:
                    throw new RelaxngException(String.Format("XML Schema facet {0} is not recognized or not supported.", p.Name));
                }
                f.Value = value;
                r.Facets.Add(f);
            }

            // Now we create XmlSchema to handle simple-type
            // based validation (since there is no other way,
            // because of sucky XmlSchemaSimpleType design).
            schema = new XSchema();
            XmlSchemaElement el = new XmlSchemaElement();

            el.Name       = "root";
            el.SchemaType = type;
            schema.Items.Add(el);
            schema.Compile(null);
        }
Esempio n. 25
0
        private string GenExportedXSD(string stnName, PdeExports pdeExports)
        {
            // initialize schema
            string schemaNamespace = "http://www.w3.org/2001/XMLSchema";

            Schema.XmlSchema expSchema = new Schema.XmlSchema();

            // create STN node (root node)
            Schema.XmlSchemaSequence stnElementSequence = CreateSequenceElement(expSchema, stnName);
            Schema.XmlSchemaAll      field = null;
            Schema.XmlSchemaAll      table = null;

            foreach (DomainExportItem expDomain in pdeExports.Items)
            {
                if (expDomain.Items == null || expDomain.Items.Count == 0)
                {
                    continue;
                }

                foreach (ExportItem expItem in expDomain.Items)
                {
                    if (!expItem.IsUsed)
                    {
                        continue;
                    }

                    switch (expItem.MapType)
                    {
                    case MapType.SingleCell:
                        #region field
                        if (field == null)
                        {
                            field = CreateElement(stnElementSequence, MarkupConstant.PdeExportField);
                        }

                        // create field informations
                        Schema.XmlSchemaElement fieldElement = new Schema.XmlSchemaElement();
                        fieldElement.Name           = expItem.EncodeTreeNodeName;
                        fieldElement.SchemaTypeName = new System.Xml.XmlQualifiedName(GetXsdDataType(expItem.DataType), schemaNamespace);
                        field.Items.Add(fieldElement);
                        #endregion
                        break;

                    case MapType.Table:
                        #region table
                        if (table == null)
                        {
                            table = CreateElement(stnElementSequence, MarkupConstant.PdeExportTable);
                        }

                        // create table informations
                        Schema.XmlSchemaElement tableElement = new Schema.XmlSchemaElement();
                        tableElement.MinOccurs       = 0;
                        tableElement.MaxOccursString = "unbounded";
                        tableElement.Name            = expItem.EncodeTreeNodeName;
                        table.Items.Add(tableElement);

                        Schema.XmlSchemaComplexType tableElementType = new Schema.XmlSchemaComplexType();
                        tableElementType.IsMixed = false;
                        Schema.XmlSchemaAll tableElementAll = new Schema.XmlSchemaAll();
                        tableElementType.Particle = tableElementAll;
                        tableElement.SchemaType   = tableElementType;

                        // gen column informations
                        if (expItem.Columns != null && expItem.Columns.Count > 0)
                        {
                            foreach (ColumnExportItem col in expItem.Columns)
                            {
                                if (!col.IsUsed)
                                {
                                    continue;
                                }
                                Schema.XmlSchemaElement colElement = new Schema.XmlSchemaElement();
                                colElement.Name           = col.EncodeTreeNodeName;
                                colElement.SchemaTypeName = new System.Xml.XmlQualifiedName(GetXsdDataType(col.DataType), schemaNamespace);
                                tableElementAll.Items.Add(colElement);
                            }
                        }
                        #endregion
                        break;

                    case MapType.Chart:
                        break;

                    default:
                        break;
                    }
                }
            }

            // complie schema
            expSchema.Compile(new Schema.ValidationEventHandler(ValidationEventHandler));

            // write schem to xsd file
            string xsdFilePath = string.Format("{0}\\{1}.xsd", AssetManager.FileAdapter.TemporaryFolderPath, Guid.NewGuid().ToString());
            using (System.IO.FileStream stream = new System.IO.FileStream(xsdFilePath, System.IO.FileMode.Create))
            {
                expSchema.Write(stream);
                stream.Close();
            }

            return(xsdFilePath);
        }
Esempio n. 26
0
        /// <summary>
        /// Executes the code generator.  Called from either the command line exe or the VS.NET wizard.  Only public function.
        /// </summary>
        /// <param name="xsdFile">Path to the XSD file stored on disk</param>
        /// <param name="language">Language for generated code</param>
        /// <param name="genNamespace">.NET namespace containing the generated types</param>
        /// <param name="fileName">File to be generated.  If null, namespace name is used</param>
        /// <param name="outputLocation">Location for the generated output file</param>
        /// <param name="constructRequiredSchema">Build a schema compliancy function -- MakeSchemaCompliant -- into each class</param>
        /// <param name="depthFirstTraversalHooks">Add DepthFirstTraversal hooks to fire custom DepthFirstTraversal events on each generated class</param>
        /// <param name="defaultInitialization">Set schema default values in class constructors</param>
        /// <param name="separateImportedNamespaces">Searate out imported namespaces into their own source files.  Default is all types in one file.</param>
        /// <param name="namespaceTable">Namespace map table.  Null if no imported namespaces exist</param>
        /// <param name="filenameTable">Filenames matching the namespaceTable.  Null if no imported namespaces exist -- and optional.</param>
        /// <param name="partialKeyword">put the .NET 2.0 partial keyword on every class</param>
        /// <param name="optionEElements"></param>
        /// <param name="acordLookupCodesFile">ACORD lookup codes file -- public</param>
        /// <param name="acordLookupCodesFilePrivate">ACORD lookup codes file -- private</param>
        /// <returns>result string</returns>
        public string[] Execute(string xsdFile, Language language, string genNamespace, string fileName,
            string outputLocation, bool constructRequiredSchema, bool depthFirstTraversalHooks, bool defaultInitialization,
            ref Hashtable namespaceTable, Hashtable filenameTable, bool partialKeyword, List<string> optionEElements, string acordLookupCodesFile, string acordLookupCodesFilePrivate)
        {
            FileStream schemaFile = null;

            try
            {
                schemaFile = new FileStream(xsdFile, FileMode.Open, FileAccess.Read);
                if (schemaFile == null) throw new XSDObjectGenException("Could not open the XSD schema file: " + xsdFile);

                schema = XmlSchema.Read(schemaFile, new ValidationEventHandler(ShowCompileError));
                schema.Compile(new ValidationEventHandler(ShowCompileError));

                elementFormDefault = schema.ElementFormDefault;
                attributeFormDefault = schema.AttributeFormDefault;

                if (language == Language.VB)
                {
                    code = (LanguageBase)new VBTemplate();
                }
                else if (language == Language.CS)
                {
                    code = (LanguageBase)new CSharpTemplate();
                }
                else
                {
                    throw new XSDObjectGenException(string.Format("Language {0} not supported.", language.ToString()));
                }

                if (!string.IsNullOrEmpty(acordLookupCodesFile))
                {
                    acordLookup = new XmlDocument();
                    try
                    {
                        acordLookup.Load(acordLookupCodesFile);
                    }
                    catch (Exception)
                    {
                        throw new XSDObjectGenException("Bad ACORD lookup file path or file");
                    }
                }

                if (!string.IsNullOrEmpty(acordLookupCodesFilePrivate))
                {
                    acordLookupPrivate = new XmlDocument();
                    try
                    {
                        acordLookupPrivate.Load(acordLookupCodesFilePrivate);
                    }
                    catch (Exception)
                    {
                        throw new XSDObjectGenException("Bad ACORD private codes lookup file path or file");
                    }
                }

                optionDefaultInitialization = defaultInitialization;
                optionConstructRequiredSchema = constructRequiredSchema;
                optionDepthFirstTraversalHooks = depthFirstTraversalHooks;
                LanguageBase.partialClasses = partialKeyword;
                globalComplexTypeClasses = new Hashtable();
                globalQualifiedComplexTypeClasses = new Hashtable();
                globalQualifiedAbstractTypeClasses = new Hashtable();
                enumerations = new Hashtable();
                enumerableClasses = new Hashtable();
                classesReferencingAbstractTypes = new Hashtable();
                ArrayList parentClassStack = new ArrayList();  // arraylist to collect a stack of parent owner .NET classes for  nested complexTypes 
                Globals.globalSchemaTypeTable.Clear();			// clear globals schema type table as it's a global object created at assembly load scope
                Globals.globalSeparateImportedNamespaces = false;   // means we have imported namespace and will have multiple source files
                Globals.globalClrNamespaceList.Clear();

                // Get list of all imported schemas -- to be used only if separateImportedNamespaces = true
                // Add the main xsd namespace.  If separateImportedNamespaces is false, there will be only
                //    one .net file generated with all of the types from all the xsd namespaces.  Otherwise multiple files. 
                //    First namespace in the list is the namespace for the base leaf schema -- for which code is being generated.
                ArrayList references = new ArrayList();
                if (namespaceTable != null)
                {
                    if (schema.TargetNamespace != null)
                        genNamespace = (string)namespaceTable[schema.TargetNamespace];  // in case it was changed while changing imported ns names
                    else
                        genNamespace = (string)namespaceTable[""];
                }

                if (schema.TargetNamespace != null)
                {
                    namespaces.Add(schema.TargetNamespace, references);
                    namespacesList.Add(schema.TargetNamespace);
                    xsdNsToClrNs.Add(schema.TargetNamespace, genNamespace);
                }
                else
                {
                    // targetNamespace can be null
                    namespaces.Add("", references);
                    namespacesList.Add("");
                    xsdNsToClrNs.Add("", genNamespace);
                }

                // Break down the imported namespaces if any.  There will be one .cs or .vb file generated for each xsd namespace.
                // Set the globalSelectedImportedNamespaces flag to determine if we generate just one file or many files.
                RecurseImportedNamespaces(schema, references);
                if (namespacesList.Count > 1 && namespaceTable == null)
                {
                    namespaceTable = xsdNsToClrNs;
                    return null;
                }
                else if (namespaceTable != null)
                {
                    xsdNsToClrNs = namespaceTable;
                }

                foreach (string clrNs in xsdNsToClrNs.Values)
                {
                    Globals.globalClrNamespaceList.Add(clrNs);
                }

                /*******/
                //   Walk through, prepare and build the global class collections from the xsd complexTypes 
                //   contained in the global scope -- child of the <schema> element.  Point of this stuff is 
                //   to handle all the combination of naming conflicts.
                //      Build and populate these structures
                //          globalQualifiedAbstractTypeClasses
                //          globalQualifiedComplexTypeClasses
                //          globalComplexTypeClasses
                //          globalSchemaTypeTable
                /*******/

                foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                {
                    if (schemaType is XmlSchemaComplexType)
                    {
                        string dotnetTypeName = CalculateUniqueTypeOrFieldName(schemaType.Name, schemaType.QualifiedName.Namespace, globalComplexTypeClasses);
                        globalComplexTypeClasses.Add(dotnetTypeName, schemaType.Name);

                        GlobalSchemaType gst = new GlobalSchemaType(schemaType.QualifiedName.Namespace, schemaType.Name, GlobalXsdType.ComplexType,
                            (string)xsdNsToClrNs[schemaType.QualifiedName.Namespace], dotnetTypeName);
                        Globals.globalSchemaTypeTable.Add(gst.XsdNamespaceAndTypeName, gst);

                        if (globalQualifiedComplexTypeClasses[schemaType.QualifiedName] == null)
                        {
                            globalQualifiedComplexTypeClasses.Add(schemaType.QualifiedName, dotnetTypeName);

                            // collect the list of types marked as abstract.  This is needed to later add XmlIncludeAttribute to their usage.
                            if (((XmlSchemaComplexType)schemaType).IsAbstract)
                            {
                                globalQualifiedAbstractTypeClasses.Add(schemaType.QualifiedName, new Hashtable());
                            }
                        }
                    }
                }
                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    if (element.ElementType is XmlSchemaComplexType)
                    {
                        XmlSchemaComplexType complexType = (XmlSchemaComplexType)element.ElementType;

                        string dotnetTypeName = element.Name;

                        if (globalComplexTypeClasses[element.Name] == null)
                        {
                            // Each namespace can have one global schema level CT (schema type) and global schema level element WITH THE SAME NAME.
                            //  We get here assuming a complexType with the same name hasn't already been added (which will be a .NET class).
                            dotnetTypeName = CalculateUniqueTypeOrFieldName(element.Name, element.QualifiedName.Namespace, globalComplexTypeClasses);
                            globalComplexTypeClasses.Add(dotnetTypeName, element.Name);
                        }

                        GlobalSchemaType gst = new GlobalSchemaType(element.QualifiedName.Namespace, element.Name, GlobalXsdType.Element,
                                (string)xsdNsToClrNs[element.QualifiedName.Namespace], dotnetTypeName);
                        Globals.globalSchemaTypeTable.Add(gst.XsdNamespaceAndTypeName, gst);

                        if (globalQualifiedComplexTypeClasses[element.QualifiedName] == null)
                        {
                            globalQualifiedComplexTypeClasses.Add(element.QualifiedName, dotnetTypeName);
                        }
                        else
                        {
                            // Each namespace can have one global schema level CT (schema type) and global schema level element WITH THE SAME NAME.
                            //  Hence schemaType.QualifiedName == element.QualifiedName for this scenerio.  Use a special Globals.ELELENT_DELIMINATOR to flag this.
                            globalQualifiedComplexTypeClasses.Add(Globals.ELELENT_DELIMINATOR + element.QualifiedName, dotnetTypeName);
                        }
                    }
                    else if (element.ElementType is XmlSchemaSimpleType)
                    {
                        XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)element.ElementType;
                        if (IsEnumeration(simpleType))
                        {
                            GlobalSchemaType gst = new GlobalSchemaType(element.QualifiedName.Namespace, element.Name, GlobalXsdType.Enum,
                                (string)xsdNsToClrNs[element.QualifiedName.Namespace], element.Name);
                            Globals.globalSchemaTypeTable.Add(gst.XsdNamespaceAndTypeName, gst);
                        }
                    }
                }
                foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                {
                    if (schemaType is XmlSchemaSimpleType)
                    {
                        XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)schemaType;
                        if (IsEnumeration(simpleType))
                        {
                            GlobalSchemaType gst = new GlobalSchemaType(simpleType.QualifiedName.Namespace, simpleType.Name, GlobalXsdType.Enum,
                                (string)xsdNsToClrNs[simpleType.QualifiedName.Namespace], simpleType.Name);
                            if (Globals.globalSchemaTypeTable[gst.XsdNamespaceAndTypeName] == null)
                                Globals.globalSchemaTypeTable.Add(gst.XsdNamespaceAndTypeName, gst);
                        }
                    }
                }

                outFiles = new string[namespaces.Count];
                int iFiles = 0;

                // Walk through all of the schema namespaces and generate .net types
                for (int i = 0; i < namespacesList.Count; i++)
                {
                    /*******/
                    // Pass1: 
                    // Walk through and add collect infomation for forward declarations (where required),
                    //  collection classes, and enumerations.  The code will be added later.
                    // There are two kinds of complex types.  
                    //	1. ComplexTypes globally defined and "named" in the schema that are not tied to an XML element name.
                    //	2. Globally defined xsd:elements that are complex types and are linked to an xml element
                    // First build classes for the global types, then traverse the elements and add those types.
                    // Note: There are actually 3 different types of ComplexTypes.  The third is a locally defined
                    //  ComplexType that are not a child of <schema>.  These are collected later in the childClasses
                    //  collection.
                    /*******/

                    string ns = (string)namespacesList[i];
                    enumerations.Clear();
                    bool optionE = optionEElements != null && optionEElements.Count > 0;
                    ElementsSubset es = new ElementsSubset();

                    // Pass0.  Uses Pass0 routines.  Only used if Option E is sent in.
                    if (optionE)
                    {
                        // Handle special optionE processing.  Parse down and build the references for this element
                        foreach (XmlSchemaElement element in schema.Elements.Values)
                        {
                            if (optionEElements.Contains(element.QualifiedName.Name))
                            {
                                XmlSchemaComplexType complexType = (XmlSchemaComplexType)element.ElementType;

                                if (!es.Elements.ContainsKey(element.QualifiedName.Name))
                                {
                                    es.Elements.Add(element.QualifiedName.Name, element.QualifiedName.Name);
                                    if (!string.IsNullOrEmpty(complexType.QualifiedName.Name) && !es.ComplexTypes.ContainsKey(complexType.QualifiedName.Name))
                                        es.ComplexTypes.Add(complexType.QualifiedName.Name, complexType.QualifiedName.Name);
                                    ParseComplexTypePass0(complexType, element.QualifiedName.Name, element.QualifiedName, element.QualifiedName.Namespace, es);
                                }
                            }
                        }
                    }

                    // Pass1 officially starts here.  Uses Pass1 routines.

                    foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                    {
                        // Add global schema type enumerations.  Locally scoped ones will be added later during ParseComplexTypePass1.
                        if (schemaType is XmlSchemaSimpleType && (!Globals.globalSeparateImportedNamespaces || ns == schemaType.QualifiedName.Namespace))
                        {
                            XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)schemaType;
                            if (optionE && !es.SimpleTypes.ContainsKey(simpleType.Name)) continue;  // only build specific classes

                            if (IsEnumeration(simpleType))
                            {
                                string globalEnumName = ParseEnumeration1(simpleType, simpleType.Name);
                            }
                        }
                    }
                    foreach (XmlSchemaElement element in schema.Elements.Values)
                    {
                        // Add global schema element enumerations.  Locally scoped ones will be added later during ParseComplexTypePass1.
                        if (element.ElementType is XmlSchemaSimpleType && (!Globals.globalSeparateImportedNamespaces || ns == element.QualifiedName.Namespace))
                        {
                            XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)element.ElementType;
                            if (optionE && !es.SimpleTypes.ContainsKey(simpleType.Name)) continue;  // only build specific classes

                            if (IsEnumeration(simpleType))
                            {
                                string globalEnumName = ParseEnumeration1(simpleType, element.Name);
                            }
                        }
                    }

                    // now deep-dive and parse into each global schema element and type

                    foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                    {
                        if (schemaType is XmlSchemaComplexType && (!Globals.globalSeparateImportedNamespaces || ns == schemaType.QualifiedName.Namespace))
                        {
                            if (optionE && !es.ComplexTypes.ContainsKey(schemaType.QualifiedName.Name)) continue;  // only build specific classes

                            parentClassStack.Clear();
                            string dotnetTypeName = (string)globalQualifiedComplexTypeClasses[schemaType.QualifiedName];
                            ParseComplexTypePass1((XmlSchemaComplexType)schemaType, dotnetTypeName, parentClassStack, schemaType.QualifiedName, ns);
                        }
                    }
                    foreach (XmlSchemaElement element in schema.Elements.Values)
                    {
                        if (element.ElementType is XmlSchemaComplexType &&
                            (!Globals.globalSeparateImportedNamespaces || ns == element.QualifiedName.Namespace) &&
                            (element.SchemaTypeName.Name == null || element.SchemaTypeName.Name == ""))
                        {
                            if (optionE && !es.Elements.ContainsKey(element.QualifiedName.Name)) continue;  // only build specific classes

                            // If element.SchemaTypeName.Name is set, then this is a global element with it's type set to a schema type.  
                            //  i.e. <xs:element name="DataServiceResponse" type="DataServiceResponseType" />
                            //  This results in a simple class in code which inherits from the SchemaType and no child fields -- so don't do anything further

                            parentClassStack.Clear();
                            XmlSchemaComplexType complexType = (XmlSchemaComplexType)element.ElementType;

                            string dotnetTypeName = GlobalElementToClrMap(element.QualifiedName);
                            ParseComplexTypePass1(complexType, dotnetTypeName, parentClassStack, element.QualifiedName, ns);
                        }
                    }

                    // ****************************
                    // Start writing out code
                    // ****************************

                    FileStream classFile = null;

                    if (outputLocation == "" || outputLocation == null)
                        outFiles[iFiles] = "";
                    else if (outputLocation[outputLocation.Length - 1] == '\\')
                        outFiles[iFiles] = outputLocation;
                    else if (outputLocation[outputLocation.Length - 1] != '\\')
                        outFiles[iFiles] = outputLocation + "\\";

                    string codeFile;
                    string targetNamespace;
                    string dotnetNamespace;

                    if (i == 0 && namespacesList.Count == 1)  // no imported namespaces
                    {
                        // first namespace in the list is the main xsd namespace we're building from
                        targetNamespace = ns;
                        codeFile = genNamespace;  // this is the default filename if not overriden with /f or /z
                        dotnetNamespace = genNamespace;

                        // use "fileName" for the main xsd generated .net file, if passed in from UI
                        if (fileName != null && fileName != "")
                            codeFile = fileName;
                    }
                    else
                    {
                        // imported namespaces
                        targetNamespace = ns;
                        dotnetNamespace = (string)xsdNsToClrNs[targetNamespace];
                        codeFile = (string)xsdNsToClrNs[targetNamespace];  // this is the default filename if not overriden with /f or /z
                        if (filenameTable != null && filenameTable.Count > 0)
                            codeFile = (string)filenameTable[targetNamespace];  // /z override
                    }


                    if (language == Language.VB)
                    {
                        if (!codeFile.ToLower().EndsWith(".vb"))
                            codeFile = codeFile + ".vb";
                    }
                    else //(language == Language.CS)
                    {
                        if (!codeFile.ToLower().EndsWith(".cs"))
                            codeFile = codeFile + ".cs";
                    }

                    outFiles[iFiles] = outFiles[iFiles] + codeFile;
                    classFile = new FileStream(outFiles[iFiles], FileMode.Create);
                    outStream = new StreamWriter(classFile);

                    // Add namespace, using statement, forward declarations, and enumerations
                    string schemaFileName = schemaFile.Name;
                    int slashIndex = 0;
                    while ((slashIndex = schemaFileName.IndexOf("\\")) >= 0)
                        schemaFileName = schemaFileName.Substring(slashIndex + 1);

                    if (genNamespace == null || genNamespace == "")
                    {
                        // the VB case where explicit namespaces are not in the code
                        code.NamespaceHeaderCode(outStream, genNamespace, schemaFileName, null,
                            targetNamespace, enumerations, optionDepthFirstTraversalHooks, (ArrayList)namespaces[targetNamespace]);
                    }
                    else
                    {
                        code.NamespaceHeaderCode(outStream, dotnetNamespace, schemaFileName, null,
                            targetNamespace, enumerations, optionDepthFirstTraversalHooks, (ArrayList)namespaces[targetNamespace]);
                    }

                    // Re-add all the globally scoped enumerations to the enumerations list.  This is done again so in Pass2 we handle locally scoped
                    //  simpleType enumerations that have duplicate names.  We go through the name calculation again for duplicate enums -- as a way
                    //  to match up the enum type name (when duplicates occur) with the enum field variables.  The assumption is made that the parsing
                    //  order of Pass1 is equal to that of Pass2 -- otherwise the duplicate locally scoped enums won't match their respective
                    //  enumeration type that was collected during Pass1.  
                    //  Note that in most schemas there won't be locally scoped duplicate enumeration names -- so this really won't matter.  And if there is,
                    //  it's probably not a good schema design.
                    enumerations.Clear();  // clear enumerations list as they will be recollected to properly account for locally scoped duplicates
                    foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                    {
                        if (schemaType is XmlSchemaSimpleType && (!Globals.globalSeparateImportedNamespaces || ns == schemaType.QualifiedName.Namespace))
                        {
                            XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)schemaType;
                            if (optionE && !es.SimpleTypes.ContainsKey(simpleType.Name)) continue;  // only build specific classes

                            if (IsEnumeration(simpleType) && (!Globals.globalSeparateImportedNamespaces || ns == simpleType.QualifiedName.Namespace))
                                enumerations.Add(LanguageBase.ReplaceInvalidChars(simpleType.Name), "");
                        }
                    }
                    foreach (XmlSchemaElement element in schema.Elements.Values)
                    {
                        if (element.ElementType is XmlSchemaSimpleType && (!Globals.globalSeparateImportedNamespaces || ns == element.QualifiedName.Namespace))
                        {
                            XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)element.ElementType;
                            if (optionE && !es.SimpleTypes.ContainsKey(simpleType.Name)) continue;  // only build specific classes

                            if (IsEnumeration(simpleType) && (!Globals.globalSeparateImportedNamespaces || ns == element.QualifiedName.Namespace))
                            {
                                if (enumerations[LanguageBase.ReplaceInvalidChars(element.Name)] == null)
                                    enumerations.Add(LanguageBase.ReplaceInvalidChars(element.Name), "");
                            }
                        }
                    }

                    /*******/
                    // Pass2: 
                    //  Walk through and build code for all complex types (these will be classes in .NET)
                    //  First add the globally defined classes, then add the classes for the schema level 
                    //  ComplexType elements.
                    /*******/

                    foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                    {
                        if (schemaType is XmlSchemaComplexType && (!Globals.globalSeparateImportedNamespaces || ns == schemaType.QualifiedName.Namespace))
                        {
                            if (optionE && !es.ComplexTypes.ContainsKey(schemaType.QualifiedName.Name)) continue;  // only build specific classes

                            parentClassStack.Clear();
                            string dotnetTypeName = (string)globalQualifiedComplexTypeClasses[schemaType.QualifiedName];

                            // If schema type and a global element have the same name, don't create a class for the element
                            // This will be a special case where the schema type .net class has both XmlTypeAttribute and XmlElementAttribute.
                            bool globalElementAndSchemaTypeHaveSameName = false;
                            if (schema.Elements[schemaType.QualifiedName] != null)
                                globalElementAndSchemaTypeHaveSameName = true;

                            ParseComplexTypePass2((XmlSchemaComplexType)schemaType, dotnetTypeName, schemaType.Name, true, false,
                                schemaType.QualifiedName.Namespace, parentClassStack, "", "", false, globalElementAndSchemaTypeHaveSameName);
                        }
                    }
                    foreach (XmlSchemaElement element in schema.Elements.Values)
                    {
                        if (element.ElementType is XmlSchemaComplexType && (!Globals.globalSeparateImportedNamespaces || ns == element.QualifiedName.Namespace))
                        {
                            if (optionE && !es.Elements.ContainsKey(element.QualifiedName.Name)) continue;  // only build specific classes

                            parentClassStack.Clear();
                            string dotnetTypeName = GlobalElementToClrMap(element.QualifiedName);
                            string elementSchemaType = "";

                            if (element.SchemaTypeName.Name != null && element.SchemaTypeName.Name != "")
                            {
                                // global element with it's type set to a schema type
                                elementSchemaType = (string)globalQualifiedComplexTypeClasses[element.SchemaTypeName];

                                // If schema type and global element have the same name, don't create a class for the element
                                // This will be a special case where the schema type .net class has both XmlTypeAttribute and XmlElementAttribute.
                                if (element.QualifiedName == element.SchemaTypeName)
                                    continue;
                            }

                            //		// don't generate a class for root level schema-typed elements that are abstract -- since these classes can't be created externally.
                            //		if (elementSchemaType != "" && element.IsAbstract)
                            //			continue; 

                            ParseComplexTypePass2((XmlSchemaComplexType)element.ElementType, dotnetTypeName, element.Name, false, false,
                                element.QualifiedName.Namespace, parentClassStack, elementSchemaType, element.SchemaTypeName.Namespace, element.IsNillable, false);
                        }
                    }

                    code.NamespaceTrailerCode(outStream, dotnetNamespace);
                    outStream.Flush();

                    iFiles++;
                    outStream.Close();
                    schemaFile.Close();
                    // Finished writing out .net for a xsd namespace
                }	// End of foreach imported namespace

                System.Diagnostics.EventLog.WriteEntry("XSDSchemaParser", String.Format("Done. Writing files"));
                return outFiles;
            }
            catch (XSDObjectGenException e)
            {
                // code logic specific exceptions
                throw e;
            }
            catch (FileNotFoundException e)
            {
                // inbound xsd file cannot be loaded
                throw new XSDObjectGenException(e.Message);
            }
            catch (UnauthorizedAccessException e)
            {
                // security 
                throw new XSDObjectGenException(e.Message);
            }
            catch (XmlSchemaException e)
            {
                // xsd schema compiler exception.  xsd has some type of error.
                if (outStream != null)
                {
                    outStream.WriteLine();
                    outStream.WriteLine("LineNumber = {0}", e.LineNumber);
                    outStream.WriteLine("LinePosition = {0}", e.LinePosition);
                    outStream.WriteLine("Message = {0}", e.Message);
                    outStream.WriteLine("Source = {0}", e.Source);
                }

                throw new XSDObjectGenException(string.Format(
                    ".NET Framework XSD Schema compile error.\nError occurred : {0}", e.Message));
            }
            catch (XmlException e)
            {
                // bad xml document -- schema cannot be read because it's not valid xml
                if (outStream != null)
                {
                    outStream.WriteLine();
                    outStream.WriteLine("LineNumber = {0}", e.LineNumber);
                    outStream.WriteLine("LinePosition = {0}", e.LinePosition);
                    outStream.WriteLine("Message = {0}", e.Message);
                    outStream.WriteLine("Source = {0}", e.Source);
                }

                throw new XSDObjectGenException(string.Format(
                    ".NET Framework could not read the XSD file.  Bad XML file.\nError occurred : {0}", e.Message));
            }
            catch (Exception e)
            {
                // unexpected exceptions
                System.Diagnostics.EventLog.WriteEntry("Unexpected XSDObjectGen exception", e.Message, System.Diagnostics.EventLogEntryType.Error);

                if (outStream != null)
                {
                    outStream.WriteLine();
                    outStream.WriteLine("Error message : {0}", e.Message);
                    outStream.WriteLine("Source : {0}", e.Source);
                    outStream.WriteLine("Stack : {0}", e.StackTrace);
                }

                throw new Exception("Unexpected XSDObjectGen Exception", e);
            }
            finally
            {
                if (outStream != null) outStream.Close();
                if (schemaFile != null) schemaFile.Close();
            }
        }
Esempio n. 27
0
 internal XmlSchema Add(string ns, SchemaInfo schemaInfo, XmlSchema schema, bool compile) {
     int errorCount = 0;
     if (schema != null) {
         if (schema.ErrorCount == 0 && compile) {
             schema.Compile(this, nameTable, schemaNames, validationEventHandler, ns, schemaInfo, true);
             ns = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace;
         }
         errorCount += schema.ErrorCount;
     } 
     else {
         errorCount += schemaInfo.ErrorCount;
         ns = NameTable.Add(ns);
     }
     if (errorCount == 0) {
         XmlSchemaCollectionNode node = new XmlSchemaCollectionNode();
         node.NamespaceURI = ns;
         node.SchemaInfo = schemaInfo; 
         node.Schema = schema; 
         Add(ns, node);
         return schema;
     }
     return null;
 }