예제 #1
0
        /// <summary>
        /// Performs the validation.
        /// </summary>
        /// <param name="option">The <see cref="CommandOption"/>.</param>
        /// <param name="context">The <see cref="ValidationContext"/>.</param>
        /// <returns>The <see cref="ValidationResult"/>.</returns>
        public ValidationResult GetValidationResult(CommandOption option, ValidationContext context)
        {
            if (option == null)
            {
                throw new ArgumentNullException(nameof(option));
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var pd = new Dictionary <string, string>();

            foreach (var p in option.Values)
            {
                string[] parts = CodeGenConsole.CreateKeyValueParts(p);
                if (parts.Length != 2)
                {
                    return(new ValidationResult($"The parameter '{p}' is not valid; must be formatted as Name=value."));
                }

                if (pd.ContainsKey(parts[0]))
                {
                    return(new ValidationResult($"The parameter '{p}' is not valid; name has been specified more than once."));
                }

                pd.Add(parts[0], parts[1]);
            }

            return(ValidationResult.Success);
        }
예제 #2
0
파일: Program.cs 프로젝트: ostat/Beef
        /// <summary>
        /// The main entry point.
        /// </summary>
        /// <param name="args">The console arguments.</param>
        /// <returns>A statuc code.</returns>
        public static async Task <int> Main(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            Logger.Default = new ColoredConsoleLogger(nameof(CodeGenConsole));

            // Check for special case / internal use arguments.
            if (args.Length == 1)
            {
                switch (args[0].ToUpperInvariant())
                {
                case "--GENERATEENTITYXMLSCHEMA": return(SpecialActivitiesCenter("Generate Entity XML Schema", "./Schema/codegen.entity.xsd", fn => XmlSchemaGenerator.Create <Config.Entity.CodeGenConfig>(ConfigType.Entity).Save(fn, System.Xml.Linq.SaveOptions.None)));

                case "--GENERATEENTITYJSONSCHEMA": return(SpecialActivitiesCenter("Generate Entity JSON Schema", "./Schema/entity.beef.json", fn => File.WriteAllText(fn, JsonSchemaGenerator.Create <Config.Entity.CodeGenConfig>("JSON Schema for Beef Entity code-generation (https://github.com/Avanade/Beef)."))));

                case "--GENERATEDATABASEXMLSCHEMA": return(SpecialActivitiesCenter("Generate Database XML Schema", "./Schema/codegen.table.xsd", fn => XmlSchemaGenerator.Create <Config.Database.CodeGenConfig>(ConfigType.Database).Save(fn, System.Xml.Linq.SaveOptions.None)));

                case "--GENERATEDATABASEJSONSCHEMA": return(SpecialActivitiesCenter("Generate Database JSON Schema", "./Schema/database.beef.json", fn => File.WriteAllText(fn, JsonSchemaGenerator.Create <Config.Database.CodeGenConfig>("JSON Schema for Beef Database code-generation (https://github.com/Avanade/Beef)."))));

                case "--GENERATEENTITYMARKDOWN": return(SpecialActivitiesCenter("Generate Entity YAML documentation markdown file(s)", "../../docs/", fn => SchemaMarkdownGenerator.Create <Config.Entity.CodeGenConfig>(fn, ConfigType.Entity, true)));

                case "--GENERATEENTITYXMLMARKDOWN": return(SpecialActivitiesCenter("Generate Entity XML documentation markdown file(s)", "../../docs/", fn => SchemaMarkdownGenerator.Create <Config.Entity.CodeGenConfig>(fn, ConfigType.Entity, false)));

                case "--GENERATEDATABASEMARKDOWN": return(SpecialActivitiesCenter("Generate Database YAML documentation markdown file(s)", "../../docs/", fn => SchemaMarkdownGenerator.Create <Config.Database.CodeGenConfig>(fn, ConfigType.Database, true)));

                case "--GENERATEDATABASEXMLMARKDOWN": return(SpecialActivitiesCenter("Generate Database XML documentation markdown file(s)", "../../docs/", fn => SchemaMarkdownGenerator.Create <Config.Database.CodeGenConfig>(fn, ConfigType.Database, false)));
                }
            }

            return(await CodeGenConsole.Create().RunAsync(args).ConfigureAwait(false));
        }
예제 #3
0
        /// <summary>
        /// Executes the underlying <see cref="CodeGenConsole"/> using the code generation arguments.
        /// </summary>
        /// <param name="args">The code generation arguments.</param>
        /// <returns><b>Zero</b> indicates success; otherwise, unsucessful.</returns>
        public int Run(string[] args)
        {
            var app = new CommandLineApplication(false)
            {
                Name        = "beef.codegen",
                Description = "Business Entity Execution Framework (Beef) Code Generator."
            };

            var cmd = app.Argument <CommandType>("command", "Execution command type: Entity, Database, RefData or All.", false).IsRequired();
            var cs  = app.Option("-c|--connectionString", "Override the connection string for Database.", CommandOptionType.SingleValue);
            var cx  = app.Option("-x|--xml", "Override the filename for the configuration XML.", CommandOptionType.SingleValue).Accepts(v => v.ExistingFile());

            var entityFileName   = EntityFileNameTemplate;
            var databaseFileName = DatabaseFileNameTemplate;
            var refDataFileName  = RefDataFileNameTemplate;

            app.OnExecute(() =>
            {
                var ct = Enum.Parse <CommandType>(cmd.Value, true);
                if (cx.HasValue())
                {
                    if (ct == CommandType.All)
                    {
                        throw new CommandParsingException(app, "Command 'All' is not compatible with --xml; the command must be more specific when using a configuration XML file.");
                    }

                    entityFileName = databaseFileName = refDataFileName = cx.Value();
                }

                var rc = 0;
                if (IsDatabaseSupported && ct.HasFlag(CommandType.Database))
                {
                    rc = CodeGenConsole.Create().Run(AppendAssemblies(ReplaceMoustache(databaseFileName + " " + DatabaseCommandLineTemplate) + (cs.HasValue() ? $" -p \"ConnectionString={cs.Value()}\"" : "")));
                }

                if (IsRefDataSupported && ct.HasFlag(CommandType.RefData))
                {
                    rc = CodeGenConsole.Create().Run(AppendAssemblies(ReplaceMoustache(refDataFileName + " " + RefDataCommandLineTemplate)));
                }

                if (IsEntitySupported && ct.HasFlag(CommandType.Entity))
                {
                    rc = CodeGenConsole.Create().Run(AppendAssemblies(ReplaceMoustache(entityFileName + " " + EntityCommandLineTemplate)));
                }
            });

            try
            {
                return(app.Execute(args));
            }
            catch (CommandParsingException cpex)
            {
                Console.WriteLine(cpex.Message);
                return(-1);
            }
        }
예제 #4
0
 /// <summary>
 /// The main entry point.
 /// </summary>
 /// <param name="args">The console arguments.</param>
 /// <returns>A statuc code.</returns>
 public static int Main(string[] args)
 {
     return(CodeGenConsole.Create().Run(args));
 }
예제 #5
0
        /// <summary>
        /// Executes the underlying <see cref="CodeGenConsole"/> using the code generation arguments.
        /// </summary>
        /// <param name="args">The code generation arguments.</param>
        /// <returns><b>Zero</b> indicates success; otherwise, unsucessful.</returns>
        public async Task <int> RunAsync(string[] args)
        {
            using var app = new CommandLineApplication()
                  {
                      Name        = "beef.codegen",
                      Description = "Business Entity Execution Framework (Beef) Code Generator."
                  };

            var cmd            = app.Argument <CommandType>("command", "Execution command type: Entity, Database, RefData or All.", false).IsRequired();
            var cs             = app.Option("-c|--connectionString", "Override the connection string for Database.", CommandOptionType.SingleValue);
            var cx             = app.Option("-x|--xml", "Override the filename for the configuration XML.", CommandOptionType.SingleValue).Accepts(v => v.ExistingFile());
            var expectNoChange = app.Option("--expectNoChanges", "Expect no changes in the output, exit if changes are detected (for build pipelines).", CommandOptionType.NoValue);

            var entityFileName    = EntityFileNameTemplate;
            var databaseFileName  = DatabaseFileNameTemplate;
            var refDataFileName   = RefDataFileNameTemplate;
            var dataModelFileName = DataModelFileNameTemplate;

            app.OnExecuteAsync(async(_) =>
            {
                var ct = cmd.Value == null ? CommandType.All : Enum.Parse <CommandType>(cmd.Value, true);
                if (cx.HasValue())
                {
                    if (ct == CommandType.All)
                    {
                        throw new CommandParsingException(app, "Command 'All' is not compatible with --xml; the command must be more specific when using a configuration XML file.");
                    }

                    entityFileName = databaseFileName = refDataFileName = dataModelFileName = cx.Value() !;
                }

                var expectNoChangeArg = expectNoChange.HasValue() ? " --expectNoChanges" : "";
                var rc = 0;
                if (IsDatabaseSupported && ct.HasFlag(CommandType.Database))
                {
                    rc = await CodeGenConsole.Create().RunAsync(AppendAssemblies(ReplaceMoustache(databaseFileName + " " + DatabaseCommandLineTemplate) + expectNoChangeArg + (cs.HasValue() ? $" -p \"ConnectionString={cs.Value()}\"" : ""))).ConfigureAwait(false);
                }

                if (rc == 0 && IsRefDataSupported && ct.HasFlag(CommandType.RefData))
                {
                    rc = await CodeGenConsole.Create().RunAsync(AppendAssemblies(ReplaceMoustache(refDataFileName + " " + RefDataCommandLineTemplate) + expectNoChangeArg)).ConfigureAwait(false);
                }

                if (rc == 0 && IsEntitySupported && ct.HasFlag(CommandType.Entity))
                {
                    rc = await CodeGenConsole.Create().RunAsync(AppendAssemblies(ReplaceMoustache(entityFileName + " " + EntityCommandLineTemplate) + expectNoChangeArg)).ConfigureAwait(false);
                }

                if (rc == 0 && IsDataModelSupported && ct.HasFlag(CommandType.DataModel))
                {
                    rc = await CodeGenConsole.Create().RunAsync(AppendAssemblies(ReplaceMoustache(dataModelFileName + " " + DataModelCommandLineTemplate) + expectNoChangeArg)).ConfigureAwait(false);
                }

                return(rc);
            });

            try
            {
                return(await app.ExecuteAsync(args).ConfigureAwait(false));
            }
            catch (CommandParsingException cpex)
            {
                Console.WriteLine(cpex.Message);
                return(-1);
            }
        }
예제 #6
0
 /// <summary>
 /// The main entry point.
 /// </summary>
 /// <param name="args">The console arguments.</param>
 /// <returns>A statuc code.</returns>
 public static Task <int> Main(string[] args)
 {
     return(CodeGenConsole.Create().RunAsync(args));
 }
예제 #7
0
        /// <summary>
        /// Executes the underlying <see cref="CodeGenConsole"/> using the code generation arguments.
        /// </summary>
        /// <param name="args">The code generation arguments.</param>
        /// <returns><b>Zero</b> indicates success; otherwise, unsucessful.</returns>
        public async Task <int> RunAsync(string[] args)
        {
            using var app = new CommandLineApplication()
                  {
                      Name        = "beef.codegen",
                      Description = "Business Entity Execution Framework (Beef) Code Generator."
                  };

            var cmd = app.Argument <CommandType>("command", "Execution command type: Entity, Database, RefData or All.", false).IsRequired();
            var cs  = app.Option("-cs|--connectionString", "Override the connection string for Database.", CommandOptionType.SingleValue);
            var cf  = app.Option("-cf|--configFile", "Override the filename for the configuration.", CommandOptionType.SingleValue).Accepts(v => v.ExistingFile());
            var sf  = app.Option("-s|--scriptFile", "Override the filename for the script orchestration.", CommandOptionType.SingleValue).Accepts(v => v.ExistingFile());
            var enc = app.Option("-enc|--expectNoChanges", "Expect no changes in the artefact output and error where changes are detected (e.g. within build pipeline).", CommandOptionType.NoValue);
            var x2y = app.Option("-x2y|--xmlToYaml", "Convert the XML configuration into YAML equivalent (will not codegen).", CommandOptionType.NoValue);

            app.OnExecuteAsync(async(_) =>
            {
                var ct     = cmd.Value == null ? CommandType.All : Enum.Parse <CommandType>(cmd.Value, true);
                string?cfn = null;
                if (cf.HasValue())
                {
                    if (ct == CommandType.All)
                    {
                        throw new CommandParsingException(app, "Command 'All' is not compatible with --configFile; the command must be more specific when using a specified configuration file.");
                    }

                    cfn = cf.Value() !;
                }

                string?sfn = null;
                if (sf.HasValue())
                {
                    if (ct == CommandType.All)
                    {
                        throw new CommandParsingException(app, "Command 'All' is not compatible with --scriptFile; the command must be more specific when using a specified script file.");
                    }

                    sfn = sf.Value() !;
                }

                if (x2y.HasValue())
                {
                    if (ct == CommandType.All)
                    {
                        throw new CommandParsingException(app, "Command 'All' is not compatible with --xmlToYaml; the command must be more specific when converting XML configuration to YAML.");
                    }

                    CodeGenConsole.WriteMasthead();
                    return(await CodeGenFileManager.ConvertXmlToYamlAsync(ct, cfn ?? CodeGenFileManager.GetConfigFilename(_exeDir, ct, Company, AppName)).ConfigureAwait(false));
                }

                var encArg = enc.HasValue() ? " --expectNoChanges" : string.Empty;

                var rc = 0;
                if (IsDatabaseSupported && ct.HasFlag(CommandType.Database))
                {
                    rc = await CodeGenConsole.Create().RunAsync(AppendAssemblies(ReplaceMoustache($"\"{cfn ?? CodeGenFileManager.GetConfigFilename(_exeDir, CommandType.Database, Company, AppName)}\"" + " " + DatabaseCommandLineTemplate, sfn ?? _databaseScript) + (cs.HasValue() ? $" -p \"ConnectionString={cs.Value()}\""
                        : (string.IsNullOrEmpty(ConnectionString) ? "" : $" -p \"ConnectionString={ConnectionString}\"")) + encArg)).ConfigureAwait(false);
                }

                if (rc == 0 && IsRefDataSupported && ct.HasFlag(CommandType.RefData))
                {
                    rc = await CodeGenConsole.Create().RunAsync(AppendAssemblies(ReplaceMoustache($"\"{cfn ?? CodeGenFileManager.GetConfigFilename(_exeDir, CommandType.RefData, Company, AppName)}\"" + " " + RefDataCommandLineTemplate, sfn ?? _refDataScript) + encArg)).ConfigureAwait(false);
                }

                if (rc == 0 && IsEntitySupported && ct.HasFlag(CommandType.Entity))
                {
                    rc = await CodeGenConsole.Create().RunAsync(AppendAssemblies(ReplaceMoustache($"\"{cfn ?? CodeGenFileManager.GetConfigFilename(_exeDir, CommandType.Entity, Company, AppName)}\"" + " " + EntityCommandLineTemplate, sfn ?? _entityScript) + encArg)).ConfigureAwait(false);
                }

                if (rc == 0 && IsDataModelSupported && ct.HasFlag(CommandType.DataModel))
                {
                    rc = await CodeGenConsole.Create().RunAsync(AppendAssemblies(ReplaceMoustache($"\"{cfn ?? CodeGenFileManager.GetConfigFilename(_exeDir, CommandType.DataModel, Company, AppName)}\"" + " " + DataModelCommandLineTemplate, sfn ?? _dataModelScript) + encArg)).ConfigureAwait(false);
                }

                return(rc);
            });

            try
            {
                return(await app.ExecuteAsync(args).ConfigureAwait(false));
            }
            catch (CommandParsingException cpex)
            {
                Console.Error.WriteLine(cpex.Message);
                return(-1);
            }
        }