コード例 #1
0
        /// <summary>
        /// Executes the program.
        /// </summary>
        /// <returns>The exit code of the program.</returns>
        public int Execute()
        {
            LoggerVerbosity verbosity = ForwardingLogger.ParseLoggerVerbosity(_arguments.Verbosity?.LastOrDefault());

            ConsoleForwardingLogger consoleLogger = new ConsoleForwardingLogger(_console)
            {
                NoWarn     = _arguments.NoWarn,
                Parameters = _arguments.ConsoleLoggerParameters.Arguments.IsNullOrWhiteSpace() ? "ForceNoAlign=true;Summary" : _arguments.ConsoleLoggerParameters.Arguments,
                Verbosity  = verbosity,
            };

            ForwardingLogger forwardingLogger = new ForwardingLogger(GetLoggers(consoleLogger), _arguments.NoWarn)
            {
                Verbosity = verbosity,
            };

            using (ProjectCollection projectCollection = new ProjectCollection(
                       globalProperties: null,
                       loggers: new ILogger[]
            {
                forwardingLogger,
            },
                       remoteLoggers: null,
                       toolsetDefinitionLocations: ToolsetDefinitionLocations.Default,
                       maxNodeCount: 1,
#if NET46
                       onlyLogCriticalEvents: false))
#else
                       onlyLogCriticalEvents : false,
                       loadProjectsReadOnly : true))
#endif
            {
                try
                {
                    forwardingLogger.LogMessageLow("Command Line Arguments: {0}", Environment.CommandLine);

                    forwardingLogger.LogMessageLow("Using MSBuild from \"{0}\"", _msbuildExePath);

                    foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies().Where(i => i.FullName.StartsWith("Microsoft.Build")))
                    {
                        forwardingLogger.LogMessageLow("Loaded assembly: \"{0}\" from \"{1}\"", assembly.FullName, assembly.Location);
                    }

                    (TimeSpan evaluationTime, int evaluationCount) = LoadProjects(projectCollection, forwardingLogger);

                    if (forwardingLogger.HasLoggedErrors)
                    {
                        return(1);
                    }

                    (string solutionFileFullPath, int customProjectTypeGuidCount, int solutionItemCount) = GenerateSolutionFile(projectCollection.LoadedProjects.Where(i => !i.GlobalProperties.ContainsKey("TargetFramework")), forwardingLogger);

                    if (_arguments.ShouldLaunchVisualStudio())
                    {
                        bool loadProjectsInVisualStudio = _arguments.ShouldLoadProjectsInVisualStudio();
                        bool enableShellExecute         = _arguments.EnableShellExecute();

                        string devEnvFullPath = _arguments.DevEnvFullPath?.LastOrDefault();

                        if (!enableShellExecute || !loadProjectsInVisualStudio || IsCorext)
                        {
                            if (_instance == null)
                            {
                                forwardingLogger.LogError("Cannot launch Visual Studio.");

                                return(1);
                            }

                            if (_instance.IsBuildTools)
                            {
                                forwardingLogger.LogError("Cannot use a BuildTools instance of Visual Studio.");

                                return(1);
                            }

                            devEnvFullPath = Path.Combine(_instance.InstallationPath, "Common7", "IDE", "devenv.exe");
                        }

                        VisualStudioLauncher.Launch(solutionFileFullPath, loadProjectsInVisualStudio, devEnvFullPath, forwardingLogger);
                    }

                    try
                    {
                        LogTelemetry(evaluationTime, evaluationCount, customProjectTypeGuidCount, solutionItemCount);
                    }
                    catch (Exception)
                    {
                    }
                }
                catch (Exception e)
                {
                    forwardingLogger.LogError($"Unhandled exception: {e}");
                    throw;
                }
            }

            return(0);
        }
コード例 #2
0
ファイル: VisualStudioLauncher.cs プロジェクト: jeffkl/SlnGen
        /// <summary>
        /// Launches Visual Studio.
        /// </summary>
        /// <param name="arguments">The current <see cref="ProgramArguments" />.</param>
        /// <param name="visualStudioInstance">A <see cref="VisualStudioInstance" /> object representing which instance of Visual Studio to launch.</param>
        /// <param name="solutionFileFullPath">The full path to the solution file.</param>
        /// <param name="logger">A <see cref="ISlnGenLogger" /> to use for logging.</param>
        /// <returns>true if Visual Studio was launched, otherwise false.</returns>
        public static bool TryLaunch(ProgramArguments arguments, VisualStudioInstance visualStudioInstance, string solutionFileFullPath, ISlnGenLogger logger)
        {
            if (!arguments.ShouldLaunchVisualStudio())
            {
                return(true);
            }

            if (!Utility.RunningOnWindows)
            {
                logger.LogWarning("Launching Visual Studio is not currently supported on your operating system.");

                return(true);
            }

            bool loadProjectsInVisualStudio = arguments.ShouldLoadProjectsInVisualStudio();
            bool enableShellExecute         = arguments.EnableShellExecute();

            string devEnvFullPath = arguments.DevEnvFullPath?.LastOrDefault();

            if (!enableShellExecute || !loadProjectsInVisualStudio || Program.CurrentDevelopmentEnvironment.IsCorext)
            {
                if (devEnvFullPath.IsNullOrWhiteSpace())
                {
                    if (visualStudioInstance == null)
                    {
                        logger.LogError(
                            Program.CurrentDevelopmentEnvironment.IsCorext
                                ? $"Could not find a Visual Studio {Environment.GetEnvironmentVariable("VisualStudioVersion")} installation.  Please do one of the following:\n a) Specify a full path to devenv.exe via the -vs command-line argument\n b) Update your corext.config to specify a version of MSBuild.Corext that matches a Visual Studio version you have installed\n c) Install a version of Visual Studio that matches the version of MSBuild.Corext in your corext.config"
                                : "Could not find a Visual Studio installation.  Please specify the full path to devenv.exe via the -vs command-line argument");

                        return(false);
                    }

                    if (visualStudioInstance.IsBuildTools)
                    {
                        logger.LogError("Cannot use a BuildTools instance of Visual Studio.");

                        return(false);
                    }

                    devEnvFullPath = Path.Combine(visualStudioInstance.InstallationPath, "Common7", "IDE", "devenv.exe");
                }
            }

            if (solutionFileFullPath.IsNullOrWhiteSpace())
            {
                throw new ArgumentNullException(nameof(solutionFileFullPath));
            }

            CommandLineBuilder commandLineBuilder = new CommandLineBuilder();

            ProcessStartInfo processStartInfo;

            if (!devEnvFullPath.IsNullOrWhiteSpace())
            {
                if (!File.Exists(devEnvFullPath))
                {
                    logger.LogError($"The specified path to Visual Studio ({devEnvFullPath}) does not exist or is inaccessible.");

                    return(false);
                }

                processStartInfo = new ProcessStartInfo
                {
                    FileName        = devEnvFullPath !,
                    UseShellExecute = false,
                };

                commandLineBuilder.AppendFileNameIfNotNull(solutionFileFullPath);

                if (!arguments.ShouldLoadProjectsInVisualStudio())
                {
                    commandLineBuilder.AppendSwitch(DoNotLoadProjectsCommandLineArgument);
                }
            }
            else
            {
                processStartInfo = new ProcessStartInfo
                {
                    FileName        = solutionFileFullPath,
                    UseShellExecute = true,
                };
            }

            try
            {
                processStartInfo.Arguments = commandLineBuilder.ToString();

                Process process = new Process
                {
                    StartInfo = processStartInfo,
                };

                logger.LogMessageHigh("Launching Visual Studio...");
                logger.LogMessageLow("  FileName = {0}", processStartInfo.FileName);
                logger.LogMessageLow("  Arguments = {0}", processStartInfo.Arguments);
                logger.LogMessageLow("  UseShellExecute = {0}", processStartInfo.UseShellExecute);
                logger.LogMessageLow("  WindowStyle = {0}", processStartInfo.WindowStyle);

                if (!process.Start())
                {
                    logger.LogError("Failed to launch Visual Studio.");
                }
            }
            catch (Exception e)
            {
                logger.LogError($"Failed to launch Visual Studio. {e.Message}");
            }

            return(true);
        }