Error loading DLL - Console App - Visual Studio Community 2022 - c#

I'm trying to load a third-party DLL in a Console App project created in Visual Studio Community 2022. Environment is Windows 10. I have tried both .NET 5.0 and 6.0
No matter what I have tried, I get the error "Unhandled exception. System.BadImageFormatException: Bad IL format. The format of the file is invalid."
I have checked and normally this error is because I'm trying to load a x64 DLL in a x86 app or viceversa, but I know this is not the case because:
I have been able to load this specific DLL in C (using LoadLibrary() in Codeblocks) and JAVA (using JNA), configuring the applications for a x86 target platform. I have configured this console app for a x86 target platform as well in properties.
The DLL when loaded starts writing to a log file. The log file destination is fixed, and can't be deactivated. Whenever I run my app, I see the log being written to. I realized that the log was being written to by using Sysinternals' Process Monitor.
The log only says
INFO: 2.23.00 12:14:27(00000015) PCLService.cpp:138 [22.11.2021] logCreate
INFO: 2.23.00 12:14:27(00000000) PCLService.cpp:141 PDA_Manager: DllMain attached
INFO: 2.23.00 12:14:27(00000000) PCLService.cpp:145 PDA_Manager: DllMain detach
Normally, the detach should only happen when the DLL is unloaded/program is closed. Here it happens automatically. It is like the program can't keep the DLL loaded, giving the error message.
Here is my current code.
using System;
using System.Reflection;
namespace ConsoleApp5
{
internal class Program
{
static void Main(string[] args)
{
//var DLL = Assembly.LoadFile(#"C:\Documentacion\VisaNet\Proyectos\Simpler\bin\Debug\x86\PCLService.dll");
var DLL = Assembly.LoadFrom("PCLService.dll");
Console.ReadLine();
}
}
}
I have tried both LoadFrom() and LoadFile(). Even tried Load(), but the error is different about additional information that I don't know how to get.
I have checked Assembly Binding Log Viewer (fuslogvw.exe) and Process Monitor. I do not see any obvious problem.
I assume that whatever error happens, it did happen by the time of the last 4 entries about PCLService.log, which must the ones writing in the DLL log about detaching, because there are no more entries about the log in Process Monitor.
While I'm a experienced programmer, I'm totally new to Visual Studio / C#
Any assistance would be welcome.

To call a native dll, you have to use [DllImport] together with a function prototype. Any of the Assembly.LoadXXX() methods are for managed libraries only. Maybe Using a 32bit or 64bit dll in C# DllImport will help you.

Related

Why does using SQLite in Azure Functions give me a DLLNotFoundException?

I'm trying to write a timer-triggered Azure Function that downloads a bunch of data and processes it into a SQLite database. I've written code that does this and runs fine on my own machine. But, the same code in Azure yields a DllNotFoundException, complaining that the system can't load "e_sqlite3."
Here is the full error message (for the inner exception):
Exception while executing function: FnordFunction
Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception
while executing function: FnordFunction --->
System.TypeInitializationException : The type initializer for
'SQLite.SQLiteConnection' threw an exception. --->
System.DllNotFoundException : Unable to load DLL 'e_sqlite3': The
specified module could not be found. (Exception from HRESULT:
0x8007007E)
at
SQLitePCL.SQLite3Provider_e_sqlite3.NativeMethods.sqlite3_libversion_number()
at
SQLitePCL.SQLite3Provider_e_sqlite3.SQLitePCL.ISQLite3Provider.sqlite3_libversion_number()
at SQLitePCL.raw.SetProvider(ISQLite3Provider imp)
at SQLitePCL.Batteries_V2.Init()
at SQLite.SQLiteConnection..cctor()
End of inner exception
Here are the steps to reproduce:
In Visual Studio 2017, I created an Azure Function project using the latest template.
I added my code files to the project, and edited the "Run" method to call the code.
Using NuGet, I added sqlite-net-pcl, and some other libraries I need. (I've also tried this with EntityFrameworkCore, using SQLite; that didn't work either).
Build
Publish
Run. Failure.
The problem might be that my code is wrong--but it works fine when I just make a console .exe.
The problem might be that VS2017 is not bundling the correct dll for SQLite when it builds. I'm not sure how to fix that. I've seen from other searches that the same error message pops up when the platform target is set to "Any CPU," but changing that to x86 or x64 does not fix the problem.
The problem might be that the SQLite libraries I have tried won't run in the Azure Functions sandbox. If so, are there any simple SQLite libraries that will run in the sandbox?
Thanks in advance...
The problem is that when running in a Function App, native binaries can't be automatically loaded from your bin folder, so it's not finding the DLL.
One way to solve this is to drop it in your D:\home\site\tools folder (e.g. using Kudu Console), as that folder is automatically place on the PATH.

Unable to load DLL when process not started in the current directory (.NET Core 2.1.4)

This is a .NET Core 2.0 console app that loads a C++ dll (DllImport). It "works on my machine" (windows 10, .NET Core 2.1.103) in all situations.
But when deployed in the staging env. it does not work if the exe is not executed from its current directory: if I run the executable from the parent directory, I get a System.DllNotFoundException: Unable to load DLL '***' : The specified module could not be found. (Exception from HRESULT: 0x8007007E)
The problem is that this process is started this way and I have no other choices! (i.e. started from a parent process located in a parent folder)
I have tried to add a SetCurrentDirectory + SetDllDirectory in the Main method w/o any effects.
To summarize:
If the app is started from the CLI using dotnet ***.dll, it works from any directory
If the app is started the same way from another process using Process.Start(), it fails
If the app is published as an executable, it works using the CLI from its current directory
But it fails from the parent directory and of course, also using Process.Start() (which is the final use case)
Last detail: the DllImport is done in the context of an Activator.CreateInstance (using Windsor)
A bit upset...
As Thomas suggested, it was related to the c++ runtime: it works in all situations if dependencies are all present in the current executable directory. A bit confusing as it worked in some cases without copying these dependencies (maybe a problem with the runtime installation)

Application-internal exception in Windows.UI.Xaml.dll

I'm working on a Windows 10 Store Windows Universal app using Visual Studio 2015 Community, c#, and XAML. It is decompressing a compressed file and displaying images found therein.
The build provides 0 warnings.
The debug version runs fine regardless of input file size.
The release version runs fine with typical input file sizes.
For large input file sizes (~100 1 megapixel images), the release build crashes consistently with 'Unhandled exception at 0x55E9A305 (Windows.UI.Xaml.dll) in appname.exe: 0xC000027B: An application-internal exception has occurred (parameters: 0x127DC468, 0x00000005).'
The crash occurs when the user tries to display the second image. All decompression is complete and all the bitmaps have been created by this time.
I've fiddled with the Build settings and narrowed down the difference to the option 'Compile with .NET Native Tool chain'. If that option is checked, the application crashes. If that option is unchecked, the application runs fine.
All told, the application is using about 400 MB of heap so although not small it isn't near the capacity of the machine.
"So uncheck the option!", I hear you cry. Unchecking the box leads to the certification failure shown below:
FAILED
Supported APIs
• Error Found: The supported APIs test detected the following errors:
-API OpenSemaphore in api-ms-win-core-synch-l1-1-0.dll is not supported for this application type. System.Threading.dll calls this API.
-API CreateSemaphore in api-ms-win-core-kernel32-legacy-l1-1-0.dll is not supported for this application type. System.Threading.dll calls this API.
-API ExecuteAssembly in uwphost.dll is not supported for this application type. StupidTest.exe calls this API.
-API DllGetActivationFactory in uwphost.dll is not supported for this application type. StupidTest.exe has an export that forwards to this API.
An empty project suffers the same failure if Compile .Net Native tool chain is not selected.
So my questions:
Must Universal Apps use Compile .Net Native tool chain?
Is there any documentation on the meanings of the parameters in the internal exception or somewhere else I can turn to troubleshoot?
In short, any advice on getting out the "It doesn't work if selected, but you must select it to get certified" dilemma I find myself in?
I struggled with this issue also for the past few days, and I've found the answer!
So if you haven't updated Visual Studio 2015 to Update 1, do it. Because this error is a bug in the compiler and after the update you will be able to build the project with the Compile .Net Native tool chain option selected.
And yes, those four errors that the WACK tool picks up, is because of compiling your project without checking the .Net Native tool chain option in the Build menu of the Package.appxmanifest file.

Winforms CL20R3 with CefSharp Project

I have a similar problem to this question C# windows appication Event: CLR20r3 on application start
The error is like this:
Application: MantenedorPlanesMain.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
Battery:
in CefSharp.Example.CefExample.Init ()
in CefSharp.WinForms.Example.Program.Main ()
But only on some machines, for example, on my computer I can use the program without any problem and in a computer of my office too.
I tried to find the source of the problem here in stackoverflow and realized that the error was caused by a cs file not found, but is within the project.
When I go to see CefSharp.WinForms.Example.Program.cs and comment the line of CefSharp.Example.CefExample.Init() throws me the same error in another file.
I tried everything, even the CopyLocal = true and x86, but still not working. I think there may be a problem with the system language, which is the only common factor of the machines that worked, Spanish language system.
any ideas?
In this context FileNotFoundException usually means you need to install VC++ or that you compiled in Debug mode (You need to build in Release mode when running on a machine without VS installed)
https://github.com/cefsharp/CefSharp/blob/master/NuGet/Readme.txt#L18
Also See the Note within https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#6-how-do-i-include-the-visual-studio-c-2012-redistributables-on-the-target-app

Unable to load dll file - exception 0x8007007E

I'm working with National Instruments Measurement Studio in C#, and I've come across a bit of a problem in deploying my application to a particular computer (running Windows 7). I've tried asking on the National Instruments forums, but haven't got any solutions yet - could anyone here give me some tips?
Essentially, I have deployed this application several times on a number of computers, but in this particular case I receive an error when running the program -
"System.DllNotFoundException: Unable to load DLL 'nianlys.dll': The specified module could not be found. (Exception from HRESULT: 0x80070007E)
I have ensured that nianlys.dll is present in C:\Program Files
(x86)\National Instruments\Shared\Analysis.
I have ensured that libiomp5md.dll and LV110000_BLASLAPACK.dll, the files from mkl.msm (nianlys.dll has a dependency on mkl.msm), are present. nianlys.dll also has a dependency on nimetautils.msm, but I'm not sure which dlls are included in this.
I have ensured the program is installed by running the setup.exe as an administrator (as opposed to running the .msi that is generated, see here).
I have ensured the computer in question is up to date with updates to the .net framework via windows update.
I have tried reinstalling the program several times, sometimes with a freshly-recompiled installer.
I have tried adding in the 64 bit nianlys.msm into the setup project manually - this throws an error because the TargetPlatform property of the setup project is set to x86. The 32 bit version is, of course, already present in the detected dependencies.
Interestingly, taking a copy of nianlys.dll from C:\Program Files (x86)\National Instruments\Shared\Analysis and inserting it into the directory the program is installed in throws up a different error - in this case, the error is:
"An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)"
Taking a copy of the 64 bit version of nianlys.dll from another computer (default location C:\Program Files\National Instruments\Shared\Analysis) and inserting it into the directory the program is installed in throws up a third type of error - "System.DllNotFoundException: Unable to load DLL 'nianlys.dll': A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A)". It should be noted that this .dll was present before installing the program on the machines that the program works on, but is not present on the target computer that is throwing up problems.
Taking the same 64 bit nianlys.dll and inserting it into the location it was found on on another computer, C:\Program Files\National Instruments\Shared\Analysis, does not solve the original error.
Even more interestingly, I have tried to reproduce the error on a computer on which the program works - removing the x64 version of nianlys.dll throws up the original HRESULT: 0x80070007E error, whereas removing the x86 version causes a windows installer to appear when running the program.
On a computer upon which the program works with no problems, the windows task manager does not seem to indicate that the program is 32 bit (with the *32 suffix on the program name), despite the target platform being set to x86. It seems from all this that there is some issue with the nianlys.dll being used in both its x64 and x86 versions, despite the target platform only being x86.
I'm running out of ideas about what kind of thing I could try to solve this problem.
I suspect that even though the setup is for X86, the project itself is AnyCPU and thus runs as a 64bit process on 64bit systems and as a 32bit process on 32bit systems. As you said your DLL is in the Program Files (x86) folder I assume it is 32bit only, so you should compile your application explicitly as x86, too. It is your bullet #7 that leads me to this conclusion.
Just copying the nianlys.dll 64bit DLL doesn't seem to work as it seems to rely on other DLLs it then can't find. (bullet #8).
It may caused by the dependents of nianlys.dll are not found. You can diagnose this problem with the process monitor , one of the system internal tools. It can capture the loading/unloading DLL activities, so if something wrong, you can find it in the log.
Be sure to use the filter when use this tool, otherwise the log file will be huge.

Categories