예제 #1
0
        // Creates a command to execute dotnet-aspnet-codegenerator-design
        private Command CreateDipatchCommand(
            IProjectContext context,
            string[] args,
            string buildBasePath,
            string configuration,
            NuGetFramework frameworkToUse,
            ScaffoldingServer server)
        {
            var projectDirectory = Directory.GetParent(context.ProjectFullPath).FullName;

            // Command Resolution Args
            // To invoke dotnet-aspnet-codegenerator-design with the user project's dependency graph,
            // we need to pass in the runtime config and deps file to dotnet for netcore app projects.
            // For projects that target net4x, since the dotnet-aspnet-codegenerator-design.exe is in the project's bin folder
            // and `dotnet build` generates a binding redirect file for it, we can directly invoke the exe from output location.

            var targetDir         = Path.GetDirectoryName(context.AssemblyFullPath);
            var runtimeConfigPath = Path.Combine(targetDir, context.RuntimeConfig);
            var depsFile          = Path.Combine(targetDir, context.DepsFile);

            string dotnetCodeGenInsideManPath = string.Empty;

            if (IsNetCoreAppFramework(frameworkToUse))
            {
                dotnetCodeGenInsideManPath = context.CompilationAssemblies
                                             .Where(c => Path.GetFileNameWithoutExtension(c.Name)
                                                    .Equals(DESIGN_TOOL_NAME, StringComparison.OrdinalIgnoreCase))
                                             .Select(reference => reference.ResolvedPath)
                                             .FirstOrDefault();
                if (string.IsNullOrEmpty(dotnetCodeGenInsideManPath))
                {
                    throw new InvalidOperationException(Resources.AddDesignPackage);
                }
            }
            else
            {
                dotnetCodeGenInsideManPath = Path.Combine(Path.GetDirectoryName(context.AssemblyFullPath), DESIGN_TOOL_NAME + ".exe");
                if (!File.Exists(dotnetCodeGenInsideManPath))
                {
                    throw new InvalidOperationException(Resources.AddDesignPackage);
                }
            }

            var dependencyArgs = ToolCommandLineHelper.GetProjectDependencyCommandArgs(
                args,
                frameworkToUse.GetShortFolderName(),
                server.Port.ToString());

            return(DotnetToolDispatcher.CreateDispatchCommand(
                       runtimeConfigPath: runtimeConfigPath,
                       depsFile: depsFile,
                       dependencyToolPath: dotnetCodeGenInsideManPath,
                       dispatchArgs: dependencyArgs,
                       framework: frameworkToUse,
                       configuration: configuration,
                       projectDirectory: projectDirectory,
                       assemblyFullPath: context.AssemblyFullPath)
                   .InWorkingDirectory(projectDirectory));
        }
예제 #2
0
        private static void Dispatch(string[] args)
        {
            var projectFile      = ProjectReader.GetProject(string.Empty);
            var targetFrameworks = projectFile
                                   .GetTargetFrameworks()
                                   .Select(frameworkInformation => frameworkInformation.FrameworkName);
            var framework = default(NuGetFramework);

            if (!TryResolveFramework(targetFrameworks, out framework))
            {
                return;
            }

            // Let's build the project first.
            var buildCommand = BuildCommandFactory.Create(
                projectFile.ProjectFilePath,
                "Debug",
                framework,
                null,
                null);
            var buildExitCode = buildCommand
                                .ForwardStdErr()
                                .ForwardStdOut()
                                .Execute()
                                .ExitCode;

            if (buildExitCode != 0)
            {
                throw new Exception($"Building {projectFile.Name} failed...");
            }
            Console.WriteLine();

            var dispatchCommand = DotnetToolDispatcher.CreateDispatchCommand(
                args,
                framework,
                "Debug",
                outputPath: null,
                buildBasePath: null,
                projectDirectory: projectFile.ProjectDirectory);

            using (var errorWriter = new StringWriter())
            {
                var commandExitCode = dispatchCommand
                                      .ForwardStdErr(errorWriter)
                                      .ForwardStdOut()
                                      .Execute()
                                      .ExitCode;

                if (commandExitCode != 0)
                {
                    Console.WriteLine(errorWriter.ToString());
                }

                return;
            }
        }
예제 #3
0
        private static void Dispatch(string[] args)
        {
            var projectFile      = ProjectReader.GetProject(string.Empty);
            var targetFrameworks = projectFile.TargetFrameworks;

            if (!TryResolveFramework(targetFrameworks, out var framework))
            {
                return;
            }

            // Let's build the project first.
            var buildCommand = BuildCommandFactory.Create(
                projectFile.ProjectFilePath,
                "Debug",
                framework.Framework,
                null,
                null);
            var buildExitCode = buildCommand
                                .ForwardStdErr()
                                .ForwardStdOut()
                                .Execute()
                                .ExitCode;

            if (buildExitCode != 0)
            {
                throw new Exception($"Building {projectFile.Name} failed...");
            }
            Console.WriteLine();

            var runtime      = GetRuntimeOption(args) ?? string.Empty;
            var toolPath     = Path.Combine(projectFile.ProjectDirectory, "bin", "Debug", framework.TFM, runtime, "dotnet-ef.exe");
            var assemblyPath = Path.Combine(projectFile.ProjectDirectory, "bin", "Debug", framework.TFM, runtime, projectFile.Name + ".exe");

            var dispatchCommand = DotnetToolDispatcher.CreateDispatchCommand(
                toolPath,
                args,
                framework.Framework,
                "Debug",
                assemblyPath);

            using (var errorWriter = new StringWriter())
            {
                var commandExitCode = dispatchCommand
                                      .ForwardStdErr(errorWriter)
                                      .ForwardStdOut()
                                      .Execute()
                                      .ExitCode;

                if (commandExitCode != 0)
                {
                    Console.WriteLine(errorWriter.ToString());
                }

                return;
            }
        }
예제 #4
0
        private static int BuildAndDispatchDependencyCommand(
            string[] args,
            NuGetFramework frameworkToUse,
            string projectPath,
            string buildBasePath,
            string configuration)
        {
            if (frameworkToUse == null)
            {
                throw new ArgumentNullException(nameof(frameworkToUse));
            }
            if (string.IsNullOrEmpty(projectPath))
            {
                throw new ArgumentNullException(nameof(projectPath));
            }

            var buildResult = DotNetBuildCommandHelper.Build(
                projectPath,
                configuration,
                frameworkToUse,
                buildBasePath);

            if (buildResult.ExitCode != 0)
            {
                //Build failed.
                // Stop the process here.
                _logger.LogMessage(buildResult.StdErr, LogMessageLevel.Error);
                return(buildResult.ExitCode);
            }

            // Invoke the dependency command
            var projectFilePath = projectPath.EndsWith("project.json")
                ? projectPath
                : Path.Combine(projectPath, "project.json");

            var projectDirectory = Directory.GetParent(projectFilePath).FullName;

            var dependencyArgs = ToolCommandLineHelper.GetProjectDependencyCommandArgs(
                args,
                frameworkToUse.GetShortFolderName());

            var exitCode = DotnetToolDispatcher.CreateDispatchCommand(
                dependencyArgs,
                frameworkToUse,
                configuration,
                null,
                buildBasePath,
                projectDirectory)
                           .ForwardStdErr()
                           .ForwardStdOut()
                           .Execute()
                           .ExitCode;

            return(exitCode);
        }
        protected override int OnExecute()
        {
            var projectFile      = ProjectReader.GetProject(ProjectArgument.Value);
            var targetFrameworks = projectFile
                                   .GetTargetFrameworks()
                                   .Select(frameworkInformation => frameworkInformation.FrameworkName);

            NuGetFramework framework;

            if (!TryResolveFramework(targetFrameworks, out framework))
            {
                // Could not resolve framework for dispatch. Error was reported, exit early.
                return(0);
            }

            var dispatchArgs = new List <string>
            {
                CommandName,
                AssemblyNamesArgument.Value,
            };

            if (ProtocolOption.HasValue())
            {
                dispatchArgs.Add("--protocol");
                dispatchArgs.Add(ProtocolOption.Value());
            }

            var dispatchCommand = DotnetToolDispatcher.CreateDispatchCommand(
                dispatchArgs,
                framework,
                ConfigurationOption.Value(),
                outputPath: null,
                buildBasePath: BuildBasePathOption.Value(),
                projectDirectory: projectFile.ProjectDirectory);

            using (var errorWriter = new StringWriter())
            {
                var commandExitCode = dispatchCommand
                                      .ForwardStdErr(errorWriter)
                                      .ForwardStdOut()
                                      .Execute()
                                      .ExitCode;

                if (commandExitCode != 0)
                {
                    ReportError(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.FailedToExecuteRazorTooling,
                            errorWriter.ToString()));
                }

                return(0);
            }
        }
예제 #6
0
        public static CommandLineApplication Create()
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name     = "dotnet ef",
                FullName = "Entity Framework .NET Core CLI Commands Dispatcher"
            };

            var noBuildOption = app.Option("--no-build", "Do not build before executing");

            var configurationOption = app.Option(
                "-c|--configuration <CONFIGURATION>",
                "Configuration under which to load");
            var frameworkOption = app.Option(
                "-f|--framework <FRAMEWORK>",
                "Target framework to load");
            var buildBasePathOption = app.Option(
                "-b|--build-base-path <OUTPUT_DIR>",
                "Directory in which to find temporary outputs");

            var outputOption = app.Option(
                "-o|--output <OUTPUT_DIR>",
                "Directory in which to find outputs");

            app.OnExecute(() =>
            {
                var project = Directory.GetCurrentDirectory();

                Reporter.Verbose.WriteLine(ToolsStrings.LogUsingProject(project));

                var projectFile = ProjectReader.GetProject(project);

                var framework = frameworkOption.HasValue()
                    ? NuGetFramework.Parse(frameworkOption.Value())
                    : null;

                if (framework == null)
                {
                    var frameworks = projectFile.GetTargetFrameworks().Select(i => i.FrameworkName);
                    framework      = NuGetFrameworkUtility.GetNearest(frameworks, FrameworkConstants.CommonFrameworks.NetCoreApp10, f => f)
                                     ?? frameworks.FirstOrDefault();

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingFramework(framework.GetShortFolderName()));
                }

                var configuration = configurationOption.Value();

                if (configuration == null)
                {
                    configuration = Constants.DefaultConfiguration;

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingConfiguration(configuration));
                }


                if (!noBuildOption.HasValue())
                {
                    var buildExitCode = BuildCommandFactory.Create(
                        projectFile.ProjectFilePath,
                        configuration,
                        framework,
                        buildBasePathOption.Value(),
                        outputOption.Value())
                                        .ForwardStdErr()
                                        .ForwardStdOut()
                                        .Execute()
                                        .ExitCode;
                    if (buildExitCode != 0)
                    {
                        throw new OperationException(ToolsStrings.BuildFailed(projectFile.Name));
                    }
                }

                Reporter.Verbose.WriteLine(ToolsStrings.LogBeginDispatch(ProjectDependencyToolName, projectFile.Name));

                try
                {
                    bool isVerbose;
                    bool.TryParse(Environment.GetEnvironmentVariable(CommandContext.Variables.Verbose), out isVerbose);
                    var dispatchArgs = ExecuteCommand
                                       .CreateArgs(framework, configuration, buildBasePathOption.Value(), noBuildOption.HasValue(), isVerbose)
                                       .Concat(app.RemainingArguments);

                    return(DotnetToolDispatcher.CreateDispatchCommand(
                               dispatchArgs,
                               framework,
                               configuration,
                               outputPath: outputOption.Value(),
                               buildBasePath: buildBasePathOption.Value(),
                               projectDirectory: projectFile.ProjectDirectory,
                               toolName: ProjectDependencyToolName)
                           .ForwardStdErr()
                           .ForwardStdOut()
                           .Execute()
                           .ExitCode);
                }
                catch (CommandUnknownException ex)
                {
                    Reporter.Verbose.WriteLine(ex.Message);
                    // intentionally put DispatcherToolName in error because "Microsoft.EntityFrameworkCore.Tools.Cli" is
                    // brought in automatically as a dependency of "Microsoft.EntityFrameworkCore.Tools"
                    Reporter.Error.WriteLine(ToolsStrings.ProjectDependencyCommandNotFound(DispatcherToolName));
                    return(1);
                }
            });

            return(app);
        }
예제 #7
0
        private int Execute()
        {
            ParseArguments();

            var runtimeContext = GetRuntimeContext();

            var outputPaths     = runtimeContext.GetOutputPaths(Configuration);
            var applicationName = Path.GetFileNameWithoutExtension(outputPaths.CompilationFiles.Assembly);
            var dispatchArgs    = new List <string>
            {
                ProjectPath,
                PrecompileRunCommand.ApplicationNameTemplate,
                applicationName,
                PrecompileRunCommand.OutputPathTemplate,
                OutputPath,
                CommonOptions.ContentRootTemplate,
                Options.ContentRootOption.Value() ?? Directory.GetCurrentDirectory(),
            };

            if (Options.ConfigureCompilationType.HasValue())
            {
                dispatchArgs.Add(CommonOptions.ConfigureCompilationTypeTemplate);
                dispatchArgs.Add(Options.ConfigureCompilationType.Value());
            }

            var compilerOptions = runtimeContext.ProjectFile.GetCompilerOptions(TargetFramework, Configuration);

            if (!string.IsNullOrEmpty(compilerOptions.KeyFile))
            {
                dispatchArgs.Add(StrongNameOptions.StrongNameKeyPath);
                var keyFilePath = Path.GetFullPath(Path.Combine(runtimeContext.ProjectDirectory, compilerOptions.KeyFile));
                dispatchArgs.Add(keyFilePath);

                if (compilerOptions.DelaySign ?? false)
                {
                    dispatchArgs.Add(StrongNameOptions.DelaySignTemplate);
                }

                if (compilerOptions.PublicSign ?? false)
                {
                    dispatchArgs.Add(StrongNameOptions.PublicSignTemplate);
                }
            }

#if DEBUG
            var commandLineArgs = Environment.GetCommandLineArgs();
            if (commandLineArgs.Length > 0 && commandLineArgs[0] == "--debug")
            {
                dispatchArgs.Insert(0, commandLineArgs[0]);
            }
#endif

            var toolName        = typeof(Design.Program).GetTypeInfo().Assembly.GetName().Name;
            var dispatchCommand = DotnetToolDispatcher.CreateDispatchCommand(
                dispatchArgs,
                TargetFramework,
                Configuration,
                outputPath: outputPaths.RuntimeOutputPath,
                buildBasePath: null,
                projectDirectory: ProjectPath,
                toolName: toolName);

            var commandExitCode = dispatchCommand
                                  .ForwardStdErr(Console.Error)
                                  .ForwardStdOut(Console.Out)
                                  .Execute()
                                  .ExitCode;

            return(commandExitCode);
        }
예제 #8
0
        public static CommandLineApplication Create()
        {
            var app = new CommandLineApplication(throwOnUnexpectedArg: false)
            {
                Name     = "dotnet ef",
                FullName = "Entity Framework .NET Core CLI Commands Dispatcher"
            };

            var noBuildOption = app.Option("--no-build", "Do not build before executing");

            var configurationOption = app.Option(
                "-c|--configuration <CONFIGURATION>",
                "Configuration under which to load");
            var frameworkOption = app.Option(
                "-f|--framework <FRAMEWORK>",
                "Target framework to load");
            var buildBasePathOption = app.Option(
                "-b|--build-base-path <OUTPUT_DIR>",
                "Directory in which to find temporary outputs");
            var outputOption = app.Option(
                "-o|--output <OUTPUT_DIR>",
                "Directory in which to find outputs");

            app.OnExecute(() =>
            {
                var project = Directory.GetCurrentDirectory();

                Reporter.Verbose.WriteLine(ToolsStrings.LogUsingProject(project));

                var projectFile = ProjectReader.GetProject(project);

                var framework = frameworkOption.HasValue()
                    ? NuGetFramework.Parse(frameworkOption.Value())
                    : null;

                if (framework == null)
                {
                    var frameworks = projectFile.GetTargetFrameworks().Select(i => i.FrameworkName);
                    framework      = NuGetFrameworkUtility.GetNearest(frameworks, FrameworkConstants.CommonFrameworks.NetCoreApp10, f => f)
                                     ?? frameworks.FirstOrDefault();

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingFramework(framework.GetShortFolderName()));
                }

                var configuration = configurationOption.Value();

                if (configuration == null)
                {
                    configuration = Constants.DefaultConfiguration;

                    Reporter.Verbose.WriteLine(ToolsStrings.LogUsingConfiguration(configuration));
                }

                if (!noBuildOption.HasValue())
                {
                    var buildExitCode = BuildCommandFactory.Create(
                        projectFile.ProjectFilePath,
                        configuration,
                        framework,
                        buildBasePathOption.Value(),
                        outputOption.Value())
                                        .ForwardStdErr()
                                        .ForwardStdOut()
                                        .Execute()
                                        .ExitCode;
                    if (buildExitCode != 0)
                    {
                        throw new OperationException(ToolsStrings.BuildFailed(projectFile.Name));
                    }
                }

                // TODO remove when https://github.com/dotnet/cli/issues/2645 is resolved
                Func <bool> isClassLibrary = () =>
                {
                    var projectContext = ProjectContext.Create(
                        projectFile.ProjectFilePath,
                        framework,
                        RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

                    var runtimeFiles = projectContext
                                       .GetOutputPaths(configuration, buildBasePathOption.Value(), outputOption.Value())
                                       ?.RuntimeFiles;

                    return(runtimeFiles == null ||
                           (
                               framework.IsDesktop()
                                ? !Directory.Exists(runtimeFiles.BasePath)
                                : !File.Exists(runtimeFiles.RuntimeConfigJson) || !File.Exists(runtimeFiles.DepsJson)
                           ));
                };

                Reporter.Verbose.WriteLine(ToolsStrings.LogBeginDispatch(ProjectDependencyToolName, projectFile.Name));

                try
                {
                    bool isVerbose;
                    bool.TryParse(Environment.GetEnvironmentVariable(CommandContext.Variables.Verbose), out isVerbose);
                    var dispatchArgs = ExecuteCommand
                                       .CreateArgs(framework, configuration, isVerbose)
                                       .Concat(app.RemainingArguments);

                    return(DotnetToolDispatcher.CreateDispatchCommand(
                               dispatchArgs,
                               framework,
                               configuration,
                               outputPath: outputOption.Value(),
                               buildBasePath: buildBasePathOption.Value(),
                               projectDirectory: projectFile.ProjectDirectory,
                               toolName: ProjectDependencyToolName)
                           .ForwardStdErr()
                           .ForwardStdOut()
                           .Execute()
                           .ExitCode);
                }
                catch (CommandUnknownException ex)
                {
                    Reporter.Verbose.WriteLine(ex.Message);

                    var fwlink = "http://go.microsoft.com/fwlink/?LinkId=798221";

                    if (isClassLibrary())
                    {
                        Reporter.Error.WriteLine(ToolsStrings.ClassLibrariesNotSupportedInCli(fwlink));
                    }
                    else
                    {
                        // intentionally put DispatcherToolName in error because "Microsoft.EntityFrameworkCore.Tools.Cli" is
                        // brought in automatically as a dependency of "Microsoft.EntityFrameworkCore.Tools"
                        Reporter.Error.WriteLine(ToolsStrings.ProjectDependencyCommandNotFound(DispatcherToolName, fwlink));
                    }

                    return(1);
                }
            });

            return(app);
        }