Could not load file or assembly in NHibernate - c#

I recently had some problems with the hibernate.cfg.xml file as I hadn't had the following line in.
<property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
Now that this is fixed I get the following error.
Could not load file or assembly 'NHibernate, Version=2.1.0.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
Why do I get this error and how do I fix it?

These files should be in the same directory as the referenced file, NHibernate.dll:
Antlr3.Runtime.dll
Iesi.Collections.dll
log4net.dll
Castle.Core.dll
Castle.DynamicProxy2.dll
Also you should add a reference or copy this one too:
NHibernate.ByteCode.Castle.dll

As a future reference:
If your're experiencing the same issues Randy Klingelheber pointed out (dependency problems between NHibernate and FluentNHibernate, or any other dependent library), you can specify a redirection for the assemblies that target the old version in app.config. This prevents one from having to recompile the dependent assembly.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="NHibernate" publicKeyToken="aa95f207798dfdb4" />
<bindingRedirect oldVersion="3.0.0.3001" newVersion="3.0.0.4000" />
</dependentAssembly>
</assemblyBinding>
</runtime>
This code redirects requests for the old version (3.0.0.3001 in my case) to the one actually used (3.0.0.4000). The publicKeyToken is included in the error message.

I'm assuming you recently upgraded NHibernate to 2.1?
If so, my guess is you have different projects referencing different versions of NHibernate.
This happened to me and is harder to track down than you might think.
These are the steps I took to solve it:
Delete all files in all bin directories in your projects. Usually Clean Solution works well for this, but it doesn't, you may have to do it with a command line call or by hand
Edit all your .csproj files. Edit them either with a text editor or do the Unload Project then edit your .csproj file.
Make sure ALL your HintPath nodes point to the same (new) version of the DLL
That will hopefully clear up this issue for you.

I had this problem as well.
For me, the issue was that FluentNHibernate expected a different version of NHibernate (2.1.0.4000) than I was including in the project (2.1.2.4000). I stumbled on this by separately downloading the latest releases of each library.
To fix the issue, I changed my NHibernate reference to point to the older version of NHibernate that came with FluenNHibernate 1.0 RTM (2.1.0.4000).
Another solution may be to explicitly set your assembly bindings from the app.config file.

In my case, "Clean Solution", followed by "Rebuild Solution" solved the problem.

I recently upgraded our project with the 1.0 RTM version of FluentNHibernate, which required the latest NHibernate bits. This led to the same problem you are having.
Our project's structure was something like this:
Repository root
Solution
Web
References
DataAccess
... other projects/layers ...
DataAccess
References
..\ReferenceAssemblies\NHibernate.dll
..\ReferenceAssemblies\FluentNHibernate.dll
ReferenceAssemblies
(All external DLL's reside in the ReferenceAssemblies directory.)
My first attempt to solve the problem was by adding a reference to NHibernate.ByteCode.Castle.dll to the DataAccess project. This worked... but only in development...
When I published the web application to our customer acceptance test server (which happens automatically with the help of TeamCity and a script containing a call to aspnet_compiler.exe), the NHibernate.ByteCode.Castle.dll was nowhere to be found.
I am not sure why this is happening, but I suspect that it has something to do with the fact that no code whatsoever in our application actually calls code in that specific dll. Also, there's (correct me if I'm wrong) no hardcoded reference from NHibernate.dll to NHibernate.ByteCode.Castle, so somewhere down the line the (presumably unused) dll is overlooked.
The second (and successful) attempt was to add a reference to the missing dll directly to the web project. Now, I could remove the reference I added in the first attempt without any problems.
(I'm not particularly fond of having such a reference in that particular project, but hey!) :-)

You probably have code referencing two different versions of the NHibernate DLL. The NHibernate.dll that you download with NHibernate is likely a different version from the one you download with, say, Castle ActiveRecord. Try to stick with just the version of the NHibernate DLL that came with NHibernate.ByteCode.Castle. And make sure you don't have the NHibernate DLL (any version) in your GAC (at least until you get this problem resolved).

I had this problem after upgrading NHibernate to 3.0 and Spring to nightly build which used NH 3.0. The problem was that Spring.Data.NHibernate30.dll referenced older version of NHibernate.dll (v 3.0.0.2002) and I had v 3.0.0.4000.
My solution was to open project Spring.Data.NHibernate30 source, remove references to older version of NHibernate, add reference to version 3.0.0.4000, rebuild and now in my project add reference to this (newly built) version of Spring.Data.NHibernate30.dll.

I just had this happen to me -- in my case this was my first time trying out NHibernate (and Fluent NHibernate). I had implemented most of my application in a .dll assembly, referenced by a separate executable assembly. The executable, which didn't have references to NHibernate directly, was giving me the error.
I'm using NuGet to pull down Fluent NHibernate, so I added the Fluent NHibernate reference to the executable assemblies as well. Doesn't feel super clean, but it gets the dependencies into the .bin folder and resolves the error. (funny that it doesn't (seem to?) happen with other libraries, like NLog)

I was facing the same issue. I cleared ''Temporary Internet Files'', and this issue went away.

You should reference the dependent assemblies (I guess it's "NHibernate.ByteCode.Castle") and set their "copy local" attribute to true.

NHibernate has a few other assemblies other than nhibernate.dll. Did you have all of them in (from the same release)?

You might have different projects in your solution. Those project might be referencing different versions of NHibernate.dll. Checks versions in all projects and rebuild the project

It looks like the NHibernate dll isn't being copied to the bin directory of your application. Make sure it's referenced and exists in the bin directory.

Related

How to resolve reference issues in Visual Studio [duplicate]

I'm getting a:
type or namespace name could not be found
error for a C# WPF app in VS2010. This area of code was compiling fine, but suddenly I'm getting this error. I've tried removing the Project Reference and the using statement, shutting VS2010 and restarting, but still I have this issue.
Any ideas why this might be occurring, where it seems like I'm doing the right thing re Reference & using statement?
I also noted in VS2010 that intellisense for that namespace is working ok, so it seems like VS2010 has the project reference and is seeing the namespace on one hand, but during compile doesn't see it?
This can be the result of a .Net framework version incompatibility between two projects.
It can happen in two ways:
a client profile project referencing a full framework project; or
an older framework version targeting a newer framework version
For example it will happen when an application is set to target the .Net 4 Client Profile framework, and the project it references targets the full .Net 4 framework.
So to make that clearer:
Project A targets the Client Profile framework
Project A references Project B
Project B targets the full framework
The solution in this case is to either upgrade the framework target of the application (Project A), or downgrade the target of referenced assembly (Project B). It is okay for a full framework app to reference/consume a client profile framework assembly, but not the other way round (client profile cannot reference full framework targeted assembly).
Note that you can also get this error when you create a new project in VS2012 or VS2013 (which uses .Net 4.5 as the default framework) and:
the referencing project(s) use .Net 4.0 (this is common when you have migrated from VS2010 to VS2012 or VS2013 and you then add a new project)
the referenced projects use a greater version i.e. 4.5.1 or 4.5.3 (you've re-targeted your existing projects to the latest version, but VS still creates new projects targeting v4.5, and you then reference those older projects from the new project)
Reinstalling nuget packages did the trick for me. After I changed .NET Framework versions to be in sync for all projects, some of the nuget packages (especially Entity Framework) were still installed for previous versions. This command in Packages Manager Console reinstalls packages for the whole solution:
Update-Package –reinstall
I've no idea why this worked, but I removed the project reference that VS2015 was telling me it couldn't find, and added it again. Solved the problem. I'd tried both cleaning, building and restarting VS to no avail.
When building the solution I was getting the same error (type or namespace ' ' could not be found). Below it I saw a warning stating that "the reference could not be resolved" and to make sure "the assembly exists on disk".
I was very confused, because my DLL was very clearly in the location that the reference was pointing to. VS didn't seem to highlight any errors, until I tried to build the solution.
I finally realized the problem (or at least what I suspect was the problem). I was building the library file in the same solution. So even though it existed on the disk, it was being rebuilt in that location (somehow in the process of the library getting rebuilt my other project - in the same solution - that referenced the library must have decided that the library didn't exist)
When I right-clicked on the project and built that only, instead of the entire solution, I didn't get the error.
To fix this problem I added the library as a dependency to the project that was using it.
To do this:
I right-clicked on my Solution in the Solution Explorer and selected
"Properties"
Then in "Common Properties" I selected "Project Dependencies".
Then in the Projects drop-down menu I selected the project that
relied on the library, and
Checked the box next to the library found under "Depends On"
This ensures that the library project gets built first.
First I would verify that your project's generated information isn't corrupt. Do a clean and rebuild on your solution.
If that doesn't help, one thing I've seen work in the past for designer issues is opening up a windows forms project, then closing it again. This is a little chicken-entrails-ish, though, so don't hold your breath.
A trickier situation I ran into was:
Project one targets the 4.0 full framework with Microsoft.Bcl.Async package installed.
Project two target the 4.0 full framework but would not compile when reference a Project one class.
Once I installed the Async NuGet package on the second project it compiled fine.
In my case, I find the reference in the VisualStudio have a triangle, and a exclamation mark as this image,
then, I right click remove it, and add the dll reference correctly again, the problem was solved.
I had a similar issue: The compiler was unable to detect a folder inside the same project, so a using directive linking to that folder generated an error. In my case, the problem originated from renaming the folder. Even though I updated the namespace of all the classes inside that folder, the project info somehow failed to update. I tried everything: deleting the .suo file and the bin and obj folders, cleaning the solution, reloading the project - nothing helped. I resolved the problem by deleting the folder and the classes inside, creating a new folder and creating new classes in that new folder (simply moving the classes inside the new folder didn't help).
PS: In my case I was working on a web application, but this problem may occur in different types of projects.
This one worked for me. In your class, where the class name is defined, eg: Public class ABC, remove one character and wait a little. You error list will increase because you have changed the name. Now put back the character that you have typed. This worked for me, hopefully it will work for you too. Good Luck!!!
[Facepalm] My issue was that I had added the dependency in the C++ way of doing things.
Go to the project that won't build, open up the 'References' folder in Solution Explorer, and see if your dependency is listed.
If not, you can 'Add Reference' and choose the dependency on the Projects tab.
Boom Shankar.
Check the Build Action of the .cs file containing the missing type. Make sure it's C# compiler.
Click on the .cs file containing the missing type.
Press F4 to bring up Properties.
Make sure Build Action is set to C# compiler.
Before:
After:
It even happens in Visual Studio 2017.
Restart Visual Studio
Clean project that fails to build.
Rebuild the project.
Had the same errors, my story was following:
after bad merging (via git) one of my .csproj files had duplicated compile entries like:
<Compile Include="Clients\Tree.cs" />
<Compile Include="Clients\Car.cs" />
<Compile Include="Clients\Tree.cs" /> //it's a duplicate
If you have a big solution and more than 300 messages in the errors window it's hard to detect this issue.
So I've opened damaged .csproj file via notepad and removed duplicated entries. Worked in my case.
I had same problem as discussed: VS 2017 underlines a class in referenced project as error but the solution builds ok and even intellisense works.
Here is how I managed to solve this issu:
Unload the referenced project
Open .proj file in VS ( i was looking for duplicates as someone suggested here)
Reload project again (I did not change or even save the proj file as I did not have any duplicates)
We had a weird case of this that I just fixed in a solution. There was a hidden/whitespace character in front of a "using" statement in the main project. That project would build fine and the website worked fine, but the unit test project that referenced it could not be built.
I encountered this problem when upgrading existing projects from VS2008 to VS2012. I found that two projects (the only two that I created) were targeting different .Net Frameworks (3.5 and 4.0). I resolved this on the Application tab of the projects by making sure that both projects had ".NET Framework 4" in the Target Framework box.
In my case I had a Class that was listed in the proper source folder, but was not registering in Solution Explorer. I had to do right click the project > Add Existing item and manually select that Class it said it was missing. Then everything worked fine!
I know its old, but I've found the same issue. My project did build, I then updated Visual Studio to the latest & the project wouldnt build as it couldnt find a type definition from a separate assembly. The other assembly built OK, the main project referenced it correctly & nothing had changed since it built OK.
I cleaned the whole solution & rebuilt it, it failed. I built the assembly on its own, it built OK. The project didnt build. I cleaned & built multiple times, and it failed. I then called a colleague to look at it, when I built with him watching, it all built OK.
I think Visual Studio tooling is the problem, especially as I just updated it.
In my case, I unload the project, then:
Opened myProject.csproj and update the ToolsVersion="4.0" to ToolsVersion="12.0"(I'm using vs 2017)(using Paulus's answer https://stackoverflow.com/a/64552201/1594487).
Deleted following lines from the myProject.csproj:
<Import Project="..\packages\EntityFramework.6.4.0\build\EntityFramework.props" Condition="Exists('..\packages\EntityFramework.6.4.0\build\EntityFramework.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
And the problem solved.
You might also try eliminating the code you think you're having problems with and seeing if it compiles with no references to that code. If not, fix things until it compiles again, and then work your suspected problem code back in. Sometimes I get strange errors about classes or methods that I know are correct when the compiler doesn't like something else. Once I fix the thing that it's really getting hung up on, these 'phantom' errors disappear.
I know this is kicking a dead horse but I had this error and the frameworks where fine. My problem was basically stating that an interface could not be found, yet it build and accessed just fine. So I got to thinking: "Why just this interface when others are working fine?"
It ended up that I was actually accessing a service using WCF with an endpoint's interface that was using Entity Version 6 and the rest of the projects were using version 5. Instead of using NuGet I simply copied the nuget packages to a local repository for reuse and listed them differently.
e.g. EntityFramework6.dll versus EntityFramework.dll.
I then added the references to the client project and poof, my error went away. I realize this is an edge case as most people will not mix versions of Entity Framework.
Adding my solution to the mix because it was a bit different and took me a while to figure out.
In my case I added a new class to one project but because my version control bindings weren't set I needed to make the file writable outside of Visual Studio (via the VC). I had cancelled out of the save in Visual Studio but after I made the file writable outside VS I then hit Save All again in VS. This inadvertently caused the new class file to not be saved in the project..however..Intellisense still showed it up as blue and valid in the referencing projects even though when I'd try to recompile the file wasn't found and got the type not found error. Closing and opening Visual Studio still showed the issue (but if I had taken note the class file was missing upon reopening).
Once I realized this, the fix was simple: with the project file set to writeable, readd the missing file to the project. All builds fine now.
I had the same issue. One night my project would compile the next morning ERRORS!.
I eventually found out that visual studio decided to "tweak" some of my references and point them elsewhere. for example:
System.ComponentModel.ISupportInitialize somehow became "blahblah.System.ComponentModel.ISupportInitialize"
Quite a rude thing for vs to do if you as me
My case was same as discussed here but nothing solved it until I've removed the System.Core reference from the references list (Everything worked fine without it)
hope it will help someone because this issue is quite frustrating
To solve this issue it can also help to delete and recreate the *.sln.DotSettings file of the associated solution.
Ok, years later using VS 2017 .NET Core 2.2 Razor Pages I feel this answer might help someone.
If it was a snake it would have bit me.
I was throwing stuff around, changing names, renaming Models, and all of a sudden I got this error:
Error CS0246 The type or namespace name 'UploadFileModel' could not be
found (are you missing a using directive or an assembly reference?)
This was underlined in red in my .chstml Razor Page. (not underlined after fix):
#page
#model UploadFileModel
So, finally, and luckily, I found the code from someone else that I had originally used, and low and behold, the namespace did not include the .cshtml file name!!!
Here is my bad dummy error spank myself with the page name in the namespace:
namespace OESAC.Pages.UploadFile
{
public class UploadFileModel : PageModel
{
What my original code had and all I had to do was delete the page name from the namespace, UploadFile:
namespace OESAC.Pages
{
public class UploadFileModel : PageModel
{
And low and behold, all the errors disappeared!!
Silly me. But you know, MS has made this .NET C# MVC stuff really confusing for us non-computer scientists. I am constantly tripping on my shoelaces trying to figure out model names, page names, and syntax to use them. It shouldn't be this hard. Oh well. I hope error and solution helps someone. The error was right, there is no Namespace named "UploadFileModel" haha.
In my case the problem was that after changing namespace to exactly same as is in another project (intentionally), the name of assembly was changed as well by VS, so there were two assemblies with same name, one overriding the other
Had the same problem after merging some new code into a vs2019 project.
Restarted VS, unloaded and reloaded projects, ensured all projects in solution had same ToolsVersion= and TargetFrameworkVersion. None of this helped.
I had a case of project Substrate, failing to find namespace Skin (in project Skin).
Finally I opened up Substrate.csproj and checked all the ProjectReference Include entries. The others were there, but no reference to Skin, even though Skin did show up in the check box of the little project dependencies dialog. So the project dependencies dialog took the check box for Skin (and saved it somewhere) but did not alter Substrate.csproj. I then added the ProjectReference Include manually, ensuring I had the correct path and GUID for the skin project.
<ProjectReference Include="..\Skin\Skin.csproj">
<Project>{1ad4b5d7-5014-4f5f-983e-2c59ac0e0028}</Project>
<Name>Skin</Name>
</ProjectReference>
I then saved the Substrate.csproj and the problem was solved. So as others have said this is a problem with VS tooling
In my case I had a file built by external dependency (xsd2code) and somehow its designer.cs files were not processed by VS correctly. Creating a new file in Visual Studio and pasting the code in it did the trick for me.
To anyone that is getting this error when they try to publish their website to Azure, none of the promising-looking solutions above helped me. I was in the same boat - my solution built fine on its own. I ended up having to
Remove all nuget packages in my solution.
Close and reopen my solution.
Re-add all the nuget packages.
A little painful but was the only way I could get my website to publish to Azure.

Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0

I do not understand the following problem I am facing.
I have 3 projects, A, B and C. All of them have a reference to Newtonsoft.Json, version 12.0.1
Project a has a reference to both projects B and C. Project B, has a references to Microsoft.IdentityModel.Tokens.Jwt
When I run project A, I get the following runtime error when trying to execute the function necessary for creating my token.
Message:
"The type initializer for 'System.IdentityModel.Tokens.Jwt.JsonExtensions' threw an exception."
Inner Exception:
"Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified."
I have verified that all projects reference the same Newtonsoft.Json package with version 12.0.1.
I have also checked my project files, to make sure there is no reference to Newtonsoft.Json version 10.0.0.0
What am I missing?
Newtonsoft Json while useful is the source of many issues.
You will need to check all the NuGet packages referenced by every project in your solution to see what version of Newtonsoft Json they require. Some specify a minimal version, in which case you don't have an issue ( like > 10, anything higher than 10 will work ), others require a certain, fixed version ( = 10, must be 10, not less, not higher). This is up to the author of that particular NuGet package.
When you hit build, the dlls required by the referenced packages will be copied over, then the dlls required by any referenced projects will copied over and it is possible a certain version will be copied over and when you run your application, you get the error you have seen.
You can check this by looking in the bin folder of your build profile, right click the dll file and inspect its version to see what you have. Assembly redirection should help, when done in the right place, but there is an alternative solution, although it's not always possible.
If you can drop the Newtonsoft Json to the minimum version which satisfies all requirements then that is a good way to solve the problem. Chances are you don't need version 12, depending on what you are using from it and depending on what other packages require. You might be able to change all projects to reference the lower version without any side effects. If you can, you're golden, just make sure you don't upgrade by mistake. If not, you'll have to do the version redirecting like indicated in other answers.
The basic idea is to make sure, that in your solution, you only use one version of Newtonsoft. you can check this package at solution level, there is a consolidate option as well.
So, check all projects in the solution, make sure they all use one version of Newtonsoft and that version is the same across all of them.
Once you manage to get everything on one level make sure that:
you delete the Temporary ASp.Net folder contents, in Windows / Microsoft.Net, Framework23 or 64 depends which one you're using.
remove all dlls from all bin folders, a simple Cleanup may not be sufficient.
With all this done, providing you have one version everywhere, you should be able to run you project without issues
I think some of your project is referring version 10, while other is referring version 12 of newtonsoft.json.dll.
It seems the v12 DLL is getting copied to output directory. The project which refers v10 is throwing this error.
For all the strong named assemblies, the specific version of DLL is searched in the application directory or GAC. You can overwrite this default behavior by using below configuration file entry - which instructs .net framework to always look for v12 whenever any version from 0 to 12 is called.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-12.0.1.0" newVersion="12.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Hope this helps to resolve your issue.
I finally got this working. In order to do Assembly Redirect Binding in Azure Functions, it takes a little more effort than a normal .Net application.
I followed the following post:
https://codopia.wordpress.com/2017/07/21/how-to-fix-the-assembly-binding-redirect-problem-in-azure-functions/
Find out what project trying to load this library. Right click on project->Manage Nuget Packages->Find NewtonJson library in installed libs and click Uninstall, maybe this will help. Also like people provided before use could you assembly redirect.
Where you are using Microsoft.IdentityModel.Tokens.Jwt don't add it as a using to the page instead make a direct reference to it.

Unable to load SqlServerSpatial.dll after referencing Microsoft.SqlServer.Types package

I'm running into an issue when trying to access some spatial data from a Sql Server table.
The exception I receive is
Unable to load DLL 'SqlServerSpatial.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
I tried the solutions mentioned here, and here, which is in essence
Install the Microsoft.SqlServer.Types package.
Ensure that Microsoft.SqlServer.Types, EntityFramework and EntityFramework.SqlServer references are set to Copy always
Load the native libraries (in my case, adding SqlServerTypes.Utilities.LoadNativeAssemblies(HttpRuntime.BinDirectory); to the end of the Application_Start method in Global.asax.cs
After doing these, I end up with the same exception occurring in the same place, which in a way makes sense, because I don't have a SqlServerSpatial.dll, but rather a SqlServerSpatial140.dll included with the Microsoft.SqlServer.Types package.
What can I do to resolve this issue?
I came across this same problem recently and decided to dig into it because all of the answers I found on Stack Overflow were voodoo and hand-waving to fix the symptom instead of understand the problem.
Note: This applies to Entity Framework 6 and .NET Framework. Since newer versions of .NET don't have a GAC this may not be a problem there.
The problem
What I found is that when using EntityFramework.SqlServer alongside Microsoft.SqlServer.Types can lead to runtime assembly version problems depending on what versions of the Types assembly you have installed in the GAC or other locations in the assembly resolution path. This is pretty easy to happen, since this assembly comes with SQL Server, SQL Server Management Studio, as a standalone installer (which, ironically, some answers suggest using to fix this problem), and probably other ways.
When using SQL Server CLR types like DbGeography, Entity Framework delegates the work out to the Microsoft.SqlServer.Types library (even though there isn't a dependency between the packages). To do this it has to load that assembly, and to decide which assembly version to load, it uses the System.Data.Entity.SqlServer.SqlTypesAssemblyLoader class that has the following heuristic:
If System.Data.Entity.SqlServer.SqlProviderServices.SqlServerTypesAssemblyName is populated, use that.
Try to load version 11.
Try to load version 10.
Try to load each version from 20 down to 12 until one works.
The current major version of Microsoft.SqlServer.Types is 14. This means if you have an older version of 11 or 10 installed in the GAC, those versions will be preferred by Entity Framework and will be loaded into your AppDomain, even if you already have version 14 loaded from the nuget package.
This leads to multiple versions of the Microsoft.SqlServer.Types assembly being loaded with the older version of the library getting used in ways that are not supported, resulting in runtime exceptions. Symptoms include looking for the old SqlServerSpatial.dll native library instead of the expected SqlServerSpatial140.dll native library which comes with version 14 of the Microsoft.SqlServer.Types nuget package (and is loaded via the Loader.cs file that comes with that package).
You can verify this is happening by enabling Fusion binding logs, or by adding the following to your program (before and after using Entity Framework) and noting that you go from one assembly to two with different versions.
AppDomain.CurrentDomain.GetAssemblies()
.Where(a => a.FullName.Contains("Microsoft.SqlServer.Types")).ToArray();
The end result is an exception being raised, such as Exception has been thrown by the target of an invocation. --> Unable to load DLL 'SqlServerSpatial.dll'.
The solution
There are two separate ways to address the problem, depending on your situation and preference. You need to do one of these (I suggest leaving a comment for the poor future developer who runs into this again after Nuget packages are updated):
Add an assembly redirect binding for Microsoft.SqlServer.Types so that Entity Framework (and everything else) is forced to use the version you have via Nuget:
<dependentAssembly>
<assemblyIdentity name="Microsoft.SqlServer.Types" publicKeyToken="89845dcd8080cc91" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-14.0.0.0" newVersion="14.0.0.0" />
</dependentAssembly>
Specify the version you want Entity Framework to use via the static property SqlProviderServices.SqlServerTypesAssemblyName property. You'll need to do this early in the lifecycle of the program, such as in Startup / Main / Application_Start / etc.
System.Data.Entity.SqlServer.SqlProviderServices.SqlServerTypesAssemblyName
= "Microsoft.SqlServer.Types, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91";
That's it.
Make a copy of your SqlServerSpatial140.dll (or download a newer version) and name your copy SqlServerSpatial.dll and move it to your system32 directory. Worked for me.

Binding Redirect being added to every app.config

I have 20 projects in a solution file. 1 of the projects is a standard library project that all the the projects reference.
About a year ago we added a new nuget package, we'll call it Package A Version 5.0.0.0. It had a bunch of files that it would transfer all over when we compiled but we eventually dealt with it. We added the package to our standard library project (the one the other 19 reference).
I am new to Nuget (so maybe I did something wrong) so I made a new package to serve as a helper for Package A. I had set everything up so that the helper has a dependency on Package A version 3.0.0.0 to 5.0.0.0 (So it works for others who have a lower version than us). Lets call this new package Package A helper
I install Package A helper and everything is working as it should. I go to do a pull request and every single app.config in our solution now has
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Package.A" publicKeyToken="8FC3CCAD86" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
It will compile fine without it, but visual studio complains and gives a warning. What gives? My manager won't let me merge my code now because it adds too much noise into app.config and depends too much on Package A.
why did adding a nuget package that depended on Package A then have to have this new bindingRedirect when the main dependency was already met before we installed Package A Helper?
And why does it say 0.0.0.0-5.0.0.0 when I specified 3.0.0.0-5.0.0.0 in the nuget package and package.config
Update:
When I build Package A helper with references to Package A version 5.0.0.0 then all the bindingRedirects don't get auto-populated in every app.config but instead warnings are generated. I had originally built it with 3.0.0.0 because I figured it was best to build it with the lowest dependency. The problem still exists because visual studio is still warning and suggesting bindingRedirects are created.
No way to resolve conflict between "Package A, Version=5.0.0.0, Culture=neutral, PublicKeyToken=83hfhsd33" and "Package A, Version=3.0.0.0, Culture=neutral, PublicKeyToken=83hfhsd33". Choosing "Package A, Version=5.0.0.0, Culture=neutral, PublicKeyToken=83hfhsd33" arbitrarily.
Consider app.config remapping of assembly "Package A, Culture=neutral, PublicKeyToken=83hfhsd33" from Version "3.0.0.0" [] to Version "5.0.0.0" [path to Package A dll] to solve conflict and get rid of warning.
Is the solution just to change my nuget package dependency from 3.0.0.0 to 5.0.0.0 and just allow 5.0.0.0 and get rid of my allowedVersions="[3,6)" in me packages.config? I don't want to reduce the helpfulness and backwards compatiblity of my nuget package but at the same time I want no warnings or bindingRedirects required for my main solution.
Update 2: So setting Copy Local in the reference properties to False actually solved my issues, but I don't understand why.
I had originally built it with 3.0.0.0 because I figured it was best ...
That is where the problem started. Your solution now depends on two distinct versions of A.dll, one is going to overwrite the other. Which version of A.dll ends up getting copied into bin\Debug is random. Whatever project was built last.
This can not come to good end, the solution is doomed to fail to execute. If will either be the code in A-helper.dll, it will fail when version 5.0.0.0 ends up getting copied. Or it will be the code in whatever other project uses A.dll, it will fail when version 3.0.0.0 gets copied. End result is that the solution will always fail.
So you are seeing the build system doing something about it. It notices the discrepancy and elects one of the versions to win. It picks 5.0.0.0, that was the correct choice. And it also modifies app.config, adding the bindingRedirect so code that asks for the 3.0.0.0 version to be loaded will actually get 5.0.0.0. That could work if you made version 5 compatible enough with version 3. Or not, two increments in the major version number usually spells trouble. You'll find out when you test.
So setting Copy Local in the reference properties to False actually solved my issues
That did not solve an issue, you merely prevented the build system from assuming that it should solve this problem for you. Since it no longer had to copy the DLL, it guesses that you'll install the assemblies in the GAC so that both versions can co-exist. Maybe you did, it is not common and in general very unwise to do so on a dev machine. Very unlikely that your boss and team members will like this solution given the extra install step.
So there are two basic things you can do:
Let the build system sort this out. As it did, it solved the problem correctly and your solution will work. If version 5 is compatible enough with version 3 then the code in A-helper.dll will even execute correctly. If the boss doesn't like it then you'll of course have to scratch this and do:
Change the reference in the A-helper project to A version 5.0.0.0. Now there no longer is any incompatibility, the one-and-only A.dll is good for all the code. Given your requirement, this is the only solution your boss will like.

Determine the source of an indirect dependency on incorrect .NET Framework version

I would like to know how I can determine the source of this build error;
Warning 4 The primary reference "MyNamespace.MyProject" could not be resolved because
it has an indirect dependency on the .NET Framework assembly "System.Xml, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089" which has a higher version "4.0.0.0" than
the version "2.0.0.0" in the current target framework. MyNamespace.MyOtherProject
I understand the meaning of this error (and the 5 others like it for this same project), but I cannot work out how to resolve it in my case. The 'primary reference' in this case (MyNamespace.MyProject) has no direct dependencies on .NET 4.0.x.
The primary reference depends on only one other project of mine (MyNamespace.MyCoreProject), which the source project for the build (MyNamespace.MyOtherProject) also depends directly on. And the build is not complaining about that project having indirect references to .NET 4.0.x, so I assume I can rule that out.
The primary reference has a direct dependency on three (3) 3rd party DLLs, all of which also Target .NET 2.0.
I have employed dotPeek to examine the built libraries, and cannot see any reference to anything using .NET 4.0.
The only other potential spanner in the works is the use of PostSharp, which is directly referenced by 'MyNamespace.MyCoreProject' (referenced by the primary reference project), which may be causing the problem, as I believe there is a related VS2010 bug when referencing PostSharp.dll (http://www.sharpcrafters.com/forum/Topic4444-4-1.aspx#bm4462), however I also removed that from the build chain and still see this error, so I assume I can also rule that out.
If someone can tell me why this is happening, fantastic! If not, some direction on how to work out what the unnamaed 'indirect reference' is would be just as helpful!
Incidentally, I have tried all of the following tools to get some info, but they're not telling me much I didn't already know (which is the direct dependencies of the DLL in question);
- .NET Reflector
- dotPeek
- IldAsm
- Depends (Dependency Walker)
Whilst I have not actually worked out a good way to actually solve the problem of determining how MsBuild determines the references it uses (why it does not just tell me how it comes up with these indirect references, instead of making me guess I don't know...) I have solved my problem.
In the end, I basically removed all references in the 'primary reference' project, (which required excluding all code piece by piece - a somewhat painful process) to determine that the source of the supposed indirect reference to .NET 4.0 libs was caused by a 3rd party DLL that was referenced.
However, I do believe there is a bug in MsBuild behind this problem, as;
The 3rd party DLL was referenced by 'Browse' to a specific DLL file on my machine - one that VERY EXPLICITLY depends only on .NET 2.0
Setting 'Specific Version' to true in the build did nothing to fix this
MsBuild appeared to be going to the GAC for a different version of this DLL and causing the incorrect reference error.
Now, another curiosity is that I've not touched or changed the relevant libs in some time, so this has just started happening for some other unrelated reason - what that may be, I don't know.
In the end, the only way I found to solve this issue was to run gacutil /u for each of the relevant libs to remove previously installed/used versions of the 4.0 libs. (There were about 40 in the package, so that was also painful! as the package's uninstaller did not remove the libs in the GAC)
This seems to have let msbuild start using the references I told it to, rather than coming up with its own idea of what 'use this file' and 'use this specific version means.
Solved, but I would have loved a cleaner way to do this!
Try to use MSIL Disassembler tool for all suspicious assemblies.
Open Dll, click Ctr + M and go to end of the screen. You may see reference to some .NET 4 assembly like this one:
AssemblyRef #1 (23000001)
Token: 0x23000001
Public Key or Token: b7 7a 5c 56 19 34 e0 89
Name: mscorlib
Version: 4.0.0.0
Major Version: 0x00000004
Minor Version: 0x00000000
Build Number: 0x00000000
Revision Number: 0x00000000
Locale: <null>
HashValue Blob:
Flags: [none] (00000000)
Find type that is loaded from that .NET assembly usinf ref # as search criteria.
This is sample of type you can find in screen
TypeRef #18 (01000012)
Token: 0x01000012
ResolutionScope: 0x23000001
TypeRefName: System.Runtime.CompilerServices.CompilationRelaxationsAttribute
Investigate why that type is used.
Update:
Did you try to set set MSBuild Project Build Output Verbosity to "Detailed" on Tools\Options\Projects and Solutions\Build And Run page, and then rebuild solution? You may see something in ResolveAssemblyReference target
I had this problem and used CheckAsm to determine that one of my own assemblies for some strange reason was referring to a .NET 4.0 version of a 3rd party library, whereas the app itself was .NET 2.0. I deleted all instances of that assembly from my hard drive (there were a lot of copies lying around), rebuilt the solution and all was good.
In my case, the assembly was uninstalled and all references (to my knowledge) were removed.
Found it in the app.config:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
...
</dependentAssembly>
</assemblyBinding>
</runtime>
Deleted the dependentAssembly and got my app working again.
I also had this problem, and event.er lead me to the solution. I had the following in my app.config:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
I changed newVersion to "2.0.0.0" and the solution built.
My guess is the 3rd party DLL is the one that does not have specific version set to true for it's dependencies and is causing your problem.
I was having problems with System.Data.SQLite.dll in a project targeting .NET 4.5 which turned out to be that a version targeting 4.5.1 was installed to GAC_32.
If I built the solution with Copy Local = True, all would be well. But as I was embedding the SQLite assemblies in the final build this seemed unnecessary and I wanted to sort it out.
I tried running gacutil -u System.Data.SQLite.dll but had trouble with it so in the end I just used Windows' Programs And Features to uninstall it and then all was well.
If using Visual Studio 2019 and trying to build .NET 3.5 projects this will help.
Visual Studio service packs and the newer Visual Studio 2019 puts a program (usually WebDeploy) in Program Files and puts this folder high in the assembly probing path for your machine (so the net45 JSON.NET assembly gets picked up before any other one).
To figure out where your one is being resolved from, just use SysInternals Process Monitor and filter on the referenced DLL. Then kick off your build. Process Monitor will tell you where it's resolving that assembly from and it's usually the one in a WebDeploy folder for VS2019 installations. You can purge the folder if you're not using the WebDeploy tool.
Specifically, for my case, I removed C:\Program Files\IIS\Microsoft Web Deploy V3\Newtonsoft.Json.dll and my build worked.

Categories