Update-database failing - BadImageFormatException - c#

We have a team of developers working on an Asp.Net MVC5 solution, and often after doing a git pull to get the other developers changes we need to update our local databases with any new Database Migrations (entity framework 6.1.3) which have been added.
We run update-database in the Package Manager Console to update the database. This worked until we changed all the projects to compile x64 output. Which was needed to resolve memory requirements.
However now I am getting :
System.BadImageFormatException: Could not load file or assembly 'My.Data' or one of its dependencies.
An attempt was made to load a program with an incorrect format.
When I run Update-database. I've cleaned down all bin and obj folders before recompiling (to ensure all output would be the same format x64).
It looks like the problem may be that the migrate.exe is not compatible with x64. SO,Original MSDN article.
However this post is for EF5. Is this still the case? And is there a workaround? if not it seems bizarre, its not as if x64 or EF are new additions to Visual studio.

Managed to find the answer.
The problem is that the enable-migrations command appears to have a
hard-coded path where EF looks for built DLLs of your project at
/bin/Debug, no matter what the actual build path is. When you change a
Project to x64, Visual Studio quietly changes your project's build
path to /bin/x64/Debug - while EF keeps looking in /bin/Debug. That
causes this vague System.BadImageFormatException
It's harmless to just change your Project build path to /bin/Debug and
magically, everything begins working like it's supposed to.
https://stackoverflow.com/a/23666717

Related

"Unable to find an entry point named 'sqlite3_open_interop' in DLL 'SQLite.Interop.dll'."

I am using a C# application to try to connect to a SQLite database. The application uses the library System.Data.Sqlite, version 108. In Visual Studio 2017, my Solution Configuration is Debug, and my Solution Platform is Any CPU. Whenever I build and run the application, I get the following runtime exception:
The exception is unhandled, and the application terminates.
There is, of course, a SQLite.Interop.dll file in my bin\Debug directory. (If there wasn't, the exception would be different.) Specifically, there are two, each in their own subdirectories named x64 and x86. My assumption is that the file in the x86 directory is being used, since the Solution Platform is set to Any CPU. The version of the SQLite.Interop.dll assembly matches that of System.Data.SQLite.dll, being 1.0.108.0.
When I use the following command to interrogate the assemblies:
dumpbin /exports SQLite.Interop.dll
I do find the following line in the output for the x64 version of the assembly:
175 AE 00040750 sqlite3_open_interop
but in the output for the x86 version I do not. Instead, I find this line:
175 26 00037F10 _sqlite3_open_interop#20
which is close, but not a match. So there is indeed no such method as sqlite3_open_interop exposed by the assembly.
I have tried the obvious solution of changing the Solution Platform to x64, but that change leads to another exception (BadImageFormatException) which I don't much want to contend with.
I have tried dropping the reference to System.Data.SQLite and using Nuget to add the most recent version, 1.0.111.0, then cleaning and rebuilding the solution, but all to no effect. The same issue recurs.
Could anyone suggest a solution to this issue? SQLite is widely used, I believe, so I have to think there's a way to work through it.
*Edit1: I tried this project on my home computer, and observed the same difference between the two SQLite.Interop.dll files. The x64 version had a sqlite3_open_interop, while the x86 version had a _sqlite3_open_interop#20. However, the problem did not occur there. So apparently this mangled name "issue" is a red herring. I am still very interested in solving this problem, and would appreciate the assistance of someone who works on System.Data.Sqlite!
Delete your x64 and x86 directory then do a build. It will put the correct version in the folder when the installer does the NuGet check. For some reason, when you upgrade to a newer version, the x64 and x86 folders do not update the interop file in those folders if one already exists.
It turned out the issue was that the assembly was being blocked or disrupted somehow by McAfee Host Intrusion Prevention. The Activity log had the following message:
Attack type: DISA McAfee - Prevent unexpected DLL files from Running
in User AppData and ProgramData folders (Sig Id = 7020)
Which is odd because I don't think my program was executing in either such folder; in fact, there are no such folders, as I am looking at the matter. I was able to fix the issue by moving the program to My Documents.
It's also notable that the exception made no hint of interference by a security scanner.
Sigh. I don't know how generally useful this answer is, but I will leave it here. It might help someone. The admins can remove it if they deem appropriate.
Though its an old thread but nevertheless someone else may face similar issue again. In my case, this error occurs when I try to make connection string with password, since in the latest version of sqlite, ecnryption has been a paid feature that's why it doesn't work in free version. So, to circumvant this issue I restored old version of sqlite (picked from my old project) and it worked ok.
Add following reference in your project:
System.Data.SQLite.dll
Copy following files in binary folder:
System.Data.SQLite.dll.config (Optional)
System.Data.SQLite.xml (Optional)
x64\SQLite.Interop.dll
x86\SQLite.Interop.dll
Where 'x64' and 'x86' are folders
Packages available on nuget have same issue so you need old dll

Your project does not reference ".NETFramework,Version=v4.6.2" framework. Add a reference to ".NETFramework,Version=v4.6.2" in the "TargetFrameworks"

I can't run my unit tests.
I have the next error:
Your project does not reference ".NETFramework,Version=v4.6.2"
framework. Add a reference to ".NETFramework,Version=v4.6.2" in the
"TargetFrameworks" property of your project file and then re-run NuGet
restore.
In app.config:
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
</startup>
In Project > Properties > Application > TargetFramework (.NET Framework 4.6.2)
How can I fix it?
Please make the next steps
Clean solution
Clean folder "packages"
Delete folder "bin"
Delete folder "obj"
I experienced similar issue, but with v4.7.2. Namely, I kept getting build log message like this:
error : Your project does not reference ".NETFramework,Version=v4.7.2" framework. Add a reference to ".NETFramework,Version=v4.7.2" in the "TargetFrameworks" property of your project file and then re-run NuGet restore.
Despite the fact that it looked similar, none of the above proposed steps worked for me. I kept seeing this message after each build. Nothing seemed to be able to help.
In fact, the problem was related to that, due to migration, I had to put two projects in one folder of code. One of them was targeted at .Net Core, another at .Net Framework, both referenced same .Net Standard libraries. Apparently, they share the same obj folder where Core projects put project.assets.json file. Actually, exactly this file interferres with the Framework project preventing its normal build. Seems even if you performed Migrate from packages.config to PackageReference... which was recommended as one of possible solution.
You can try to fix the issue by putting the following snippet into your Framework project file:
<Project>
...
<PropertyGroup>
<BaseOutputPath>$(MSBuildProjectDirectory)/out/$(MSBuildProjectName)/bin</BaseOutputPath>
<BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/out/$(MSBuildProjectName)/obj</BaseIntermediateOutputPath>
</PropertyGroup>
...
</Project>
It immediately worked for me, it was only later when I attentively read why we need it and why it works. I unexpectedly found it in part 2 of Migrating a Sample WPF App to .NET Core 3 under Making sure the .NET Framework project still builds section. BaseOutputPath and BaseIntermediateOutputPath msbuild variables can be found there, not sure if they are documented well anywhere.
That happened to me when opening a VS2015 project in VS2017. Deleting the project.assets.json from the obj folder did the trick.
Anyway, the Framework from the message was missing in the file, I did not add it there though, went with deleting it.
git clean -xdf
That should do the trick. It worked for us also in Jenkins. (we simply replayed the failed build with a modified script that ran git clean first).
For some reason MSBuild / Visual Studio get confused when switching between branches that target different versions of .NET Framework, so I had to do git cleans regularly while switching between branches.
The file that was causing issue for me was obj/project.assets.json inside project folder. Deleting it and rebuilding the project worked.
I had deleted the obj folder and rerun the build after choosing the target framework required in the property window it worked for me.
I up-voted Larissa but I thought it might be helpful to know how I got into this. I added a .net standard project file to my build (we target lots of platforms) and it produced the debris found in the obj folder. When the android sanity build came around, it threw up on the obj folder. My solution was to clean that folder out as a pre-build step. This is a difficult problem because it was working just fine for years...needle meet haystack.
For my case, delete the .pkgrefgen/ folder under the project folder works, it contains a file project.assets.json that refer to old .net framework
I ran into the same thing with .net 4.71. In my case, I simply migrated from packages.config to "package references" per
Migrate from packages.config to PackageReference
... and it fixed my issue. For me, I was going to do this anyway, so if you're going this way already, I'd just skip the above and migrate to package references.
Renaming the project solved the error for me. The issue happened after I created .NET Core project, then I deleted it and created a .NET Standard one with the same name. Obj folder was not present at all. Deleting bin folder, packages, clean and rebuild solution and getting latest with override did not help.
I have not tried this, but this thread proposed workaround is to include into csproj tag:
<ResolveNuGetPackages>false</ResolveNuGetPackages>
I am using a very old .NET project, and it was working fine until it stopped all of a sudden. Upgrading Visual Studio fixed for me thou.
On VS2019 I had to follow the error message and edit the project.json file that was in the project directory.
was ".NETFramework,Version=v4.0": {} // whatever the copied project was set to
now ".NETFramework,Version=v4.7.2": {} // set to whatever the current build is set to
Problem: In VS2017. Missing reference to .netframework 4.5.2, even though it was referenced as the target framework.
My solution: Verified framework was installed and restarted machine. After a git clean and simply right clicking on the solution in the explore and 'Restore nuget packages' did the trick.
For whatever reason, I got this build error in VS2022.
The same build in VS2019 was successful.
I had the same issue in CI/CD process, when i had upgraded .net framework version from 4.6.1 to 4.7.2 which worked fine locally without any other modification.
However, the jenkins 'slave' node where the build was actually getting generated had some issue with nuget restore and it was not able to pick the latest build for some reason.
Logged into jenkins slave machine/node (basically the machine which jenkins uses to create the build/artifact), go to deployment path and then try deleting projects old builds along with .nugets folder and trigger CI/CD process again worked for me.
This error also occurs if you have removed an old SDK that provided nuget packages, but it is still referenced in your package sources list under Nuget manager/settings. Remove the nuget package source no longer in use to fix this. Otherwise, Visual studio on building will create the project.assets.json file with a reference to the old sdk and if the path is not there, you get the OP's error.
In my case, I had DevExpress 20.2 in my list which I removed to resolve this issue.

SQLite.SQLite3: Exception System.DllNotFoundException

I am able to build and execute on my development box my Winforms applicaiton, however I run into this error, when I attempt to run my application on another clean box (a VM).
Application: MyApp.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.DllNotFoundException
at System.Data.SQLite.UnsafeNativeMethods.sqlite3_config_none(System.Data.SQLite.SQLiteConfigOpsEnum)
at System.Data.SQLite.SQLite3.StaticIsInitialized()
at System.Data.SQLite.SQLiteLog.Initialize()
at System.Data.SQLite.SQLiteConnection..ctor(System.String, Boolean)
at System.Data.SQLite.SQLiteConnection..ctor()
at DittoSql.SQL..ctor()
at MyApp.Program..cctor()
Exception Info: System.TypeInitializationException
at MyApp.Program.Main(System.String[])
I used Nuget to add SQLite to my project.
Sadly, the event viewer log does not provide what DLL that the system cannot find. I did research and the one thing that turned up is .Net compatibility. I was at 4.6.2, which on SQLite v1.08 does not support, so I downgraded to .Net 4.6, which is listed.
Both machines run Windows 10 X64 with all the latest updates.
Here is a screenshot of the app folder showing the files.
UPDATE
Based on the comment from #Plutonix, here is a screenshot showing the references to my project. Missing is System.Data.SQLite.Core, which contains the interop files. There are different versions for each .Net version and OS type, so I cannot just browse for the folder inside the packages folder, besides that is a terrible hack. There should be a clean way to add the reference.
For the record, I briefly thought of that file, but I did not see it or the core and figured version 1.08 does not use it, but I guess that it does.
NOTE: I copied the SQLite.Interop.dll file manually to the VM and the project loaded. Procman was not that helpful, too much information perhaps, though I filtered out everything but my app. Anyways, the problem is how to get a reference to the SQLite core.
UPDATE 2
Uninstalling all sqlite components from NuGet and then reinstalling SQLite does not add reference the core in the project, annoyingly.
UPDATE 3
This SO article (in the answer) states the problem. Basically, NuGet for whatever messed up reason correctly "requires" the core, but then does nothing with it. As such, NuGet does not distribute a required file. I saw the answer to "copy" the X86/X64 folders, etc.
I, for one, name that as a serious defect/bug in the NuGet SQLite package. Yes, this question becomes sort of a duplicate of the referenced question, if you know the answer, but I did not, so it is not. I never received any error message on the interop DLL.
(I want someone to come up with a better answer, as mine is a hack.)
Until a real elegant and proper solution comes along, I thought of this workaround. Add the following to the Post-build event command line" onBuild Events` tab of the project settings.
Anyone using my command line would obviously have to set net46 to the .Net version used in the project and set the SQLite version, here 1.0.108.0 to whatever the version will be.
robocopy "$(ProjectDir)\..\packages\System.Data.SQLite.Core.1.0.108.0\build\net46\$(PlatformName)" $(TargetDir) SQLite.Interop.dll
Here is a screenshot.
NOTE
I also thought of conditional logic to the project file that would include a DLL, but that was more complicated than a simple RoboCopy.

Visual Studio 2015 build class library portable error

I am rebuilding a class library (portable).
The Library --> Targeting is set to:
The errors list shows in the first position:
Severity Code Description Project File Line
Error CS0234
The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)
If a do a rebuild I get the error:
Severity Code Description Project File Line
Error There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll", "x86". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.
NOTE If I change the targeting (but I don't want to do it, only for test!)
to NET Framework 4.0.3 the errors go away and all rebuilds fine!
I have tried to Clean/Rebuild the whole solution, close/reopen VS, restart Windows...
Yesterday I have updated all the VS2015 Extensions and Updates, that has updated also a lot things (Azure, VS restarted, ecc...)
The using statements:
Question:
1) What could have happened that has corrupted my VS installation?
2) What test could I do?
EDIT
In the file system, under *c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETPortable*
I have these folders:
v4.0\
v4.5\
v4.6\
v5.0\
The project is a Class library that essentially contains .resx and only one .cs file.
All the .resx files shows errors, if I click on one of them I get:
Could not resolve mscorlib for target framework
'.NETPortable,Version=v4.0,Profile=Profile328'. This can happen if
the target framework is not installed or if the framework moniker is
incorrectly formatted.
EDIT2
In Configuration Manager if I set target to x86
the error mismatch goes aways
BUT
the other errors remains:
essentially that seems that
using System.--> points to a different location ??!!
Before System.Linq was found.
If I change Targeting-->Net 4.0.3 System.Linq is found
If I change Targeting-->Net 4.0 System.Linq is missing!
Where the hell is VS searching this System.Linq?
Question: 1) What could have happened that has corrupted my VS
installation?
Yesterday I have updated all the VS2015 Extensions and Updates, that has updated also a lot things (Azure, VS restarted, ecc...)
As you stated you have applied updates. This has somehow caused an assembly conflict . Based on the error message it appears you are trying to build a x64bit or any cpu configuration build and it is throwing an error . Try changing your build to target x86.
If it compiles as x86 then this means you have no choice in the matter unless you find the dependent x86 assemblies and compile it separately or update the code to 64 bit. Otherwise there is nothing you can do to run your process x64 and any cpu even if management says it's got to be. A 64 bit processor can run both 32 and 64. A 32 bit processor can run only 32 natively.
2) What test could I do?
The first thing you can do is a diff of your local workspace and what is in source control. Hopefully you are using source control and do not check in broken builds. See what has changed if anything. Possibly rollback .
If no code has changed from source then have a peer try and build it.
You could uncheck all targets in your picture and compile your solution. Adding back the targets after getting a successful build and narrowing down the target that is the root problem.
If all else falls uninstall your updates or restore your PC from a last know restore point.
When updating references it is always good to test and makes sure nothing breaks.

AppHarbor build doesn't fail, is missing dlls

I have a very small, simple ASP.NET MVC app (MVC 4 I think. .NET Framework 4) it consists of one controller with one action serving one page.
I'm deploying it on AppHarbor, pushing it with git on my local machine, I've never had problems running it locally and it has never had build issues/errors on AppHarbour but every now and then a new build (with no relevant change in my mind) will start throwing the following error:
Could not load file or assembly 'Microsoft.Threading.Tasks,
Version=1.0.12.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or
one of its dependencies. The system cannot find the file specified.
Looking into this the top answer here sorted it, I removed the dependent assemblies listed and it worked again. But then it came back. Tried a lot of different suggestions, it has always used nuget, tried removing everything and re-installing, it started working again when I wasn't even sure what I'd changed and now it isn't working again. Today I switched it to NuGet Package Restore as outlined here but that hasn't made any difference.
I can re-deploy the last working build, what I notice comparing working/not working builds downloaded from AppHarbor is that the Web/App.configs are identical (no dependent assembly entriy for this) but the Microsoft.Threading.Tasks dlls and xmls (including Extensions and Extensions.Desktop) are not in the broken build (in the working build they appear in the root and in the bin)?
In the project the dlls are linked from the packages folder for the app and Copy Local is True, they aren't a direct dependency of the Web App but of the Google Calendar API its using.
Update
On the back of writing the answer I've looked more closely at the build logs and noticed a distinct difference between a working and not-working build.
The Microsoft.Threading.Tasks.dll is not a direct dependency, its required by Google.Apis.Gmail.v1.dll, in a working build the build log will contain (see the bottom line copying Microsoft.Threading.Tasks.dll):
\Google.Apis.Gmail.v1.dll".
Copying file from "D:\temp\voz3srsa.vhb\input\TwitterBot\packages\Google.Apis.1.9.0\lib\net40\Google.Apis.PlatformServices.dll"
to "D:\temp\voz3srsa.vhb\output\Google.Apis.PlatformServices.dll".
Copying file from "D:\temp\voz3srsa.vhb\input\TwitterBot\packages\TweetSharp.2.3.1\lib\4.0\Hammock.ClientProfile.dll"
to "D:\temp\voz3srsa.vhb\output\Hammock.ClientProfile.dll".
Copying file from "D:\temp\voz3srsa.vhb\input\TwitterBot\packages\log4net.2.0.3\lib\net40-full\log4net.dll"
to "D:\temp\voz3srsa.vhb\output\log4net.dll".
Copying file from "D:\temp\voz3srsa.vhb\input\TwitterBot\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.dll"
to "D:\temp\voz3srsa.vhb\output\Microsoft.Threading.Tasks.dll".
A not-working build will have a different dll in its place (see the bottom line again, Microsoft.Web.Infrastructure.dll):
\Google.Apis.Gmail.v1.dll".
Copying file from "D:\temp\0kzqakoc.4jo\input\TwitterBot\packages\Google.Apis.1.9.0\lib\net40\Google.Apis.PlatformServices.dll"
to "D:\temp\0kzqakoc.4jo\output\Google.Apis.PlatformServices.dll".
Copying file from "D:\temp\0kzqakoc.4jo\input\TwitterBot\packages\TweetSharp.2.3.1\lib\4.0\Hammock.ClientProfile.dll"
to "D:\temp\0kzqakoc.4jo\output\Hammock.ClientProfile.dll".
Copying file from "D:\temp\0kzqakoc.4jo\input\TwitterBot\packages\log4net.2.0.3\lib\net40-full\log4net.dll"
to "D:\temp\0kzqakoc.4jo\output\log4net.dll".
Copying file from "D:\temp\0kzqakoc.4jo\input\TwitterBot\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll"
to "D:\temp\0kzqakoc.4jo\output\Microsoft.Web.Infrastructure.dll".
Looking into dlls missing in the build I found this answer but I have tried a command prompt build locally and it works fine.
Update 2
Also in trying to solve this I had noticed a comment on the build (not a warning) around reference versions:
1> Consider app.config remapping of assembly "Newtonsoft.Json, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" from Version "4.5.0.0" [C:\Users...\packages\TweetSharp.2.3.1\lib\4.0\Newtonsoft.Json.dll] to Version "6.0.0.0" [C:\Users...\packages\Newtonsoft.Json.6.0.6\lib\net40\Newtonsoft.Json.dll] to solve conflict and get rid of warning.
1>C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(1605,5): warning MSB3247: Found conflicts between different versions of the same dependent assembly.
Couldn't get a remapping that sorted it but did get this where adding an app.config (which makes no sense for a web app) redirect fixed it where the redirect in the web.config didn't. This did stop the build issue but made little sense.
I took this to the AppHarbor support forum as this didn't get any response here, Build succeeding but missing dll and they were very helpful and it now looks like it is resolved.
Although in Visual Studio 2012 Professional all references were marked as Copy Local True, they did not have the True tag so I added these by hand for the three libraries in question. And that was it, DLLs copied.
There are a lot of links around this discrepancy, that MSBuild needs them (although I had tried an MSBuild build and it was fine), Visual Studio doesn't insert them by default (may appear if you toggle the setting false and then true) and it manifests in not copying references-of-references.
Stack Overflow question, see highest voted answer not accepted hack
Raised with Microsoft and closed as not reproducible

Categories