protected override Task OnRunAsync(ExecutorRunArgs args) { if (_throwState == 2) { throw new DivideByZeroException(); } return(Task.CompletedTask); }
/// <summary> /// Execute the database upgrade. /// </summary> protected override async Task OnRunAsync(ExecutorRunArgs args) { var ls = new LoggerSink(); if (_command.HasFlag(DatabaseExecutorCommand.Drop)) { Logger.Default.Info(string.Empty); Logger.Default.Info(new string('-', 80)); Logger.Default.Info("DB DROP: Checking database existence and dropping where found..."); await TimeExecutionAsync(() => { DropDatabase.For.SqlDatabase(_connectionString, ls); return(Task.FromResult(true)); }).ConfigureAwait(false); } if (_command.HasFlag(DatabaseExecutorCommand.Create)) { Logger.Default.Info(string.Empty); Logger.Default.Info(new string('-', 80)); Logger.Default.Info("DB CREATE: Checking database existence and creating where not found..."); await TimeExecutionAsync(() => { EnsureDatabase.For.SqlDatabase(_connectionString, ls); return(Task.FromResult(true)); }).ConfigureAwait(false); } if (_command.HasFlag(DatabaseExecutorCommand.Migrate)) { Logger.Default.Info(string.Empty); Logger.Default.Info(new string('-', 80)); Logger.Default.Info("DB MIGRATE: Migrating the database..."); Logger.Default.Info($"Probing for embedded resources: {(string.Join(", ", GetNamespacesWithSuffix($"{MigrationsNamespace}.*.sql")))}"); DatabaseUpgradeResult?result = null; await TimeExecutionAsync(() => { result = DeployChanges.To .SqlDatabase(_connectionString) .WithScripts(GetMigrationScripts(_assemblies)) .WithoutTransaction() .LogTo(ls) .Build() .PerformUpgrade(); return(Task.FromResult(result.Successful)); }).ConfigureAwait(false); if (!result !.Successful) { Logger.Default.Exception(result.Error); return; } } if (_command.HasFlag(DatabaseExecutorCommand.CodeGen)) { Logger.Default.Info(string.Empty); Logger.Default.Info(new string('-', 80)); Logger.Default.Info("DB CODEGEN: Code-gen database objects..."); CodeGenConsole.LogCodeGenExecutionArgs(_codeGenArgs); if (!await TimeExecutionAsync(async() => { var em = ExecutionManager.Create(() => new CodeGenExecutor(_codeGenArgs)); await em.RunAsync().ConfigureAwait(false); return(em.StopExecutor?.Exception == null); }).ConfigureAwait(false)) { return; } } if (_command.HasFlag(DatabaseExecutorCommand.Schema)) { Logger.Default.Info(string.Empty); Logger.Default.Info(new string('-', 80)); Logger.Default.Info("DB SCHEMA: Drops and creates the database objects..."); if (!await TimeExecutionAsync(() => DropAndCreateAllObjectsAsync(new string[] { "dbo", "Ref" })).ConfigureAwait(false)) { return; } } if (_command.HasFlag(DatabaseExecutorCommand.Reset)) { Logger.Default.Info(string.Empty); Logger.Default.Info(new string('-', 80)); Logger.Default.Info("DB RESET: Resets database by dropping data from all tables..."); if (!await TimeExecutionAsync(() => DeleteAllAndResetAsync()).ConfigureAwait(false)) { return; } } if (_command.HasFlag(DatabaseExecutorCommand.Data)) { Logger.Default.Info(string.Empty); Logger.Default.Info(new string('-', 80)); Logger.Default.Info("DB DATA: Insert or merge the embedded YAML data..."); if (!await TimeExecutionAsync(() => InsertOrMergeYamlDataAsync()).ConfigureAwait(false)) { return; } } if (_command.HasFlag(DatabaseExecutorCommand.ScriptNew)) { Logger.Default.Info(string.Empty); Logger.Default.Info(new string('-', 80)); Logger.Default.Info("DB SCRIPTNEW: Creating a new SQL script from embedded template..."); if (!await TimeExecutionAsync(() => CreateScriptNewAsync()).ConfigureAwait(false)) { return; } } ReturnCode = 0; }
/// <summary> /// Executes the selected code generation. /// </summary> protected override Task OnRunAsync(ExecutorRunArgs args) { try { // Load the script file instructions. XElement xmlScript = (_args.ScriptFile.Exists) ? XElement.Load(_args.ScriptFile.FullName) : ResourceManager.GetScriptContentXml(_args.ScriptFile.Name, _args.Assemblies.ToArray()); if (xmlScript.Name != "Script") { throw new CodeGenException("The Script XML file must have a root element named 'Script'."); } if (xmlScript.Elements("Generate").Count() == 0) { throw new CodeGenException("The Script XML file must have at least a single 'Generate' element."); } // Create the code generator instance. string outputDir = null; var gen = CodeGenerator.Create(XElement.Load(_args.ConfigFile.FullName), GetLoaders(xmlScript)); gen.CodeGenerated += (sender, e) => { CodeGenerated(outputDir, e); }; // Execute each of the script instructions. foreach (var scriptEle in xmlScript.Elements("Generate")) { // As this can be long running, check and see if a stop has been initiated. if (this.State != ExecutionState.Running) { return(Task.CompletedTask); } string template = null; string outDir = null; var otherParameters = new Dictionary <string, string>(); foreach (var att in scriptEle.Attributes()) { switch (att.Name.LocalName) { case "Template": template = att.Value; break; case "OutDir": outDir = att.Value; break; default: otherParameters.Add(att.Name.LocalName, att.Value); break; } } // Manage the parameters. gen.ClearParameters(); gen.CopyParameters(_args.Parameters); gen.CopyParameters(otherParameters); // Log progress. CreatedCount = 0; UpdatedCount = 0; NotChangedCount = 0; Logger.Default.Info(" Template: {0}", template); XElement xmlTemplate; if (_args.TemplatePath != null) { var fi = new FileInfo(Path.Combine(_args.TemplatePath.FullName, template)); if (!fi.Exists) { throw new CodeGenException(string.Format("The Template XML file '{0}' does not exist.", fi.FullName)); } xmlTemplate = XElement.Load(fi.FullName); } else { xmlTemplate = ResourceManager.GetTemplateContentXml(template, _args.Assemblies.ToArray()) ?? throw new CodeGenException(string.Format("The Template XML resource '{0}' does not exist.", template)); } // Execute the code generation itself. outputDir = Path.Combine(_args.OutputPath.FullName, SubstituteOutputDir(outDir)); gen.Generate(xmlTemplate); // Provide statistics. Logger.Default.Info(" [Files: Unchanged = {0}, Updated = {1}, Created = {2}]", NotChangedCount, UpdatedCount, CreatedCount); } } catch (CodeGenException gcex) { Logger.Default.Error(gcex.Message); Logger.Default.Info(string.Empty); } return(Task.CompletedTask); }
/// <summary> /// Executes the selected code generation. /// </summary> protected override async Task OnRunAsync(ExecutorRunArgs args) { var overallCreatedCount = 0; var overallUpdatedCount = 0; try { XElement?xmlScript; if (_args.ScriptFile !.Exists) { using var fs = File.OpenText(_args.ScriptFile.FullName); xmlScript = await XElement.LoadAsync(fs, LoadOptions.None, CancellationToken.None).ConfigureAwait(false); } else { xmlScript = await ResourceManager.GetScriptContentXmlAsync(_args.ScriptFile.Name, _args.Assemblies.ToArray()).ConfigureAwait(false); } if (xmlScript?.Name != "Script") { throw new CodeGenException("The Script XML file must have a root element named 'Script'."); } if (!xmlScript.Elements("Generate").Any()) { throw new CodeGenException("The Script XML file must have at least a single 'Generate' element."); } // Create the code generator instance. string?outputDir = null; using var cfs = File.OpenText(_args.ConfigFile !.FullName); var gen = CodeGenerator.Create(await XElement.LoadAsync(cfs, LoadOptions.None, CancellationToken.None).ConfigureAwait(false), GetLoaders(xmlScript)); gen.CodeGenerated += (sender, e) => { CodeGenerated(outputDir !, e); }; // Execute each of the script instructions. foreach (var scriptEle in xmlScript.Elements("Generate")) { // As this can be long running, check and see if a stop has been initiated. if (State != ExecutionState.Running) { return; } string?template = null; string?outDir = null; string?helpText = null; var otherParameters = new Dictionary <string, string>(); foreach (var att in scriptEle.Attributes()) { switch (att.Name.LocalName) { case "Template": template = att.Value; break; case "OutDir": outDir = att.Value; break; case "HelpText": helpText = att.Value; break; default: otherParameters.Add(att.Name.LocalName, att.Value); break; } } // Manage the parameters. gen.ClearParameters(); gen.CopyParameters(_args.Parameters); gen.CopyParameters(otherParameters); // Log progress. CreatedCount = 0; UpdatedCount = 0; NotChangedCount = 0; Logger.Default.Info(" Template: {0} {1}", template !, helpText == null ? string.Empty : $"({helpText})"); XElement xmlTemplate; if (_args.TemplatePath != null) { var fi = new FileInfo(Path.Combine(_args.TemplatePath.FullName, template !)); if (!fi.Exists) { throw new CodeGenException($"The Template XML file '{fi.FullName}' does not exist."); } using var fs = File.OpenText(fi.FullName); xmlTemplate = await XElement.LoadAsync(fs, LoadOptions.None, CancellationToken.None).ConfigureAwait(false); } else { xmlTemplate = await ResourceManager.GetTemplateContentXmlAsync(template !, _args.Assemblies.ToArray()).ConfigureAwait(false) ?? throw new CodeGenException($"The Template XML resource '{template}' does not exist."); } // Execute the code generation itself. outputDir = Path.Combine(_args.OutputPath !.FullName, SubstituteOutputDir(outDir !)); await gen.GenerateAsync(xmlTemplate).ConfigureAwait(false); // Provide statistics. Logger.Default.Info(" [Files: Unchanged = {0}, Updated = {1}, Created = {2}]", NotChangedCount, UpdatedCount, CreatedCount); // Keep track of overall counts. overallCreatedCount += CreatedCount; overallUpdatedCount += UpdatedCount; } }