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.
How to make Microsoft.Build.Evaluation.Project use same base properties as Visual Studio?
Microsoft.Build.Evaluation.Project
seems to have some rather odd ideas of what values to use when loading projects. In particular, I have a number of projects with the following dependency:
<PackageReference Include="Microsoft.Web.WebJobs.Publish" Version="2.0.0" />
Visual Studio consumes these projects without any problems, but if I try to load one of them with
var proj = new Project(@"path\to\project.csproj");
it throws an InvalidProjectFileException
with error message
The imported project "C:\Program Files\dotnet\sdk\3.1.202\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the expression in the Import declaration "C:\Program Files\dotnet\sdk\3.1.202\Microsoft\VisualStudio\v16.0\WebApplications\Microsoft.WebApplication.targets" is correct, and that the file exists on disk. E:\Users\ptaylor\.nuget\packages\microsoft.web.webjobs.publish\2.0.0\build\webjobs.console.targets
The relevant import (which, note, comes from a Microsoft nuget and is not under my control) is
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
where $(VSToolsPath)
is
$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
The fundamental problem is that Visual Studio uses the sane value for $(MSBuildExtensionsPath32)
of C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild
, whereas Microsoft.Build.Evaluation
is using C:\Program Files\dotnet\sdk\3.1.202
. I note that the project has <TargetFramework>net471</TargetFramework>
, so it's not .Net Core and I can't understand why it would make sense to use a .Net Core SDK.
The idea behind using Microsoft.Build.Evaluation.Project
is to write some tooling to complement Visual Studio, so it defeats the point if the two can't agree on basic things like where Microsoft installs its tools. My question is therefore: is there a clean and robust way to make Microsoft.Build.Evaluation
use the same properties as Visual Studio? I can see hacky solutions involving passing values for MSBuildExtensionsPath32
and similar properties via at least two different mechanisms, but the least hacky value I can think of with the properties available is $(VSAPPIDDIR)\..\..\MSBuild
and that doesn't really pass the sniff test.
1 answer
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 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);
1 comment thread