コード例 #1
0
        /// <summary>
        /// Loads the current development environment.
        /// </summary>
        /// <returns>A <see cref="DevelopmentEnvironment" /> object containing information about the current development environment.</returns>
        public static DevelopmentEnvironment LoadCurrentDevelopmentEnvironment()
        {
            string msbuildToolset = Environment.GetEnvironmentVariable("MSBuildToolset")?.Trim();

            if (!msbuildToolset.IsNullOrWhiteSpace())
            {
                string msbuildToolsPath = Environment.GetEnvironmentVariable($"MSBuildToolsPath_{msbuildToolset}")?.Trim();

                if (!msbuildToolsPath.IsNullOrWhiteSpace())
                {
#if NETFRAMEWORK
                    if (!Version.TryParse(Environment.GetEnvironmentVariable("VisualStudioVersion") ?? string.Empty, out Version visualStudioVersion))
                    {
                        return(new DevelopmentEnvironment("The VisualStudioVersion environment variable must be set in CoreXT"));
                    }

                    if (visualStudioVersion.Major <= 14)
                    {
                        return(new DevelopmentEnvironment("MSBuild.Corext version 15.0 or greater is required"));
                    }

                    return(new DevelopmentEnvironment
                    {
                        MSBuildExe = new FileInfo(Path.Combine(msbuildToolsPath !, "MSBuild.exe")),
                        IsCorext = true,
                        VisualStudio = VisualStudioConfiguration.GetLaunchableInstances()
                                       .Where(i => !i.IsBuildTools && i.HasMSBuild && i.InstallationVersion.Major == visualStudioVersion.Major)
                                       .OrderByDescending(i => i.InstallationVersion)
                                       .FirstOrDefault(),
                    });
コード例 #2
0
        private static bool TryGetVisualStudioFromCorext(out VisualStudioInstance instance)
        {
            instance = null;

            if (!Version.TryParse(Environment.GetEnvironmentVariable("VisualStudioVersion"), out Version visualStudioVersion))
            {
                return(false);
            }

            VisualStudioConfiguration configuration = new VisualStudioConfiguration();

            instance = configuration.GetLaunchableInstances()
                       .Where(i => !i.IsBuildTools && i.HasMSBuild && i.InstallationVersion.Major == visualStudioVersion.Major)
                       .OrderByDescending(i => i.InstallationVersion)
                       .FirstOrDefault();

            return(instance != null);
        }
コード例 #3
0
        private static DevelopmentEnvironment LoadDevelopmentEnvironmentFromCoreXT(string msbuildToolsPath)
        {
            if (!Version.TryParse(Environment.GetEnvironmentVariable("VisualStudioVersion") ?? string.Empty, out Version visualStudioVersion))
            {
                return(new DevelopmentEnvironment("The VisualStudioVersion environment variable must be set in CoreXT"));
            }

            if (visualStudioVersion.Major <= 14)
            {
                return(new DevelopmentEnvironment("MSBuild.Corext version 15.0 or greater is required"));
            }

            return(new DevelopmentEnvironment
            {
                MSBuildExe = new FileInfo(Path.Combine(msbuildToolsPath !, "MSBuild.exe")),
                IsCorext = true,
                VisualStudio = VisualStudioConfiguration.GetLaunchableInstances()
                               .Where(i => !i.IsBuildTools && i.HasMSBuild && i.InstallationVersion.Major == visualStudioVersion.Major)
                               .OrderByDescending(i => i.InstallationVersion)
                               .FirstOrDefault(),
            });
コード例 #4
0
        private static bool TryGetVisualStudioFromDeveloperConsole(out VisualStudioInstance instance)
        {
            instance = null;

            string vsInstallDirEnvVar = Environment.GetEnvironmentVariable("VSINSTALLDIR");

            if (vsInstallDirEnvVar.IsNullOrWhiteSpace())
            {
                return(false);
            }

            if (!Directory.Exists(vsInstallDirEnvVar))
            {
                return(false);
            }

            VisualStudioConfiguration configuration = new VisualStudioConfiguration();

            instance = configuration.GetInstanceForPath(vsInstallDirEnvVar);

            return(instance != null);
        }
コード例 #5
0
        private static DevelopmentEnvironment LoadDevelopmentEnvironmentFromCurrentWindow()
        {
            string basePath = null;

            using (ManualResetEvent processExited = new ManualResetEvent(false))
                using (Process process = new Process
                {
                    EnableRaisingEvents = true,
                    StartInfo = new ProcessStartInfo
                    {
                        Arguments = "--info",
                        CreateNoWindow = true,
                        FileName = "dotnet",
                        UseShellExecute = false,
                        RedirectStandardError = true,
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true,
                        WorkingDirectory = Environment.CurrentDirectory,
                    },
                })
                {
                    process.StartInfo.EnvironmentVariables["DOTNET_CLI_UI_LANGUAGE"]      = "en-US";
                    process.StartInfo.EnvironmentVariables["DOTNET_CLI_TELEMETRY_OPTOUT"] = bool.TrueString;

                    process.ErrorDataReceived += (sender, args) => { };

                    process.OutputDataReceived += (sender, args) =>
                    {
                        if (!String.IsNullOrWhiteSpace(args?.Data))
                        {
                            Match match = DotNetBasePathRegex.Match(args.Data);

                            if (match.Success && match.Groups["Path"].Success)
                            {
                                basePath = match.Groups["Path"].Value.Trim();
                            }
                        }
                    };

                    process.Exited += (sender, args) => { processExited.Set(); };

                    try
                    {
                        if (!process.Start())
                        {
                            return(new DevelopmentEnvironment("Failed to find .NET Core SDK, could not start dotnet"));
                        }
                    }
                    catch (Exception e)
                    {
                        return(new DevelopmentEnvironment("Failed to find .NET Core SDK, failed launching dotnet", e.ToString()));
                    }

                    process.StandardInput.Close();

                    process.BeginErrorReadLine();
                    process.BeginOutputReadLine();

                    switch (WaitHandle.WaitAny(new WaitHandle[] { processExited }, TimeSpan.FromSeconds(5)))
                    {
                    case WaitHandle.WaitTimeout:
                        break;

                    case 0:
                        break;
                    }

                    if (!process.HasExited)
                    {
                        try
                        {
                            process.Kill();
                        }
                        catch
                        {
                        }
                    }

                    if (!basePath.IsNullOrWhiteSpace())
                    {
                        DevelopmentEnvironment developmentEnvironment = new DevelopmentEnvironment
                        {
                            MSBuildDll = new FileInfo(Path.Combine(basePath, "MSBuild.dll")),
                        };

                        RegisterMSBuildAssemblyResolver(developmentEnvironment);

                        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && TryFindMSBuildOnPath(out string msbuildExePath))
                        {
                            developmentEnvironment.MSBuildExe   = new FileInfo(msbuildExePath);
                            developmentEnvironment.VisualStudio = VisualStudioConfiguration.GetInstanceForPath(msbuildExePath);
                        }

                        return(developmentEnvironment);
                    }

                    return(new DevelopmentEnvironment("Failed to find .NET Core SDK, ensure you have .NET Core SDK installed and if you have a global.json that it specifies a version you have installed."));
                }
        }
コード例 #6
0
        public static bool TryLocate(Action <string> error, out VisualStudioInstance instance, out string msbuildBinPath)
        {
            instance       = null;
            msbuildBinPath = null;

            string msbuildToolset = Environment.GetEnvironmentVariable("MSBuildToolset")?.Trim();

            if (!msbuildToolset.IsNullOrWhiteSpace())
            {
                string msbuildToolsPath = Environment.GetEnvironmentVariable($"MSBuildToolsPath_{msbuildToolset}")?.Trim();

                if (!msbuildToolsPath.IsNullOrWhiteSpace())
                {
                    if (Program.IsNetCore)
                    {
                        error("The .NET Core version of SlnGen is not supported in CoreXT.  You must use the .NET Framework version via the SlnGen.Corext package");

                        return(false);
                    }

                    msbuildBinPath = msbuildToolsPath;

                    if (Version.TryParse(Environment.GetEnvironmentVariable("VisualStudioVersion") ?? string.Empty, out Version visualStudioVersion))
                    {
                        if (visualStudioVersion.Major <= 14)
                        {
                            error("MSBuild.Corext version 15.0 or greater is required");

                            return(false);
                        }

                        VisualStudioConfiguration configuration = new VisualStudioConfiguration();

                        instance = configuration.GetLaunchableInstances()
                                   .Where(i => !i.IsBuildTools && i.HasMSBuild && i.InstallationVersion.Major == visualStudioVersion.Major)
                                   .OrderByDescending(i => i.InstallationVersion)
                                   .FirstOrDefault();
                    }
                    else
                    {
                        error("The VisualStudioVersion environment variable must be set in CoreXT");

                        return(false);
                    }

                    Program.IsCorext = true;

                    return(true);
                }
            }

            TryGetVisualStudioFromDeveloperConsole(out instance);

            if (Program.IsNetCore)
            {
                if (!TryGetMSBuildInNetCore(out msbuildBinPath, out string errorMessage))
                {
                    if (!string.IsNullOrWhiteSpace(errorMessage))
                    {
                        error($"Failed to find .NET Core: {errorMessage}");
                    }
                    else
                    {
                        error("Failed to find .NET Core.  Run dotnet --info for more information.");
                    }

                    return(false);
                }

                return(true);
            }

            if (instance == null)
            {
                error("You must run SlnGen in a Visual Studio Developer Command Prompt");

                return(false);
            }

            msbuildBinPath = Path.Combine(
                instance.InstallationPath,
                "MSBuild",
                instance.InstallationVersion.Major >= 16 ? "Current" : "15.0",
                "Bin");

            return(true);
        }
コード例 #7
0
        /// <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);
            }

            string devEnvFullPath = arguments.GetDevEnvFullPath(visualStudioInstance);

            if (!devEnvFullPath.IsNullOrWhiteSpace())
            {
                visualStudioInstance = VisualStudioConfiguration.GetInstanceForPath(devEnvFullPath);
            }

            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 run from a command window that has MSBuild.exe on the PATH or 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);
            }

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

                return(false);
            }

            CommandLineBuilder commandLineBuilder = new CommandLineBuilder();

            commandLineBuilder.AppendFileNameIfNotNull(solutionFileFullPath);

            if (!arguments.ShouldLoadProjectsInVisualStudio())
            {
                commandLineBuilder.AppendSwitch(DoNotLoadProjectsCommandLineArgument);
            }

            try
            {
                Process process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName        = devEnvFullPath,
                        Arguments       = commandLineBuilder.ToString(),
                        UseShellExecute = false,
                    },
                };

                logger.LogMessageHigh("Launching Visual Studio...");
                logger.LogMessageLow("  FileName = {0}", process.StartInfo.FileName);
                logger.LogMessageLow("  Arguments = {0}", process.StartInfo.Arguments);

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

            return(true);
        }