Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Project object can no longer be created if the change wave 17.10 is in use. #9869

Closed
MarkKharitonov opened this issue Mar 14, 2024 · 21 comments
Assignees
Labels

Comments

@MarkKharitonov
Copy link

Issue Description

Consider the following code:

using Microsoft.Build.Evaluation;
using Microsoft.Build.Locator;

internal class Program
{
    private static void Main(string[] args)
    {
        Environment.SetEnvironmentVariable("MSBUILDDISABLEFEATURESFROMVERSION", new Version(17, 10).ToString());
        var msbuildDir = GetMSBuildDir();

        if (string.IsNullOrEmpty(msbuildDir))
        {
            MSBuildLocator.RegisterDefaults();
        }
        else
        {
            MSBuildLocator.RegisterMSBuildPath(msbuildDir);
        }
        Run(SLN_DIR_PATH, SLN_DIR_PATH + CSPROJ_REL_PATH);
    }

    private static void Run(string slnDirPath, string csprojPath)
    {
        new Project(csprojPath, new Dictionary<string, string>
        {
            ["SolutionDir"] = Path.GetDirectoryName(slnDirPath) + "\\"
        }, null);
    }

    private static string? GetMSBuildDir()
    {
        var vsInstallDir = Environment.GetEnvironmentVariable("VSINSTALLDIR");
        if (vsInstallDir == null)
        {
            vsInstallDir = Environment.GetEnvironmentVariable("VSAPPIDDIR");
            if (!string.IsNullOrEmpty(vsInstallDir))
            {
                vsInstallDir = Path.GetFullPath(vsInstallDir + "\\..\\..\\");
            }
        }
        if (!string.IsNullOrEmpty(vsInstallDir))
        {
            vsInstallDir += "MSBuild\\Current\\Bin\\";
        }

        return vsInstallDir;
    }
}

And assume SLN_DIR_PATH + CSPROJ_REL_PATH point at an existing csproj file with a solution file inside SLN_DIR_PATH.

When I run this code - it succeeds. However, if I comment the MSBUILDDISABLEFEATURESFROMVERSION line, then it fails with the following exception:

Microsoft.Build.Exceptions.InvalidProjectFileException
  HResult=0x80131500
  Message=The SDK resolver assembly "C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Current\Bin\SdkResolvers\Microsoft.DotNet.MSBuildSdkResolver\Microsoft.DotNet.MSBuildSdkResolver.dll" could not be loaded. Could not load file or assembly 'Microsoft.DotNet.MSBuildSdkResolver, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.  C:\dayforce\CSTool\scratch\scratch.csproj
  Source=Microsoft.Build
  StackTrace:
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, String errorSubCategoryResourceName, BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.ThrowInvalidProjectFile(BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.LoadResolvers(String resolverPath, ElementLocation location, List`1 resolvers)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.LoadResolversFromManifest(SdkResolverManifest manifest, ElementLocation location)
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverLoader.<>n__0(SdkResolverManifest manifest, ElementLocation location)
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverLoader.<>c__DisplayClass10_0.<LoadResolversFromManifest>b__0(SdkResolverManifest manifest)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverLoader.LoadResolversFromManifest(SdkResolverManifest manifest, ElementLocation location)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.GetResolvers(IList`1 resolversManifests, LoggingContext loggingContext, ElementLocation sdkReferenceLocation)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.ResolveSdkUsingResolversWithPatternsFirst(Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, Boolean failOnUnresolvedSdk)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.ResolveSdk(Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, Boolean failOnUnresolvedSdk)
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverService.<>n__0(Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, Boolean failOnUnresolvedSdk)
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverService.<>c__DisplayClass3_0.<ResolveSdk>b__2()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverService.ResolveSdk(Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, Boolean failOnUnresolvedSdk)
   at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(String directoryOfImportingFile, ProjectImportElement importElement, List`1& projects, SdkResult& sdkResult)
   at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImports(String directoryOfImportingFile, ProjectImportElement importElement, SdkResult& sdkResult)
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement)
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport)
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate()
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate(IEvaluatorData`4 data, Project project, ProjectRootElement root, ProjectLoadSettings loadSettings, Int32 maxNodeCount, PropertyDictionary`1 environmentProperties, ILoggingService loggingService, IItemFactory`2 itemFactory, IToolsetProvider toolsetProvider, IDirectoryCacheFactory directoryCacheFactory, ProjectRootElementCacheBase projectRootElementCache, BuildEventContext buildEventContext, ISdkResolverService sdkResolverService, Int32 submissionId, EvaluationContext evaluationContext, Boolean interactive)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Reevaluate(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Initialize(IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, Boolean interactive)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, IDirectoryCacheFactory directoryCacheFactory, Boolean interactive)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, ProjectCollection projectCollection)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion)
   at Program.Run(String slnDirPath, String csprojPath) in C:\dayforce\CSTool\scratch\Program.cs:line 24
   at Program.Main(String[] args) in C:\dayforce\CSTool\scratch\Program.cs:line 19

  This exception was originally thrown at this call stack:
    System.Reflection.RuntimeAssembly.InternalLoad(System.Reflection.AssemblyName, ref System.Threading.StackCrawlMark, System.Runtime.Loader.AssemblyLoadContext, System.Reflection.RuntimeAssembly, bool)
    System.Reflection.Assembly.Load(System.Reflection.AssemblyName)
    Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.LoadResolverAssembly(string)
    Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.LoadResolvers(string, Microsoft.Build.Construction.ElementLocation, System.Collections.Generic.List<Microsoft.Build.Framework.SdkResolver>)

Inner Exception 1:
FileNotFoundException: Could not load file or assembly 'Microsoft.DotNet.MSBuildSdkResolver, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

Steps to Reproduce

scratch.zip
msbuild.zip

Since the binary log is small and without any secrets, I just renamed msbuild.binlog to msbuild.,zip and uploaded here.

To show the issue pass the 3rd parameter exp.

Good run

C:\scratch> .\bin\Debug\net8.0\scratch.exe . .\scratch.csproj
C:\scratch>

Bad run

C:\scratch> .\bin\Debug\net8.0\scratch.exe . .\scratch.csproj exp
Unhandled exception. Microsoft.Build.Exceptions.InvalidProjectFileException: The SDK resolver assembly "C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Current\Bin\SdkResolvers\Microsoft.DotNet.MSBuildSdkResolver\Microsoft.DotNet.MSBuildSdkResolver.dll" could not be loaded. Could not load file or assembly 'Microsoft.DotNet.MSBuildSdkResolver, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.  C:\dayforce\CSTool\scratch\scratch.csproj
 ---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.DotNet.MSBuildSdkResolver, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
File name: 'Microsoft.DotNet.MSBuildSdkResolver, Culture=neutral, PublicKeyToken=null'
   at System.Reflection.RuntimeAssembly.InternalLoad(AssemblyName assemblyName, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext, RuntimeAssembly requestingAssembly, Boolean throwOnFileNotFound)
   at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.LoadResolverAssembly(String resolverPath)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.LoadResolvers(String resolverPath, ElementLocation location, List`1 resolvers)
   --- End of inner exception stack trace ---
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, String errorSubCategoryResourceName, BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.ThrowInvalidProjectFile(BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.LoadResolvers(String resolverPath, ElementLocation location, List`1 resolvers)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverLoader.LoadResolversFromManifest(SdkResolverManifest manifest, ElementLocation location)
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverLoader.<>n__0(SdkResolverManifest manifest, ElementLocation location)
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverLoader.<>c__DisplayClass10_0.<LoadResolversFromManifest>b__0(SdkResolverManifest manifest)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverLoader.LoadResolversFromManifest(SdkResolverManifest manifest, ElementLocation location)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.GetResolvers(IList`1 resolversManifests, LoggingContext loggingContext, ElementLocation sdkReferenceLocation)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.ResolveSdkUsingResolversWithPatternsFirst(Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, Boolean failOnUnresolvedSdk)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.ResolveSdk(Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, Boolean failOnUnresolvedSdk)
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverService.<>n__0(Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, Boolean failOnUnresolvedSdk)
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverService.<>c__DisplayClass3_0.<ResolveSdk>b__2()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Microsoft.Build.BackEnd.SdkResolution.CachingSdkResolverService.ResolveSdk(Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, Boolean failOnUnresolvedSdk)
   at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(String directoryOfImportingFile, ProjectImportElement importElement, List`1& projects, SdkResult& sdkResult)
   at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImports(String directoryOfImportingFile, ProjectImportElement importElement, SdkResult& sdkResult)
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement)
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport)
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate()
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate(IEvaluatorData`4 data, Project project, ProjectRootElement root, ProjectLoadSettings loadSettings, Int32 maxNodeCount, PropertyDictionary`1 environmentProperties, ILoggingService loggingService, IItemFactory`2 itemFactory, IToolsetProvider toolsetProvider, IDirectoryCacheFactory directoryCacheFactory, ProjectRootElementCacheBase projectRootElementCache, BuildEventContext buildEventContext, ISdkResolverService sdkResolverService, Int32 submissionId, EvaluationContext evaluationContext, Boolean interactive)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Reevaluate(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Initialize(IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, Boolean interactive)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, IDirectoryCacheFactory directoryCacheFactory, Boolean interactive)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, ProjectCollection projectCollection)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion)
   at Program.Run(String slnDirPath, String csprojPath) in C:\dayforce\CSTool\scratch\Program.cs:line 54
   at Program.Main(String[] args) in C:\dayforce\CSTool\scratch\Program.cs:line 48
C:\scratch>

Expected Behavior

The code succeeds without disabling the latest change wave.

Actual Behavior

The code fails.

Analysis

No response

Versions & Configurations

See the attached msbuild binary log, but here it is:

C:\scratch> msbuild --version
MSBuild version 17.9.5+33de0b227 for .NET Framework
17.9.5.7608
C:\scratch>
@ladipro
Copy link
Member

ladipro commented Mar 19, 2024

@MarkKharitonov you are loading MSBuild from VS, which is built to target .NET Framework - into a .NET 8 app. I'm afraid this is unsupported and the fact that it worked before 17.9 would be considered a lucky accident.

@rainersigwald have we ever made such guarantees before? Do you think it's generally a reasonable expectation for the NetFx MSBuild to be usable in a .NET process, at least to the point that it can evaluate a project?

(Incidentally, the change that broke this is being reverted for other reasons and the next servicing release of 17.9 should work for you again. We have another change lined up for 17.10, though, which will have a similar effect.)

@MarkKharitonov
Copy link
Author

@ladipro - would you be able to recommend the proper way to do it?

My goal is to have a tool written in the modern .NET stack (like .NET 8) that analyzes projects targeting .NET 4. Some of these projects are not even SDK style projects.

The code I have attached is what I have used so far with success. But if it is wrong, I will gladly change it with your help (hopefully).
Thank you very much.

@rainersigwald
Copy link
Member

@rainersigwald have we ever made such guarantees before? Do you think it's generally a reasonable expectation for the NetFx MSBuild to be usable in a .NET process, at least to the point that it can evaluate a project?

No, and actually we should probably put an explicit break in MSBuildLocator for this (cc @YuliiaKovalova).

@MarkKharitonov Unfortunately if you want to analyze non-SDK projects targeting .NET 4 (or 3.5 or whatever) your tool must run on .NET Framework today.

@MarkKharitonov
Copy link
Author

That is indeed very unfortunate, since there is a ton of legacy code out there to be analyzed.

This requirement for a tool to be written in .NET Framework in order to analyze code written in .NET Framework (using msbuild API) - was it documented anywhere? Maybe I have missed that part. For me (granted, not the mainstream case) this is a breaking change.

@rainersigwald
Copy link
Member

That's how it's been since the first port of MSBuild in .NET Core 1.0; MSBuild on .NET Framework is the compatible can-load-anything solution. I'm genuinely surprised you ever got it to work even partially.

@rainersigwald
Copy link
Member

Some analysis tools will use a modern .NET process that will spawn a child process to use MSBuild to extract information about non-SDK projects and pass it back via IPC.

@MarkKharitonov
Copy link
Author

MarkKharitonov commented Mar 19, 2024

I cannot explain it, of course, since I do not understand the root of the problem. But it did work and still does if I disable the new feature through that environment variable.

It is very problematic to target .NET 4, because it prevents me from using the latest versions of all kinds of packages I depend on. And to implement IPC and spawn child processes is, of course, possible, but it makes the tool so much more complicated...

@ladipro
Copy link
Member

ladipro commented Mar 19, 2024

I cannot explain it, of course, since I do not understand the root of the problem.

I think the best way to describe the problem is that .NET (Core) API is not a superset of .NET Framework API and it is certainly not bug-for-bug compatible. So while the VS MSBuild and the .NET SDK MSBuild share most of the code, there are places where the code is platform-specific, such as to take advantage of a feature present in one but not the other. I believe in this case we're looking at differences in assembly binding behavior.

It probably would be technically possible to keep the scenario of cross-loading working, but it would mean additional code complexity and a larger test matrix, so more dev burden for something that's not architecturally sound to begin with.

@ladipro
Copy link
Member

ladipro commented Mar 20, 2024

Closing as won't fix. @MarkKharitonov you should be good with MSBUILDDISABLEFEATURESFROMVERSION=17.10 for now but unfortunately we can't officially support this scenario.

@ladipro ladipro closed this as not planned Won't fix, can't repro, duplicate, stale Mar 20, 2024
@MarkKharitonov
Copy link
Author

@ladipro - may I get a moment of your time once more?

I changed the csproj file by replacing

<TargetFramework>net8.0</TargetFramework>

With

 <TargetFramework>net472</TargetFramework>
 <LangVersion>12.0</LangVersion>

But it still does not work. This time the error is different and it is the same whether the environment variable is set or unset:

C:\scratch> .\bin\Debug\net472\scratch.exe . .\scratch.csproj

Unhandled Exception: Microsoft.Build.Exceptions.InvalidProjectFileException: SDK Resolver Failure: "The SDK resolver "Microsoft.DotNet.MSBuildSdkResolver" failed while attempting to resolve the SDK "Microsoft.NET.Sdk". Exception: "System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.CachingWorkloadResolver.Resolve(String sdkReferenceName, String dotnetRootPath, String sdkVersion, String userProfileDir, String globalJsonPath)
   at Microsoft.DotNet.MSBuildSdkResolver.DotNetMSBuildSdkResolver.Resolve(SdkReference sdkReference, SdkResolverContext context, SdkResultFactory factory)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.TryResolveSdkUsingSpecifiedResolvers(IReadOnlyList`1 resolvers, Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, SdkResult& sdkResult, IEnumerable`1& errors, IEnumerable`1& warnings)

=== Pre-bind state information ===
LOG: DisplayName = System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)
LOG: Appbase = file:///C:/scratch/bin/Debug/net472/
LOG: Initial PrivatePath = NULL
Calling assembly : System.Collections.Immutable, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.
===
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: C:\dayforce\CSTool\scratch\bin\Debug\net472\scratch.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Post-policy reference: System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
LOG: Attempting download of new URL file:///C:/scratch/bin/Debug/net472/System.Runtime.DLL.
LOG: Attempting download of new URL file:///C:/scratch/bin/Debug/net472/System.Runtime/System.Runtime.DLL.
LOG: Attempting download of new URL file:///C:/scratch/bin/Debug/net472/System.Runtime.EXE.
LOG: Attempting download of new URL file:///C:/scratch/bin/Debug/net472/System.Runtime/System.Runtime.EXE.
LOG: Attempting download of new URL file:///C:/Program Files/Microsoft Visual Studio/2022/Professional/MSBuild/Current/Bin/SdkResolvers/Microsoft.DotNet.MSBuildSdkResolver/System.Runtime.DLL.
LOG: Attempting download of new URL file:///C:/Program Files/Microsoft Visual Studio/2022/Professional/MSBuild/Current/Bin/SdkResolvers/Microsoft.DotNet.MSBuildSdkResolver/System.Runtime/System.Runtime.DLL.
LOG: Attempting download of new URL file:///C:/Program Files/Microsoft Visual Studio/2022/Professional/MSBuild/Current/Bin/SdkResolvers/Microsoft.DotNet.MSBuildSdkResolver/System.Runtime.EXE.
LOG: Attempting download of new URL file:///C:/Program Files/Microsoft Visual Studio/2022/Professional/MSBuild/Current/Bin/SdkResolvers/Microsoft.DotNet.MSBuildSdkResolver/System.Runtime/System.Runtime.EXE.
""  C:\dayforce\CSTool\scratch\scratch.csproj
   at Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(String errorSubCategoryResourceName, IElementLocation elementLocation, String resourceName, Object[] args)
   at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(String directoryOfImportingFile, ProjectImportElement importElement, List`1& projects, SdkResult& sdkResult)
   at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImports(String directoryOfImportingFile, ProjectImportElement importElement, SdkResult& sdkResult)
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement)
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport)
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate()
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate(IEvaluatorData`4 data, Project project, ProjectRootElement root, ProjectLoadSettings loadSettings, Int32 maxNodeCount, PropertyDictionary`1 environmentProperties, ILoggingService loggingService, IItemFactory`2 itemFactory, IToolsetProvider toolsetProvider, IDirectoryCacheFactory directoryCacheFactory, ProjectRootElementCacheBase projectRootElementCache, BuildEventContext buildEventContext, ISdkResolverService sdkResolverService, Int32 submissionId, EvaluationContext evaluationContext, Boolean interactive)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Reevaluate(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Initialize(IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, Boolean interactive)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, IDirectoryCacheFactory directoryCacheFactory, Boolean interactive)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion)
   at Program.Run(String slnDirPath, String csprojPath) in C:\dayforce\CSTool\scratch\Program.cs:line 54
   at Program.Main(String[] args) in C:\dayforce\CSTool\scratch\Program.cs:line 48
C:\scratch>

Would you be able to indicate what I am doing wrong?

Thank you so much.

@MarkKharitonov
Copy link
Author

@rainersigwald
Copy link
Member

@MarkKharitonov I don't reproduce your failure--your code works fine for me. What versions of EVERYTHING are set up in the repro environment?

@MarkKharitonov
Copy link
Author

@rainersigwald - I have pushed a small test code to GitHub - https://github.com/MarkKharitonov/test_load_msbuild_project.

I will copy here the Introduction and the final Summary from the README:


Introduction

This README shows the result of running the tool in 3 different environments x 2 different target frameworks x 3 kinds of projects to be parsed:

3 different run environments:

  1. From within VS IDE
  2. On a shell with VS Dev environment loaded
  3. On a bare shell without any VS Dev environment

2 different target frameworks (for which the tool is compiled):

  1. .NET 8
  2. .NET Framework 4.7.2

3 kinds of projects to be parsed:

  1. Legacy style project targeting .NET Framework 4.7.2 - sample_net472_legacy.proj
  2. SDK style project targeting .NET Framework 4.7.2 - sample_net472_sdk.proj
  3. A project targeting .NET 8 (SDK style, of course) - sample_net8.proj

By default sample_net472_legacy.proj is parsed. To parse another project pass its path on the command line.

The runs where done with Visual Studio 2022 version 17.9.5 and .NET 8 CLI:

Microsoft Visual Studio Professional 2022
Version 17.9.5
VisualStudio.17.Release/17.9.5+34723.18
Microsoft .NET Framework
Version 4.8.04161
C:\work\test_load_msbuild_project> dotnet --version
8.0.202
C:\work\test_load_msbuild_project> msbuild --version
MSBuild version 17.9.8+b34f75857 for .NET Framework
17.9.8.16306
C:\work\test_load_msbuild_project [master +10 ~0 -0 ~]>

...

Summary

The code must target .NET 8 in order to be able to parse both SDK and non SDK style projects targeting .NET or .NET Framework.
When targeting .NET Framework 4.7.2 only legacy style projects can be parsed.

Target Framework Project Environment Result
.NET 8 All All OK
.NET Framework 4.7.2 legacy All OK
.NET Framework 4.7.2 SDK style All Error

All the errors are the same one:

Unhandled Exception: Microsoft.Build.Exceptions.InvalidProjectFileException: SDK Resolver Failure: "The SDK resolver "Microsoft.DotNet.MSBuildSdkResolver" failed while attempting to resolve the SDK "Microsoft.NET.Sdk". Exception: "System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.NET.Sdk.WorkloadMSBuildSdkResolver.CachingWorkloadResolver.Resolve(String sdkReferenceName, String dotnetRootPath, String sdkVersion, String userProfileDir, String globalJsonPath)
   at Microsoft.DotNet.MSBuildSdkResolver.DotNetMSBuildSdkResolver.Resolve(SdkReference sdkReference, SdkResolverContext context, SdkResultFactory factory)
   at Microsoft.Build.BackEnd.SdkResolution.SdkResolverService.TryResolveSdkUsingSpecifiedResolvers(IReadOnlyList`1 resolvers, Int32 submissionId, SdkReference sdk, LoggingContext loggingContext, ElementLocation sdkReferenceLocation, String solutionPath, String projectPath, Boolean interactive, Boolean isRunningInVisualStudio, SdkResult& sdkResult, IEnumerable`1& errors, IEnumerable`1& warnings)

=== Pre-bind state information ===
LOG: DisplayName = System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)
LOG: Appbase = file:///C:/work/test_load_msbuild_project/bin/Debug/net472/
LOG: Initial PrivatePath = NULL
Calling assembly : System.Collections.Immutable, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.
===
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: C:\work\test_load_msbuild_project\bin\Debug\net472\test_load_msbuild_project.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Post-policy reference: System.Runtime, Version=7.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
LOG: Attempting download of new URL file:///C:/work/test_load_msbuild_project/bin/Debug/net472/System.Runtime.DLL.
LOG: Attempting download of new URL file:///C:/work/test_load_msbuild_project/bin/Debug/net472/System.Runtime/System.Runtime.DLL.
LOG: Attempting download of new URL file:///C:/work/test_load_msbuild_project/bin/Debug/net472/System.Runtime.EXE.
LOG: Attempting download of new URL file:///C:/work/test_load_msbuild_project/bin/Debug/net472/System.Runtime/System.Runtime.EXE.
LOG: Attempting download of new URL file:///C:/Program Files/Microsoft Visual Studio/2022/Professional/MSBuild/Current/Bin/SdkResolvers/Microsoft.DotNet.MSBuildSdkResolver/System.Runtime.DLL.
LOG: Attempting download of new URL file:///C:/Program Files/Microsoft Visual Studio/2022/Professional/MSBuild/Current/Bin/SdkResolvers/Microsoft.DotNet.MSBuildSdkResolver/System.Runtime/System.Runtime.DLL.
LOG: Attempting download of new URL file:///C:/Program Files/Microsoft Visual Studio/2022/Professional/MSBuild/Current/Bin/SdkResolvers/Microsoft.DotNet.MSBuildSdkResolver/System.Runtime.EXE.
LOG: Attempting download of new URL file:///C:/Program Files/Microsoft Visual Studio/2022/Professional/MSBuild/Current/Bin/SdkResolvers/Microsoft.DotNet.MSBuildSdkResolver/System.Runtime/System.Runtime.EXE.
""  C:\work\test_load_msbuild_project\sample_net8.proj
   at Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(String errorSubCategoryResourceName, IElementLocation elementLocation, String resourceName, Object[] args)
   at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(String directoryOfImportingFile, ProjectImportElement importElement, List`1& projects, SdkResult& sdkResult)
   at Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImports(String directoryOfImportingFile, ProjectImportElement importElement, SdkResult& sdkResult)
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement)
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport)
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate()
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate(IEvaluatorData`4 data, Project project, ProjectRootElement root, ProjectLoadSettings loadSettings, Int32 maxNodeCount, PropertyDictionary`1 environmentProperties, ILoggingService loggingService, IItemFactory`2 itemFactory, IToolsetProvider toolsetProvider, IDirectoryCacheFactory directoryCacheFactory, ProjectRootElementCacheBase projectRootElementCache, BuildEventContext buildEventContext, ISdkResolverService sdkResolverService, Int32 submissionId, EvaluationContext evaluationContext, Boolean interactive)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Reevaluate(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(EvaluationContext evaluationContext)
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Initialize(IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, Boolean interactive)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, IDirectoryCacheFactory directoryCacheFactory, Boolean interactive)
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile)
   at Program.Run(String csprojFileName) in C:\work\test_load_msbuild_project\Program.cs:line 33
   at Program.Main(String[] args) in C:\work\test_load_msbuild_project\Program.cs:line 24

As far as I understand, my tool must target .NET 4.7.2 , but I just cannot make it work. Your help is greatly appreciated.

@ladipro
Copy link
Member

ladipro commented Apr 2, 2024

@MarkKharitonov, I cannot reproduce this either. It looks like on your system the tool is picking up
the .NET Core version of System.Collections.Immutable. The .NET Framework version does not depend on System.Runtime so it couldn't fail in this way. Can you check where it's loading System.Collections.Immutable from?

@MarkKharitonov
Copy link
Author

@ladipro - sure I can do it. But I have multiple run environments comprised of different target frameworks, ways to run (IDE, dev console, bare) and projects to parse (legacy/sdk, .NET Framework/.NET). Which one would you like me to run?

@ladipro
Copy link
Member

ladipro commented Apr 2, 2024

@MarkKharitonov, oh, any environment where you're getting the FileNotFoundException: Could not load file or assembly 'System.Runtime error.

@MarkKharitonov
Copy link
Author

When ran from IDE it is loaded from C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Current\Bin\SdkResolvers\Microsoft.DotNet.MSBuildSdkResolver:

image

@ladipro
Copy link
Member

ladipro commented Apr 2, 2024

This screenshot is from my 17.9.5 install - the file is not there:

image

Is it possible that the file was copied to this location manually, maybe as a workaround?

@MarkKharitonov
Copy link
Author

Ouch. Stupid me. I must have placed it there while trying to make it work with the previous version of Visual Studio.

I removed the file and now all the matrix cases work beautifully.

Since it works I will continue to target .NET 8 in my tool even if it parses projects targeting .NET Framework 4.7.2. It would be fantastic if this ability is not broken in the future, even though you guys are saying it will be.

@MarkKharitonov
Copy link
Author

@ladipro I hate to bother you again, but with the release of 17.10 the code that worked before no longer works. The test project is still available at https://github.com/MarkKharitonov/test_load_msbuild_project.git. I pushed a change where I hard code the location of the msbuild.exe to the locally built one (from this repo).

When I build msbuild at v17.9.8 and then run my app here is what I get:

C:\work\test_load_msbuild_project [master ≡]> .\bin\Debug\net8\test_load_msbuild_project.exe sample_net472_legacy.proj
msbuildDir              = "c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Current\Bin\"
InformationalVersion    = 17.9.8+b34f75857bacf5ecd5531f7ff763a5739d3ae435
csprojFileName          = "sample_net472_legacy.proj"
MSBuildExtensionsPath   = c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild
MSBuildToolsVersion     = Current
MSBuildBinPath          = c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Current\Bin\amd64
VSToolsPath             = c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Microsoft\VisualStudio\v17.0
TargetPath              = C:\work\test_load_msbuild_project\Bin\xyz.dll
C:\work\test_load_msbuild_project [master ≡]> .\bin\Debug\net8\test_load_msbuild_project.exe .\sample_net472_sdk.proj
msbuildDir              = "c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Current\Bin\"
InformationalVersion    = 17.9.8+b34f75857bacf5ecd5531f7ff763a5739d3ae435
csprojFileName          = ".\sample_net472_sdk.proj"
MSBuildExtensionsPath   = c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild
MSBuildToolsVersion     = Current
MSBuildBinPath          = c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Current\Bin\amd64
VSToolsPath             =
TargetPath              = C:\work\test_load_msbuild_project\bin\Debug\net472\sample_net472_sdk.dll
C:\work\test_load_msbuild_project [master ≡]> .\bin\Debug\net8\test_load_msbuild_project.exe .\sample_net8.proj
msbuildDir              = "c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Current\Bin\"
InformationalVersion    = 17.9.8+b34f75857bacf5ecd5531f7ff763a5739d3ae435
csprojFileName          = ".\sample_net8.proj"
MSBuildExtensionsPath   = c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild
MSBuildToolsVersion     = Current
MSBuildBinPath          = c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Current\Bin\amd64
VSToolsPath             =
TargetPath              = C:\work\test_load_msbuild_project\bin\Debug\net8\sample_net8.dll
C:\work\test_load_msbuild_project [master ≡]>

All is great.

However, when I build msbuild at v17.10.4 and rerun the same commands, I get this result:

C:\work\test_load_msbuild_project [master ≡]> .\bin\Debug\net8\test_load_msbuild_project.exe sample_net472_legacy.proj
msbuildDir              = "c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Current\Bin\"
InformationalVersion    = 17.10.4+10fbfbf2eeb0597fdc1f600d87d38c7f57317bdc
csprojFileName          = "sample_net472_legacy.proj"
MSBuildExtensionsPath   = c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild
MSBuildToolsVersion     = Current
MSBuildBinPath          = c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Current\Bin\amd64
VSToolsPath             = c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Microsoft\VisualStudio\v17.0
TargetPath              = C:\work\test_load_msbuild_project\Bin\xyz.dll
C:\work\test_load_msbuild_project [master ≡]> .\bin\Debug\net8\test_load_msbuild_project.exe .\sample_net472_sdk.proj
msbuildDir              = "c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Current\Bin\"
InformationalVersion    = 17.10.4+10fbfbf2eeb0597fdc1f600d87d38c7f57317bdc
csprojFileName          = ".\sample_net472_sdk.proj"
Unhandled exception. Microsoft.Build.Exceptions.InvalidProjectFileException: The expression "[MSBuild]::GetTargetFrameworkIdentifier(net472)" cannot be evaluated. Method not found: 'System.AppDomain System.AppDomain.CreateDomain(System.String, System.Security.Policy.Evidence, System.AppDomainSetup)'.  C:\Program Files\dotnet\sdk\8.0.300\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.TargetFrameworkInference.targets
   at Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(String errorSubCategoryResourceName, IElementLocation elementLocation, String resourceName, Object[] args) in C:\work\msbuild\src\Shared\ProjectErrorUtilities.cs:line 268
   at Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject[T1,T2](IElementLocation elementLocation, String resourceName, T1 arg0, T2 arg1) in C:\work\msbuild\src\Shared\ProjectErrorUtilities.cs:line 65
   at Microsoft.Build.Evaluation.Expander`2.Function`1.Execute(Object objectInstance, IPropertyProvider`1 properties, ExpanderOptions options, IElementLocation elementLocation) in C:\work\msbuild\src\Build\Evaluation\Expander.cs:line 3537
   at Microsoft.Build.Evaluation.Expander`2.PropertyExpander`1.ExpandPropertyBody(String propertyBody, Object propertyValue, IPropertyProvider`1 properties, ExpanderOptions options, IElementLocation elementLocation, UsedUninitializedProperties usedUninitializedProperties, IFileSystem fileSystem) in C:\work\msbuild\src\Build\Evaluation\Expander.cs:line 1401
   at Microsoft.Build.Evaluation.Expander`2.PropertyExpander`1.ExpandPropertiesLeaveTypedAndEscaped(String expression, IPropertyProvider`1 properties, ExpanderOptions options, IElementLocation elementLocation, UsedUninitializedProperties usedUninitializedProperties, IFileSystem fileSystem, LoggingContext loggingContext) in C:\work\msbuild\src\Build\Evaluation\Expander.cs:line 1249
   at Microsoft.Build.Evaluation.Expander`2.PropertyExpander`1.ExpandPropertiesLeaveEscaped(String expression, IPropertyProvider`1 properties, ExpanderOptions options, IElementLocation elementLocation, UsedUninitializedProperties usedUninitializedProperties, IFileSystem fileSystem, LoggingContext loggingContext) in C:\work\msbuild\src\Build\Evaluation\Expander.cs:line 1110
   at Microsoft.Build.Evaluation.Expander`2.ExpandIntoStringLeaveEscaped(String expression, ExpanderOptions options, IElementLocation elementLocation, LoggingContext loggingContext) in C:\work\msbuild\src\Build\Evaluation\Expander.cs:line 452
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluatePropertyElement(ProjectPropertyElement propertyElement) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 1297
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluatePropertyGroupElement(ProjectPropertyGroupElement propertyGroupElement) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 981
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 894
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 1462
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 910
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 1462
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 910
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 1462
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 935
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate() in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 639
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate(IEvaluatorData`4 data, Project project, ProjectRootElement root, ProjectLoadSettings loadSettings, Int32 maxNodeCount, PropertyDictionary`1 environmentProperties, ILoggingService loggingService, IItemFactory`2 itemFactory, IToolsetProvider toolsetProvider, IDirectoryCacheFactory directoryCacheFactory, ProjectRootElementCacheBase projectRootElementCache, BuildEventContext buildEventContext, ISdkResolverService sdkResolverService, Int32 submissionId, EvaluationContext evaluationContext, Boolean interactive) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 341
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Reevaluate(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext) in C:\work\msbuild\src\Build\Definition\Project.cs:line 3719
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext) in C:\work\msbuild\src\Build\Definition\Project.cs:line 3689
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, EvaluationContext evaluationContext) in C:\work\msbuild\src\Build\Definition\Project.cs:line 3672
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(EvaluationContext evaluationContext) in C:\work\msbuild\src\Build\Definition\Project.cs:line 3305
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Initialize(IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, Boolean interactive) in C:\work\msbuild\src\Build\Definition\Project.cs:line 3807
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, IDirectoryCacheFactory directoryCacheFactory, Boolean interactive) in C:\work\msbuild\src\Build\Definition\Project.cs:line 472
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings) in C:\work\msbuild\src\Build\Definition\Project.cs:line 450
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings) in C:\work\msbuild\src\Build\Definition\Project.cs:line 431
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, ProjectCollection projectCollection) in C:\work\msbuild\src\Build\Definition\Project.cs:line 413
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion) in C:\work\msbuild\src\Build\Definition\Project.cs:line 396
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile) in C:\work\msbuild\src\Build\Definition\Project.cs:line 383
   at Program.Run(String csprojFileName) in C:\work\test_load_msbuild_project\Program.cs:line 35
   at Program.Main(String[] args) in C:\work\test_load_msbuild_project\Program.cs:line 25
C:\work\test_load_msbuild_project [master ≡]> .\bin\Debug\net8\test_load_msbuild_project.exe .\sample_net8.proj
msbuildDir              = "c:\work\msbuild\artifacts\bin\bootstrap\net472\MSBuild\Current\Bin\"
InformationalVersion    = 17.10.4+10fbfbf2eeb0597fdc1f600d87d38c7f57317bdc
csprojFileName          = ".\sample_net8.proj"
Unhandled exception. Microsoft.Build.Exceptions.InvalidProjectFileException: The expression "[MSBuild]::GetTargetFrameworkIdentifier(net8)" cannot be evaluated. Method not found: 'System.AppDomain System.AppDomain.CreateDomain(System.String, System.Security.Policy.Evidence, System.AppDomainSetup)'.  C:\Program Files\dotnet\sdk\8.0.300\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.TargetFrameworkInference.targets
   at Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(String errorSubCategoryResourceName, IElementLocation elementLocation, String resourceName, Object[] args) in C:\work\msbuild\src\Shared\ProjectErrorUtilities.cs:line 268
   at Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject[T1,T2](IElementLocation elementLocation, String resourceName, T1 arg0, T2 arg1) in C:\work\msbuild\src\Shared\ProjectErrorUtilities.cs:line 65
   at Microsoft.Build.Evaluation.Expander`2.Function`1.Execute(Object objectInstance, IPropertyProvider`1 properties, ExpanderOptions options, IElementLocation elementLocation) in C:\work\msbuild\src\Build\Evaluation\Expander.cs:line 3537
   at Microsoft.Build.Evaluation.Expander`2.PropertyExpander`1.ExpandPropertyBody(String propertyBody, Object propertyValue, IPropertyProvider`1 properties, ExpanderOptions options, IElementLocation elementLocation, UsedUninitializedProperties usedUninitializedProperties, IFileSystem fileSystem) in C:\work\msbuild\src\Build\Evaluation\Expander.cs:line 1401
   at Microsoft.Build.Evaluation.Expander`2.PropertyExpander`1.ExpandPropertiesLeaveTypedAndEscaped(String expression, IPropertyProvider`1 properties, ExpanderOptions options, IElementLocation elementLocation, UsedUninitializedProperties usedUninitializedProperties, IFileSystem fileSystem, LoggingContext loggingContext) in C:\work\msbuild\src\Build\Evaluation\Expander.cs:line 1249
   at Microsoft.Build.Evaluation.Expander`2.PropertyExpander`1.ExpandPropertiesLeaveEscaped(String expression, IPropertyProvider`1 properties, ExpanderOptions options, IElementLocation elementLocation, UsedUninitializedProperties usedUninitializedProperties, IFileSystem fileSystem, LoggingContext loggingContext) in C:\work\msbuild\src\Build\Evaluation\Expander.cs:line 1110
   at Microsoft.Build.Evaluation.Expander`2.ExpandIntoStringLeaveEscaped(String expression, ExpanderOptions options, IElementLocation elementLocation, LoggingContext loggingContext) in C:\work\msbuild\src\Build\Evaluation\Expander.cs:line 452
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluatePropertyElement(ProjectPropertyElement propertyElement) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 1297
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluatePropertyGroupElement(ProjectPropertyGroupElement propertyGroupElement) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 981
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 894
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 1462
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 910
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 1462
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 910
   at Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 1462
   at Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 935
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate() in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 639
   at Microsoft.Build.Evaluation.Evaluator`4.Evaluate(IEvaluatorData`4 data, Project project, ProjectRootElement root, ProjectLoadSettings loadSettings, Int32 maxNodeCount, PropertyDictionary`1 environmentProperties, ILoggingService loggingService, IItemFactory`2 itemFactory, IToolsetProvider toolsetProvider, IDirectoryCacheFactory directoryCacheFactory, ProjectRootElementCacheBase projectRootElementCache, BuildEventContext buildEventContext, ISdkResolverService sdkResolverService, Int32 submissionId, EvaluationContext evaluationContext, Boolean interactive) in C:\work\msbuild\src\Build\Evaluation\Evaluator.cs:line 341
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Reevaluate(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext) in C:\work\msbuild\src\Build\Definition\Project.cs:line 3719
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext) in C:\work\msbuild\src\Build\Definition\Project.cs:line 3689
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, EvaluationContext evaluationContext) in C:\work\msbuild\src\Build\Definition\Project.cs:line 3672
   at Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(EvaluationContext evaluationContext) in C:\work\msbuild\src\Build\Definition\Project.cs:line 3305
   at Microsoft.Build.Evaluation.Project.ProjectImpl.Initialize(IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, Boolean interactive) in C:\work\msbuild\src\Build\Definition\Project.cs:line 3807
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext, IDirectoryCacheFactory directoryCacheFactory, Boolean interactive) in C:\work\msbuild\src\Build\Definition\Project.cs:line 472
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings) in C:\work\msbuild\src\Build\Definition\Project.cs:line 450
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings) in C:\work\msbuild\src\Build\Definition\Project.cs:line 431
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, ProjectCollection projectCollection) in C:\work\msbuild\src\Build\Definition\Project.cs:line 413
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion) in C:\work\msbuild\src\Build\Definition\Project.cs:line 396
   at Microsoft.Build.Evaluation.Project..ctor(String projectFile) in C:\work\msbuild\src\Build\Definition\Project.cs:line 383
   at Program.Run(String csprojFileName) in C:\work\test_load_msbuild_project\Program.cs:line 35
   at Program.Main(String[] args) in C:\work\test_load_msbuild_project\Program.cs:line 25
C:\work\test_load_msbuild_project [master ≡]>

I am pretty sure it is related to #9446.

Please, advise.

@ladipro
Copy link
Member

ladipro commented May 27, 2024

@MarkKharitonov so this is still loading the net472 build of MSBuild into a .NET 8 process, is that correct? As discussed before, it's unfortunately not a supported scenario. Though in this case, there may be a relatively simple workaround, let me try something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants