dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
19.03k stars 4.03k forks source link

System.Reflection.ReflectionTypeLoadException when calling Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create().OpenProjectAsync #17401

Open shaggygi opened 7 years ago

shaggygi commented 7 years ago

Version Used: Visual Studio 2017 RC4 Microsoft.CodeAnalysis NuGet package 2.0.0-rc4

Steps to Reproduce:

  1. Create new WPF app (.NET 4.6.1)
  2. Add CodeAnalysis package from NuGet
  3. Add code (I did within an async Button Click event.
    Project project = await Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create().OpenProjectAsync(@"C:\Projects\WpfApp4\WpfApp4\WpfApp4.csproj");
  4. Run/debug code.

Expected Behavior: Should be able to load a Project object.

Actual Behavior: Get the following error.

System.Reflection.ReflectionTypeLoadException occurred HResult=0x80131602 Message=Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. Source=mscorlib StackTrace: at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module) at System.Reflection.RuntimeAssembly.get_DefinedTypes() at System.Composition.Hosting.ContainerConfiguration.b0(Assembly a) at System.Linq.Enumerable.d162.MoveNext() at System.Composition.TypedParts.TypedPartExportDescriptorProvider..ctor(IEnumerable1 types, AttributedModelProvider attributeContext) at System.Composition.Hosting.ContainerConfiguration.CreateContainer() at Microsoft.CodeAnalysis.Host.Mef.MefHostServices.Create(IEnumerable`1 assemblies) at Microsoft.CodeAnalysis.Host.Mef.DesktopMefHostServices.get_DefaultServices() at Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create() at WpfApp4.MainWindow.d__2.MoveNext() in c:\Projects\WpfApp4\WpfApp4\MainWindow.xaml.cs:line 38

0xd4d commented 7 years ago

I couldn't repro this. What's the value of the LoaderExceptions property? (see the Message above)

shaggygi commented 7 years ago

I tried this in VS 2015 with similar results. I looked in the View Detail dialog. @0xd4d Were you asking for the data under the LoaderExceptions? It shows the following, does that help?

[System.Exception {System.IO.FileNotFoundException}] {"Could not load file or assembly 'Microsoft.Build, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.":"Microsoft.Build, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"}

shaggygi commented 7 years ago

OK, it looks like I got it to work, but had to download a few other NuGet packages.

Microsoft.Build Microsoft.Build.Framework Microsoft.Build.Tasks.Core

I guess my question now is why would these not already be included or not pulled down when getting Microsoft.CodeAnalysis? Is it because of VS RC and RC packages?

Pilchie commented 7 years ago

Yes, this is related to https://github.com/dotnet/roslyn/issues/15056, but we should probably add dependencies to our packages now. Tagging @mattwar

shaggygi commented 7 years ago

Thank you

kristersz commented 7 years ago

I get the same issue on a machine running VS 2015.3 while trying to call MSBuildWorkspace.Create(). I have added Microsoft.Build and Microsoft.Build.Tasks.Core NuGet packages both v15.1.1012 to the project. I have no issues running the application on a machine with VS 2017 installed. Anything I am missing?

LoaderExceptions: Could not load file or assembly 'Microsoft.Build, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

Could not load file or assembly 'Microsoft.Build.Tasks.Core, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

rigofunc commented 7 years ago

I get the same issue on VS2017 running on Windows 10 while trying to call var workspace = MSBuildWorkspace.Create();

var workspace = MSBuildWorkspace.Create();
var solution = workspace.OpenSolutionAsync(_slnPath).Result;

_documents = new List<Document>();

foreach (var projectId in solution.ProjectIds)
{
    var project = solution.GetProject(projectId);
    foreach (var documentId in project.DocumentIds)
    {
        var document = solution.GetDocument(documentId);
        if (document.SupportsSyntaxTree)
        {
            _documents.Add(document);
        }
    }
}
kristersz commented 7 years ago

I solved my issue.. the real problem was with the app build configuration, however, now the Compilation does not seem to resolve any references outside of the solution and the containing assembly of mscorlib types is 'Missing Core Assembly'. MSBuildWorkspace basically fails to build all the .NET 4.5.2 projects. {[Failure] Msbuild failed when processing the file '***.csproj'}

Pilchie commented 7 years ago

@kristersz - if you use the latest 2.3 prerelease nuget packages from MyGet, @mattwar added additional logging that should help you understand what the msbuild failures are.

kristersz commented 7 years ago

Thank you, @Pilchie, for the tip. This is the message I got:

Msbuild failed when processing the file '*.csproj' with message: C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets: (620, 5): The "Message" task could not be instantiated from the assembly "Microsoft.Build.Tasks.v12.0, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a". Please verify the task assembly has been built using the same version of the Microsoft.Build.Framework assembly as the one installed on your computer and that your host application is not missing a binding redirect for Microsoft.Build.Framework. Unable to cast object of type 'Microsoft.Build.Tasks.Message' to type 'Microsoft.Build.Framework.ITask'. C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets: (620, 5): The "Message" task has been declared or used incorrectly, or failed during construction. Check the spelling of the task name and the assembly name.

Pilchie commented 7 years ago

That sounds like your .exe.config needs to have BindingRedirects in place to redirect the msbuild task assemblies to the version of msbuild you are using.

kristersz commented 7 years ago

Added these for the host application, they do not seem to be helping.

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Build" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="15.1.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Build.Framework" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="15.1.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Build.Tasks.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="15.1.0.0"/>
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Build.Utilities.Core" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-99.9.9.9" newVersion="15.1.0.0"/>
  </dependentAssembly>
</assemblyBinding>
mattwar commented 7 years ago

The machine that only as vs 2015 probably needs the redirects that use the 14.x version numbers. VS 2017 msbuild uses the 15.x version numbers.

kristersz commented 7 years ago

That did it, thank you @mattwar.

shaggygi commented 6 years ago

Still get this with VS15.5 Preview 4. Must reference the following Nugets...

Microsoft.Build Microsoft.Build.Framework Microsoft.Build.Tasks.Core

sorensenmatias commented 6 years ago

Still present in VS15.7.5, when referencing these nuget packages it works:

Microsoft.Build Microsoft.Build.Framework Microsoft.Build.Tasks.Core

pistonexia commented 5 years ago

Still present in VS15.9.5. And it doesn't work by adding the Microsoft.Build packages. Project is a new project created from the VS "Stand-alone Code Analysis Tool" template without any change. Nuget references: image

I also tried to install the newest version of these packages. Didn't work.

The exception says "Can't load Microsoft.Build.Framework version 15.1.0.0“, even after I Install-Packaged Microsoft.Build.Framework.

pistonexia commented 5 years ago

Update: this only happens when the project is a "stand-alone code analysis tool" created from extensibility template. If I create a normal console app and manually add references to the Roslyn packages, everything is fine. So who owns the template, Roslyn, or VS?

Still present in VS15.9.5. And it doesn't work by adding the Microsoft.Build packages. Project is a new project created from the VS "Stand-alone Code Analysis Tool" template without any change. Nuget references:

I also tried to install the newest version of these packages. Didn't work. The exception says "Can't load Microsoft.Build.Framework version 15.1.0.0“, even after I Install-Packaged Microsoft.Build.Framework.

Otto404 commented 5 years ago

still present in vs 16.1.0 preview 3.0 console-app. adding

Microsoft.Build Microsoft.Build.Framework Microsoft.Build.Tasks.Core all worked.

codehunter13 commented 4 years ago

Just creating a new project "Stand-alone Code Analysis Tool". dit nothing else and also get this error... (issue is opened since 26 Feb 2017 ???)

Muchaszewski commented 4 years ago

Why this issue is closed, as it clearly wasn't fixed yet. As of August 2020!

bert2 commented 4 years ago

Just hit the same issue when trying to create an MSBuildWorkspace in an MSTest. Loading of System.Threading.Tasks.Extensions failed.

System.Reflection.ReflectionTypeLoadException HResult=0x80131602 Message=Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. Source=mscorlib StackTrace: at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module) at System.Reflection.RuntimeAssembly.get_DefinedTypes() at System.Composition.Hosting.ContainerConfiguration.<>c.b__16_0(Assembly a) at System.Linq.Enumerable.d__172.MoveNext() at System.Composition.TypedParts.TypedPartExportDescriptorProvider..ctor(IEnumerable1 types, AttributedModelProvider attributeContext) at System.Composition.Hosting.ContainerConfiguration.CreateContainer() at Microsoft.CodeAnalysis.Host.Mef.MefHostServices.Create(IEnumerable`1 assemblies) at Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices.get_DefaultServices() at Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create() at Microscope.Tests.GetMethodExtTests.Init(String testClassFile) in D:\DEV\microscope\src\Tests\GetMethodExtTests.cs:line 28

And this is one of the loader exceptions (all five are mentioning System.Threading.Tasks.Extensions) :

System.IO.FileLoadException: Could not load file or assembly 'System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) File name: 'System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'

=== Pre-bind state information === LOG: DisplayName = System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51 (Fully-specified) LOG: Appbase = file:///D:/DEV/microscope/src/Tests/bin/Debug LOG: Initial PrivatePath = NULL Calling assembly : Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. \=== LOG: This bind starts in default load context. LOG: Using application configuration file: C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\Extensions\TestPlatform\testhost.x86.exe.Config LOG: Using host configuration file: LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config. LOG: The same bind was seen before, and was failed with hr = 0x80131040.

Unfortunately the fusion log is cut off (The same bind was seen before) in all five of the loader exceptions and they all seem to be identical.

Installing System.Threading.Tasks.Extensions to my test project didn't help. I could only find 4.3.0, but not 4.2.0 on NuGet, though...

bert2 commented 4 years ago

I could resolve the above problem by adding an app.config with the following binding redirect to my test project:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Threading.Tasks.Extensions" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.1" newVersion="4.2.0.1" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
Saseska commented 4 years ago

Had this issue in an empty project(in Rider IDE) with nuget CodeAnalysis 3.3.1. Solved by a simple call MSBuildLocator.RegisterDefaults(); before creating workspace.

Shayan-To commented 4 years ago

Same problem here. DotNet version: 5.0.100-rc.1.20452.10. With package references:

> dotnet run

Unhandled exception. System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
Could not load file or assembly 'Microsoft.Build.Framework, Version=15.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.

...
ZjzMisaka commented 2 years ago

I get the same issue on VS2019 running on Windows 10.

NeverMore-Father commented 1 year ago

I got the same issue on VS2019 running on Windows 10. Whether it is a netcore project or a framework project

image image

gBell-Arch commented 8 months ago

Also getting this issue in 2024