public static XmlSchemaSet Infer(Type type)
        {
            XmlSchemaSet          schemaSet      = new XmlSchemaSet();
            XmlReflectionImporter importer       = new XmlReflectionImporter();
            XmlSchemas            schemas        = new XmlSchemas();
            XmlSchemaExporter     exporter       = new XmlSchemaExporter(schemas);
            XmlTypeMapping        xmlTypeMapping = importer.ImportTypeMapping(type);

            exporter.ExportTypeMapping(xmlTypeMapping);
            schemas.Compile(new ValidationEventHandler(delegate(object sender, ValidationEventArgs args)
            {
                throw args.Exception;
            }), false);

            for (int i = 0; i < schemas.Count; i++)
            {
                XmlSchema schema = schemas[i];
                schema.Namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema");

                try
                {
                    schemaSet.Add(schema);
                }
                catch (Exception exception2)
                {
                    if (((exception2 is ThreadAbortException) || (exception2 is StackOverflowException)) || (exception2 is OutOfMemoryException))
                    {
                        throw;
                    }
                    throw;
                }
            }
            return(schemaSet);
        }
Пример #2
0
        internal static IEnumerable <XmlSchema> InferXmlSchema(Type type)
        {
            var reflectedType = Reflector.GetReflectedType(type);
            var isDataEntity  = reflectedType.IsDataEntity;

            if (isDataEntity || reflectedType.IsList)
            {
                var innerTypes = new HashSet <Type>();
                var isArray    = !isDataEntity;

                var elementName = reflectedType.XmlElementName;
                var schemaXml   = new StringBuilder();
                schemaXml.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?><xs:schema elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">");
                schemaXml.AppendFormat("<xs:element name=\"{0}\" nillable=\"true\" type=\"{1}\" />", (isArray ? "ArrayOf" : "") + elementName, Reflector.ClrToXmlType(type));
                WriteTypeSchema(type, schemaXml, innerTypes);
                schemaXml.Append("</xs:schema>");

                var schema = XmlSchema.Read(new StringReader(schemaXml.ToString()), null);
                return(schema.Return());
            }
            else
            {
                var importer = new XmlReflectionImporter();
                var schemas  = new XmlSchemas();
                var exporter = new XmlSchemaExporter(schemas);

                var xmlTypeMapping = importer.ImportTypeMapping(type);
                exporter.ExportTypeMapping(xmlTypeMapping);

                schemas.Compile(null, false);
                return(schemas);
            }
        }
        /// <summary>
        /// Generate a set of schemas from the given types
        /// </summary>
        /// <param name="types">Array of types to generate schemas from</param>
        /// <returns>An array of schemas</returns>
        public IList <XmlSchema> GenerateSchemas(Type[] types)
        {
            Trace.Assert(types != null);
            if (types.Length == 0)
            {
                return(null);
            }

            #region generate the schema from the type
            XmlReflectionImporter reflectionImporter = new XmlReflectionImporter();

            XmlSchemas schemas = new XmlSchemas();

            XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);

            foreach (Type type in types)
            {
                // we can provide the default namespace as a parameter here
                XmlTypeMapping map = reflectionImporter.ImportTypeMapping(type);

                exporter.ExportTypeMapping(map);
            }
            #endregion

            // compile the schemas to make sure they were generated correctly
            schemas.Compile(null, true);

            ResolveImportedSchemas(schemas, types[0].Name);

            // convert the generated schemas to an array of schemas
            return(XmlSchemasToArray(schemas));
        }
Пример #4
0
 private static void Compile(XmlSchemas userSchemas, Hashtable uris, Hashtable includeSchemas)
 {
     foreach (XmlSchema xmlSchema in userSchemas)
     {
         if (xmlSchema.TargetNamespace != null && xmlSchema.TargetNamespace.Length == 0)
         {
             xmlSchema.TargetNamespace = null;
         }
         Uri uri = (Uri)uris[xmlSchema];
         CollectIncludes(xmlSchema, uri, includeSchemas, uri.ToString().ToLower(CultureInfo.InvariantCulture));
     }
     try
     {
         userSchemas.Compile(ValidationCallbackWithErrorCode, true);
     } catch (Exception ex)
     {
         if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
         {
             throw;
         }
         Console.WriteLine(string.Concat(Environment.NewLine, Res.GetString("SchemaValidationWarning"), Environment.NewLine, ex.Message, Environment.NewLine));
     }
     if (!userSchemas.IsCompiled)
     {
         Console.WriteLine(Environment.NewLine + Res.GetString("SchemaValidationWarning") + Environment.NewLine);
     }
 }
Пример #5
0
 internal static StringCollection Compile(XmlSchemas schemas)
 {
     AddImports(schemas);
     Warnings.Clear();
     schemas.Compile(new ValidationEventHandler(ValidationCallbackWithErrorCode), true);
     return(Warnings);
 }
Пример #6
0
        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();
        }
Пример #7
0
        public void XsdToClassTest()
        {
            // identify the path to the xsd
            string xsdFileName = "Account.xsd";
            string path        = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string xsdPath     = Path.Combine(path, xsdFileName);

            // load the xsd
            XmlSchema xsd;

            using (FileStream stream = new FileStream(xsdPath, FileMode.Open, FileAccess.Read))
            {
                xsd = XmlSchema.Read(stream, null);
            }
            Console.WriteLine("xsd.IsCompiled {0}", xsd.IsCompiled);

            XmlSchemas xsds = new XmlSchemas();

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

            // create the codedom
            CodeNamespace   codeNamespace = new CodeNamespace("Generated");
            XmlCodeExporter codeExporter  = new XmlCodeExporter(codeNamespace);

            List maps = new List();

            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);
            }

            RemoveAttributes(codeNamespace);

            // 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());
                Console.WriteLine(writer.GetStringBuilder().ToString());
            }

            Console.ReadLine();
        }
Пример #8
0
        /// <summary>
        /// Loads and compiles all schemas specified in the target XML file.
        /// </summary>
        /// <param name="targetXmlFile">The target XML file specifying the list of top-level schemas to process.</param>
        /// <param name="dataSchemaRootFolder">The root folder for the data schemas.</param>
        /// <param name="schemaSubstitutions">The schema substitutions.  The keys are top-level schemas.  The values are included schemas that the schemas are to be substituted for.</param>
        /// <param name="namespaceSubstitutions">Namespace substitutions.</param>
        /// <returns>The loaded and compiled schemas.</returns>
        private static XmlSchemas LoadAndCompileAllSchemas(string targetXmlFile, string dataSchemaRootFolder, Dictionary <string, string> schemaSubstitutions, Dictionary <string, string> namespaceSubstitutions)
        {
            XmlSchemas topLevelSchemas = LoadTopLevelSchemas(targetXmlFile, namespaceSubstitutions);
            var        loadedSchemas   = GetLoadedSchemasWithSbustituations(topLevelSchemas, schemaSubstitutions);

            LoadIncludesFromAllSchemas(topLevelSchemas, dataSchemaRootFolder, loadedSchemas, schemaSubstitutions, namespaceSubstitutions);

            topLevelSchemas.Compile(null, true);

            return(topLevelSchemas);
        }
Пример #9
0
 /// <summary>
 /// Compiles collection of XML schemas.
 /// </summary>
 /// <param name="schemas">Collection of XML schemas.</param>
 private void CompileSchemas(XmlSchemas schemas)
 {
     schemas.Compile(this.ValidationErrorHandler, true);
     if (!schemas.IsCompiled)
     {
         CompilerError error = new CompilerError();
         error.FileName  = Host.TemplateFile;
         error.ErrorText = "Schema could not be compiled";
         error.IsWarning = true;
         this.Errors.Add(error);
     }
 }
Пример #10
0
            static XmlQualifiedName StaticGetSchema(XmlSchemaSet schemaSet)
            {
                XmlReflectionImporter importer       = new XmlReflectionImporter();
                XmlTypeMapping        xmlTypeMapping = importer.ImportTypeMapping(typeof(T));
                XmlSchemas            schemas        = new XmlSchemas();
                XmlSchemaExporter     exporter       = new XmlSchemaExporter(schemas);

                exporter.ExportTypeMapping(xmlTypeMapping);
                schemas.Compile(new ValidationEventHandler(ValidationCallbackWithErrorCode), true);
                for (int i = 0; i < schemas.Count; i++)
                {
                    XmlSchema schema = schemas[i];
                    schemaSet.Add(schema);
                }
                return(new XmlQualifiedName(xmlTypeMapping.TypeName, xmlTypeMapping.Namespace));
            }
Пример #11
0
        static void Main(string[] args)
        {
            // identify the path to the xsd
            const string xsdFileName = @"schema.xsd";
            var          path        = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var          xsdPath     = Path.Combine(path, xsdFileName);
            // load the xsd
            XmlSchema xsd;

            using (var stream = new FileStream(xsdPath, FileMode.Open, FileAccess.Read))
            {
                xsd = XmlSchema.Read(stream, null);
            }
            var xsds = new XmlSchemas();

            xsds.Add(xsd);
            xsds.Compile(null, true);
            var schemaImporter = new XmlSchemaImporter(xsds);
            // create the codedom
            var codeNamespace = new CodeNamespace("Generated");
            var codeExporter  = new XmlCodeExporter(codeNamespace);
            var 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 (var map in maps)
            {
                codeExporter.ExportTypeMapping(map);
            }
            PostProcess(codeNamespace);
            // Check for invalid characters in identifiers
            CodeGenerator.ValidateIdentifiers(codeNamespace);
            // output the C# code
            var codeProvider = new CSharpCodeProvider();

            using (var writer = new StringWriter())
            {
                codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions());
                Console.WriteLine(writer.GetStringBuilder().ToString());
            }
        }
Пример #12
0
        static void Main(string[] args)
        {
            var xmlSchemas = new XmlSchemas();

            xmlSchemas.Add(XmlSchema.Read(File.OpenRead("contacts.xsd"), validationHandler));
            xmlSchemas.Compile(validationHandler, true);
            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xmlSchemas);

            CodeNamespace   codeNamespace = new CodeNamespace("CSharpGenerated");
            XmlCodeExporter codeExporter  = new XmlCodeExporter(codeNamespace, null, CodeGenerationOptions.None);

            foreach (XmlSchema xsd in xmlSchemas)
            {
                foreach (XmlSchemaElement schemaElement in xsd.Elements.Values)
                {
                    Console.WriteLine($"{schemaElement.Name} is {schemaElement.GetType().Name}");
                    var t = schemaImporter.ImportTypeMapping(schemaElement.QualifiedName);
                    codeExporter.ExportTypeMapping(t);
                }
                foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) // XmlSchemaComplexType or XmlSchemaSimpleType
                {
                    var t = schemaImporter.ImportSchemaType(schemaType.QualifiedName);
                    Console.WriteLine($"{schemaType.Name} is a {schemaType.GetType().Name}");
                    // Generates far to many xmlroot attributes
                    //codeExporter.ExportTypeMapping(schemaImporter.ImportSchemaType(schemaType.QualifiedName));
                }
            }

            RemoveAttributes(codeNamespace);
            CodeGenerator.ValidateIdentifiers(codeNamespace);
            CSharpCodeProvider   codeProvider = new CSharpCodeProvider();
            CodeGeneratorOptions opts         = new CodeGeneratorOptions
            {
                BlankLinesBetweenMembers = false,
                VerbatimOrder            = true
            };

            codeProvider.GenerateCodeFromNamespace(codeNamespace, Console.Out, opts);

            foreach (CodeTypeDeclaration codeType in codeNamespace.Types)
            {
                Console.WriteLine($"{codeType.Name} is a {codeType.GetType().Name}");
                var t = codeType.TypeParameters;
            }

            Console.ReadLine();
        }
Пример #13
0
        private CodeNamespace GeneratedClassFromStream(Stream stream, string nameSpace)
        {
            try
            {
                XmlSchema xsd;
                stream.Seek(0, SeekOrigin.Begin);
                using (stream)
                {
                    xsd = XmlSchema.Read(stream, null);
                }

                var xsds = new XmlSchemas();

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

                // create the codedom
                var codeNamespace = new CodeNamespace(nameSpace);
                var codeExporter  = new XmlCodeExporter(codeNamespace);
                var 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);
                }
                return(codeNamespace);
            }

            catch (Exception e)
            {
                return(null);
            }
        }
    public void XsdToClassTest(IEnumerable <Func <TextReader> > xsds, TextWriter codeWriter)
    {
        var schemas = new XmlSchemas();

        foreach (var getReader in xsds)
        {
            using (var reader = getReader())
            {
                var xsd = XmlSchema.Read(reader, null);
                schemas.Add(xsd);
            }
        }
        schemas.Compile(null, true);
        var schemaImporter = new XmlSchemaImporter(schemas);
        var maps           = new List <XmlTypeMapping>();

        foreach (XmlSchema xsd in schemas)
        {
            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));
            }
        }
        // create the codedom
        var codeNamespace = new CodeNamespace(this.Namespace);
        var codeExporter  = new XmlCodeExporter(codeNamespace);

        foreach (XmlTypeMapping map in maps)
        {
            codeExporter.ExportTypeMapping(map);
        }
        ModifyGeneratedCode(codeNamespace);
        // Check for invalid characters in identifiers
        CodeGenerator.ValidateIdentifiers(codeNamespace);
        // output the C# code
        var codeProvider = new CSharpCodeProvider();

        codeProvider.GenerateCodeFromNamespace(codeNamespace, codeWriter, new CodeGeneratorOptions());
    }
        private void MoveSchemas()
        {
            ValidationEventHandler handler   = null;
            XmlSchemas             schemas   = this.Schemas;
            XmlSchemaSet           schemaSet = base.SchemaSet;

            if (schemas != null)
            {
                if (handler == null)
                {
                    handler = (sender, args) => SchemaHelper.HandleSchemaValidationError(sender, args, base.exporter.Errors);
                }
                schemas.Compile(handler, false);
                foreach (System.Xml.Schema.XmlSchema schema in schemas)
                {
                    if (!schemaSet.Contains(schema))
                    {
                        schemaSet.Add(schema);
                        schemaSet.Reprocess(schema);
                    }
                }
            }
        }
Пример #16
0
        public static byte[] GetXmlSchemaFromType(Type type)
        {
            XmlSchemas            sms = new XmlSchemas();
            XmlSchemaExporter     ex  = new XmlSchemaExporter(sms);
            XmlReflectionImporter im  = new XmlReflectionImporter();
            XmlTypeMapping        map = im.ImportTypeMapping(type);

            ex.ExportTypeMapping(map);
            sms.Compile(null, false);

            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(ms);

            foreach (System.Xml.Schema.XmlSchema sm in sms)
            {
                sm.Write(sw);
            }
            sw.Close();
            ms.Flush();

            byte[] data = ms.ToArray();
            return(data);
        }
Пример #17
0
 private static void Compile(XmlSchemas userSchemas, Hashtable uris, Hashtable includeSchemas)
 {
     foreach (XmlSchema schema in userSchemas)
     {
         if ((schema.TargetNamespace != null) && (schema.TargetNamespace.Length == 0))
         {
             schema.TargetNamespace = null;
         }
         Uri baseUri = (Uri)uris[schema];
         CollectIncludes(schema, baseUri, includeSchemas, baseUri.ToString().ToLower(CultureInfo.InvariantCulture));
     }
     try
     {
         userSchemas.Compile(new ValidationEventHandler(ValidationCallbackWithErrorCode), true);
     }
     catch (Exception ex)
     {
         throw new ArgumentException("Compile Xsd Error!", ex);
     }
     if (!userSchemas.IsCompiled)
     {
         throw new ArgumentException("Compile Xsd Error!");
     }
 }
Пример #18
0
        private CodeNamespace CreateCodeNamespace(XmlSchemaSet schemaSet, string[] rootNamespaces)
        {
            var schemas = new XmlSchemas();

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

            schemas.Compile(_options.ValidationHandler, true);
            var schemaImporter = new XmlSchemaImporter(schemas);

            schemaImporter.Extensions.Clear();

            var codeNamespace = new CodeNamespace(_options.Namespace);
            var codeOptions   = CodeGenerationOptions.GenerateOrder | CodeGenerationOptions.GenerateNewAsync;
            var codeExporter  = new XmlCodeExporter(codeNamespace, null, codeOptions);

            var maps = new List <XmlTypeMapping>();

            //foreach (XmlSchema schema in schemaSet.Schemas().Cast<XmlSchema>().Where(x => x.SourceUri.Contains("maindoc")))
            //{
            //    foreach (XmlSchemaElement element in schema.Elements.Values)
            //    {
            //        var xmlTypeMapping = schemaImporter.ImportTypeMapping(element.QualifiedName);
            //        maps.Add(xmlTypeMapping);
            //    }
            //}

            //foreach (var schemaType in schemaSet.Schemas().Cast<XmlSchema>().Where(x => !x.SourceUri.Contains("maindoc")).SelectMany(x => x.SchemaTypes.Values.Cast<XmlSchemaType>()))
            //{
            //    var xmlTypeMapping = schemaImporter.ImportSchemaType(schemaType.QualifiedName);
            //    maps.Add(xmlTypeMapping);
            //}

            // var qnamesMap = new Dictionary<XmlQualifiedName, string>();

            foreach (var ns in rootNamespaces)
            {
                var schema = schemas[ns];

                Console.WriteLine($"Import root namespace: {ns}");
                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    Console.WriteLine($"Import type mapping for {element.QualifiedName.Namespace} : {element.QualifiedName.Name}");
                    var xmlTypeMapping = schemaImporter.ImportTypeMapping(element.QualifiedName);
                    maps.Add(xmlTypeMapping);
                }
            }

            //foreach (XmlSchemaType element in schemaSet.Schemas().Cast<XmlSchema>().Where(x => !rootNamespaces.Contains(x.TargetNamespace)).SelectMany(x => x.SchemaTypes.Values.Cast<XmlSchemaType>()))
            //{
            //    var xmlTypeMapping = schemaImporter.ImportSchemaType(element.QualifiedName);
            //    maps.Add(xmlTypeMapping);
            //}

            foreach (var xmlTypeMapping in maps)
            {
                codeExporter.ExportTypeMapping(xmlTypeMapping);
            }

            var codeDeclarations = codeNamespace.Types.Cast <CodeTypeDeclaration>().ToList();

            foreach (var codeDecl in codeDeclarations)
            {
                codeDecl.Comments.Clear();
                foreach (var item in codeDecl.Members.OfType <CodeTypeMember>())
                {
                    item.Comments.Clear();
                }

                var qname = codeDecl.GetQualifiedName();
                codeDecl.UserData[CodeTypeMemberExtensions.QualifiedNameKey] = qname;
                var schema = schemas[qname.Namespace];
                codeDecl.UserData[CodeTypeMemberExtensions.XmlSchemaKey] = schema;
                var xmlSchemaType = (XmlSchemaType)schema.SchemaTypes[qname];
                codeDecl.UserData[CodeTypeMemberExtensions.XmlSchemaTypeKey] = xmlSchemaType;

                foreach (CodeTypeMember member in codeDecl.Members)
                {
                    member.UserData[CodeTypeMemberExtensions.XmlSchemaKey]     = schema;
                    member.UserData[CodeTypeMemberExtensions.XmlSchemaTypeKey] = xmlSchemaType;
                }
            }

            return(codeNamespace);
        }
Пример #19
0
        private static void Generar(string rootFolder, string includeFolder, string _namespace, string nombreArchivo)
        {
            //Aqui voy agregando todos los esquemas que voy encontrando
            var schemas         = new XmlSchemas();
            var listRootSchemas = new List <XmlSchema>();

            //Aqui Almaceno todos los include
            var schemaSet = new List <XmlSchemaExternal>();

            //Comienso leyendo los xsd que se encuentran en el directorio de root
            var dir = new DirectoryInfo(rootFolder);

            //En este punto ya tengo todos los XSD que voy a procesar
            foreach (var item in dir.GetFiles("*.xsd"))
            {
                //leo el esquema y lo guardo
                var schema = GetSchemaFromFile(item.Name, rootFolder);
                listRootSchemas.Add(schema);

                //Aqui voy consultando los includes existentes y los guardo en schemaSet(recordar que esta variable que al ser una lista este se pasa como referencia si o si)
                ExtractIncludes(includeFolder, schema, schemaSet);
            }

            var includes = new StringBuilder();

            foreach (var elemento in schemaSet)
            {
                includes.AppendLine(elemento.SchemaLocation);
            }

            Console.WriteLine("Se encontraron las siguientes dependencias");
            Console.WriteLine(includes.ToString());

            //Voy juntando todos mis esquemas principales
            listRootSchemas.ForEach(elemento => schemas.Add(elemento));

            //Aqui schemaSet ya contiene toda las rutas de los includes necesarios entonces los leo y los agrego a mis schemas
            schemaSet.ForEach(schemaExternal => schemas.Add(GetSchemaFromFile(schemaExternal.SchemaLocation, includeFolder)));

            schemas.Compile(null, true);

            //Llegando a este puntos ya tenemos todos los esquemas cargados correctamente
            Console.WriteLine("Lectura de esquemas correcta");

            //Aqui procedemos a Generar el codigo mirar http://mikehadlow.blogspot.pe/2007/01/writing-your-own-xsdexe.html
            //Tambien leer aqui https://weblogs.asp.net/cazzu/33302


            var xmlSchemaImporter = new XmlSchemaImporter(schemas);
            //var codeNamespace = new CodeNamespace("SimpleUbl.Xml");
            var codeNamespace = new CodeNamespace(_namespace);

            var xmlCodeExporter = new XmlCodeExporter(codeNamespace);

            var xmlTypeMappings = new List <XmlTypeMapping>();

            //Voy a recorrer todos los esquemas de rootFolder
            foreach (var xsd in listRootSchemas)
            {
                //foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values)
                //    xmlTypeMappings.Add(xmlSchemaImporter.ImportSchemaType(schemaType.QualifiedName));

                //foreach (XmlSchemaElement schemaElement in xsd.Elements.Values)
                //    xmlTypeMappings.Add(xmlSchemaImporter.ImportTypeMapping(schemaElement.QualifiedName));

                foreach (XmlSchemaObject item in xsd.Items)
                {
                    if (item is XmlSchemaElement)
                    {
                        var type = xmlSchemaImporter.ImportTypeMapping(new System.Xml.XmlQualifiedName(((XmlSchemaElement)item).Name, xsd.TargetNamespace));
                        xmlTypeMappings.Add(type);
                        Console.WriteLine($"Se encontro : {type.TypeName}");
                    }
                }
            }

            //Aqui Agrego todos los elementos a mi XmlCodeExporter
            xmlTypeMappings.ForEach(xmlCodeExporter.ExportTypeMapping);


            CodeGenerator.ValidateIdentifiers(codeNamespace);

            //Aqui solo por moneria le pongo que fue generado por la utilidad UblXsd :P y arreglo un poco el codigo
            GeneratedCodeAttribute   generatedCodeAttribute = new GeneratedCodeAttribute("ITUblXsd", "1.0.0.0");
            CodeAttributeDeclaration codeAttrDecl           =
                new CodeAttributeDeclaration("System.CodeDom.Compiler.GeneratedCodeAttribute",
                                             new CodeAttributeArgument(
                                                 new CodePrimitiveExpression(generatedCodeAttribute.Tool)),
                                             new CodeAttributeArgument(
                                                 new CodePrimitiveExpression(generatedCodeAttribute.Version)));

            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);
                        codeTypeDeclaration.CustomAttributes[i] = codeAttrDecl;
                    }

                    if (cad.Name == "System.Diagnostics.DebuggerStepThroughAttribute")
                    {
                        codeTypeDeclaration.CustomAttributes.RemoveAt(i);
                    }
                    if (cad.Name == "System.ComponentModel.DesignerCategoryAttribute")
                    {
                        codeTypeDeclaration.CustomAttributes.RemoveAt(i);
                    }
                }
            }

            using (var writer = new StringWriter())
            {
                writer.WriteLine("//----------------------------------------------------------------------------");
                writer.WriteLine("// <auto-generated>");
                writer.WriteLine($"//    Generado por UblXsdToCS el: {DateTime.Now.ToString()}");
                writer.WriteLine("//    *** No es recomendable editar este archivo ***");
                writer.WriteLine("//    Actualizaciones en https://github.com/LarrySoza/UblXsdToCS");
                writer.WriteLine("//    Dudas o consultas escribir a [email protected]");
                writer.WriteLine("// </auto-generated>");
                writer.WriteLine("//----------------------------------------------------------------------------");
                writer.WriteLine();
                writer.WriteLine("using System;");
                writer.WriteLine("using System.Xml;");
                writer.WriteLine("using System.Xml.Serialization;");
                writer.WriteLine("using System.CodeDom.Compiler;");
                writer.WriteLine();

                string src = string.Empty;

                using (var sourceWriter = new StringWriter())
                {
                    var options = new CodeGeneratorOptions();
                    options.ElseOnClosing            = true;
                    options.BracingStyle             = "C";
                    options.BlankLinesBetweenMembers = false;

                    //CompilerParameters opt = new CompilerParameters(new string[]{
                    //                  "System.dll",
                    //                  "System.Xml.dll",
                    //                  "System.Windows.Forms.dll",
                    //                  "System.Data.dll",
                    //                  "System.Drawing.dll"});

                    var provider = new CSharpCodeProvider();

                    provider.GenerateCodeFromNamespace(codeNamespace, sourceWriter, options);

                    var source = sourceWriter.GetStringBuilder().Replace("/// <comentarios/>", "");
                    source = source.Replace("System.Xml.Serialization.", "");
                    source = source.Replace("System.CodeDom.Compiler.", "");
                    source = source.Replace("System.Xml.", "");
                    source = source.Replace("System.", "");
                    source = source.Replace("GeneratedCodeAttribute", "GeneratedCode");
                    source = source.Replace("SerializableAttribute", "Serializable");
                    source = source.Replace("XmlTypeAttribute", "XmlType");
                    source = source.Replace("XmlRootAttribute", "XmlRoot");
                    source = source.Replace("XmlIncludeAttribute", "XmlInclude");
                    source = source.Replace("XmlAttributeAttribute", "XmlAttribute");
                    source = source.Replace("XmlEnumAttribute", "XmlEnum");
                    source = source.Replace("XmlElementAttribute", "XmlElement");
                    source = source.Replace("XmlTextAttribute", "XmlText");
                    source = source.Replace("XmlArrayAttribute", "XmlArray");
                    source = source.Replace("XmlArrayItemAttribute", "XmlArrayItem");
                    source = source.Replace("XmlIgnoreAttribute", "XmlIgnore");

                    //Por defecto se genera codigo con "public partial" yo quiero que todos mis metodos sean internal
                    source = source.Replace("public partial", "public");

                    src = source.ToString();
                }

                writer.Write(src);

                File.WriteAllText(Path.Combine(rutaSalida, nombreArchivo), writer.ToString());
            }

            Console.WriteLine(String.Format("Archivo generador Correctamente en  {0}", Path.Combine(rutaSalida, nombreArchivo)));
        }
Пример #20
0
        public IEnumerable <CodeTypeDeclaration> CreateCodeTypeDeclarations(XmlSchemaSet schemaSet, string[] targetNamespaces)
        {
            XmlSchemas allSchemas = new XmlSchemas();

            foreach (XmlSchema schema in schemaSet.Schemas().Cast <XmlSchema>())
            {
                allSchemas.Add(schema);
            }

            allSchemas.Compile(UblSettings.XsdValidationEvent, true);
            if (!allSchemas.IsCompiled)
            {
                Console.WriteLine("Warning: allSchemas is not compiled!!! .NET BUG?");
            }
            XmlSchemaImporter importer = new XmlSchemaImporter(allSchemas);

            importer.Extensions.Clear();                                               // Remove System.Data.SqlTypes.TypeXxxx stuff
            CodeNamespace bigBlobCodeNamespace = new CodeNamespace("UblDummyLibrary"); // temporary to hold everything

            CodeGenerationOptions opts = CodeGenerationOptions.GenerateOrder;

            if (UblSettings.OptionMemberTypeToGenerate == UblXsdSettings.FieldTypesEnum.Property)
            {
                opts |= CodeGenerationOptions.GenerateProperties;
            }
            XmlCodeExporter exporter = new XmlCodeExporter(bigBlobCodeNamespace, null, opts);

            foreach (var ns in targetNamespaces)
            {
                XmlSchema schema = allSchemas[ns];
                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName);
                    exporter.ExportTypeMapping(mapping);
                }
            }

            IEnumerable <CodeTypeDeclaration> allCodeDecls = bigBlobCodeNamespace.Types.Cast <CodeTypeDeclaration>().ToList();

            foreach (var codeDecl in allCodeDecls)
            {
                // clear auto generated comment "<remarks/>"
                codeDecl.Comments.Clear();
                foreach (var item in codeDecl.Members.OfType <CodeTypeMember>())
                {
                    item.Comments.Clear();
                }

                // populate userdata with things we often query from xsd files
                XmlQualifiedName qname  = codeDecl.GetQualifiedName();
                XmlSchema        schema = allSchemas[qname.Namespace];
                codeDecl.UserData[Constants.XmlSchemaLabel] = schema;
                XmlSchemaType xmlSchemaType = (XmlSchemaType)schema.SchemaTypes[qname];
                codeDecl.UserData[Constants.XmlSchemaTypeLabel] = xmlSchemaType;

                if (xmlSchemaType == null)
                {
                    Console.WriteLine($"Warning: {codeDecl.Name} is missing schema information {qname}");
                }
            }

            return(allCodeDecls);
        }
Пример #21
0
        private CodeCompileUnit CreateCodeNamespace(XmlSchemaSet schemaSet, CodeNamespaceProvider namespaceProvider)
        {
            var compileUnit = new CodeCompileUnit();
            var schemas     = new XmlSchemas();

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

            schemas.Compile(_options.ValidationHandler, true);

            foreach (XmlSchema schema in schemas)
            {
                var codeNamespace = namespaceProvider.CreateCodeNamespace(schema);
                compileUnit.Namespaces.Add(codeNamespace);
            }

            var codeOptions = CodeGenerationOptions.GenerateOrder | CodeGenerationOptions.GenerateNewAsync;

            // foreach (var ns in rootNamespaces.Concat(extensionNamespaces))
            foreach (XmlSchema schema in schemas)
            {
                var schemaImporter = new XmlSchemaImporter(schemas);
                schemaImporter.Extensions.Clear();

                // var schema = schemas[ns];
                var codeNamespace = compileUnit.Namespaces.OfType <CodeNamespace>().Single(x => x.UserData[CodeTypeMemberExtensions.XmlSchemaKey] == schema);

                Console.WriteLine($"Import root namespace: {schema.TargetNamespace}");

                var codeExporter = new XmlCodeExporter(codeNamespace, compileUnit, codeOptions);

                foreach (XmlSchemaElement element in schema.Elements.Values.OfType <XmlSchemaElement>())
                {
                    Console.WriteLine($"Import type mapping for {element.QualifiedName.Namespace} : {element.QualifiedName.Name}");
                    var xmlTypeMapping = schemaImporter.ImportTypeMapping(element.QualifiedName);
                    codeExporter.ExportTypeMapping(xmlTypeMapping);
                }

                var baseTypes = schema.Elements.Values.OfType <XmlSchemaElement>().Select(x => x.SchemaTypeName.Name).ToList();

                foreach (XmlSchemaComplexType element in schema.SchemaTypes.Values.OfType <XmlSchemaComplexType>().Where(x => !baseTypes.Contains(x.Name)))
                {
                    Console.WriteLine($"Import schema type for {element.QualifiedName.Namespace} : {element.QualifiedName.Name}");

                    var xmlTypeMapping = schemaImporter.ImportSchemaType(element.QualifiedName);
                    codeExporter.ExportTypeMapping(xmlTypeMapping);
                }
            }

            var codeDeclarations = compileUnit.Namespaces.OfType <CodeNamespace>().SelectMany(x => x.Types.Cast <CodeTypeDeclaration>()).ToList();

            foreach (var codeDecl in codeDeclarations)
            {
                codeDecl.Comments.Clear();
                foreach (var item in codeDecl.Members.OfType <CodeTypeMember>())
                {
                    item.Comments.Clear();
                }

                var qname = codeDecl.GetQualifiedName();
                codeDecl.UserData[CodeTypeMemberExtensions.QualifiedNameKey] = qname;
                // Note, this can fail when there are multiple schemas for one namespace, like urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2
                var schema = schemas.GetSchemas(qname.Namespace).OfType <XmlSchema>().FirstOrDefault();
                // var schema = schemas[qname.Namespace];
                codeDecl.UserData[CodeTypeMemberExtensions.XmlSchemaKey] = schema;
                var xmlSchemaType = (XmlSchemaType)schema.SchemaTypes[qname];
                codeDecl.UserData[CodeTypeMemberExtensions.XmlSchemaTypeKey] = xmlSchemaType;

                foreach (CodeTypeMember member in codeDecl.Members)
                {
                    member.UserData[CodeTypeMemberExtensions.XmlSchemaKey]     = schema;
                    member.UserData[CodeTypeMemberExtensions.XmlSchemaTypeKey] = xmlSchemaType;
                }
            }

            return(compileUnit);
        }
Пример #22
0
        public static bool TryAddSchemaTypeFromXmlSchemaProviderAttribute(this XmlDictionaryWriter writer, Type type, string name, SoapSerializer serializer, XmlNamespaceManager xmlNamespaceManager = null)
        {
            if (!useXmlSchemaProvider && !useXmlReflectionImporter)
            {
                return(false);
            }

            if (useXmlReflectionImporter)
            {
                var schemas     = new XmlSchemas();
                var xmlImporter = new XmlReflectionImporter();
                var exporter    = new XmlSchemaExporter(schemas);

                var xmlTypeMapping = xmlImporter.ImportTypeMapping(type, new XmlRootAttribute()
                {
                    ElementName = name
                });
                exporter.ExportTypeMapping(xmlTypeMapping);
                schemas.Compile(null, true);

                var memoryStream = new MemoryStream();
                foreach (XmlSchema schema in schemas)
                {
                    schema.Write(memoryStream);
                }
                memoryStream.Position = 0;

                var streamReader = new StreamReader(memoryStream);
                var result       = streamReader.ReadToEnd();

                var doc = new XmlDocument();
                doc.LoadXml(result);
                doc.DocumentElement.WriteContentTo(writer);

                return(true);
            }

            var xmlSchemaSet = xmlNamespaceManager == null ? new XmlSchemaSet() : new XmlSchemaSet(xmlNamespaceManager.NameTable);
            var xmlSchemaProviderAttribute = type.GetCustomAttribute <XmlSchemaProviderAttribute>(true);

            if (xmlSchemaProviderAttribute != null && true)
            {
                XmlSchema schema = new XmlSchema();
                if (xmlNamespaceManager != null)
                {
                    schema.Namespaces = xmlNamespaceManager.Convert();
                }
                if (xmlSchemaProviderAttribute.IsAny)
                {
                    //MetaWCFBodyWriter usage....
                    //writer.WriteAttributeString("name", name);
                    //writer.WriteAttributeString("nillable", "true");
                    //writer.WriteStartElement("xs", "complexType", Namespaces.XMLNS_XSD);
                    //writer.WriteStartElement("xs", "sequence", Namespaces.XMLNS_XSD);
                    //writer.WriteStartElement("xs", "any", Namespaces.XMLNS_XSD);
                    //writer.WriteAttributeString("minOccurs", "0");
                    //writer.WriteAttributeString("processContents", "lax");
                    //writer.WriteEndElement();
                    //writer.WriteEndElement();
                    //writer.WriteEndElement();
                    var sequence = new XmlSchemaSequence();
                    sequence.Items.Add(new XmlSchemaAny()
                    {
                        ProcessContents = XmlSchemaContentProcessing.Lax
                    });
                    var complex = new XmlSchemaComplexType()
                    {
                        Particle = sequence
                    };
                    var element = new XmlSchemaElement()
                    {
                        MinOccurs  = 0,
                        MaxOccurs  = 1,
                        Name       = name,
                        IsNillable = serializer == SoapSerializer.DataContractSerializer ? true : false,
                        SchemaType = complex
                    };
                    schema.Items.Add(element);
                }
                else
                {
                    var methodInfo    = type.GetMethod(xmlSchemaProviderAttribute.MethodName, BindingFlags.Static | BindingFlags.Public);
                    var xmlSchemaType = (XmlSchemaType)methodInfo.Invoke(null, new object[] { xmlSchemaSet });
                    var element       = new XmlSchemaElement()
                    {
                        MinOccurs  = 0,
                        MaxOccurs  = 1,
                        Name       = name,
                        SchemaType = xmlSchemaType
                    };
                    schema.Items.Add(element);
                }

                var memoryStream = new MemoryStream();
                schema.Write(memoryStream);
                memoryStream.Position = 0;

                var streamReader = new StreamReader(memoryStream);
                var result       = streamReader.ReadToEnd();

                var doc = new XmlDocument();
                doc.LoadXml(result);
                doc.DocumentElement.WriteContentTo(writer);

                return(true);
            }

            return(false);
        }
        public bool Convert()
        {
            this.m_Errors.Clear();
            this.m_Warnings.Clear();
            // identify the path to the xsd
            if (string.IsNullOrEmpty(this.XsdFileName))
            {
                this.Errors.Add(Properties.Resources.ErrorEmptyXsdFileName);
                return(false);
            }
            string _xsdFileName = string.Empty;

            if (this.XsdFileName.IndexOf(Path.DirectorySeparatorChar) < 0)
            {
                string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                _xsdFileName = Path.Combine(path, this.XsdFileName);
            }
            else
            {
                _xsdFileName = this.XsdFileName;
            }

            if (File.Exists(_xsdFileName) == false)
            {
                this.Errors.Add(Properties.Resources.ErrorMissingXsdFile);
                return(false);
            }
            this.m_FileName = _xsdFileName;

            // load the xsd

            XmlSchema xsd;

            using (FileStream stream = new FileStream(this.m_FileName, FileMode.Open, FileAccess.Read))
            {
                xsd = XmlSchema.Read(stream, null);
                ValidationEventHandler vc = new ValidationEventHandler(ValidationCallback);
            }
            //Console.WriteLine("xsd.IsCompiled {0}", xsd.IsCompiled);

            XmlSchemas             xsds     = new XmlSchemas();
            ValidationEventHandler vHandler = new ValidationEventHandler(ValidationCallback);

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

            // create the codedom
            CodeNamespace   codeNamespace = new CodeNamespace();
            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(XmlSchemaAttribute schemaAttrib in xsd.Attributes.Values)
            //{
            //    maps.Add(schemaImporter.imp)
            //}
            foreach (XmlTypeMapping map in maps)
            {
                codeExporter.ExportTypeMapping(map);
            }
            if (RemoveExtraAttributes == true)
            {
                RemoveAttributes(codeNamespace);
            }


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

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

            this.m_Code  = string.Format(Properties.Resources.AutoGenMessage, Assembly.GetExecutingAssembly().GetName().Version.ToString());
            this.m_Code += Environment.NewLine;

            using (StringWriter writer = new StringWriter())
            {
                codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions());
                //Console.WriteLine(writer.GetStringBuilder().ToString());
                this.m_Code += writer.GetStringBuilder().ToString();
            }
            return(this.HasErrors);
        }
Пример #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="xsdFilename"></param>
        /// <param name="targetNamespace"></param>
        /// <returns></returns>
        public static CodeNamespace Process(string xsdFilename, string targetNamespace)
        {
            XmlReaderSettings settings = new XmlReaderSettings
            {
            };
            XmlSchema xsd;

            using (var reader = XmlReader.Create(xsdFilename))
            {
                xsd = XmlSchema.Read(reader, MyValidationEventHandler);
            }

            XmlSchemas schemas = new XmlSchemas(); // Internal class

            int elementCount = xsd.Elements.Count; // 0 Elements is a post-schema-compilation property
            int indexOf      = schemas.Add(xsd);   // Method will only add (to end) if it does not exists, and return the one stored internally

            elementCount = xsd.Elements.Count;     // 1 OOOPS! Looks like Add do some magic to added XmlSchema


            schemas.Compile(MyValidationEventHandler, true); // What is fullCompile?
            //var appinfos = xsd.Items.OfType<XmlSchemaAnnotation>().SelectMany(a => a.Items.OfType<XmlSchemaAppInfo>().SelectMany(m => m.Markup)).ToList();

            //foreach (var attr in xsd.UnhandledAttributes)
            //{
            //    Console.WriteLine("UnhandledAttribute: " + attr.LocalName);
            //}

            // Create the importer for these schemas.
            CodeDomProvider       codeProvider    = CodeDomProvider.CreateProvider("CSharp"); // shared import & export
            CodeGenerationOptions options         = CodeGenerationOptions.GenerateProperties; // shared import & export
            CodeIdentifiers       typeIdentifiers = new CodeIdentifiers();
            ImportContext         context         = new ImportContext(typeIdentifiers, true); // true=share custom types amongst schemas

            XmlSchemaImporter importer = new XmlSchemaImporter(schemas, options, context);


            // System.CodeDom namespace for the XmlCodeExporter to put classes in.
            CodeNamespace   ns = new CodeNamespace(targetNamespace);
            CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
            Hashtable       mappings        = new Hashtable();

            XmlCodeExporter exporter = new XmlCodeExporter(ns, codeCompileUnit, options, mappings);

            // Test identifier uniqueness
            string s    = "FirstName";
            var    ustr = typeIdentifiers.MakeUnique(s); // FirstName

            ustr = typeIdentifiers.MakeUnique(s);        // FirstName
            typeIdentifiers.Add(s, s);
            ustr = typeIdentifiers.MakeUnique(s);        // FirstName1
            typeIdentifiers.Remove(s);
            ustr = typeIdentifiers.MakeUnique(s);        // FirstName
            typeIdentifiers.Add(s, s);


            // Iterate schema top-level elements and export code for each.
            foreach (XmlSchemaElement element in xsd.Elements.Values)
            {
                //var appinfos = element.Annotation.Items.OfType<XmlSchemaAppInfo>().ToArray();

                // Import the mapping first.
                var            ss      = typeIdentifiers.ToArray(typeof(string)); // 1
                XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName);
                ss = typeIdentifiers.ToArray(typeof(string));                     // 2


                // Export the code finally.
                int count = mappings.Count; // 0
                exporter.ExportTypeMapping(mapping);
                count = mappings.Count;     // 5
            }

            foreach (var schemaType in xsd.SchemaTypes.Values.Cast <XmlSchemaType>())
            {
                var    map2 = importer.ImportSchemaType(schemaType.QualifiedName);
                string s2   = map2.TypeFullName;
            }
            return(ns);
        }
Пример #25
0
        private ServiceDescriptionImportWarnings Import(CodeNamespace codeNamespace, ImportContext importContext, Hashtable exportContext, StringCollection warnings)
        {
            allSchemas = new XmlSchemas();
            foreach (XmlSchema schema in schemas)
            {
                allSchemas.Add(schema);
            }
            foreach (ServiceDescription description in serviceDescriptions)
            {
                foreach (XmlSchema schema in description.Types.Schemas)
                {
                    allSchemas.Add(schema);
                }
            }
            Hashtable references = new Hashtable();

            if (!allSchemas.Contains(ServiceDescription.Namespace))
            {
                allSchemas.AddReference(ServiceDescription.Schema);
                references[ServiceDescription.Schema] = ServiceDescription.Schema;
            }
            if (!allSchemas.Contains(Soap.Encoding))
            {
                allSchemas.AddReference(ServiceDescription.SoapEncodingSchema);
                references[ServiceDescription.SoapEncodingSchema] = ServiceDescription.SoapEncodingSchema;
            }
            allSchemas.Compile(null, false);

            // Segregate the schemas containing abstract types from those
            // containing regular XML definitions.  This is important because
            // when you import something returning the ur-type (object), then
            // you need to import ALL types/elements within ALL schemas.  We
            // don't want the RPC-based types leaking over into the XML-based
            // element definitions.  This also occurs when you have derivation:
            // we need to search the schemas for derived types: but WHICH schemas
            // should we search.
            foreach (ServiceDescription description in serviceDescriptions)
            {
                foreach (Message message in description.Messages)
                {
                    foreach (MessagePart part in message.Parts)
                    {
                        bool isEncoded;
                        bool isLiteral;
                        FindUse(part, out isEncoded, out isLiteral);
                        if (part.Element != null && !part.Element.IsEmpty)
                        {
                            if (isEncoded)
                            {
                                throw new InvalidOperationException(Res.GetString(Res.CanTSpecifyElementOnEncodedMessagePartsPart, part.Name, message.Name));
                            }
                            XmlSchemaElement element = (XmlSchemaElement)allSchemas.Find(part.Element, typeof(XmlSchemaElement));
                            if (element != null)
                            {
                                AddSchema(element.Parent as XmlSchema, isEncoded, isLiteral, abstractSchemas, concreteSchemas, references);
                                if (element.SchemaTypeName != null && !element.SchemaTypeName.IsEmpty)
                                {
                                    XmlSchemaType type = (XmlSchemaType)allSchemas.Find(element.SchemaTypeName, typeof(XmlSchemaType));
                                    if (type != null)
                                    {
                                        AddSchema(type.Parent as XmlSchema, isEncoded, isLiteral, abstractSchemas, concreteSchemas, references);
                                    }
                                }
                            }
                        }
                        if (part.Type != null && !part.Type.IsEmpty)
                        {
                            XmlSchemaType type = (XmlSchemaType)allSchemas.Find(part.Type, typeof(XmlSchemaType));
                            if (type != null)
                            {
                                AddSchema(type.Parent as XmlSchema, isEncoded, isLiteral, abstractSchemas, concreteSchemas, references);
                            }
                        }
                    }
                }
            }

            Hashtable imports;

            foreach (XmlSchemas xmlschemas in new XmlSchemas[] { abstractSchemas, concreteSchemas })
            {
                // collect all imports
                imports = new Hashtable();
                foreach (XmlSchema schema in xmlschemas)
                {
                    AddImport(schema, imports);
                }
                // make sure we add them to the corresponding schema collections
                foreach (XmlSchema schema in imports.Keys)
                {
                    if (references[schema] == null && !xmlschemas.Contains(schema))
                    {
                        xmlschemas.Add(schema);
                    }
                }
            }

            // If a schema was not referenced by either a literal or an encoded message part,
            // add it to both collections. There's no way to tell which it should be.
            imports = new Hashtable();
            foreach (XmlSchema schema in allSchemas)
            {
                if (!abstractSchemas.Contains(schema) && !concreteSchemas.Contains(schema))
                {
                    AddImport(schema, imports);
                }
            }

            // make sure we add them to the corresponding schema collections
            foreach (XmlSchema schema in imports.Keys)
            {
                if (references[schema] != null)
                {
                    continue;
                }
                if (!abstractSchemas.Contains(schema))
                {
                    abstractSchemas.Add(schema);
                }
                if (!concreteSchemas.Contains(schema))
                {
                    concreteSchemas.Add(schema);
                }
            }
            if (abstractSchemas.Count > 0)
            {
                foreach (XmlSchema schema in references.Values)
                {
                    abstractSchemas.AddReference(schema);
                }
                StringCollection schemaWarnings = SchemaCompiler.Compile(abstractSchemas);
                foreach (string warning in schemaWarnings)
                {
                    warnings.Add(warning);
                }
            }
            if (concreteSchemas.Count > 0)
            {
                foreach (XmlSchema schema in references.Values)
                {
                    concreteSchemas.AddReference(schema);
                }
                StringCollection schemaWarnings = SchemaCompiler.Compile(concreteSchemas);
                foreach (string warning in schemaWarnings)
                {
                    warnings.Add(warning);
                }
            }
            if (ProtocolName.Length > 0)
            {
                // If a protocol was specified, only try that one
                ProtocolImporter importer = FindImporterByName(ProtocolName);
                if (importer.GenerateCode(codeNamespace, importContext, exportContext))
                {
                    return(importer.Warnings);
                }
            }
            else
            {
                // Otherwise, do "best" protocol (first one that generates something)
                for (int i = 0; i < importers.Length; i++)
                {
                    ProtocolImporter importer = importers[i];
                    if (importer.GenerateCode(codeNamespace, importContext, exportContext))
                    {
                        return(importer.Warnings);
                    }
                }
            }
            return(ServiceDescriptionImportWarnings.NoCodeGenerated);
        }
Пример #26
0
        static void Demo6()
        {
            // load the xsd
            XmlSchema xsd = null;

            using (FileStream stream = new FileStream("..\\..\\Test.xsd", FileMode.Open, FileAccess.Read))
            {
                xsd = XmlSchema.Read(stream, null);
            }

            XmlSchemas xsds = new XmlSchemas();

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

            // create the codedom
            CodeNamespace   ns  = new CodeNamespace();
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.ReferencedAssemblies.Add(typeof(XmlTypeAttribute).Assembly.GetName().ToString());
            ccu.Namespaces.Add(ns);
            XmlCodeExporter codeExporter = new XmlCodeExporter(ns, ccu);

            var maps = new List <XmlTypeMapping>();

            foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values)
            {
                maps.Add(xsdImporter.ImportSchemaType(schemaType.QualifiedName));
            }
            foreach (XmlSchemaElement schemaElement in xsd.Elements.Values)
            {
                maps.Add(xsdImporter.ImportTypeMapping(schemaElement.QualifiedName));
            }
            foreach (XmlTypeMapping map in maps)
            {
                codeExporter.ExportTypeMapping(map);
            }
            var typeMap = new Dictionary <string, CodeTypeDeclaration>(StringComparer.InvariantCulture);

            _FillTypeMap(ns, typeMap);
            foreach (var kvp in typeMap)
            {
                var td       = kvp.Value;
                var propElem = new HashSet <string>(StringComparer.InvariantCulture);
                var propAttr = new HashSet <string>(StringComparer.InvariantCulture);
                var fldMap   = new Dictionary <string, string>();
                _FillPropFldMaps(td, propElem, propAttr, fldMap);
                // fix up our xml type attribute
                foreach (CodeAttributeDeclaration d in td.CustomAttributes)
                {
                    if (0 == string.Compare(d.AttributeType.BaseType, "System.Xml.Serialization.XmlAttributeAttribute", StringComparison.InvariantCulture))
                    {
                        d.Arguments.Insert(0, new CodeAttributeArgument("TypeName", new CodePrimitiveExpression(td.Name)));
                        break;
                    }
                }
                // correct the type name
                td.Name = _ToNetCase(td.Name);
                CodeDomVisitor.Visit(td, (ctx) =>
                {
                    var fldRef = ctx.Target as CodeFieldReferenceExpression;
                    if (null != fldRef && fldMap.ContainsKey(fldRef.FieldName))
                    {
                        fldRef.FieldName = _ToPrivFldName(fldRef.FieldName);
                        return;
                    }
                    var fld = ctx.Target as CodeMemberField;
                    if (null != fld && fldMap.ContainsKey(fld.Name))
                    {
                        fld.Name = _ToPrivFldName(fld.Name);
                        var ctr  = fld.Type;
                        if (0 < ctr.ArrayRank)
                        {
                            ctr = ctr.ArrayElementType;
                        }
                        if (!CodeDomResolver.IsPrimitiveType(ctr))
                        {
                            ctr.BaseType = _ToNetCase(ctr.BaseType);
                        }
                    }
                    var prop = ctx.Target as CodeMemberProperty;
                    if (null != prop && (propElem.Contains(prop.Name) || propAttr.Contains(prop.Name)))
                    {
                        var n   = prop.Name;
                        var ctr = prop.Type;
                        if (0 < ctr.ArrayRank)
                        {
                            ctr = ctr.ArrayElementType;
                        }
                        if (!CodeDomResolver.IsPrimitiveType(ctr))
                        {
                            ctr.BaseType = _ToNetCase(ctr.BaseType);
                        }
                        prop.Name = _ToNetCase(n);
                        if (propElem.Contains(n))
                        {
                            foreach (CodeAttributeDeclaration a in prop.CustomAttributes)
                            {
                                if (0 == string.Compare("System.Xml.Serialization.XmlElementAttribute", a.AttributeType.BaseType, StringComparison.InvariantCulture))
                                {
                                    a.Arguments.Insert(0, new CodeAttributeArgument("ElementName", new CodePrimitiveExpression(n)));
                                    break;
                                }
                            }
                        }
                        else
                        {
                            foreach (CodeAttributeDeclaration a in prop.CustomAttributes)
                            {
                                if (0 == string.Compare("System.Xml.Serialization.XmlAttributeAttribute", a.AttributeType.BaseType, StringComparison.InvariantCulture))
                                {
                                    a.Arguments.Insert(0, new CodeAttributeArgument("AttributeName", new CodePrimitiveExpression(n)));
                                    break;
                                }
                            }
                        }
                    }
                });
            }

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

            // output the C# code
            Console.WriteLine(CodeDomUtility.ToString(ccu));
        }
Пример #27
0
        public void Generate(IList <String> schemas, TextWriter output)
        {
            if (Options == null)
            {
                Options = new XsdCodeGeneratorOptions
                {
                    UseLists = true,
                    PropertyNameCapitalizer = new FirstCharacterCapitalizer(),
                    OutputNamespace         = "Xsd2",
                    UseNullableTypes        = true,
                    AttributesToRemove      =
                    {
                        "System.Diagnostics.DebuggerStepThroughAttribute"
                    }
                };
            }

            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));
                    }
                }
            }

            var inputs = new List <XmlSchema>();

            foreach (var path in schemas)
            {
                using (var r = File.OpenText(path))
                {
                    XmlSchema xsd = XmlSchema.Read(r, null);
                    xsds.Add(xsd);
                    inputs.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 (var xsd in inputs)
            {
                foreach (XmlSchemaElement schemaElement in xsd.Elements.Values)
                {
                    if (!ElementBelongsToImportedSchema(schemaElement))
                    {
                        maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName));
                    }
                }
            }


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

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

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

            foreach (var xsd in inputs)
            {
                ImproveCodeDom(codeNamespace, xsd);
            }

            if (OnValidateGeneratedCode != null)
            {
                foreach (var xsd in inputs)
                {
                    OnValidateGeneratedCode(codeNamespace, xsd);
                }
            }

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

            if (Options.WriteFileHeader)
            {
                // output the header
                string lineCommentCharacter;
                switch (Options.Language)
                {
                case XsdCodeGeneratorOutputLanguage.VB:
                    lineCommentCharacter = "'";
                    break;

                default:
                    lineCommentCharacter = "//";
                    break;
                }

                output.WriteLine("{0}------------------------------------------------------------------------------", lineCommentCharacter);
                output.WriteLine("{0} <auto-generated>", lineCommentCharacter);
                output.WriteLine("{0}     This code has been generated by a tool.", lineCommentCharacter);
                output.WriteLine("{0} </auto-generated>", lineCommentCharacter);
                output.WriteLine("{0}------------------------------------------------------------------------------", lineCommentCharacter);
                output.WriteLine();
            }

            // output the C# code
            CodeDomProvider codeProvider;

            switch (Options.Language)
            {
            case XsdCodeGeneratorOutputLanguage.VB:
                codeProvider = new VBCodeProvider();
                break;

            default:
                codeProvider = new CSharpCodeProvider();
                break;
            }

            codeProvider.GenerateCodeFromNamespace(codeNamespace, output, new CodeGeneratorOptions());
        }
Пример #28
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);

            // 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();

            var options = new CodeGeneratorOptions
            {
                BlankLinesBetweenMembers = true,
                BracingStyle             = "C",
                ElseOnClosing            = true,
                IndentString             = "    "
            };

            using (StringWriter writer = new StringWriter())
            {
                codeProvider.GenerateCodeFromCompileUnit(
                    new CodeSnippetCompileUnit("#pragma warning disable 1591"),
                    writer, options);
                codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, options);
                codeProvider.GenerateCodeFromCompileUnit(
                    new CodeSnippetCompileUnit("#pragma warning restore 1591"),
                    writer, options);

                string content = writer.GetStringBuilder().ToString();
                if (string.IsNullOrEmpty(output))
                {
                    Console.WriteLine(content);
                    Console.ReadLine();
                }
                else
                {
                    File.WriteAllText(output, content);
                }
            }
        }
Пример #29
0
        /// <summary>
        ///     .net assemblies (dll(s) when on disk) go in and .xsd file contents comes out
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="typeNames"></param>
        /// <returns></returns>
        public static List <string> ExportSchemas(Assembly assembly, List <string> typeNames = null, string xmlDefaultNamespace = null)
        {
            if (typeNames == null)
            {
                typeNames = new List <string>();
            }

            XmlReflectionImporter xmlReflectionImporter = new XmlReflectionImporter(xmlDefaultNamespace);
            XmlSchemas            xmlSchemas            = new XmlSchemas();
            XmlSchemaExporter     xmlSchemaExporter     = new XmlSchemaExporter(xmlSchemas);

            try
            {
                Type[] types = assembly.GetTypes();
                for (int i = 0; i < types.Length; i++)
                {
                    Type type = types[i];
                    if (type.IsPublic && (!type.IsAbstract || !type.IsSealed) && !type.IsInterface && !type.ContainsGenericParameters)
                    {
                        bool flag;
                        if (typeNames.Count == 0)
                        {
                            flag = true;
                        }
                        else
                        {
                            flag = false;
                            foreach (string text2 in typeNames)
                            {
                                if (type.FullName == text2 || type.Name == text2 || (text2.EndsWith(".*") && type.FullName.StartsWith(text2.Substring(0, text2.Length - 2))))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        if (flag)
                        {
                            XmlTypeMapping xmlTypeMapping = xmlReflectionImporter.ImportTypeMapping(type);
                            xmlSchemaExporter.ExportTypeMapping(xmlTypeMapping);
                        }
                    }
                }

                xmlSchemas.Compile(ValidationCallbackWithErrorCode, false);
            } catch (Exception ex)
            {
                if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException)
                {
                    throw;
                }
                throw new InvalidOperationException("General Error", ex);
            }

            List <string> xmlSchemasList = new List <string>(xmlSchemas.Count);

            foreach (XmlSchema _XmlSchema in xmlSchemas)
            {
                try
                {
                    using (StringWriter _StringWriter = new StringWriter())
                    {
                        XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());
                        //// the default namespace prefix of xs makes Microsoft word upset, it was found that a
                        //namespaceManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
                        _XmlSchema.Write(_StringWriter, namespaceManager);
                        xmlSchemasList.Add(_StringWriter.ToString());
                    }
                } catch (Exception ex2)
                {
                    if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException)
                    {
                        throw;
                    }
                    throw new InvalidOperationException(Res.GetString("ErrGeneral", _XmlSchema.TargetNamespace), ex2);
                }
            }

            return(xmlSchemasList);
        }
Пример #30
0
        static void Main(string[] args)
        {
            CodeCompileUnit ccu = new CodeCompileUnit();

            ccu.ReferencedAssemblies.AddRange(new[] { "System", "System.Xml.Serialization" });
            var schemaSet = new XmlSchemaSet();       // reprocess and compile as much as we want

            schemaSet.Add(null, @"xsd/mystatus.xsd"); // will add the others
            schemaSet.Compile();

            var mybaseSchema    = schemaSet.Schemas("http://tempuri.org/mybase.xsd").OfType <XmlSchema>().Single();
            var myderivedSchema = schemaSet.Schemas("http://tempuri.org/myderived.xsd").OfType <XmlSchema>().Single();
            var mystatusSchema  = schemaSet.Schemas("http://tempuri.org/mystatus.xsd").OfType <XmlSchema>().Single();

            //ReplaceBaseWithBasesBase(myderivedSchema);
            schemaSet.Reprocess(myderivedSchema);
            schemaSet.Compile();

            var xmlSysImport = new CodeNamespaceImport("System");
            var xmlNsImport  = new CodeNamespaceImport("System.Xml.Serialization");
            var mybaseNs     = new CodeNamespace("MyBase");
            var myDerivedNs  = new CodeNamespace("MyDerived")
            {
                Imports = { xmlSysImport, xmlNsImport, new CodeNamespaceImport(mybaseNs.Name) }
            };
            var myStatusNs = new CodeNamespace("MyStatus")
            {
                Imports = { xmlSysImport, xmlNsImport, new CodeNamespaceImport(myDerivedNs.Name) }
            };

            ccu.Namespaces.AddRange(new[] { mybaseNs, myDerivedNs, myStatusNs });

            var schemas = new XmlSchemas();

            foreach (XmlSchema schema in schemaSet.Schemas())
            {
                schemas.Add(schema);
            }
            //schemas.Compile(ValidationEventHandler, true); // can't change model after compile! XmlSchamaSet.Reprocess handle this!
            schemas.Compile(ValidationEventHandler, true);

            CodeIdentifiers       typeIdentifiers = new CodeIdentifiers(true);
            ImportContext         context         = new ImportContext(typeIdentifiers, shareTypes: false);
            CodeGenerationOptions options         = CodeGenerationOptions.GenerateOrder;
            var providerOptions        = new Dictionary <string, string>();
            var provider               = new CSharpCodeProvider(providerOptions);
            XmlSchemaImporter importer = new XmlSchemaImporter(schemas, options, provider, context); // for xml schemas

            importer.Extensions.Clear();
            //importer.Extensions.Add(new MyImporterExtension());
            Hashtable mappings = new Hashtable();

            MapTypes(mybaseSchema, importer, mybaseNs, ccu, provider, options, mappings);
            MapTypes(myderivedSchema, importer, myDerivedNs, ccu, provider, options, mappings);
            MapTypes(mystatusSchema, importer, myStatusNs, ccu, provider, options, mappings);

            //XmlCodeExporter exporter = new XmlCodeExporter(myStatusNs, ccu, CodeGenerationOptions.GenerateOrder);
            //foreach (XmlSchemaElement element in mystatusSchema.Elements.Values)
            //{
            //    XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName);
            //    exporter.ExportTypeMapping(mapping);
            //}

            using (StreamWriter writer = File.CreateText(@"..\..\..\TestGeneratedCode\status.cs"))
            {
                //globalNs.Comments.Clear();
                //globalNs.Name = "MyGlobal";
                provider.GenerateCodeFromCompileUnit(ccu, writer, new CodeGeneratorOptions {
                    BracingStyle = "C", BlankLinesBetweenMembers = false
                });
            }
            Console.WriteLine("Press enter");
            Console.ReadLine();
        }