Esempio n. 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;
        }
Esempio n. 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;
 }
        private static void Main(string[] args)
        {
            XmlSchema rootSchema = GetSchemaFromFile("fpml-main-4-2.xsd");

            var schemaSet = new List<XmlSchemaExternal>();

            ExtractIncludes(rootSchema, ref schemaSet);

            var schemas = new XmlSchemas { rootSchema };

            schemaSet.ForEach(schemaExternal => schemas.Add(GetSchemaFromFile(schemaExternal.SchemaLocation)));

            schemas.Compile(null, true);

            var xmlSchemaImporter = new XmlSchemaImporter(schemas);

            var codeNamespace = new CodeNamespace("Hosca.FpML4_2");
            var xmlCodeExporter = new XmlCodeExporter(codeNamespace);

            var xmlTypeMappings = new List<XmlTypeMapping>();

            foreach (XmlSchemaType schemaType in rootSchema.SchemaTypes.Values)
                xmlTypeMappings.Add(xmlSchemaImporter.ImportSchemaType(schemaType.QualifiedName));
            foreach (XmlSchemaElement schemaElement in rootSchema.Elements.Values)
                xmlTypeMappings.Add(xmlSchemaImporter.ImportTypeMapping(schemaElement.QualifiedName));

            xmlTypeMappings.ForEach(xmlCodeExporter.ExportTypeMapping);

            CodeGenerator.ValidateIdentifiers(codeNamespace);

            foreach (CodeTypeDeclaration codeTypeDeclaration in codeNamespace.Types)
            {
                for (int i = codeTypeDeclaration.CustomAttributes.Count - 1; i >= 0; i--)
                {
                    CodeAttributeDeclaration cad = codeTypeDeclaration.CustomAttributes[i];
                    if (cad.Name == "System.CodeDom.Compiler.GeneratedCodeAttribute")
                        codeTypeDeclaration.CustomAttributes.RemoveAt(i);
                }
            }

            using (var writer = new StringWriter())
            {
                new CSharpCodeProvider().GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions());

                //Console.WriteLine(writer.GetStringBuilder().ToString());

                File.WriteAllText(Path.Combine(rootFolder, "FpML4_2.Generated.cs"), writer.GetStringBuilder().ToString());
            }

            Console.ReadLine();
        }
Esempio n. 4
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);
            }
        }
Esempio n. 5
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);
                }
            }
        }
Esempio n. 6
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;
        }
Esempio n. 9
0
		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");
		}
		protected override void BeginNamespace ()
		{
#if NET_2_0
			xmlImporter = new XmlSchemaImporter (LiteralSchemas, base.CodeGenerationOptions, base.CodeGenerator, base.ImportContext);
			soapImporter = new SoapSchemaImporter (EncodedSchemas, base.CodeGenerationOptions, base.CodeGenerator, base.ImportContext);
			xmlExporter = new XmlCodeExporter (CodeNamespace, null, base.CodeGenerator, base.CodeGenerationOptions, null);
			soapExporter = new SoapCodeExporter (CodeNamespace, null, base.CodeGenerator, base.CodeGenerationOptions, null);
#else
			xmlImporter = new XmlSchemaImporter (LiteralSchemas, ClassNames);
			soapImporter = new SoapSchemaImporter (EncodedSchemas, ClassNames);
			xmlExporter = new XmlCodeExporter (CodeNamespace, null);
			soapExporter = new SoapCodeExporter (CodeNamespace, null);
#endif
		}
		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);
		}
Esempio n. 12
0
        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;

        }
Esempio n. 13
0
        private static void ImportSchemasAsClasses(CodeDomProvider codeProvider, System.IO.Stream xsdStream, string ns, string uri, CodeGenerationOptions options, IList elements, StringCollection schemaImporterExtensions)
        {
            XmlSchemas userSchemas = new XmlSchemas();

            Hashtable uris = new Hashtable();
            XmlSchema schema = ReadSchema(xsdStream);

            Uri uri2 = new Uri("http://www.w3.org/2001/XMLSchema/temp");
            uris.Add(schema, uri2);
            userSchemas.Add(schema, uri2);

            Hashtable includeSchemas = new Hashtable();
            Compile(userSchemas, uris, includeSchemas);
            try
            {
                CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
                CodeNamespace namespace2 = new CodeNamespace(ns);
                codeCompileUnit.Namespaces.Add(namespace2);
                GenerateVersionComment(namespace2);
                XmlCodeExporter codeExporter = new XmlCodeExporter(namespace2, codeCompileUnit, codeProvider, options, null);
                XmlSchemaImporter schemaImporter = new XmlSchemaImporter(userSchemas, options, codeProvider, new ImportContext(new CodeIdentifiers(), false));
                schemaImporter.Extensions.Add(new System.Data.DataSetSchemaImporterExtension());

                {
                    StringEnumerator enumerator2 = schemaImporterExtensions.GetEnumerator();
                    {
                        while (enumerator2.MoveNext())
                        {
                            Type type = Type.GetType(enumerator2.Current.Trim(), true, false);
                            schemaImporter.Extensions.Add(type.FullName, type);
                        }
                    }
                }
                AddImports(namespace2, GetNamespacesForTypes(new Type[] { typeof(XmlAttributeAttribute) }));
                for (int i = 0; i < userSchemas.Count; i++)
                {
                    ImportSchemaAsClasses(userSchemas[i], uri, elements, schemaImporter, codeExporter);
                }
                foreach (XmlSchema schema2 in includeSchemas.Values)
                {
                    ImportSchemaAsClasses(schema2, uri, elements, schemaImporter, codeExporter);
                }

                CompilerParameters compilePrams = new CompilerParameters();
                CompilerResults compileResults = codeProvider.CompileAssemblyFromDom(compilePrams, codeCompileUnit);

                if (compileResults.Errors.Count > 0)
                {
                    throw new ArgumentException("Compile Error of " + compileResults.Errors[0].ToString());
                }
                // Feng.Windows.Utils.ReflectionHelper.CreateInstanceFromType(compileResults.CompiledAssembly.GetTypes()[0])

                //CodeTypeDeclarationCollection types = namespace2.Types;
                //CodeGenerator.ValidateIdentifiers(namespace2);
                //TextWriter writer = this.CreateOutputWriter(outputdir, fileName, fileExtension);
                //codeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, null);
                //writer.Close();
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Compile Xsd Error!", ex);
            }
        }
Esempio n. 14
0
        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);
                }
            }
        }
 protected override void BeginNamespace()
 {
     try
     {
         base.MethodNames.Clear();
         base.ExtraCodeClasses.Clear();
         this.soapImporter = new SoapSchemaImporter(base.AbstractSchemas, base.ServiceImporter.CodeGenerationOptions, base.ImportContext);
         this.xmlImporter = new XmlSchemaImporter(base.ConcreteSchemas, base.ServiceImporter.CodeGenerationOptions, base.ServiceImporter.CodeGenerator, base.ImportContext);
         foreach (Type type in base.ServiceImporter.Extensions)
         {
             this.xmlImporter.Extensions.Add(type.FullName, type);
         }
         this.xmlImporter.Extensions.Add(TypedDataSetSchemaImporterExtension);
         this.xmlImporter.Extensions.Add(new DataSetSchemaImporterExtension());
         this.xmlExporter = new XmlCodeExporter(base.CodeNamespace, base.ServiceImporter.CodeCompileUnit, base.ServiceImporter.CodeGenerator, base.ServiceImporter.CodeGenerationOptions, base.ExportContext);
         this.soapExporter = new SoapCodeExporter(base.CodeNamespace, null, base.ServiceImporter.CodeGenerator, base.ServiceImporter.CodeGenerationOptions, base.ExportContext);
     }
     catch (Exception exception)
     {
         if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException))
         {
             throw;
         }
         throw new InvalidOperationException(System.Web.Services.Res.GetString("InitFailed"), exception);
     }
 }
		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
		}
Esempio n. 17
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;
        }
		protected override void ImportPartsBySchemaElement (QName qname, List<MessagePartDescription> parts, Message msg, MessagePart msgPart)
		{
			if (schema_set_cache != schema_set_in_use) {
				schema_set_cache = schema_set_in_use;
				var xss = new XmlSchemas ();
				foreach (XmlSchema xs in schema_set_cache.Schemas ())
					xss.Add (xs);
				schema_importer = new XmlSchemaImporter (xss);
				if (ccu.Namespaces.Count == 0)
					ccu.Namespaces.Add (new CodeNamespace ());
				var cns = ccu.Namespaces [0];
				code_exporter = new XmlCodeExporter (cns, ccu);
			}

			var part = new MessagePartDescription (qname.Name, qname.Namespace);
			part.XmlSerializationImporter = this;
			var mbrNS = msg.ServiceDescription.TargetNamespace;
			var xmm = schema_importer.ImportMembersMapping (qname);
			code_exporter.ExportMembersMapping (xmm);
			// FIXME: use of ElementName is a hack!
			part.CodeTypeReference = new CodeTypeReference (xmm.ElementName);
			parts.Add (part);
		}
Esempio n. 19
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;
        }
Esempio n. 20
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);
            }
        }
Esempio n. 21
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);
		}
Esempio n. 22
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();
            }
        }
Esempio n. 23
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();
        }
Esempio n. 24
0
		public void ImportMembersMapping_NullableField ()
		{
			string xsd = @"
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
  <xs:element name='Root'>
    <xs:complexType>
      <xs:sequence>
        <xs:element name='Bar' nillable='true' type='xs:int' />
        <xs:element name='Baz' type='xs:int' />
      </xs:sequence>
      <xs:attribute name='A' use='optional' type='xs:int' />
    </xs:complexType>
  </xs:element>
</xs:schema>";
			XmlSchemaImporter imp = CreateSchemaImporter (xsd);
			XmlMembersMapping map = imp.ImportMembersMapping (new XmlQualifiedName ("Root"));
			Assert.AreEqual (3, map.Count, "#1");
			XmlMemberMapping bar = map [0];
			Assert.AreEqual ("Bar", bar.ElementName, "#2-1");
			Assert.IsFalse (bar.CheckSpecified, "#2-2");
			XmlMemberMapping baz = map [1];
			Assert.AreEqual ("Baz", baz.ElementName, "#3-1");
			Assert.IsFalse (baz.CheckSpecified, "#3-2");
			XmlMemberMapping a = map [2];
			Assert.AreEqual ("A", a.ElementName, "#4-1"); // ... element name?
			Assert.IsTrue (a.CheckSpecified, "#4-2");

#if NET_2_0
			Assert.IsNull (map.TypeName, "#4-3"); // null at this state
			Assert.IsNull (map.TypeNamespace, "#4-4"); // null at this state

			CodeDomProvider p = new Microsoft.CSharp.CSharpCodeProvider ();
			Assert.AreEqual ("System.Nullable`1[System.Int32]", bar.GenerateTypeName (p), "#5-1");
			Assert.AreEqual ("System.Int32", baz.GenerateTypeName (p), "#5-2");

			var table = new Hashtable ();
			var exp = new XmlCodeExporter (new CodeNamespace ("foobar"), null, p, CodeGenerationOptions.None, table);
			exp.ExportMembersMapping (map);
			Assert.AreEqual (null, map.TypeName, "#5-3"); // filled after ExportExportMembersMapping().
			Assert.AreEqual (null, map.TypeNamespace, "#5-4"); // filled after ExportMembersMapping().
			// table contains some internal stuff that does not make sense in any public API.
#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");
		}
Esempio n. 26
0
		CodeNamespace ExportCode (XmlTypeMapping map)
		{
			CodeNamespace codeNamespace = new CodeNamespace ();
			XmlCodeExporter exp = new XmlCodeExporter (codeNamespace);
			exp.ExportTypeMapping (map);
			return codeNamespace;
		}
		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;
		}
Esempio n. 28
0
		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");
		}
		protected override void BeginNamespace ()
		{
			xmlImporter = new XmlSchemaImporter (LiteralSchemas, ClassNames);
			soapImporter = new SoapSchemaImporter (EncodedSchemas, ClassNames);
			xmlExporter = new XmlCodeExporter (CodeNamespace, null);
			xmlReflectionImporter = new XmlReflectionImporter ();
		}
Esempio n. 30
0
		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")));
		}