Exemplo n.º 1
0
        public void Test3()
        {
            var options = new XsdCodeGeneratorOptions
            {
                PropertyNameCapitalizer = new FirstCharacterCapitalizer(),
                OutputNamespace         = "XSD2",
                UseLists             = true,
                UseNullableTypes     = true,
                ExcludeImportedTypes = true,
                MixedContent         = true,
                AttributesToRemove   =
                {
                    "System.Diagnostics.DebuggerStepThroughAttribute"
                }
            };

            using (var o = File.CreateText(@"Schemas\Form.cs"))
            {
                var generator = new XsdCodeGenerator()
                {
                    Options = options
                };
                generator.Generate(new[] { @"Schemas\Form.xsd" }, o);
            }
        }
Exemplo n.º 2
0
        public void NullablePropertiesAreGeneratedWithoutUnderscore()
        {
            var options = new XsdCodeGeneratorOptions
            {
                PropertyNameCapitalizer = new FirstCharacterCapitalizer(),
                OutputNamespace         = "XSD2.Issue16",
                UseLists             = true,
                UseNullableTypes     = true,
                ExcludeImportedTypes = true,
                AttributesToRemove   =
                {
                    "System.Diagnostics.DebuggerStepThroughAttribute"
                }
            };

            using (var o = File.CreateText(@"Schemas\Issue16.cs"))
            {
                var generator = new XsdCodeGenerator()
                {
                    Options = options,
                    OnValidateGeneratedCode = (ns, schema) =>
                    {
                        var typeWithCustomElement = ns.Types.Cast <CodeTypeDeclaration>().Single(a => a.Name == "TypeWithCustomElement");
                        var valueProp             = (CodeMemberProperty)typeWithCustomElement.Members.Cast <CodeTypeMember>().Single(a => a.Name == "_SomeDate");

                        var elementName = valueProp.CustomAttributes[0].Arguments.Cast <CodeAttributeArgument>().SingleOrDefault(a => a.Name == "ElementName")?.Value as CodePrimitiveExpression;
                        Assert.IsNotNull(elementName);
                        Assert.DoesNotContain(elementName.Value.ToString(), "_");
                    }
                };
                generator.Generate(new[] { @"Schemas\Issue16.xsd" }, o);
            }
        }
Exemplo n.º 3
0
        public void UppercaseNullablePropertiesAreGenerated()
        {
            var options = new XsdCodeGeneratorOptions
            {
                PropertyNameCapitalizer = new FirstCharacterCapitalizer(),
                OutputNamespace         = "XSD2",
                UseLists             = true,
                UseNullableTypes     = true,
                ExcludeImportedTypes = true,
                AttributesToRemove   =
                {
                    "System.Diagnostics.DebuggerStepThroughAttribute"
                }
            };

            using (var o = File.CreateText(@"Schemas\Issue12.cs"))
            {
                var generator = new XsdCodeGenerator()
                {
                    Options = options,
                    OnValidateGeneratedCode = (ns, schema) =>
                    {
                        var upperCaseType = ns.Types.Cast <CodeTypeDeclaration>().Single(a => a.Name == "UpperCaseType");
                        var valueProp     = (CodeMemberProperty)upperCaseType.Members.Cast <CodeTypeMember>().Single(a => a.Name == "Value");
                        Assert.IsTrue(valueProp.Type.BaseType.Contains("Nullable"));
                    }
                };
                generator.Generate(new[] { @"Schemas\Issue12.xsd" }, o);
            }
        }
Exemplo n.º 4
0
        public void UppercaseNullablePropertiesAreGenerated()
        {
            var options = new XsdCodeGeneratorOptions
            {
                CapitalizeProperties = true,
                OutputNamespace = "XSD2",
                UseLists = true,
                UseNullableTypes = true,
                StripDebuggerStepThroughAttribute = true,
                ExcludeImportedTypes = true
            };

            using (var f = File.OpenRead(@"Schemas\Issue12.xsd"))
            using (var o = File.CreateText(@"Schemas\Issue12.cs"))
            {
                var generator = new XsdCodeGenerator()
                {
                    Options = options,
                    OnValidateGeneratedCode = (ns, schema) =>
                    {
                        var upperCaseType = ns.Types.Cast<CodeTypeDeclaration>().Single(a => a.Name == "UpperCaseType");
                        var valueProp = (CodeMemberProperty)upperCaseType.Members.Cast<CodeTypeMember>().Single(a => a.Name == "Value");
                        Assert.IsTrue(valueProp.Type.BaseType.Contains("Nullable"));
                    }
                };
                generator.Generate(f, o);
            }
        }
Exemplo n.º 5
0
        public void Test2()
        {
            var options = new XsdCodeGeneratorOptions
            {
                CapitalizeProperties = true,
                OutputNamespace = "XSD2",
                UseLists = true,
                UseNullableTypes = true,
                StripDebuggerStepThroughAttribute = true,
                ExcludeImportedTypes = true
            };

            using (var f = File.OpenRead(@"Schemas\Data.xsd"))
            using (var o = File.CreateText(@"Schemas\Data.cs"))
            {
                var generator = new XsdCodeGenerator() { Options = options };
                generator.Generate(f, o);
            }
        }
Exemplo n.º 6
0
        protected override void ProcessRecord()
        {
            string outputFileExtension;

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

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

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

            var inputs = Inputs.Select(GetPath).ToList();

            if (!string.IsNullOrEmpty(CombineTo))
            {
                using (var output = File.CreateText(GetPath(CombineTo)))
                    generator.Generate(inputs, output);
            }
            else
            {
                foreach (var path in inputs)
                {
                    var fileInfo   = new FileInfo(path);
                    var outputPath = Path.Combine(
                        !string.IsNullOrEmpty(OutputDirectory) ? GetPath(OutputDirectory) : fileInfo.DirectoryName,
                        Path.ChangeExtension(fileInfo.Name, outputFileExtension));

                    using (var output = File.CreateText(outputPath))
                        generator.Generate(new[] { path }, output);
                }
            }
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            var app = new CommandLineApplication {
                Name = "Xsd2", FullName = "Xsd2Cli"
            };

            app.HelpOption("-?|-h|--help");
            var inputs               = app.Argument("input", "Schemas to process", true);
            var outputDirectory      = app.Option("-o|--out|--output", "Sets the output directory", CommandOptionType.SingleValue);
            var language             = app.Option("-l|--language", "Sets the language to use for code generation (CS or VB)", CommandOptionType.SingleValue);
            var header               = app.Option("--header", "Write file header", CommandOptionType.NoValue);
            var order                = app.Option("--order", "Preserve the element order", CommandOptionType.NoValue);
            var enableDataBinding    = app.Option("--edb|--enableDataBinding", "Implements INotifyPropertyChanged for all types", CommandOptionType.NoValue);
            var lists                = app.Option("--lists", "Use lists", CommandOptionType.NoValue);
            var stripDebugAttributes = app.Option("--strip-debug-attributes", "Strip debug attributes", CommandOptionType.NoValue);
            var xlinq                = app.Option("--xl|--xlinq", "Use XLinq", CommandOptionType.NoValue);
            var removeAttribute      = app.Option("--ra|--remove-attribute", "Sets an attribute name to remove from the output", CommandOptionType.MultipleValue);
            var pcl = app.Option("--pcl", "Target a PCL (implies --xl)", CommandOptionType.NoValue);
            var capitalizeProperties = app.Option("--cp|--capitalize|--capitalize-properties", "Capitalize properties", CommandOptionType.NoValue);
            var capitalizeTypes      = app.Option("--ct|--capitalize-types", "Capitalize types", CommandOptionType.NoValue);
            var capitalizeEnums      = app.Option("--ce|--capitalize-enum-values", "Capitalize enum values", CommandOptionType.NoValue);
            var capitalizeAll        = app.Option("--ca|--capitalize-all", "Capitalize properties, types, and enum values (--cp, --ct and --ce)", CommandOptionType.NoValue);
            var propertyCapitalizer  = app.Option("--property-capitalizer", "Sets the capitalizer to use for the --cp option", CommandOptionType.SingleValue);
            var typeCapitalizer      = app.Option("--type-capitalizer", "Sets the capitalizer to use for the --ct option", CommandOptionType.SingleValue);
            var enumCapitalizer      = app.Option("--enum-capitalizer", "Sets the capitalizer to use for the --ce option", CommandOptionType.SingleValue);
            var mixed                = app.Option("--mixed", "Support mixed content", CommandOptionType.NoValue);
            var namespaceName        = app.Option("-n|--ns|--namespace", "Sets the output namespace", CommandOptionType.SingleValue);
            var import               = app.Option("--import", "Adds import", CommandOptionType.MultipleValue);
            var usingNamespaces      = app.Option("-u|--using", "Adds a namespace to use", CommandOptionType.MultipleValue);
            var excludeImports       = app.Option("--ei|--exclude-imports", "Exclude imported types", CommandOptionType.NoValue);
            var excludeImportsByName = app.Option("--ein|--exclude-imports-by-name", "Exclude imported types by name", CommandOptionType.NoValue);
            var nullable             = app.Option("--nullable", "Use nullable types", CommandOptionType.NoValue);
            var all     = app.Option("--all", "Enable --stip-debug-attribtues --lists --nullable --ei --mixed --ca", CommandOptionType.NoValue);
            var combine = app.Option("--combine", "Combine output to a single file", CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                var options = new XsdCodeGeneratorOptions
                {
                    UseNullableTypes     = nullable.HasValue() || all.HasValue(),
                    OutputNamespace      = namespaceName.HasValue() ? namespaceName.Value() : "Xsd2",
                    MixedContent         = mixed.HasValue() || all.HasValue(),
                    ExcludeImportedTypes = excludeImports.HasValue() || excludeImportsByName.HasValue() || all.HasValue(),
                    ExcludeImportedTypesByNameAndNamespace = excludeImportsByName.HasValue(),
                    Imports         = import.Values,
                    UsingNamespaces = usingNamespaces.Values,
                    Language        = language.HasValue() ?
                                      (XsdCodeGeneratorOutputLanguage)Enum.Parse(typeof(XsdCodeGeneratorOutputLanguage), language.Value(), true) :
                                      XsdCodeGeneratorOutputLanguage.CS,
                    WriteFileHeader    = header.HasValue(),
                    PreserveOrder      = order.HasValue(),
                    EnableDataBinding  = enableDataBinding.HasValue(),
                    UseLists           = lists.HasValue() || all.HasValue(),
                    UseXLinq           = xlinq.HasValue() || pcl.HasValue(),
                    AttributesToRemove = new HashSet <string>(removeAttribute.Values)
                };

                if (capitalizeProperties.HasValue() || capitalizeAll.HasValue() || all.HasValue())
                {
                    options.PropertyNameCapitalizer = GetCapitalizer(propertyCapitalizer.HasValue() ? propertyCapitalizer.Value() : null);
                }
                if (capitalizeTypes.HasValue() || capitalizeAll.HasValue() || all.HasValue())
                {
                    options.TypeNameCapitalizer = GetCapitalizer(typeCapitalizer.HasValue() ? typeCapitalizer.Value() : null);
                }
                if (capitalizeEnums.HasValue() || capitalizeAll.HasValue() || all.HasValue())
                {
                    options.EnumValueCapitalizer = GetCapitalizer(enumCapitalizer.HasValue() ? enumCapitalizer.Value() : null);
                }

                if (pcl.HasValue())
                {
                    options.AttributesToRemove.Add("System.SerializableAttribute");
                    options.AttributesToRemove.Add("System.ComponentModel.DesignerCategoryAttribute");
                }

                if (stripDebugAttributes.HasValue() || all.HasValue())
                {
                    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
                };

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

                            if (outputPath == null)
                            {
                                outputPath = Path.Combine(outputDirectory.HasValue() ? outputDirectory.Value() : fileInfo.DirectoryName, combine.Value());
                            }

                            Console.WriteLine(fileInfo.FullName);
                        }

                        Console.WriteLine(outputPath);

                        using (var output = File.CreateText(outputPath))
                            generator.Generate(inputs.Values, output);
                    }
                    else
                    {
                        foreach (var path in inputs.Values)
                        {
                            var fileInfo   = new FileInfo(path);
                            var outputPath = Path.Combine(
                                outputDirectory.HasValue() ? outputDirectory.Value() : 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);
            });
            app.Execute(args);
        }
Exemplo n.º 8
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>(),
                    AdditionalRootTypes = new HashSet <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 },
                    { "additional-root=", "Adds an additional xml root type", s => options.AdditionalRootTypes.Add(s) },
                    { "all-types-are-root", "All xml types should also be declared as root types", s => options.AllTypesAreRoot = 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 },
                };

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