ExportTypeMapping() public méthode

public ExportTypeMapping ( XmlTypeMapping xmlTypeMapping ) : void
xmlTypeMapping XmlTypeMapping
Résultat void
Exemple #1
0
        public static CodeNamespace GenerateCode(Stream schemaStream, string classesNamespace)
        {
            // Open schema
            XmlSchema schema = XmlSchema.Read(schemaStream, null);
            XmlSchemas schemas = new XmlSchemas();
            schemas.Add(schema);
            schemas.Compile(null, true);

            // Generate code
            CodeNamespace code = new CodeNamespace(classesNamespace);
            XmlSchemaImporter importer = new XmlSchemaImporter(schemas);
            XmlCodeExporter exporter = new XmlCodeExporter(code);
            foreach (XmlSchemaElement element in schema.Elements.Values) {
                XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName);
                exporter.ExportTypeMapping(mapping);
            }

            // Modify generated code using extensions
            schemaStream.Position = 0; // Rewind stream to the start
            XPathDocument xPathDoc = new XPathDocument(schemaStream);
            CodeGenerationContext context = new CodeGenerationContext(code, schema, xPathDoc);

            new ExplicitXmlNamesExtension().ApplyTo(context);
            new DocumentationExtension().ApplyTo(context);
            new FixXmlTextAttributeExtension().ApplyTo(context);
            new ArraysToGenericExtension().ApplyTo(context);
            new CamelCaseExtension().ApplyTo(context);
            new GetByIDExtension().ApplyTo(context);

            return code;
        }
Exemple #2
0
 public static CodeNamespace Process(string xsdFile,
     string targetNamespace)
 {
     // Load the XmlSchema and its collection.
     XmlSchema xsd;
     using (FileStream fs = new FileStream("Untitled1.xsd", FileMode.Open))
     {
         xsd = XmlSchema.Read(fs, null);
         xsd.Compile(null);
     }
     XmlSchemas schemas = new XmlSchemas();
     schemas.Add(xsd);
     // Create the importer for these schemas.
     XmlSchemaImporter importer = new XmlSchemaImporter(schemas);
     // System.CodeDom namespace for the XmlCodeExporter to put classes in.
     CodeNamespace ns = new CodeNamespace(targetNamespace);
     XmlCodeExporter exporter = new XmlCodeExporter(ns);
     // Iterate schema top-level elements and export code for each.
     foreach (XmlSchemaElement element in xsd.Elements.Values)
     {
         // Import the mapping first.
         XmlTypeMapping mapping = importer.ImportTypeMapping(
           element.QualifiedName);
         // Export the code finally.
         exporter.ExportTypeMapping(mapping);
     }
     return ns;
 }
Exemple #3
0
        public static void GenerateCode(string xsdFilepath, string codeOutPath, string nameSpace)
        {
            FileStream stream = File.OpenRead(xsdFilepath);
            XmlSchema xsd = XmlSchema.Read(stream, ValidationCallbackOne);

            // Remove namespaceattribute from schema
            xsd.TargetNamespace = null;

            XmlSchemas xsds = new XmlSchemas { xsd };
            XmlSchemaImporter imp = new XmlSchemaImporter(xsds);
            //imp.Extensions.Add(new CustomSchemaImporterExtension());

            CodeNamespace ns = new CodeNamespace(nameSpace);
            XmlCodeExporter exp = new XmlCodeExporter(ns);

            foreach (XmlSchemaObject item in xsd.Items)
            {
                if (!(item is XmlSchemaElement))
                    continue;

                XmlSchemaElement xmlSchemaElement = (XmlSchemaElement)item;
                XmlQualifiedName xmlQualifiedName = new XmlQualifiedName(xmlSchemaElement.Name, xsd.TargetNamespace);
                XmlTypeMapping map = imp.ImportTypeMapping(xmlQualifiedName);

                exp.ExportTypeMapping(map);
            }

            // Remove all the attributes from each type in the CodeNamespace, except
            // System.Xml.Serialization.XmlTypeAttribute
            RemoveAttributes(ns);

            ToProperties(ns);

            CodeCompileUnit compileUnit = new CodeCompileUnit();

            compileUnit.Namespaces.Add(ns);
            CSharpCodeProvider provider = new CSharpCodeProvider();

            using (StreamWriter sw = new StreamWriter(codeOutPath, false))
            {
                CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions();
                provider.GenerateCodeFromCompileUnit(compileUnit, sw, codeGeneratorOptions);
            }
        }
Exemple #4
0
        private static void GenerateClasses(CodeNamespace code, XmlSchema schema)
        {
            XmlSchemas schemas = new XmlSchemas();
            schemas.Add(schema);
            XmlSchemaImporter importer = new XmlSchemaImporter(schemas);

            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            CodeGenerationOptions options = CodeGenerationOptions.None;
            XmlCodeExporter exporter = new XmlCodeExporter(code, codeCompileUnit, options);

            foreach (XmlSchemaObject item in schema.Items)
            {
                XmlSchemaElement element = item as XmlSchemaElement;

                if (element != null)
                {
                    XmlQualifiedName name = new XmlQualifiedName(element.Name, schema.TargetNamespace);
                    XmlTypeMapping map = importer.ImportTypeMapping(name);
                    exporter.ExportTypeMapping(map);
                }
            }
        }
Exemple #5
0
        private CodeNamespace GeneratedClassFromStream(Stream stream, string nameSpace)
        {
            XmlSchema xsd;
            stream.Seek(0, SeekOrigin.Begin);
            using (stream)
            {

                xsd = XmlSchema.Read(stream, null);
            }

            XmlSchemas xsds = new XmlSchemas();

            xsds.Add(xsd);
            xsds.Compile(null, true);
            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds);

            // create the codedom
            CodeNamespace codeNamespace = new CodeNamespace(nameSpace);
            XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace);
            List<XmlTypeMapping> maps = new List<XmlTypeMapping>();
            foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values)
            {
                maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName));
            }
            foreach (XmlSchemaElement schemaElement in xsd.Elements.Values)
            {
                maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName));
            }
            foreach (XmlTypeMapping map in maps)
            {
                codeExporter.ExportTypeMapping(map);
            }

            this.RemoveUnusedStuff(codeNamespace);

            return codeNamespace;
        }
        public void Run(string src, string dest)
        {
            // Load the schema to process.
            XmlSchema xsd;
            using (Stream stm = File.OpenRead(src))
                xsd = XmlSchema.Read(stm, null);
            // Collection of schemas for the XmlSchemaImporter
            XmlSchemas xsds = new XmlSchemas();
            xsds.Add(xsd);
            XmlSchemaImporter imp = new XmlSchemaImporter(xsds);

            // System.CodeDom namespace for the XmlCodeExporter to put classes in
            CodeNamespace ns = new CodeNamespace("NHibernate.Mapping.Hbm");
            CodeCompileUnit ccu =  new CodeCompileUnit();
            XmlCodeExporter exp = new XmlCodeExporter(ns, ccu, ~CodeGenerationOptions.GenerateProperties);

            // Iterate schema items (top-level elements only) and generate code for each
            foreach (XmlSchemaObject item in xsd.Items)
            {
                if (item is XmlSchemaElement)
                {
                    // Import the mapping first
                    XmlTypeMapping map = imp.ImportTypeMapping(new XmlQualifiedName(((XmlSchemaElement)item).Name, xsd.TargetNamespace));
                    // Export the code finally
                    exp.ExportTypeMapping(map);
                }
            }
            ns.Imports.Add(new CodeNamespaceImport("Ayende.NHibernateQueryAnalyzer.SchemaEditing"));
            AddRequiredTags(ns, xsd);

            // Code generator to build code with.
            CodeDomProvider generator = new CSharpCodeProvider();

            // Generate untouched version
            using (StreamWriter sw = new StreamWriter(dest, false))
                generator.GenerateCodeFromNamespace(ns, sw, new CodeGeneratorOptions());
        }
        public static CodeNamespace Process(string xsdSchema, string targetNamespace)
        {
            // Load the XmlSchema and its collection.
            XmlSchema xsd;
            using (var fs = new StringReader(xsdSchema))
            {
                xsd = XmlSchema.Read(fs, null);
                xsd.Compile(null);
            }
            XmlSchemas schemas = new XmlSchemas();
            schemas.Add(xsd);
            // Create the importer for these schemas.
            XmlSchemaImporter importer = new XmlSchemaImporter(schemas);
            // System.CodeDom namespace for the XmlCodeExporter to put classes in.
            CodeNamespace ns = new CodeNamespace(targetNamespace);
            XmlCodeExporter exporter = new XmlCodeExporter(ns);
            // Iterate schema top-level elements and export code for each.
            foreach (XmlSchemaElement element in xsd.Elements.Values)
            {
                // Import the mapping first.
                XmlTypeMapping mapping = importer.ImportTypeMapping(
                    element.QualifiedName);
                // Export the code finally.
                exporter.ExportTypeMapping(mapping);
            }

            // execute extensions

            //var collectionsExt = new ArraysToCollectionsExtension();
            //collectionsExt.Process(ns, xsd);

            //var filedsExt = new FieldsToPropertiesExtension();
            //filedsExt.Process(ns, xsd);

            return ns;
        }
Exemple #8
0
        /// <summary>
        /// Generates the data contracts for given xsd file(s).
        /// </summary>        
        public CodeNamespace GenerateCode()
        {
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            CodeNamespace codeNamespace = new CodeNamespace(options.ClrNamespace);
            codeCompileUnit.Namespaces.Add(codeNamespace);

            // Build the code generation options.
            GenerationOptions generationOptions = GenerationOptions.None;

            if (options.GenerateProperties)
            {
                generationOptions |= GenerationOptions.GenerateProperties;
            }

            if (options.EnableDataBinding)
            {
                generationOptions |= GenerationOptions.EnableDataBinding;
            }
            if (options.GenerateOrderIdentifiers)
            {
                generationOptions |= GenerationOptions.GenerateOrder;
            }

            // Build the CodeDom object graph.
            XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace, codeCompileUnit, generationOptions, null);
            CodeIdentifiers codeIdentifiers = new CodeIdentifiers();
            ImportContext importContext = new ImportContext(codeIdentifiers, false);
            XmlSchemaImporter schemaimporter = new XmlSchemaImporter(schemas, generationOptions, codeProvider, importContext);
            for (int si = 0; si < schemas.Count; si++)
            {
                XmlSchema schema = schemas[si];
                IEnumerator enumerator = schema.Elements.Values.GetEnumerator();
                IEnumerator enumerator2 = schema.SchemaTypes.Values.GetEnumerator();
                try
                {
                    while (enumerator.MoveNext())
                    {
                        XmlSchemaElement element = (XmlSchemaElement)enumerator.Current;
                        if (element.IsAbstract) continue;

                        XmlTypeMapping typemapping = schemaimporter.ImportTypeMapping(element.QualifiedName);
                        codeExporter.ExportTypeMapping(typemapping);
                    }
                    while (enumerator2.MoveNext())
                    {
                        XmlSchemaType type = (XmlSchemaType)enumerator2.Current;
                        if (CouldBeAnArray(type)) continue;

                        XmlTypeMapping typemapping = schemaimporter.ImportSchemaType(type.QualifiedName);
                        codeExporter.ExportTypeMapping(typemapping);
                    }
                }
                finally
                {
                    IDisposable disposableobject = enumerator as IDisposable;
                    if (disposableobject != null)
                    {
                        disposableobject.Dispose();
                    }
                    IDisposable disposableobject2 = enumerator2 as IDisposable;
                    if (disposableobject2 != null)
                    {
                        disposableobject2.Dispose();
                    }
                }
            }
            if (codeNamespace.Types.Count == 0)
            {
                throw new Exception("No types were generated.");
            }

            return codeNamespace;
        }
Exemple #9
0
        public void Generate(Stream xsdInput, TextWriter output)
        {
            if (Options == null)
                Options = new XsdCodeGeneratorOptions
                {
                    UseLists = true,
                    CapitalizeProperties = true,
                    StripDebuggerStepThroughAttribute = true,
                    OutputNamespace = "Xsd2",
                    UseNullableTypes = true
                };

            if (Options.Imports != null)
            {
                foreach (var import in Options.Imports)
                {
                    if (File.Exists(import))
                    {
                        ImportImportedSchema(import);
                    }
                    else if (Directory.Exists(import))
                    {
                        foreach (var file in Directory.GetFiles("*.xsd"))
                            ImportImportedSchema(file);
                    }
                    else
                    {
                        throw new InvalidOperationException(String.Format("Import '{0}' is not a file nor a directory.", import));
                    }
                }
            }

            XmlSchema xsd = XmlSchema.Read(xsdInput, null);
            xsds.Add(xsd);

            xsds.Compile(null, true);

            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds);

            // create the codedom
            CodeNamespace codeNamespace = new CodeNamespace(Options.OutputNamespace);
            XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace);

            List<XmlTypeMapping> maps = new List<XmlTypeMapping>();
            foreach (XmlSchemaElement schemaElement in xsd.Elements.Values)
            {
                if (!ElementBelongsToImportedSchema(schemaElement))
                    maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName));
            }

            foreach (XmlSchemaComplexType schemaElement in xsd.Items.OfType<XmlSchemaComplexType>())
            {
                maps.Add(schemaImporter.ImportSchemaType(schemaElement.QualifiedName));
            }

            foreach (XmlSchemaSimpleType schemaElement in xsd.Items.OfType<XmlSchemaSimpleType>())
            {
                maps.Add(schemaImporter.ImportSchemaType(schemaElement.QualifiedName));
            }

            foreach (XmlTypeMapping map in maps)
            {
                codeExporter.ExportTypeMapping(map);
            }

            ImproveCodeDom(codeNamespace, xsd);

            if (OnValidateGeneratedCode != null)
                OnValidateGeneratedCode(codeNamespace, xsd);

            // Check for invalid characters in identifiers
            CodeGenerator.ValidateIdentifiers(codeNamespace);

            // output the C# code
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();

            codeProvider.GenerateCodeFromNamespace(codeNamespace, output, new CodeGeneratorOptions());
        }
		public void ImportWildcardElementAsClass ()
		{
			var xss = new XmlSchemas ();
			xss.Add (XmlSchema.Read (XmlReader.Create ("Test/XmlFiles/xsd/670945-1.xsd"), null));
			xss.Add (XmlSchema.Read (XmlReader.Create ("Test/XmlFiles/xsd/670945-2.xsd"), null));
			var imp = new XmlSchemaImporter (xss);
			var xtm = imp.ImportSchemaType (new XmlQualifiedName ("SystemDateTime", "http://www.onvif.org/ver10/schema"));
			var cns = new CodeNamespace ();
			var exp = new XmlCodeExporter (cns);
			exp.ExportTypeMapping (xtm);
			var sw = new StringWriter ();
			new CSharpCodeProvider ().GenerateCodeFromNamespace (cns, sw, null);
			Assert.IsTrue (sw.ToString ().IndexOf ("class SystemDateTimeExtension") > 0, "#1");
		}
		public void ImportComplexDerivationByExtension ()
		{
			string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
  <xs:element name='Root' type='DerivedType' />
  <xs:complexType name='DerivedType'>
    <xs:complexContent>
      <xs:extension base='BaseType'>
        <xs:attribute name='Foo' type='xs:string' />
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>
  <xs:complexType name='BaseType'>
    <xs:attribute name='Foo' type='xs:string' />
  </xs:complexType>
</xs:schema>";
			XmlSchemaImporter imp = CreateImporter (xsd);
			CodeNamespace cns = new CodeNamespace ();
			XmlCodeExporter exp = new XmlCodeExporter (cns);
			exp.ExportTypeMapping (imp.ImportTypeMapping (new XmlQualifiedName ("Root")));
		}
		public void DefaultTypeTopLevelElementImportsAllComplexTypes ()
		{
			string xsd = @"
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
  <xs:element name='Root' />
  <xs:complexType name='FooType'>
    <xs:sequence>
      <xs:element name='Child1' type='xs:string' />
      <xs:element name='Child2' type='xs:string' />
      <xs:element name='Child3' type='xs:string' />
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name='BarType' />
</xs:schema>";
			XmlSchemas xss = new XmlSchemas ();
			xss.Add (XmlSchema.Read (new XmlTextReader (new StringReader (xsd)), null));
			XmlSchemaImporter imp = new XmlSchemaImporter (xss);
			CodeNamespace cns = new CodeNamespace ();
			XmlCodeExporter exp = new XmlCodeExporter (cns);
			exp.ExportTypeMapping (imp.ImportTypeMapping (new XmlQualifiedName ("Root")));
			bool foo = false, bar = false;
			foreach (CodeTypeDeclaration td in cns.Types) {
				if (td.Name == "FooType")
					foo = true;
				else if (td.Name == "BarType")
					bar = true;
			}
			Assert.IsTrue (foo, "FooType not found");
			Assert.IsTrue (bar, "BarType not found");
		}
		CodeNamespace ExportCode (XmlTypeMapping map)
		{
			CodeNamespace codeNamespace = new CodeNamespace ();
			XmlCodeExporter exp = new XmlCodeExporter (codeNamespace);
			exp.ExportTypeMapping (map);
			return codeNamespace;
		}
        /// <summary>
        /// Generate code for the elements in the Schema
        /// </summary>
        /// <param name="xsd"></param>
        /// <param name="importer"></param>
        /// <param name="exporter"></param>
        private void GenerateForElements(
            XmlSchema xsd,
            XmlSchemaImporter importer,
            XmlCodeExporter exporter)
        {
            foreach (XmlSchemaElement element in xsd.Elements.Values)
            {
                Trace.TraceInformation("Generating for element: {0}", element.Name);

                try
                {
                    XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName);
                    exporter.ExportTypeMapping(mapping);
                }
                catch (Exception ex)
                {
                    Trace.TraceEvent(TraceEventType.Error, 10, ex.ToString());
                }
            }
        }
		public void ExportSimpleContentExtensionEnum ()
		{
			string xsd = @"
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:b='urn:bar' targetNamespace='urn:bar'>
  <xs:element name='Foo' type='b:DayOfWeek' />
  <xs:complexType name='DayOfWeek'>
    <xs:simpleContent>
      <xs:extension base='b:WeekDay' />
    </xs:simpleContent>
  </xs:complexType>
  <xs:simpleType name='WeekDay'>
    <xs:restriction base='xs:string'>
      <xs:enumeration value='Sunday'/>
      <xs:enumeration value='Monday'/>
      <xs:enumeration value='Tuesday'/>
      <xs:enumeration value='Wednesday'/>
      <xs:enumeration value='Thursday'/>
      <xs:enumeration value='Friday'/>
      <xs:enumeration value='Saturday'/>
    </xs:restriction>
  </xs:simpleType>
</xs:schema>";
			XmlSchema xs = XmlSchema.Read (new StringReader (xsd), null);
			XmlSchemas xss = new XmlSchemas ();
			xss.Add (xs);
			XmlSchemaImporter imp = new XmlSchemaImporter (xss);
			XmlTypeMapping m = imp.ImportTypeMapping (new XmlQualifiedName ("Foo", "urn:bar"));
			CodeNamespace cns = new CodeNamespace ();
			XmlCodeExporter exp = new XmlCodeExporter (cns);
			exp.ExportTypeMapping (m);
			CodeTypeDeclaration enumType = null;
			foreach (CodeTypeDeclaration ctd in cns.Types)
				if (ctd.Name == "WeekDay")
					enumType = ctd;
			Assert.IsNotNull (enumType);
		}
Exemple #16
0
        /// <summary>
        /// Initiate code generation process
        /// </summary>
        /// <param name="generatorParams">Generator parameters</param>
        /// <returns></returns>
        internal static Result<CodeNamespace> Process(GeneratorParams generatorParams)
        {
            var ns = new CodeNamespace();

            XmlReader reader = null;
            try
            {

                #region Set generation context

                GeneratorContext.GeneratorParams = generatorParams;

                #endregion

                #region Get XmlTypeMapping

                XmlSchema xsd;
                var schemas = new XmlSchemas();

                reader = XmlReader.Create(generatorParams.InputFilePath);
                xsd = XmlSchema.Read(reader, new ValidationEventHandler(Validate));

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

                foreach (XmlSchema schema in schemaSet.Schemas())
                {
                    schemas.Add(schema);
                }

                var exporter = new XmlCodeExporter(ns);

                var generationOptions = CodeGenerationOptions.None;
                if (generatorParams.Serialization.GenerateOrderXmlAttributes)
                {
                    generationOptions = CodeGenerationOptions.GenerateOrder;
                }

                var importer = new XmlSchemaImporter(schemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

                foreach (XmlSchemaElement element in xsd.Elements.Values)
                {
                    var mapping = importer.ImportTypeMapping(element.QualifiedName);
                    exporter.ExportTypeMapping(mapping);
                }

                //Fixes/handles http://xsd2code.codeplex.com/WorkItem/View.aspx?WorkItemId=6941
                foreach (XmlSchemaType type in xsd.Items.OfType<XmlSchemaType>())
                {
                    var mapping = importer.ImportSchemaType(type.QualifiedName);
                    exporter.ExportTypeMapping(mapping);
                }

                #endregion

                #region Execute extensions

                var getExtensionResult = GeneratorFactory.GetCodeExtension(generatorParams);
                if (!getExtensionResult.Success) return new Result<CodeNamespace>(ns, false, getExtensionResult.Messages);

                var ext = getExtensionResult.Entity;
                ext.Process(ns, xsd);

                #endregion Execute extensions

                return new Result<CodeNamespace>(ns, true);
            }
            catch (Exception e)
            {
                return new Result<CodeNamespace>(ns, false, e.Message, MessageType.Error);
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }
Exemple #17
0
        void ImportSchemasAsClasses(
            string outputdir,
            ICodeGenerator codeGen,
            string fileExtension,
            IList fileNames, 
            string ns, 
            string uri, 
            IList elements) {

            XmlSchemas schemasToCompile = new XmlSchemas();
            XmlSchemas userSchemas = new XmlSchemas();
            string outputSchemaName = "";
            // Create parent schema
            XmlSchema parent = new XmlSchema();
            foreach (string fileName in fileNames) {
                schemasToCompile.Add(ReadSchema(fileName, false));
                userSchemas.Add(ReadSchema(fileName, true));
                outputSchemaName += Path.ChangeExtension(fileName,"").Replace('.','_');
            }

            Hashtable includeSchemas = new Hashtable();
            foreach (XmlSchema schema in schemasToCompile) {
                CollectIncludes(schema, includeSchemas, false);
            }
            Compile(schemasToCompile);

            includeSchemas = new Hashtable();
            foreach (XmlSchema schema in userSchemas) {
                CollectIncludes(schema, includeSchemas, true);
            }

            try {
                outputSchemaName = outputSchemaName.Substring(0, outputSchemaName.Length - 1);
                XmlSchemaImporter schemaImporter = new XmlSchemaImporter(userSchemas);
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                CodeNamespace codeNamespace = new CodeNamespace(ns);
                codeCompileUnit.Namespaces.Add(codeNamespace);
                GenerateVersionComment(codeNamespace);
                XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace, codeCompileUnit);
                AddImports(codeNamespace, GetNamespacesForTypes(new Type[] { typeof(XmlAttributeAttribute) }));

                for (int i = 0; i < userSchemas.Count; i++) {
                    XmlSchema schema = userSchemas[i];
                    for (int j = 0; j < schema.Items.Count; j++) {
                        object item = schema.Items[j];
                        if (item is XmlSchemaElement) {
                            XmlSchemaElement element = (XmlSchemaElement)item;
                            if (!element.IsAbstract) {

                                if (uri.Length == 0 ||
                                    schema.TargetNamespace == uri) {

                                    bool found;
                                    if (elements.Count == 0) {
                                        found = true;
                                    }
                                    else {
                                        found = false;
                                        foreach (string e in elements) {
                                            if (e == element.Name) {
                                                found = true;
                                                break;
                                            }
                                        }
                                    }
                                    if (found) {
                                        XmlTypeMapping xmlTypeMapping = schemaImporter.ImportTypeMapping(new XmlQualifiedName(element.Name, schema.TargetNamespace));
                                        codeExporter.ExportTypeMapping(xmlTypeMapping);
                                    }
                                }
                            }
                        }
                    }
                }

                CodeTypeDeclarationCollection classes = codeNamespace.Types;
                if (classes == null || classes.Count == 0) {
                    Console.WriteLine(Res.GetString(Res.NoClassesGenerated));
                }
                else {
                    TextWriter writer = CreateOutputWriter(outputdir, outputSchemaName, fileExtension);
                    codeGen.GenerateCodeFromCompileUnit(codeCompileUnit, writer, null);
                    writer.Close();
                }
            }
            catch (Exception e) {
                throw new InvalidOperationException(Res.GetString(Res.ErrGenerateClassesForSchema, outputSchemaName), e);
            }
        }
        public ObjectCollection GenerateClasses(XmlSchema schema)
        {
            #region Generate the CodeDom from the XSD
            CodeNamespace codeNamespace = new CodeNamespace("TestNameSpace");

            XmlSchemas xmlSchemas = new XmlSchemas();
            xmlSchemas.Add(schema);
            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xmlSchemas);

            XmlCodeExporter codeExporter = new XmlCodeExporter(
                codeNamespace,
                new CodeCompileUnit(),
                CodeGenerationOptions.GenerateProperties);

            foreach (XmlSchemaElement element in schema.Elements.Values)
            {
                try
                {
                    XmlTypeMapping map = schemaImporter.ImportTypeMapping(element.QualifiedName);
                    codeExporter.ExportTypeMapping(map);
                }
                catch (Exception ex)
                {
                    throw new Exception("Error Loading Schema: ", ex);
                }

            }
            #endregion

            #region Modify the CodeDom

            foreach (ICodeModifier codeModifier in m_codeModifiers)
                codeModifier.Execute(codeNamespace);

            #endregion

            #region Generate the code
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            compileUnit.Namespaces.Add(codeNamespace);
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
#if DEBUG
            StringWriter sw = new StringWriter();
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.VerbatimOrder = true;
            provider.GenerateCodeFromCompileUnit(compileUnit, sw, options);
            m_codeString = sw.ToString();
#endif
            #endregion

            #region Compile an assembly
            CompilerParameters compilerParameters = new CompilerParameters();

            #region add references to assemblies
            // reference for 
            //  System.CodeDom.Compiler
            //  System.CodeDom
            //  System.Diagnostics
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("mscorlib.dll");

            // System.Xml
            compilerParameters.ReferencedAssemblies.Add("system.xml.dll");

            // reference to this assembly for the custom collection editor
            compilerParameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            compilerParameters.ReferencedAssemblies.Add("System.Drawing.dll");

            // System.ComponentModel
            #endregion

            compilerParameters.GenerateExecutable = false;
            compilerParameters.GenerateInMemory = true;

            CompilerResults results = provider.CompileAssemblyFromDom(compilerParameters, new CodeCompileUnit[] { compileUnit });

            // handle the errors if there are any
            if (results.Errors.HasErrors)
            {
                m_errorStrings = new StringCollection();
                m_errorStrings.Add("Error compiling assembly:\r\n");
                foreach (CompilerError error in results.Errors)
                    m_errorStrings.Add(error.ErrorText + "\r\n");
                return null;
            }

            #endregion

            #region Find the exported classes
            Assembly assembly = results.CompiledAssembly;
            Type[] exportedTypes = assembly.GetExportedTypes();

            // try to create an instance of the exported types
            ObjectCollection objectCollection = new ObjectCollection();
            objectCollection.Clear();
            foreach (Type type in exportedTypes)
            {
                object obj = Activator.CreateInstance(type);
                objectCollection.Add(new ObjectItem(type.Name, obj));
            }

            #endregion

            return objectCollection;

        }
Exemple #19
0
        public Program(params string[] args)
        {
            XmlSchemas xsds = new XmlSchemas();
            var i = 0;
            while (!args[i].StartsWith("/o:") || i >= args.Length)
            {
                xsds.Add(GetSchema(args[i]));
                i++;
            }

            var output = string.Empty;
            if (args[i].StartsWith("/o:"))
            {
                output = args[i].Substring(3);
            }

            xsds.Compile(null, true);
            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds, CodeGenerationOptions.GenerateOrder, null);

            // create the codedom
            var codeNamespace = new CodeNamespace("QbSync.QbXml.Objects");
            codeNamespace.Imports.Add(new CodeNamespaceImport("System"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Collections.Generic"));
            codeNamespace.Imports.Add(new CodeNamespaceImport("System.Linq"));
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            compileUnit.Namespaces.Add(codeNamespace);
            var codeExporter = new XmlCodeExporter(codeNamespace, compileUnit, CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateOrder);

            foreach (XmlSchema xsd in xsds)
            {
                ArrayList maps = new ArrayList();
                foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values)
                {
                    maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName));
                }
                foreach (XmlSchemaElement schemaElement in xsd.Elements.Values)
                {
                    maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName));
                }
                foreach (XmlTypeMapping map in maps)
                {
                    codeExporter.ExportTypeMapping(map);
                }
            }

            var typeEnhancer = new TypeEnhancer(codeNamespace, xsds);
            typeEnhancer.Enhance();

            // Add a comment at the top of the file
            var x = fileComment.Split('\n').Select(m => new CodeCommentStatement(m)).ToArray();
            codeNamespace.Comments.AddRange(x);

            // Check for invalid characters in identifiers
            CodeGenerator.ValidateIdentifiers(codeNamespace);

            // output the C# code
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();

            using (StringWriter writer = new StringWriter())
            {
                codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions
                {
                    BlankLinesBetweenMembers = true,
                    BracingStyle = "C",
                    ElseOnClosing = true,
                    IndentString = "    "
                });

                string content = writer.GetStringBuilder().ToString();
                if (string.IsNullOrEmpty(output))
                {
                    Console.WriteLine(content);
                    Console.ReadLine();
                }
                else
                {
                    File.WriteAllText(output, content);
                }
            }
        }
		private CodeCompileUnit GenerateTypesWithXmlSchemaImporter(XmlSchemaSet schemas)
		{
			CodeNamespace ns = new CodeNamespace(this.targetNamespace);
			CodeCompileUnit unit = new CodeCompileUnit();
			unit.Namespaces.Add(ns);

			schemas.ValidationEventHandler += this.validationEventHandler;

			try
			{
				// Validate schemas
				schemas.Compile();

				XmlSchemas xsds = new XmlSchemas();
				foreach (XmlSchema xsd in schemas.Schemas())
				{
					xsds.Add(xsd);
				}

				foreach (XmlSchema schema in xsds)
				{
					XmlSchemaImporter importer = new XmlSchemaImporter(xsds);
					XmlCodeExporter exporter = new XmlCodeExporter(ns, unit);

					// export only elements
					foreach (XmlSchemaElement schemaElement in schema.Elements.Values)
					{
						exporter.ExportTypeMapping(importer.ImportTypeMapping(schemaElement.QualifiedName));
					}

					CodeGenerator.ValidateIdentifiers(ns);
				}
			}
			catch (ArgumentException argumentException)
			{
				throw new InvalidOperationException(argumentException.Message, argumentException.InnerException);
			}
			finally
			{
				schemas.ValidationEventHandler -= this.validationEventHandler;
			}

			return unit;
		}
Exemple #21
0
        /// <summary>
        /// Imports XML type definitions as .NET classes.
        /// </summary>
        /// <param name="schema">Compiled XML schema.</param>
        /// <param name="schemaImporter">XML Schema Importer.</param>
        /// <param name="codeExporter">XML Code Exporter.</param>
        /// <param name="namespace">Namespace where .NET classes are generated.</param>
        private static void ImportSchemaAsClasses(XmlSchema schema, XmlSchemaImporter schemaImporter, XmlCodeExporter codeExporter, CodeNamespace @namespace)
        {
            foreach (XmlSchemaElement element in schema.Elements.Values)
            {
                if (!element.IsAbstract)
                {
                    XmlTypeMapping xmlTypeMapping = schemaImporter.ImportTypeMapping(element.QualifiedName);
                    codeExporter.ExportTypeMapping(xmlTypeMapping);

                    GenerateLoadMethod(xmlTypeMapping, @namespace);
                }
            }
        }
        private CodeNamespace GenerateSchemaTypes()
        {
            CodeNamespace cns = new CodeNamespace();

            // add the schemas to a Schemas collection used by the XmlSchemImporter
            XmlSchemas importSchemas = new XmlSchemas();
            foreach (MetadataSection mds in metadataSet.MetadataSections)
            {
                XmlSchema xsd = mds.Metadata as XmlSchema;
                if (xsd != null)
                {
                    importSchemas.Add(xsd);
                }
            }

            XmlSchemaImporter imp = new XmlSchemaImporter(importSchemas);

            XmlCodeExporter exp = new XmlCodeExporter(cns);

            foreach (XmlSchema xsd in importSchemas)
            {
                // Iterate schema items (top-level elements only) and generate code for each
                foreach (XmlSchemaObject item in xsd.Items)
                {
                    if (item is XmlSchemaElement)
                    {
                        // Import the mapping first
                        XmlTypeMapping map = imp.ImportTypeMapping(
                          new XmlQualifiedName(((XmlSchemaElement)item).Name, xsd.TargetNamespace));

                        // Finally, export the code 
                        exp.ExportTypeMapping(map);
                    }
                }
            }
            
            return cns;
        }
Exemple #23
0
		public void GenerateClasses ()
		{
			if (namesp == null) namesp = "Schemas";
			if (uri == null) uri = "";
			string targetFile = "";

			XmlSchemas schemas = new XmlSchemas();
			foreach (string fileName in schemaNames)
			{
				StreamReader sr = new StreamReader (fileName);
				schemas.Add (XmlSchema.Read (sr, new ValidationEventHandler (HandleValidationError)));
				sr.Close ();

				if (targetFile == "") targetFile = Path.GetFileNameWithoutExtension (fileName);
				else targetFile += "_" + Path.GetFileNameWithoutExtension (fileName);
			}

			targetFile += "." + provider.FileExtension;

			CodeCompileUnit cunit = new CodeCompileUnit ();
			CodeNamespace codeNamespace = new CodeNamespace (namesp);
			cunit.Namespaces.Add (codeNamespace);
			codeNamespace.Comments.Add (new CodeCommentStatement ("\nThis source code was auto-generated by MonoXSD\n"));

			// Locate elements to generate

			ArrayList qnames = new ArrayList ();
			if (elements.Count > 0)
			{
				foreach (string name in elements)
					qnames.Add (new XmlQualifiedName (name, uri));
			}
			else
			{
				foreach (XmlSchema schema in schemas) {
					if (!schema.IsCompiled) schema.Compile (new ValidationEventHandler (HandleValidationError));
					foreach (XmlSchemaElement el in schema.Elements.Values)
						if (!qnames.Contains (el.QualifiedName))
							qnames.Add (el.QualifiedName);
				}
			}

			// Import schemas and generate the class model

			XmlSchemaImporter importer = new XmlSchemaImporter (schemas);
			XmlCodeExporter sx = new XmlCodeExporter (codeNamespace, cunit);

			ArrayList maps = new ArrayList();

			foreach (XmlQualifiedName qname in qnames)
			{
				XmlTypeMapping tm = importer.ImportTypeMapping (qname);
				if (tm != null) maps.Add (tm);
			}
			
			foreach (XmlTypeMapping tm in maps)
			{
				sx.ExportTypeMapping (tm);
			}

			// Generate the code
			
			ICodeGenerator gen = provider.CreateGenerator();

			string genFile = Path.Combine (outputDir, targetFile);
			StreamWriter sw = new StreamWriter(genFile, false);
			gen.GenerateCodeFromCompileUnit (cunit, sw, new CodeGeneratorOptions());
			sw.Close();

			Console.WriteLine ("Written file " + genFile);
		}
Exemple #24
0
        /// <summary>
        /// Processes the schema.
        /// </summary>
        /// <param name="xsdFile">The full path to the WXS file to process.</param>
        /// <param name="targetNamespace">The namespace to put generated classes in.</param>
        /// <returns>The CodeDom tree generated from the schema.</returns>
        public static CodeNamespace Process(string xsdFile, string targetNamespace, CodeDomProvider Provider)
        {
            // Load the XmlSchema and its collection.
            //XmlSchema xsd;
            //using ( FileStream fs = new FileStream( xsdFile, FileMode.Open ) )
            //{
            //    xsd = XmlSchema.Read( fs,  VH1 );
            //    xsd.Compile( VH2  );
            //}
            XmlSchemaSet set = new XmlSchemaSet();
            XmlSchema xsd = set.Add(null, xsdFile);
            set.Compile();

            XmlSchemas schemas = new XmlSchemas();
            schemas.Add(xsd);

            // Create the importer for these schemas.
            XmlSchemaImporter importer = new XmlSchemaImporter(schemas);

            // System.CodeDom namespace for the XmlCodeExporter to put classes in.
            CodeNamespace ns = new CodeNamespace(targetNamespace);
            XmlCodeExporter exporter = new XmlCodeExporter(ns);
            // Iterate schema top-level elements and export code for each.
            foreach (XmlSchemaElement element in set.GlobalElements.Values) {
                // Import the mapping first.
                XmlTypeMapping mapping = importer.ImportTypeMapping(
                    element.QualifiedName);
                // Export the code finally.
                exporter.ExportTypeMapping(mapping);
            }

            #region Execute extensions

            XPathNavigator nav;
            using (FileStream fs = new FileStream(xsdFile, FileMode.Open, FileAccess.Read)) {
                nav = new XPathDocument(fs).CreateNavigator();
            }

            XPathNodeIterator it = nav.Select(Extensions);
            while (it.MoveNext()) {
                Dictionary<string, string> values = ParsePEValue(it.Current.Value);
                Type t = Type.GetType(values["extension-type"], true);
                // Is the type an ICodeExtension?
                Type iface = t.GetInterface(typeof(ICodeExtension).Name);
                if (iface == null)
                    throw new ArgumentException(string.Format(Resources.ex_InvalidExtensionType, it.Current.Value));

                ICodeExtension ext = (ICodeExtension)Activator.CreateInstance(t);
                ext.Initialize(values);
                // Run it!
                ext.Process(ns, xsd, Provider);
            }

            #endregion Execute extensions

            return ns;
        }
Exemple #25
0
        public string Convert(CodeDomProvider codeProvider)
        {
            StringBuilder code = new StringBuilder();
            List<XmlQualifiedName> arrayTypeList = BuildDataContractArrayTypeList();

            try
            {
                CodeCompileUnit compileUnit = new CodeCompileUnit();
                CodeNamespace namespace2 = new CodeNamespace();
                compileUnit.Namespaces.Add(namespace2);

                XmlCodeExporter codeExporter = new XmlCodeExporter(namespace2, compileUnit, codeProvider, CodeGenerationOptions.GenerateProperties, null);

                // XmlSchemaImporter needs XmlSchemas and not XmlSchemaSet
                XmlSchemas userSchemas = new XmlSchemas();
                foreach (XmlSchema schema in schemas.Schemas())
                {
                    userSchemas.Add(schema);
                }

                XmlSchemaImporter schemaImporter = new XmlSchemaImporter(userSchemas, CodeGenerationOptions.GenerateProperties, codeProvider, new ImportContext(new CodeIdentifiers(), false));

                foreach (XmlSchema schema in userSchemas)
                {
                    if (schema != null)
                    {
                        foreach (XmlSchemaElement element in schema.Elements.Values)
                        {
                            // Don't generate code for abstract elements or array types
                            if (!element.IsAbstract && !arrayTypeList.Contains(element.QualifiedName))
                            {
                                XmlTypeMapping mapping = schemaImporter.ImportTypeMapping(element.QualifiedName);
                                codeExporter.ExportTypeMapping(mapping);
                            }
                        }
                    }
                }

                CodeTypeDeclarationCollection types = namespace2.Types;
                if ((types == null) || (types.Count == 0))
                {
                    //RtlAwareMessageBox.Show(
                        PublicDI.log.error("The XML instance or XML Schema is valid, but no classes could be generated to match. Please ensure it contains a root element with some nested elements inside of it.");
                    //, "Error",
                    //    MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
                }
                else
                {
                    CodeGenerator.ValidateIdentifiers(namespace2);

                    // Now we have to run Silverlight-specific fix-up
                    
                    //DC
//                    ServiceContractGenerator generator = new ServiceContractGenerator(compileUnit);
//                    WcfSilverlightCodeGenerationExtension fixupExtension = new WcfSilverlightCodeGenerationExtension();
//                    fixupExtension.ClientGenerated(generator);

                    using (StringWriter writer = new StringWriter(code, CultureInfo.CurrentCulture))
                    {
                        foreach (CodeTypeDeclaration type in namespace2.Types)
                        {
                            codeProvider.GenerateCodeFromType(type, writer, null);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException))
                {
                    throw;
                }
                //RtlAwareMessageBox.Show(  //DC
                PublicDI.log.error("The XML instance or XML Schema is valid, but no classes could be generated to match." + Environment.NewLine + Environment.NewLine + exception.Message);
                //, "Error",
                //    MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0);
            }

            return code.ToString();
        }
		private void ExportDataContract (MessagePartDescription md)
		{
#if USE_DATA_CONTRACT_IMPORTER
			if (xsd_data_importer == null)
				xsd_data_importer = md.Importer;
#else
			var mapping = md.XmlTypeMapping;

			if (mapping == null)
				return;

			QName qname = new QName (mapping.TypeName, mapping.Namespace);
			if (imported_names.ContainsKey (qname))
				return;

			CodeNamespace cns = new CodeNamespace ();

			XmlCodeExporter xce = new XmlCodeExporter (cns);
			xce.ExportTypeMapping (mapping);

			List <CodeTypeDeclaration> to_remove = new List <CodeTypeDeclaration> ();
			
			//Process the types just generated
			//FIXME: Iterate and assign the types to correct namespaces
			//At the end, add all those namespaces to the ccu
			foreach (CodeTypeDeclaration type in cns.Types) {
				string ns = GetXmlNamespace (type);
				if (ns == null)
					//FIXME: do what here?
					continue;

				QName type_name = new QName (type.Name, ns);
				if (imported_names.ContainsKey (type_name)) {
					//Type got reemitted, so remove it!
					to_remove.Add (type);
					continue;
				}
				if (ns == ms_arrays_ns) {
					//Do not emit arrays as an independent type.
					to_remove.Add (type);
					continue;
				}

				imported_names [type_name] = type_name;

				type.Comments.Clear ();
				//Custom Attributes
				type.CustomAttributes.Clear ();

				if (type.IsEnum)
					continue;
	
				type.CustomAttributes.Add (
					new CodeAttributeDeclaration (
						new CodeTypeReference ("System.CodeDom.Compiler.GeneratedCodeAttribute"),
						new CodeAttributeArgument (new CodePrimitiveExpression ("System.Runtime.Serialization")),
						new CodeAttributeArgument (new CodePrimitiveExpression ("3.0.0.0"))));
			
				type.CustomAttributes.Add (
					new CodeAttributeDeclaration (
						new CodeTypeReference ("System.Runtime.Serialization.DataContractAttribute")));

				//BaseType and interface
				type.BaseTypes.Add (new CodeTypeReference (typeof (object)));
				type.BaseTypes.Add (new CodeTypeReference ("System.Runtime.Serialization.IExtensibleDataObject"));

				foreach (CodeTypeMember mbr in type.Members) {
					CodeMemberProperty p = mbr as CodeMemberProperty;
					if (p == null)
						continue;

					if ((p.Attributes & MemberAttributes.Public) == MemberAttributes.Public) {
						//FIXME: Clear all attributes or only XmlElementAttribute?
						p.CustomAttributes.Clear ();
						p.CustomAttributes.Add (new CodeAttributeDeclaration (
							new CodeTypeReference ("System.Runtime.Serialization.DataMemberAttribute")));

						p.Comments.Clear ();
					}
				}

				//Fields
				CodeMemberField field = new CodeMemberField (
					new CodeTypeReference ("System.Runtime.Serialization.ExtensionDataObject"),
					"extensionDataField");
				field.Attributes = MemberAttributes.Private | MemberAttributes.Final;
				type.Members.Add (field);

				//Property 
				CodeMemberProperty prop = new CodeMemberProperty ();
				prop.Type = new CodeTypeReference ("System.Runtime.Serialization.ExtensionDataObject");
				prop.Name = "ExtensionData";
				prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;

				//Get
				prop.GetStatements.Add (new CodeMethodReturnStatement (
					new CodeFieldReferenceExpression (
					new CodeThisReferenceExpression (),
					"extensionDataField")));

				//Set
				prop.SetStatements.Add (new CodeAssignStatement (
					new CodeFieldReferenceExpression (
					new CodeThisReferenceExpression (),
					"extensionDataField"),
					new CodePropertySetValueReferenceExpression ()));

				type.Members.Add (prop);
			}

			foreach (CodeTypeDeclaration type in to_remove)
				cns.Types.Remove (type);

			ccu.Namespaces.Add (cns);
#endif
		}
		public void DuplicateIdentifiers ()
		{
			XmlSchema xs = XmlSchema.Read (File.OpenText ("Test/XmlFiles/xsd/82078.xsd"), null);

			XmlSchemas xss = new XmlSchemas ();
			xss.Add (xs);
			XmlSchemaImporter imp = new XmlSchemaImporter (xss);
			CodeNamespace cns = new CodeNamespace ();
			XmlCodeExporter exp = new XmlCodeExporter (cns);
			XmlQualifiedName qname = new XmlQualifiedName (
				"Operation", "http://tempuri.org/");
			exp.ExportTypeMapping (imp.ImportTypeMapping (qname));
			CodeCompileUnit ccu = new CodeCompileUnit ();
			ccu.Namespaces.Add (cns);

			CodeDomProvider provider = new CSharpCodeProvider ();
			ICodeCompiler compiler = provider.CreateCompiler ();

			CompilerParameters options = new CompilerParameters ();
			options.ReferencedAssemblies.Add ("System.dll");
			options.ReferencedAssemblies.Add ("System.Xml.dll");
			options.GenerateInMemory = true;

			CompilerResults result = compiler.CompileAssemblyFromDom (options, ccu);
			Assert.AreEqual (0, result.Errors.Count, "#1");
			Assert.IsNotNull (result.CompiledAssembly, "#2");
		}
        private static void ImportSchemaAsClasses(XmlSchema schema, string uri, IList elements, XmlSchemaImporter schemaImporter, XmlCodeExporter codeExporter)
        {
            if (schema != null)
            {
                ArrayList list = new ArrayList();

                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    bool flag;
                    if (element.IsAbstract || ((uri.Length != 0) && !(element.QualifiedName.Namespace == uri)))
                    {
                        continue;
                    }
                    if (elements.Count == 0)
                    {
                        flag = true;
                    }
                    else
                    {
                        flag = false;
                        foreach (string str in elements)
                        {
                            if (str == element.Name)
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                    if (flag)
                    {
                        list.Add(schemaImporter.ImportTypeMapping(element.QualifiedName));
                    }
                }
                foreach (XmlTypeMapping mapping in list)
                {
                    codeExporter.ExportTypeMapping(mapping);
                }
            }
        }
		CodeNamespace ExportCode (Type type)
		{
			XmlReflectionImporter imp = new XmlReflectionImporter ();
			XmlTypeMapping map = imp.ImportTypeMapping (type);
			CodeNamespace codeNamespace = new CodeNamespace ();
			XmlCodeExporter exp = new XmlCodeExporter (codeNamespace);
			exp.ExportTypeMapping (map);
			return codeNamespace;
		}
        /// <summary>
        /// Generate code for all of the complex types in the schema
        /// </summary>
        /// <param name="xsd"></param>
        /// <param name="importer"></param>
        /// <param name="exporter"></param>
        private void GenerateForComplexTypes(
            XmlSchema xsd,
            XmlSchemaImporter importer,
            XmlCodeExporter exporter)
        {
            foreach (XmlSchemaObject type in xsd.SchemaTypes.Values)
            {
                XmlSchemaComplexType ct = type as XmlSchemaComplexType;

                if (ct != null)
                {
                    Trace.TraceInformation("Generating for Complex Type: {0}", ct.Name);

                    XmlTypeMapping mapping = importer.ImportSchemaType(ct.QualifiedName);
                    exporter.ExportTypeMapping(mapping);
                }
            }
        }