Beispiel #1
0
        public static int Main([NotNull] string[] args)
        {
            ConsoleCommandLogger.IsVerbose = HandleVerboseOption(ref args);
            HandleDebugSwitch(ref args);

            try
            {
                return(ExecuteCommand.Create(ref args).Execute(args));
            }
            catch (Exception ex)
            {
                // TODO ensure always a json response if --json is supplied
                if (ex is TargetInvocationException)
                {
                    ex = ex.InnerException;
                }

                if (!(ex is OperationException))
                {
                    ConsoleCommandLogger.Error(ex.ToString());
                }

                ConsoleCommandLogger.Error(ex.Message.Bold().Red());
                return(1);
            }
        }
        private static int Execute(CommonOptions commonOptions,
                                   string from,
                                   string to,
                                   string output,
                                   bool idempotent,
                                   string context,
                                   string environment)
        {
            var sql = new OperationExecutor(commonOptions, environment)
                      .ScriptMigration(from, to, idempotent, context);

            if (string.IsNullOrEmpty(output))
            {
                ConsoleCommandLogger.Output(sql);
            }
            else
            {
                ConsoleCommandLogger.Verbose("Writing SQL script to '" + output + "'".Bold().Black());
                File.WriteAllText(output, sql, Encoding.UTF8);

                ConsoleCommandLogger.Output("Done");
            }

            return(0);
        }
Beispiel #3
0
        private static async Task <int> ExecuteAsync(CommonOptions commonOptions,
                                                     string connection,
                                                     string provider,
                                                     bool dataAnnotations,
                                                     string context,
                                                     bool force,
                                                     string outputDir,
                                                     IEnumerable <string> schemas,
                                                     IEnumerable <string> tables,
                                                     string environment)
        {
            await new OperationExecutor(commonOptions, environment)
            .ReverseEngineerAsync(
                provider,
                connection,
                outputDir,
                context,
                schemas,
                tables,
                dataAnnotations,
                force);

            ConsoleCommandLogger.Output("Done");

            return(0);
        }
Beispiel #4
0
        private static void EnsureValidDispatchRecipient(ref string[] args)
        {
            if (!args.Contains(DispatcherVersionArgumentName, StringComparer.OrdinalIgnoreCase))
            {
                return;
            }

            var dispatcherArgumentIndex = Array.FindIndex(
                args,
                (value) => string.Equals(value, DispatcherVersionArgumentName, StringComparison.OrdinalIgnoreCase));
            var dispatcherArgumentValueIndex = dispatcherArgumentIndex + 1;

            if (dispatcherArgumentValueIndex < args.Length)
            {
                var dispatcherVersion = args[dispatcherArgumentValueIndex];

                if (string.Equals(dispatcherVersion, GetVersion(), StringComparison.Ordinal))
                {
                    // Remove dispatcher arguments from
                    var preDispatcherArgument  = args.Take(dispatcherArgumentIndex);
                    var postDispatcherArgument = args.Skip(dispatcherArgumentIndex + 2);
                    var newProgramArguments    = preDispatcherArgument.Concat(postDispatcherArgument);
                    args = newProgramArguments.ToArray();
                    return;
                }

                ConsoleCommandLogger.Verbose("Expected dispatch version " + GetVersion() + " but received " + dispatcherVersion);
            }

            // Could not validate the dispatcher version.
            throw new OperationException(
                      "Could not invoke command. Ensure project.json has matching versions of 'Microsoft.EntityFrameworkCore.Design' in the 'dependencies' section and 'Microsoft.EntityFrameworkCore.Tools' in the 'tools' section.");
        }
Beispiel #5
0
        private static void ReportJson(MigrationFiles files)
        {
            var sb = new StringBuilder();

            sb.AppendLine("//BEGIN");
            sb.AppendLine("{");
            sb.AppendLine("  \"MigrationFile\": \"" + SerializePath(files.MigrationFile) + "\",");
            sb.AppendLine("  \"MetadataFile\": \"" + SerializePath(files.MetadataFile) + "\",");
            sb.AppendLine("  \"SnapshotFile\": \"" + SerializePath(files.SnapshotFile) + "\"");
            sb.AppendLine("}");
            sb.AppendLine("//END");
            ConsoleCommandLogger.Output(sb.ToString());
        }
Beispiel #6
0
        private static void ReportResults(IEnumerable <MigrationInfo> migrations)
        {
            var any = false;

            foreach (var migration in migrations)
            {
                ConsoleCommandLogger.Output(migration.Id as string);
                any = true;
            }

            if (!any)
            {
                ConsoleCommandLogger.Error("No migrations were found");
            }
        }
Beispiel #7
0
        private static void ReportJsonResults(IEnumerable <MigrationInfo> migrations)
        {
            var nameGroups = migrations.GroupBy(m => m.Name).ToList();
            var output     = migrations.Select(
                m => new
            {
                id       = m.Id,
                name     = m.Name,
                safeName = nameGroups.Count(g => g.Key == m.Name) == 1
                        ? m.Name
                        : m.Id
            }).ToArray();

            ConsoleCommandLogger.Json(output);
        }
Beispiel #8
0
        private static void ReportResults(IEnumerable <Type> contextTypes)
        {
            var any = false;

            foreach (var contextType in contextTypes)
            {
                ConsoleCommandLogger.Output(contextType.FullName as string);
                any = true;
            }

            if (!any)
            {
                ConsoleCommandLogger.Error("No DbContext was found");
            }
        }
        private static int Execute(CommonOptions commonOptions,
                                   string name,
                                   string outputDir,
                                   string context,
                                   string environment,
                                   Action <MigrationFiles> reporter)
        {
            var files = new OperationExecutor(commonOptions, environment)
                        .AddMigration(name, outputDir, context);

            reporter?.Invoke(files);

            ConsoleCommandLogger.Output("Done. To undo this action, use 'dotnet ef migrations remove'");

            return(0);
        }
Beispiel #10
0
        private static void WriteLogo()
        {
            const string Bold    = "\x1b[1m";
            const string Normal  = "\x1b[22m";
            const string Magenta = "\x1b[35m";
            const string White   = "\x1b[37m";
            const string Default = "\x1b[39m";

            ConsoleCommandLogger.Output("");
            ConsoleCommandLogger.Output(@"                     _/\__       ".Insert(21, Bold + White));
            ConsoleCommandLogger.Output(@"               ---==/    \\      ".Insert(20, Bold + White));
            ConsoleCommandLogger.Output(@"         ___  ___   |.    \|\    ".Insert(26, Bold).Insert(21, Normal).Insert(20, Bold + White).Insert(9, Normal + Magenta));
            ConsoleCommandLogger.Output(@"        | __|| __|  |  )   \\\   ".Insert(20, Bold + White).Insert(8, Normal + Magenta));
            ConsoleCommandLogger.Output(@"        | _| | _|   \_/ |  //|\\ ".Insert(20, Bold + White).Insert(8, Normal + Magenta));
            ConsoleCommandLogger.Output(@"        |___||_|       /   \\\/\\".Insert(33, Normal + Default).Insert(23, Bold + White).Insert(8, Normal + Magenta));
            ConsoleCommandLogger.Output("");
        }
Beispiel #11
0
        private static void ReportJsonResults(IEnumerable <Type> contextTypes)
        {
            var nameGroups     = contextTypes.GroupBy(t => t.Name).ToList();
            var fullNameGroups = contextTypes.GroupBy(t => t.FullName).ToList();

            var output = new StringBuilder();

            output.AppendLine("//BEGIN");
            output.Append("[");

            var first = true;

            foreach (var contextType in contextTypes)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    output.Append(",");
                }
                var safeName = nameGroups.Count(g => g.Key == contextType.Name) == 1
                    ? contextType.Name
                    : fullNameGroups.Count(g => g.Key == contextType.FullName) == 1
                        ? contextType.FullName
                        : contextType.AssemblyQualifiedName;

                output.AppendLine();
                output.AppendLine("  {");
                output.AppendLine("     \"fullName\": \"" + contextType.FullName + "\",");
                output.AppendLine("     \"safeName\": \"" + safeName + "\",");
                output.AppendLine("     \"name\": \"" + contextType.Name + "\",");
                output.AppendLine("     \"assemblyQualifiedName\": \"" + contextType.AssemblyQualifiedName + "\"");
                output.AppendLine("  }");
            }

            output.AppendLine();
            output.AppendLine("]");
            output.AppendLine("//END");

            ConsoleCommandLogger.Output(output.ToString());
        }
        public static void Configure([NotNull] CommandLineApplication command, [NotNull] CommonCommandOptions commonOptions)
        {
            command.Description = "Add a new migration";

            var name = command.Argument("[name]", "The name of the migration");

            var outputDir = command.Option(
                "-o|--output-dir <path>",
                "The directory (and sub-namespace) to use. If omitted, \"Migrations\" is used. Relative paths are relative the directory in which the command is executed.");
            var context = command.Option(
                "-c|--context <context>",
                "The DbContext to use. If omitted, the default DbContext is used");
            var environment = command.Option(
                "-e|--environment <environment>",
                "The environment to use. If omitted, \"Development\" is used.");
            var json = command.JsonOption();

            command.HelpOption();
            command.VerboseOption();

            command.OnExecute(
                () =>
            {
                if (string.IsNullOrEmpty(name.Value))
                {
                    ConsoleCommandLogger.Error(("Missing required argument '" + name.Name + "'").Bold().Red());
                    command.ShowHelp();

                    return(1);
                }

                return(Execute(commonOptions.Value(),
                               name.Value,
                               outputDir.Value(),
                               context.Value(),
                               environment.Value(),
                               json.HasValue()
                            ? (Action <MigrationFiles>)ReportJson
                            : null));
            });
        }
Beispiel #13
0
        private static void ReportJsonResults(IEnumerable <MigrationInfo> migrations)
        {
            var nameGroups = migrations.GroupBy(m => m.Name).ToList();
            var output     = new StringBuilder();

            output.AppendLine("//BEGIN");
            output.Append("[");

            var first = true;

            foreach (var m in migrations)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    output.Append(",");
                }

                var safeName = nameGroups.Count(g => g.Key == m.Name) == 1
                    ? m.Name
                    : m.Id;

                output.AppendLine();
                output.AppendLine("  {");
                output.AppendLine("    \"id\": \"" + m.Id + "\",");
                output.AppendLine("    \"name\": \"" + m.Name + "\",");
                output.AppendLine("    \"safeName\": \"" + safeName + "\"");
                output.Append("  }");
            }

            output.AppendLine();
            output.AppendLine("]");
            output.AppendLine("//END");

            ConsoleCommandLogger.Output(output.ToString());
        }
Beispiel #14
0
        private static int Execute(CommonOptions commonOptions,
                                   string context,
                                   string environment,
                                   bool isForced)
        {
            new OperationExecutor(commonOptions, environment)
            .DropDatabase(
                context,
                (database, dataSource) =>
            {
                if (isForced)
                {
                    return(true);
                }

                ConsoleCommandLogger.Output(
                    $"Are you sure you want to drop the database '{database}' on server '{dataSource}'? (y/N)");
                var readedKey = Console.ReadKey().KeyChar;

                return((readedKey == 'y') || (readedKey == 'Y'));
            });

            return(0);
        }
Beispiel #15
0
        public static void Configure([NotNull] CommandLineApplication command, [NotNull] CommonCommandOptions commonOptions)
        {
            command.Description = "Scaffolds a DbContext and entity type classes for a specified database";

            var connection = command.Argument(
                "[connection]",
                "The connection string of the database");
            var provider = command.Argument(
                "[provider]",
                "The provider to use. For example, Microsoft.EntityFrameworkCore.SqlServer");

            var dataAnnotations = command.Option(
                "-a|--data-annotations",
                "Use DataAnnotation attributes to configure the model where possible. If omitted, the output code will use only the fluent API.",
                CommandOptionType.NoValue);
            var context = command.Option(
                "-c|--context <name>",
                "Name of the generated DbContext class.");
            var force = command.Option(
                "-f|--force",
                "Force scaffolding to overwrite existing files. Otherwise, the code will only proceed if no output files would be overwritten.",
                CommandOptionType.NoValue);
            var outputDir = command.Option(
                "-o|--output-dir <path>",
                "Directory of the project where the classes should be output. If omitted, the top-level project directory is used.");
            var schemas = command.Option(
                "--schema <schema>",
                "Selects a schema for which to generate classes.",
                CommandOptionType.MultipleValue);
            var tables = command.Option(
                "-t|--table <schema.table>",
                "Selects a table for which to generate classes.",
                CommandOptionType.MultipleValue);
            var environment = command.Option(
                "-e|--environment <environment>",
                "The environment to use. If omitted, \"Development\" is used.");

            command.HelpOption();
            command.VerboseOption();

            command.OnExecute(
                () =>
            {
                if (string.IsNullOrEmpty(connection.Value))
                {
                    ConsoleCommandLogger.Error(("Missing required argument '" + connection.Name + "'").Bold().Red());
                    command.ShowHelp();

                    return(Task.FromResult(1));
                }
                if (string.IsNullOrEmpty(provider.Value))
                {
                    ConsoleCommandLogger.Error(("Missing required argument '" + provider.Name + "'").Bold().Red());
                    command.ShowHelp();

                    return(Task.FromResult(1));
                }

                return(ExecuteAsync(commonOptions.Value(),
                                    connection.Value,
                                    provider.Value,
                                    dataAnnotations.HasValue(),
                                    context.Value(),
                                    force.HasValue(),
                                    outputDir.Value(),
                                    schemas.Values,
                                    tables.Values,
                                    environment.Value()));
            });
        }
        private static void ReportJsonResults(IEnumerable <Type> contextTypes)
        {
            var typeNames = contextTypes.Select(t => new { fullName = t.FullName }).ToArray();

            ConsoleCommandLogger.Json(typeNames);
        }
 private static void ReportJson(MigrationFiles files)
 => ConsoleCommandLogger.Json(files);