Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

66%
+2 −0
Q&A How to make Microsoft.Build.Evaluation.Project use same base properties as Visual Studio?

By forking MSBuildLocator and basically just removing the #ifdef it's straightforward to list the available VS instances. It even works to register one, although if you want the same application to...

posted 3y ago by Peter Taylor‭

Answer
#1: Initial revision by user avatar Peter Taylor‭ · 2020-11-13T11:30:39Z (over 3 years ago)
By forking [MSBuildLocator](https://github.com/microsoft/MSBuildLocator/blob/master/src/MSBuildLocator/MSBuildLocator.cs) and basically just removing the `#ifdef` it's straightforward to list the available VS instances. It even works to register one, although if you want the same application to properly support both .Net Core and .Net Framework projects then you have to process them in different AppDomains and communicate via interops.

If you just want to process the project files, though, the following is only minimally hacky.

    using Microsoft.VisualStudio.Setup.Configuration;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.InteropServices;

    namespace VisualSolutionGenerator
    {
        /// <summary>
        /// MSBuildLocator in a .Net Core application believes that the only MSBuild is the .Net Core SDK.
        /// This class allows you to locate the Visual Studio instances that MSBuildLocator would find if compiled for .Net Framework.
        /// </summary>
        static class VisualStudioLocator
        {
            /// <summary>Query for all installed Visual Studio instances.</summary>
            public static IEnumerable<VisualStudioInstallation> QueryVisualStudioInstances()
            {
                const string MSBuild = "Microsoft.Component.MSBuild";

                var validInstances = new List<VisualStudioInstallation>();
                try
                {
                    var iterator = (GetQuery() as ISetupConfiguration2).EnumAllInstances();
                    while (true)
                    {
                        var instances = new ISetupInstance[1];
                        // Call e.Next to query for the next instance (single item or nothing returned).
                        iterator.Next(1, instances, out int fetched);
                        if (fetched <= 0) break;

                        var instance = (ISetupInstance2)instances[0];
                        if (!Version.TryParse(instance.GetInstallationVersion(), out Version version))
                            continue;

                        // If the install was complete and a valid version, consider it.
                        InstanceState state = instance.GetState();
                        if (state == InstanceState.Complete || (state.HasFlag(InstanceState.Registered) && state.HasFlag(InstanceState.NoRebootRequired)))
                        {
                            if (instance.GetPackages().Any(pkg => string.Equals(pkg.GetId(), MSBuild, StringComparison.OrdinalIgnoreCase)))
                            {
                                validInstances.Add(new VisualStudioInstallation(instance.GetDisplayName(), instance.GetInstallationPath(), version));
                            }
                        }
                    }
                }
                catch (COMException) { }
                catch (DllNotFoundException) { }

                return validInstances;
            }

            private static ISetupConfiguration GetQuery()
            {
                const int REGDB_E_CLASSNOTREG = unchecked((int)0x80040154);

                try { return new SetupConfiguration(); }
                catch (COMException ex) when (ex.ErrorCode == REGDB_E_CLASSNOTREG)
                {
                    // Try to get the class object using app-local call.
                    var result = GetSetupConfiguration(out ISetupConfiguration query, IntPtr.Zero);
                    if (result < 0) throw new COMException($"Failed to get setup configuration", result);
                    return query;
                }
            }

            [DllImport("Microsoft.VisualStudio.Setup.Configuration.Native.dll")]
            private static extern int GetSetupConfiguration([Out, MarshalAs(UnmanagedType.Interface)] out ISetupConfiguration configuration, IntPtr reserved);
        }

        public class VisualStudioInstallation
        {
            internal VisualStudioInstallation(string name, string path, Version version)
            {
                Name = name;
                Version = version;
                VisualStudioRootPath = path;
            }

            public string Name { get; }
            public Version Version { get; }
            public string VisualStudioRootPath { get; }
        }
    }

with helper functions

    private static readonly Lazy<IDictionary<string, string>> NetFrameworkProperties = new Lazy<IDictionary<string, string>>(() =>
    {
        var vsInstance = VisualStudioLocator.QueryVisualStudioInstances().OrderBy(vs => vs.Version).LastOrDefault();
        return vsInstance == null ? null :
            new Dictionary<string, string>
            {
                ["MSBuildExtensionsPath"] = Path.Combine(vsInstance.VisualStudioRootPath, "MSBuild"),
                ["MSBuildExtensionsPath32"] = Path.Combine(vsInstance.VisualStudioRootPath, "MSBuild"),
                ["MSBuildExtensionsPath64"] = @"C:\Program Files\MSBuild"
            };
    });

    private static bool IsNetCoreProject(FileInfo projectPath)
    {
        // I would have expected ProjectRootElement to handle this, but in testing it doesn't extract a single property.
        var projXml = XDocument.Load(projectPath.FullName);
        var targetFramework =
            projXml.Descendants("TargetFramework").FirstOrDefault() ??
            projXml.Descendants("TargetFrameworks").FirstOrDefault() ??
            projXml.Descendants("TargetFrameworkVersion").FirstOrDefault();
        return (targetFramework?.Value?.Contains("core")).GetValueOrDefault();
    }


and project loading

    var props = IsNetCoreProject(filePath) ? null : NetFrameworkProperties.Value;
    var project = new MSPROJECT(filePath.FullName, props, null);