Beispiel #1
0
        private static void SetAutoPropertyOption(string paramValue, XsdCodeGeneratorOptions options)
        {
            switch (paramValue?.ToLower())
            {
            case null:
            case "inline":
                options.GenerateAutoProperty = XsdCodeGeneratorAutoPropertyType.AssignInline;
                break;

            case "ctor":
                options.GenerateAutoProperty = XsdCodeGeneratorAutoPropertyType.AssignInConstructor;
                break;

            default:
                options.GenerateAutoProperty = XsdCodeGeneratorAutoPropertyType.None;
                break;
            }
        }
Beispiel #2
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());
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            try
            {
                var inputs = new List<String>();

                var options = new XsdCodeGeneratorOptions
                {
                    UseNullableTypes = false,
                    OutputNamespace = "Xsd2",
                    UseLists = false,
                    CapitalizeProperties = false,
                    StripDebuggerStepThroughAttribute = false,
                    MixedContent = false,
                    ExcludeImportedTypes = false,
                    Imports = new List<string>(),
                    UsingNamespaces = new List<string>()
                };

                var generator = new XsdCodeGenerator() { Options = options };
                String outputDirectory = null;

                foreach (var arg in args)
                {
                    if (!arg.StartsWith("/"))
                        inputs.Add(arg);
                    else
                    {
                        String option, value;
                        var colonIndex = arg.IndexOf(':');
                        if (colonIndex == -1)
                        {
                            option = arg;
                            value = null;
                        }
                        else
                        {
                            option = arg.Substring(0, colonIndex + 1);
                            value = arg.Substring(colonIndex + 1);
                        }

                        switch (option.ToLower())
                        {
                            case "/o:":
                            case "/output:":
                                outputDirectory = value;
                                break;

                            case "/lists":
                                options.UseLists = true;
                                break;

                            case "/strip-debug-attributes":
                                options.StripDebuggerStepThroughAttribute = true;
                                break;

                            case "/capitalize":
                                options.CapitalizeProperties = true;
                                break;

                            case "/capitalize-enum-values":
                                options.CapitalizeEnumValues = true;
                                break;

                            case "/mixed":
                                options.MixedContent = true;
                                break;

                            case "/n:":
                            case "/ns:":
                            case "/namespace:":
                                options.OutputNamespace = value;
                                break;

                            case "/import:":
                                options.Imports.Add(value);
                                break;

                            case "/u:":
                            case "/using:":
                                options.UsingNamespaces.Add(value);
                                break;

                            case "/ei":
                            case "/exclude-imports":
                                options.ExcludeImportedTypes = true;
                                break;

                            case "/all":
                                options.CapitalizeProperties = true;
                                options.StripDebuggerStepThroughAttribute = true;
                                options.UseLists = true;
                                options.UseNullableTypes = true;
                                options.ExcludeImportedTypes = true;
                                options.MixedContent = true;
                                break;
                        }
                    }
                }

                foreach (var path in inputs)
                {
                    var fileInfo = new FileInfo(path);
                    var outputPath = Path.Combine(outputDirectory ?? fileInfo.DirectoryName, Path.ChangeExtension(fileInfo.Name, ".cs"));

                    Console.WriteLine(fileInfo.FullName);
                    Console.WriteLine(outputPath);

                    using (var input = fileInfo.OpenRead())
                    using (var output = File.CreateText(outputPath))
                        generator.Generate(input, output);
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("XSD2 code generation failed.");
                Console.Error.Write(ex.ToString());
            }
        }
Beispiel #4
0
        static int Main(string[] args)
        {
            try
            {
                var options = new XsdCodeGeneratorOptions
                {
                    UseNullableTypes     = false,
                    OutputNamespace      = "Xsd2",
                    UseLists             = false,
                    MixedContent         = false,
                    ExcludeImportedTypes = false,
                    Imports         = new List <string>(),
                    UsingNamespaces = new List <string>()
                };

                String outputDirectory = null;
                var    combine         = false;
                string outputFileName  = null;
                var    help            = false;
                var    pclTarget       = false;
                var    stripDebuggerStepThroughAttribute = false;

                var optionSet = new Mono.Options.OptionSet()
                {
                    { "?|h|help", "Shows the help text", s => help = true },
                    { "o|out|output=", "Sets the output directory", s => outputDirectory = s },
                    { "l|language=", "Sets the language to use for code generation (CS or VB)", s => options.Language = (XsdCodeGeneratorOutputLanguage)Enum.Parse(typeof(XsdCodeGeneratorOutputLanguage), s, true) },
                    { "header", "Write file header", s => options.WriteFileHeader = s != null },
                    { "order", "Preserve the element order", s => options.PreserveOrder = s != null },
                    { "edb|enableDataBinding", "Implements INotifyPropertyChanged for all types", s => options.EnableDataBinding = s != null },
                    { "lists", "Use lists", s => options.UseLists = s != null },
                    { "strip-debug-attributes", "Strip debug attributes", s => stripDebuggerStepThroughAttribute = s != null },
                    { "xl|xlinq", s => options.UseXLinq = s != null },
                    { "ra|remove-attribute=", s => options.AttributesToRemove.Add(s) },
                    { "pcl", "Target a PCL", s => pclTarget = s != null },
                    { "cp|capitalize:", "Capitalize properties", (k, v) => options.PropertyNameCapitalizer = GetCapitalizer(k, v) },
                    { "ca|capitalize-all:", "Capitalize properties, types, and enum vlaues", (k, v) => options.PropertyNameCapitalizer = options.EnumValueCapitalizer = options.TypeNameCapitalizer = GetCapitalizer(k, v) },
                    { "ct|capitalize-types:", "Capitalize types", (k, v) => options.TypeNameCapitalizer = GetCapitalizer(k, v) },
                    { "ce|capitalize-enum-values:", "Capitalize enum values", (k, v) => options.EnumValueCapitalizer = GetCapitalizer(k, v) },
                    { "mixed", "Support mixed content", s => options.MixedContent = s != null },
                    { "n|ns|namespace=", "Sets the output namespace", s => options.OutputNamespace = s },
                    { "import=", "Adds import", s => options.Imports.Add(s) },
                    { "u|using=", "Adds a namespace to use", s => options.UsingNamespaces.Add(s) },
                    { "ei|exclude-imports", "Exclude imported types", s => options.ExcludeImportedTypes = s != null },
                    { "ein|exclude-imports-by-name", "Exclude imported types by name", s => options.ExcludeImportedTypes = options.ExcludeImportedTypesByNameAndNamespace = s != null },
                    { "nullable", "Use nullable types", s => options.UseNullableTypes = options.HideUnderlyingNullableProperties = s != null },
                    { "all", "Enable all flags", s =>
                      {
                          stripDebuggerStepThroughAttribute = options.UseLists = options.UseNullableTypes = options.ExcludeImportedTypes = options.MixedContent = s != null;
                          options.PropertyNameCapitalizer   = new FirstCharacterCapitalizer();
                      } },
                    { "combine:", "Combine output to a single file", s => { combine = true; outputFileName = s; } },
                    { "c|classes", "Generates classes for the schema", s => { }, true },
                    { "nologo", "Suppresses application banner", s => { }, true },
                    { "ap|auto-property:", "Generate auto-property instead of backing field. If VALUE=ctor then default value is assigned in constructor, if VALUE=inline then in the same line.",
                      s => SetAutoPropertyOption(s, options) },
                    { "eec|exclude-empty-comments", "Exclude empty comments (<remarks /> etc.)", s => options.ExcludeEmptyComments = s != null },
                    { "rs|remove-specified-property", "Remove [PropertyName]Specified properties", s => options.RemoveSpecifiedProperties = s != null },
                    { "sot|set-original-type", "Set property type to the data type, specified in XmlAttribute (DataType argument)", s => options.SetOriginalType = s != null },
                };

                var inputs = optionSet.Parse(args);
                if (help || args.Length == 0 || inputs.Count == 0)
                {
                    Console.Error.WriteLine("Xsd2 [options] schema.xsd ...");
                    optionSet.WriteOptionDescriptions(Console.Error);
                    return(1);
                }

                if (pclTarget)
                {
                    options.UseXLinq = true;
                    options.AttributesToRemove.Add("System.SerializableAttribute");
                    options.AttributesToRemove.Add("System.ComponentModel.DesignerCategoryAttribute");
                }

                if (stripDebuggerStepThroughAttribute)
                {
                    options.AttributesToRemove.Add("System.Diagnostics.DebuggerStepThroughAttribute");
                }

                string outputFileExtension;
                switch (options.Language)
                {
                case XsdCodeGeneratorOutputLanguage.VB:
                    outputFileExtension = ".vb";
                    break;

                default:
                    outputFileExtension = ".cs";
                    break;
                }

                var generator = new XsdCodeGenerator()
                {
                    Options = options
                };

                if (combine)
                {
                    String outputPath = null;
                    foreach (var path in inputs)
                    {
                        var fileInfo = new FileInfo(path);

                        if (outputPath == null)
                        {
                            if (string.IsNullOrEmpty(outputFileName))
                            {
                                outputFileName = Path.ChangeExtension(fileInfo.Name, outputFileExtension);
                            }
                            outputPath = Path.Combine(outputDirectory ?? fileInfo.DirectoryName, outputFileName);
                        }

                        Console.WriteLine(fileInfo.FullName);
                    }

                    Console.WriteLine(outputPath);

                    using (var output = File.CreateText(outputPath))
                        generator.Generate(inputs, output);
                }
                else
                {
                    foreach (var path in inputs)
                    {
                        var fileInfo   = new FileInfo(path);
                        var outputPath = Path.Combine(outputDirectory ?? fileInfo.DirectoryName, Path.ChangeExtension(fileInfo.Name, outputFileExtension));

                        Console.WriteLine(fileInfo.FullName);
                        Console.WriteLine(outputPath);

                        using (var output = File.CreateText(outputPath))
                            generator.Generate(new[] { path }, output);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("XSD2 code generation failed.");
                Console.Error.Write(ex.ToString());
                return(2);
            }

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

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

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

            xsds.Compile(null, true);

            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds);

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

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

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

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

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

            ImproveCodeDom(codeNamespace, xsd);

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

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

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

            codeProvider.GenerateCodeFromNamespace(codeNamespace, output, new CodeGeneratorOptions());
        }