vs-setup-samples icon indicating copy to clipboard operation
vs-setup-samples copied to clipboard

How to get a specific tool absolute path?

Open FrenchMigVaz opened this issue 9 years ago • 9 comments

Our software infrastructure has a custom-made build system written in C# that wraps project builds using msbuild.exe. With the Microsoft.VisualStudio.Setup.Configuration namespace, I understand how to check if the MsBuild component is correctly installed:

ISetupPackageReference msbuildPackage = packages.FirstOrDefault(p => p.GetId().Equals("Microsoft.Component.MSBuild", StringComparison.InvariantCultureIgnoreCase));

But then, the ISetupPackageReference does not contain a list of available tools.

How do I determine the full path to MsBuild.exe from there, without hard-coding its relative path "MSBuild\15.0\Bin\MSBuild.exe"?

FrenchMigVaz avatar Mar 14 '17 12:03 FrenchMigVaz

As required with previous scripts, hardcoding the relative path is required. With the exception of MSBuild, the relative paths really haven't changed since Visual Studio 7.0 (hence "Common7\IDE" being the parent directory of many of them).

heaths avatar Mar 14 '17 16:03 heaths

after you get InstallationPath = instance2.GetInstallationPath() in the environment you can do

FOR /F %F IN ('dir /b %InstallationPath%\msbuild.exe /s') DO ECHO %F

But INHO it's over kill if @heaths promises it will be in {InstallationPath}\MSBuild\15.0\Bin\MSBuild.exe

refack avatar Mar 14 '17 20:03 refack

There's no promise (I don't make those decisions), but that is the directory pattern we've had for many releases (just a new root for VS2017). You might make it future proof, however, by getting the Version.Major field and using that in place of "15".

heaths avatar Mar 14 '17 20:03 heaths

Version proof? i.e. will it stay in {InstallationPath}\MSBuild\15.0\Bin\MSBuild.exe for the life of ver 15? (I'm asking since cl.exe moves with even semver "patch" versions)

refack avatar Mar 14 '17 20:03 refack

15.0, yes. But the example didn't cap the max version so if there is a 16.0 or newer, hardcoding "15.0" may not be the best idea.

heaths avatar Mar 14 '17 21:03 heaths

Thanks @heaths and @refack for your inputs. I am fine with hard-coded relative paths, I just wanted to make sure I did not miss something in the new VS Setup API.

We do not hard-code the MsBuild version in the path, it is given by our MsBuild wrapper algorithm and determined according to the desired Visual Studio version in the codebase. It means that if the codebase defined its Visual Studio Version to 2017/v15, the wrapper will look for MsBuild version 15.0. The algorithm is also specifying a ToolsVersion equal to the MsBuild version in the auto-generated Project file it executes.

With the new Setup API, we could look for the specific Visual Studio version installed, get the version of the MsBuild component and use the latest available within this Visual Studio install. Then, if MsBuild v16.0 is released within VS 2017, our algorithm will use it automatically.

FrenchMigVaz avatar Mar 15 '17 09:03 FrenchMigVaz

@heaths here's the code I rolled for this, based on your example in this repo (C#):

public class MsBuildLocator
    {
        private const int REGDB_E_CLASSNOTREG = unchecked((int)0x80040154);

        private static string[] _msbuildPaths = new string[2];

        public static (GetMsbuildResult result, string path) GetMsbuildPath(bool useLatest)
        {
            if (CanServeResultFromCache(useLatest, out var cacheResult))
            {
                return cacheResult;
            }

            try
            {
                var query = new SetupConfiguration();
                var query2 = (ISetupConfiguration2)query;
                var e = query2.EnumAllInstances();

                var helper = (ISetupHelper)query;

                int fetched;
                var instances = new ISetupInstance[1];
                
                string lastFoundMsbuildPath = null;
                do
                {
                    e.Next(1, instances, out fetched);
                    if (fetched > 0)
                    {
                        var msBuildPath = FindMsbuildFromInstance(instances[0]);
                        if (!string.IsNullOrEmpty(msBuildPath))
                        {
                            if (!useLatest)
                            {
                                _msbuildPaths[0] = msBuildPath;
                                return (GetMsbuildResult.Success, msBuildPath);
                            }
                            lastFoundMsbuildPath = msBuildPath;
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(lastFoundMsbuildPath))
                        {
                            _msbuildPaths[1] = lastFoundMsbuildPath;
                            return (GetMsbuildResult.Success, lastFoundMsbuildPath);
                        }
                        else
                        {
                            return (
                                GetMsbuildResult.QueryApiNotInstalledOrNoVsInstance,
                                PowerExtensionsResources.QueryApiNotInstalledOrNoVsInstance);
                        }
                    }
                }
                while (fetched > 0);

                return (GetMsbuildResult.QueryApiNotInstalledOrNoVsInstance, "No VS Instance found.");
            }
            catch (COMException ex) when (ex.HResult == REGDB_E_CLASSNOTREG)
            {
                return (GetMsbuildResult.QueryApiNotInstalledOrNoVsInstance, PowerExtensionsResources.QueryApiNotInstalledOrNoVsInstance);
            }
            catch (Exception ex)
            {
                return (GetMsbuildResult.UnknownError, $"Error 0x{ex.HResult:x8}: {ex.Message}");
            }
        }

        private static bool CanServeResultFromCache(bool useLatest, out (GetMsbuildResult, string) cacheResult)
        {
            int cachePosition = useLatest ? 1 : 0;
            string findResult = _msbuildPaths[cachePosition];
            if (string.IsNullOrEmpty(findResult))
            {
                cacheResult = (GetMsbuildResult.Success, findResult);
                return true;
            }
            else
            {
                cacheResult = (GetMsbuildResult.UnknownError, "MSBuild queries have not been executed for this location.");
                return false;
            }
        }

        private static string FindMsbuildFromInstance(ISetupInstance instance)
        {
            var vsRoot = instance.ResolvePath();
            var filePath = Directory.EnumerateFiles(vsRoot, "msbuild.exe", SearchOption.AllDirectories).LastOrDefault();
            return filePath;
        }
    }

public enum GetMsbuildResult
    {
        Success = 0,
        QueryApiNotInstalledOrNoVsInstance,
        UnknownError
    }

In your opinion, based on current understanding, is this a reliable implementation for the community? I'm happy to publish a P/R for the community that demonstrates finding MSBuild specifically if so. If not, I'd personally appreciate an example, and I'm sure others would as well.

Context: my current org has a custom VS extension for legacy reasons that depends on MSBuild. I'm trying to patch it to support VS2019, without any particular dependency on things like VS Editions (Pro versus Enterprise with current product offerings) and versions (2017, 2019). It's written in C#.

Thank you for putting this repo up!

briandrennan avatar Apr 30 '19 00:04 briandrennan

This repo is really about providing generic samples of using the query API, which is used to find more than just MSBuild. However, have you looked at https://github.com/Microsoft/vswhere? I recently added support to find msbuild.exe using the new -find parameter. The example in the current README even shows you how, and it's easy to get a single value. In fact, this is what many Azure Pipelines tasks use, as well as other tools like cmake, boost, et. al.

heaths avatar Apr 30 '19 03:04 heaths

I actually use vswhere in my PowerShell profile. I just wanted to use the query API interop for my org's VS extension. The example I posted succeeds at that.

Thanks!

briandrennan avatar Apr 30 '19 23:04 briandrennan