/// <summary>
        /// Performs building codedom tree objects from Xsd schema
        /// </summary>
        /// <param name="xsdContext">Holds data about XSD schema</param>
        /// <param name="codeDomContext">Holds codeDomTree</param>
        public void Execute(XsdContext xsdContext, CodeDomContext codeDomContext)
        {
            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsdContext.XmlSchemas);

            // Step 1:  Create code namespace
            xsdContext.CodeExporter = new XmlCodeExporter(codeDomContext.CodeNamespace);

            List <object> maps = new List <object>();

            // Find out schema types of objects and add to collection
            foreach (XmlSchema xsd in xsdContext.XmlSchemaList)
            {
                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));
                }
            }

            // export object collection to namespace. Now defined namespace will have all schema objects such as complexTypes, simpleTypes etc.
            foreach (XmlTypeMapping map in maps)
            {
                xsdContext.CodeExporter.ExportTypeMapping(map);
            }
        }
Esempio n. 2
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();
        }
Esempio n. 3
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();
        }
Esempio n. 4
0
 private static void GenerateForComplexTypes(XmlSchema xsd, XmlSchemaImporter importer, XmlCodeExporter exporter)
 {
     foreach (XmlSchemaObject type in xsd.SchemaTypes.Values)
     {
         XmlSchemaComplexType ct = type as XmlSchemaComplexType;
         if (ct != null)
         {
             XmlTypeMapping mapping = importer.ImportSchemaType(ct.QualifiedName);
             exporter.ExportTypeMapping(mapping);
         }
     }
 }
Esempio n. 5
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());
            }
        }
Esempio n. 6
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();
        }
Esempio n. 7
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());
    }
Esempio n. 9
0
        private static CodeNamespace ProcessSchema(SchemaDefinition schemaDefinition, bool includeDataContractAttributes)
        {
            var ns = new CodeNamespace(schemaDefinition.Namespace);

            var reader = XmlReader.Create(schemaDefinition.SchemaPath);
            var xsd    = XmlSchema.Read(reader, Validate);

            var schemas = new XmlSchemas();

            var schemaSet = new XmlSchemaSet();

            schemaSet.Add(xsd);
            schemaSet.Compile();

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

            const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateOrder;
            var exporter = new XmlCodeExporter(ns);
            var importer = new XmlSchemaImporter(schemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

            foreach (var mapping in
                     xsd.Items.OfType <XmlSchemaType>().Select(item => importer.ImportSchemaType(item.QualifiedName)))
            {
                exporter.ExportTypeMapping(mapping);
            }

            var includes = Helper.GetSchemaIncludes(schemaSet);

            FilterIncludedTypes(ns, xsd);
            AddIncludeImports(ns, includes);
            RemoveXmlRootAttributeForNoneRootTypes(ns, schemaSet);
            if (includeDataContractAttributes)
            {
                AddDataContractAttributes(ns, schemaDefinition.XmlNamespace);
            }

            return(ns);
        }
        private CodeCompileUnit ExportCodeFromSchemas(XmlSchemas schemas)
        {
            CodeNamespace   ns   = new CodeNamespace(this.TargetNamespace);
            CodeCompileUnit unit = new CodeCompileUnit();

            unit.Namespaces.Add(ns);

            XmlSchemaImporter importer = new XmlSchemaImporter(schemas,
                                                               CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync,
                                                               new ImportContext(new CodeIdentifiers(), true));
            XmlCodeExporter exporter = new XmlCodeExporter(ns, unit,
                                                           CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties);

            List <XmlTypeMapping> mappings = new List <XmlTypeMapping>();

            foreach (XmlSchema xsd in schemas)
            {
                foreach (XmlSchemaType type in xsd.SchemaTypes.Values)
                {
                    mappings.Add(importer.ImportSchemaType(type.QualifiedName));
                }

                if (!this.ProcessComplexTypesOnly)
                {
                    foreach (XmlSchemaElement element in xsd.Elements.Values)
                    {
                        mappings.Add(importer.ImportTypeMapping(element.QualifiedName));
                    }
                }
            }

            foreach (XmlTypeMapping mapping in mappings)
            {
                exporter.ExportTypeMapping(mapping);
            }

            CodeGenerator.ValidateIdentifiers(ns);

            return(unit);
        }
            private static void AddTypes(CodeNamespace codeNamespace, XmlSchemaSet schemaSet)
            {
                var schemas = new XmlSchemas();

                foreach (var schema in schemaSet.Schemas().Cast <XmlSchema>())
                {
                    schemas.Add(schema);
                }
                var schemaImporter = new XmlSchemaImporter(schemas);

#if NETFRAMEWORK
                schemaImporter.Extensions.Add(new NodaTimeSchemaImporterExtension());
                var codeExporter = new XmlCodeExporter(codeNamespace);
                foreach (var schemaObject in schemas.SelectMany(e => e.Items.Cast <XmlSchemaObject>()))
                {
                    XmlTypeMapping mapping;
                    switch (schemaObject)
                    {
                    case XmlSchemaType schemaType:
                        mapping = schemaImporter.ImportSchemaType(schemaType.QualifiedName);
                        break;

                    case XmlSchemaElement schemaElement:
                        mapping = schemaImporter.ImportTypeMapping(schemaElement.QualifiedName);
                        break;

                    default:
                        continue;
                    }
                    codeExporter.ExportTypeMapping(mapping);
                }
                CodeGenerator.ValidateIdentifiers(codeNamespace);
#else
                throw new PlatformNotSupportedException($"{nameof(XmlCodeExporterAssemblyCreator)} is not available");
#endif
            }
        /// <summary>
        /// Generates the <see cref="CodeNamespace"/> based on the provide context.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        public CodeNamespace[] GenerateCodes(ICodeGeneratorContext codeGeneratorContext)
        {
            CodeGenOptions codeGenOptions = codeGeneratorContext.CodeGenOptions;
            XmlSchemas     xmlSchemas     = codeGeneratorContext.XmlSchemas;

            List <CodeNamespace> codeNamespaces = new List <CodeNamespace>();

            // Generate DataContracts
            const CodeGenerationOptions            generationOptions                  = CodeGenerationOptions.GenerateProperties;
            IDictionary <string, XmlSchemaType>    typeName2schemaTypeMapping         = codeGeneratorContext.TypeName2schemaTypeMapping;
            IDictionary <XmlQualifiedName, string> elementName2TypeNameMapping        = codeGeneratorContext.ElementName2TypeNameMapping;
            IDictionary <string, string>           elementName2TargetNamespaceMapping = codeGeneratorContext.ElementName2TargetNamespaceMapping;

            foreach (XmlSchema schema in xmlSchemas)
            {
                CodeNamespace codeNamespace = new CodeNamespace();
                codeNamespace.UserData.Add(Constants.SCHEMA, schema);

                // TypeName to XmlSchemaType mapping
                XmlCodeExporter   exporter = new XmlCodeExporter(codeNamespace);
                XmlSchemaImporter importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName);
                    if (element.IsAbstract)
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    if (typeMapping.XsdTypeName == "anyType")
                    {
                        continue;                                       // ignore no type element
                    }
                    if (string.IsNullOrWhiteSpace(typeMapping.XsdTypeName))
                    {
                        throw new Exception("Cannot use anonymous type for Request/Response element: " + element.Name + ".");
                    }
                    typeName2schemaTypeMapping[typeMapping.XsdTypeName]            = element.ElementSchemaType;
                    elementName2TypeNameMapping[element.QualifiedName]             = typeMapping.XsdTypeName;
                    elementName2TargetNamespaceMapping[element.QualifiedName.Name] = schema.TargetNamespace;
                }

                foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                {
                    if (String.IsNullOrWhiteSpace(schemaType.SourceUri))
                    {
                        schemaType.SourceUri = schema.SourceUri;
                    }
                    XmlTypeMapping typeMapping = importer.ImportSchemaType(schemaType.QualifiedName);
                    if (DataContractGenerator.CouldBeAnArray(schemaType))
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    typeName2schemaTypeMapping[typeMapping.TypeName] = schemaType;
                }

                if (codeNamespace.Types.Count > 0)
                {
                    codeNamespaces.Add(codeNamespace);
                }
            }

            if (codeNamespaces.Count == 0)
            {
                throw new Exception("No types were generated.");
            }

            // Build type name to code type declaration mapping
            codeGeneratorContext.CodeTypeMap = DataContractGenerator.BuildCodeTypeMap(codeNamespaces.ToArray());

            for (int i = 0; i < codeNamespaces.Count; i++)
            {
                CodeNamespace codeNamespace = codeNamespaces[i];
                // Decorate data contracts code
                ICodeExtension codeExtension = new CodeExtension();
                codeExtension.Process(codeNamespace, codeGeneratorContext);

                // Import SOA common type namespace before removing code types
                codeNamespace.Imports.Add(new CodeNamespaceImport(Constants.C_SERVICE_STACK_COMMON_TYPES_NAMESPACE));
                // Remove SOA common types since they have already been included in CSerivceStack DLL
                CodeExtension.RemoveSOACommonTypes(codeNamespace);

                CodeExtension.RemoveDefaultTypes(codeNamespace);

                XmlSchema schema = codeNamespace.UserData[Constants.SCHEMA] as XmlSchema;
                List <CodeTypeDeclaration> types = new List <CodeTypeDeclaration>();
                foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                {
                    foreach (CodeTypeDeclaration codeType in codeNamespace.Types)
                    {
                        if (codeType.Name == schemaType.Name &&
                            schema.SourceUri == schemaType.SourceUri)
                        {
                            types.Add(codeType);
                        }
                    }
                }
                codeNamespace.Types.Clear();
                codeNamespace.Types.AddRange(types.ToArray());
                if (codeNamespace.Types.Count == 0)
                {
                    codeNamespaces.RemoveAt(i--);
                }
            }

            codeNamespaces.ImplementsBaijiSerialization(codeGeneratorContext);

            //Add Interface CodeNamespace
            CodeNamespace interfaceNamespace = new CodeNamespace(codeGenOptions.ClrNamespace);
            // Generate interface code
            string                        wsdlFile          = codeGeneratorContext.CodeGenOptions.MetadataLocation;
            InterfaceContract             interfaceContract = ServiceDescriptionEngine.GetInterfaceContract(wsdlFile);
            CodeTypeDeclaration           interfaceType;
            CodeNamespaceImportCollection imports;

            this.buildInterfaceCode(codeGeneratorContext, interfaceContract, out interfaceType, out imports);
            interfaceNamespace.Types.Add(interfaceType);
            foreach (CodeNamespaceImport @import in imports)
            {
                interfaceNamespace.Imports.Add(@import);
            }

            // Import SOA common type namespace before removing code types
            interfaceNamespace.Imports.Add(new CodeNamespaceImport(Constants.C_SERVICE_STACK_COMMON_TYPES_NAMESPACE));
            // Remove SOA common types since they have already been included in CSerivceStack DLL
            CodeExtension.RemoveSOACommonTypes(interfaceNamespace);
            CodeExtension.RemoveDefaultTypes(interfaceNamespace);

            string fileName = null;

            if (codeGeneratorContext.CodeGenOptions.CodeGeneratorMode == CodeGeneratorMode.Service)
            {
                fileName = "I" + interfaceContract.ServiceName.Replace("Interface", string.Empty);
            }
            else
            {
                fileName = interfaceContract.ServiceName.Replace("Interface", string.Empty) + "Client";
            }
            interfaceNamespace.UserData.Add(Constants.FILE_NAME, fileName);

            codeNamespaces.Add(interfaceNamespace);

            return(codeNamespaces.ToArray());
        }
Esempio n. 13
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. 14
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);
        }
Esempio n. 15
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);
        }
Esempio n. 16
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);
                }
            }
        }
        /// <summary>
        /// Generates classes for the schemaFileName specified.
        /// </summary>
        public override void Execute()
        {
            // Load the XmlSchema and its collection.
            XmlSchema xsd;
            string    xsdImportPath;

            using (FileStream fs = new FileStream(this.xsdFile, FileMode.Open))
            {
                xsd = XmlSchema.Read(fs, null);
                XmlSchemaSet schemaSet = new XmlSchemaSet();
                schemaSet.Add(xsd);

                foreach (XmlSchemaImport import in xsd.Includes)
                {
                    xsdImportPath = ResolveImportPath(import);

                    using (FileStream fsSchemaImport = new FileStream(xsdImportPath, FileMode.Open))
                    {
                        XmlSchema xsdTemp = XmlSchema.Read(fsSchemaImport, null);
                        schemaSet.Add(xsdTemp);
                    }
                }

                schemaSet.Compile();
            }

            XmlSchemas schemas = new XmlSchemas();

            schemas.Add(xsd);

            foreach (XmlSchemaImport import in xsd.Includes)
            {
                xsdImportPath = ResolveImportPath(import);

                using (FileStream fs = new FileStream(xsdImportPath, FileMode.Open))
                {
                    XmlSchema xsdTemp = XmlSchema.Read(fs, null);
                    schemas.Add(xsdTemp);
                }
            }

            // 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(this.targetNamespace);
            XmlCodeExporter exporter = new XmlCodeExporter(ns);

            List <XmlTypeMapping> mappings = new List <XmlTypeMapping>();

            foreach (XmlSchemaType type in xsd.SchemaTypes.Values)
            {
                mappings.Add(importer.ImportSchemaType(type.QualifiedName));
            }

            if (!this.ProcessComplexTypesOnly)
            {
                foreach (XmlSchemaElement element in xsd.Elements.Values)
                {
                    mappings.Add(importer.ImportTypeMapping(element.QualifiedName));
                }
            }

            foreach (XmlTypeMapping mapping in mappings)
            {
                exporter.ExportTypeMapping(mapping);
            }

            CodeGenerator.ValidateIdentifiers(ns);

            compileUnit = new CodeCompileUnit();

            schemas.Remove(xsd);

            //Remove Types from CodeCompileUnit that belong to the imported schemas
            RemoveTypes(schemas, ns);

            compileUnit.Namespaces.Add(ns);
        }
Esempio n. 18
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));
        }
Esempio n. 19
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);
                }

                const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateOrder;
                var exporter = new XmlCodeExporter(ns);
                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 (XmlSchemaComplexType complex in xsd.Items.OfType <XmlSchemaComplexType>())
                {
                    var mapping = importer.ImportSchemaType(complex.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();
                }
            }
        }
        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);
        }
        /// <summary>
        /// Generates the <see cref="CodeNamespace"/> based on the provide context.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        public CodeNamespace GenerateCode(ICodeGeneratorContext codeGeneratorContext)
        {
            CodeGenOptions codeGenOptions = codeGeneratorContext.CodeGenOptions;
            XmlSchemas     xmlSchemas     = codeGeneratorContext.XmlSchemas;

            CodeNamespace codeNamespace = new CodeNamespace();

            // Generate DataContracts
            const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties;
            var exporter = new XmlCodeExporter(codeNamespace);
            var importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

            // TypeName to XmlSchemaType mapping
            IDictionary <string, XmlSchemaType>    typeName2schemaTypeMapping         = codeGeneratorContext.TypeName2schemaTypeMapping;
            IDictionary <XmlQualifiedName, string> elementName2TypeNameMapping        = codeGeneratorContext.ElementName2TypeNameMapping;
            IDictionary <string, string>           elementName2TargetNamespaceMapping = codeGeneratorContext.ElementName2TargetNamespaceMapping;

            foreach (XmlSchema schema in xmlSchemas)
            {
                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName);
                    if (element.IsAbstract)
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    if (typeMapping.XsdTypeName == "anyType")
                    {
                        continue;                                       // ignore no type element
                    }
                    if (string.IsNullOrWhiteSpace(typeMapping.XsdTypeName))
                    {
                        throw new Exception("Cannot use anonymous type for Request/Response element: " + element.Name + ".");
                    }
                    typeName2schemaTypeMapping[typeMapping.XsdTypeName] = element.ElementSchemaType;
                    elementName2TypeNameMapping[element.QualifiedName]  = typeMapping.XsdTypeName;

                    elementName2TargetNamespaceMapping[element.QualifiedName.Name] = schema.TargetNamespace;
                }

                foreach (XmlSchemaType complexType in schema.SchemaTypes.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportSchemaType(complexType.QualifiedName);
                    if (DataContractGenerator.CouldBeAnArray(complexType))
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    typeName2schemaTypeMapping[typeMapping.TypeName] = complexType;
                }
            }

            if (codeNamespace.Types.Count == 0)
            {
                throw new Exception("No types were generated.");
            }

            // Build type name to code type declaration mapping
            codeGeneratorContext.CodeTypeMap = DataContractGenerator.BuildCodeTypeMap(codeNamespace);

            // Decorate data contracts code
            ICodeExtension codeExtension = new CodeExtension();

            codeExtension.Process(codeNamespace, codeGeneratorContext);

            codeNamespace.ImplementsBaijiSerialization(codeGeneratorContext);

            // Generate interface code
            string                        wsdlFile          = codeGeneratorContext.CodeGenOptions.MetadataLocation;
            InterfaceContract             interfaceContract = ServiceDescriptionEngine.GetInterfaceContract(wsdlFile);
            CodeTypeDeclaration           codeType;
            CodeNamespaceImportCollection imports;

            this.buildInterfaceCode(codeGeneratorContext, interfaceContract, out codeType, out imports);
            codeNamespace.Types.Add(codeType);
            foreach (CodeNamespaceImport @import in imports)
            {
                codeNamespace.Imports.Add(@import);
            }

            // Import SOA common type namespace before removing code types
            codeNamespace.Imports.Add(new CodeNamespaceImport(Constants.C_SERVICE_STACK_COMMON_TYPES_NAMESPACE));
            // Remove SOA common types since they have already been included in CSerivceStack DLL
            CodeExtension.RemoveSOACommonTypes(codeNamespace);

            CodeExtension.RemoveDefaultTypes(codeNamespace);

            return(codeNamespace);
        }
Esempio n. 22
0
        /// <summary>
        /// Generates the <see cref="CodeNamespace"/> based on the provide context.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        public CodeNamespace GenerateCode(ICodeGeneratorContext codeGeneratorContext)
        {
            CodeGenOptions codeGenOptions = codeGeneratorContext.CodeGenOptions;
            XmlSchemas     xmlSchemas     = codeGeneratorContext.XmlSchemas;

            CodeNamespace codeNamespace = new CodeNamespace();

            // Generate DataContracts
            const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties;
            var exporter = new XmlCodeExporter(codeNamespace);
            var importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

            // TypeName to XmlSchemaType mapping
            IDictionary <string, XmlSchemaType> typeName2schemaTypeMapping = codeGeneratorContext.TypeName2schemaTypeMapping;

            foreach (XmlSchema schema in xmlSchemas)
            {
                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName);
                    if (element.IsAbstract)
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    typeName2schemaTypeMapping[typeMapping.TypeName] = element.ElementSchemaType;
                }

                foreach (XmlSchemaType complexType in schema.SchemaTypes.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportSchemaType(complexType.QualifiedName);
                    if (CouldBeAnArray(complexType))
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    typeName2schemaTypeMapping[typeMapping.TypeName] = complexType;
                }
            }

            if (codeNamespace.Types.Count == 0)
            {
                throw new Exception("No types were generated.");
            }

            // Build type name to code type declaration mapping
            codeGeneratorContext.CodeTypeMap = BuildCodeTypeMap(codeNamespace);
            if (codeGenOptions.ForceElementName)
            {
                DataContractGenerator.BuildElementName2TypeNameMapping(codeGeneratorContext);
            }
            if (codeGenOptions.ForceElementNamespace)
            {
                DataContractGenerator.BuildElementName2TargetNamespaceMapping(codeGeneratorContext);
            }

            // Decorate data contracts code
            ICodeExtension codeExtension = new CodeExtension();

            codeExtension.Process(codeNamespace, codeGeneratorContext);

            CodeExtension.RemoveDefaultTypes(codeNamespace);

            return(codeNamespace);
        }
Esempio n. 23
0
        void resolveParticle(XmlSchemaImporter schema_importer,
                             XmlSchemaParticle particle,
                             List <MessagePartDescription> parts,
                             string ns,
                             int depth)
        {
            if (particle is XmlSchemaGroupBase)
            {
                //sequence,
                //FIXME: others?
                if (depth <= 0)
                {
                    return;
                }

                XmlSchemaGroupBase groupBase = particle as XmlSchemaGroupBase;
                foreach (XmlSchemaParticle item in groupBase.Items)
                {
                    resolveParticle(schema_importer, item, parts, ns, depth - 1);
                }

                return;
            }

            XmlSchemaElement elem = particle as XmlSchemaElement;

            if (elem == null)
            {
                return;
            }

            MessagePartDescription msg_part = null;

            XmlSchemaComplexType ct = elem.ElementSchemaType as XmlSchemaComplexType;

            if (ct == null)
            {
                //Not a complex type
                XmlSchemaSimpleType simple = elem.ElementSchemaType as XmlSchemaSimpleType;
                msg_part = new MessagePartDescription(
                    elem.Name, ns);
                if (elem.SchemaType != null)
                {
                    msg_part.XmlTypeMapping = schema_importer.ImportTypeMapping(elem.QualifiedName);
                }
                else
                {
                    msg_part.XmlTypeMapping = schema_importer.ImportSchemaType(elem.SchemaTypeName);
                }
                msg_part.TypeName = new QName(GetCLRTypeName(elem.SchemaTypeName), "");
                parts.Add(msg_part);

                return;
            }

            if (depth > 0)
            {
                resolveParticle(schema_importer, ct.ContentTypeParticle, parts, ns, depth - 1);
                return;
            }

            //depth <= 0
            msg_part = new MessagePartDescription(elem.Name, ns);
            if (elem.SchemaType != null)
            {
                msg_part.XmlTypeMapping = schema_importer.ImportTypeMapping(elem.QualifiedName);
            }
            else
            {
                msg_part.XmlTypeMapping = schema_importer.ImportSchemaType(elem.SchemaTypeName);
            }
            msg_part.TypeName = elem.SchemaTypeName;

            parts.Add(msg_part);
        }
Esempio n. 24
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());
        }
Esempio n. 25
0
        /// <summary>
        /// Generates the <see cref="CodeNamespace"/> based on the provide context.
        /// </summary>
        /// <param name="codeGeneratorContext">The code generator context.</param>
        public CodeNamespace[] GenerateCodes(ICodeGeneratorContext codeGeneratorContext)
        {
            CodeGenOptions codeGenOptions = codeGeneratorContext.CodeGenOptions;
            XmlSchemas     xmlSchemas     = codeGeneratorContext.XmlSchemas;

            // Generate DataContracts
            const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties;

            List <CodeNamespace> codeNamespaces = new List <CodeNamespace>();

            // TypeName to XmlSchemaType mapping
            IDictionary <string, XmlSchemaType> typeName2schemaTypeMapping = codeGeneratorContext.TypeName2schemaTypeMapping;

            foreach (XmlSchema schema in xmlSchemas)
            {
                CodeNamespace codeNamespace = new CodeNamespace();
                codeNamespace.UserData.Add(Constants.SCHEMA, schema);

                XmlCodeExporter   exporter = new XmlCodeExporter(codeNamespace);
                XmlSchemaImporter importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false));

                foreach (XmlSchemaElement element in schema.Elements.Values)
                {
                    XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName);
                    if (element.IsAbstract)
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    typeName2schemaTypeMapping[typeMapping.TypeName] = element.ElementSchemaType;
                }

                foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                {
                    if (String.IsNullOrWhiteSpace(schemaType.SourceUri))
                    {
                        schemaType.SourceUri = schema.SourceUri;
                    }
                    XmlTypeMapping typeMapping = importer.ImportSchemaType(schemaType.QualifiedName);
                    if (CouldBeAnArray(schemaType))
                    {
                        continue;
                    }

                    exporter.ExportTypeMapping(typeMapping);
                    typeName2schemaTypeMapping[typeMapping.TypeName] = schemaType;
                }

                if (codeNamespace.Types.Count > 0)
                {
                    codeNamespaces.Add(codeNamespace);
                }
            }

            if (codeNamespaces.Count == 0)
            {
                throw new Exception("No types were generated.");
            }
            // Build type name to code type declaration mapping
            codeGeneratorContext.CodeTypeMap = DataContractGenerator.BuildCodeTypeMap(codeNamespaces.ToArray());
            if (codeGenOptions.ForceElementName)
            {
                DataContractGenerator.BuildElementName2TypeNameMapping(codeGeneratorContext);
            }
            if (codeGenOptions.ForceElementNamespace)
            {
                DataContractGenerator.BuildElementName2TargetNamespaceMapping(codeGeneratorContext);
            }

            for (int i = 0; i < codeNamespaces.Count; i++)
            {
                CodeNamespace codeNamespace = codeNamespaces[i];
                // Decorate data contracts code
                ICodeExtension codeExtension = new CodeExtension();
                codeExtension.Process(codeNamespace, codeGeneratorContext);

                CodeExtension.RemoveDefaultTypes(codeNamespace);

                List <CodeTypeDeclaration> types = new List <CodeTypeDeclaration>();
                XmlSchema schema = codeNamespace.UserData[Constants.SCHEMA] as XmlSchema;

                foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values)
                {
                    foreach (CodeTypeDeclaration codeType in codeNamespace.Types)
                    {
                        if (codeType.Name == schemaType.Name &&
                            schema.SourceUri == schemaType.SourceUri)
                        {
                            types.Add(codeType);
                        }
                    }
                }
                codeNamespace.Types.Clear();
                codeNamespace.Types.AddRange(types.ToArray());

                if (codeNamespace.Types.Count == 0)
                {
                    codeNamespaces.RemoveAt(i--);
                }
            }

            return(codeNamespaces.ToArray());
        }