Errors trying to load an assembly in C# - c#

Ok this question is more about understanding what the issues are as I dont think anyone will be able to tell me how to fix the problem.
I am writing a .net 4 application and I have a 3rd party dll ( hasp dongle protection ) that I want to reference.
Visual studio allows me to create the reference fine and use classes contained within the dll within my code.
The first issue occurs when the program is run and the dll is actually loaded. I then get the following error.
System.BadImageFormatException: Could not load file or assembly
'hasp_net_windows.dll' or one of its dependencies. is not a valid
Win32 application
This weblink states how to fix this error. Coud someone expalain what the issue is and why im getting it.
After following this advice I then set the main project build to x86 and I then get another error replacing the other. The new error is:
System.IO.FileLoadException: Mixed mode assembly is built against
version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0
runtime without additional configuration information
This weblink states how to fix the error, but I dont have an app.config in my project and want to avoid having one if at all possible. If someone could explain what the issue is again that would be helpful?
Please let me know if you require anymore information.

The issue is the "bitness" of your application. Once chosen (32 bit or 64 bit) all DLLs within that process need to be the same. This exception tells me that one of your DLLs is the wrong "bitness".
You simply cannot have DLLs with different compilation targets within a given process, a process has "bitness" affinity.
If this is a third party unmanaged DLL then it is very likely 32-bit compiled.
Setting the build output as x86 for the root project (the one that creates the exe) should suffice as this will dictate the process that is created. Any other .NET projects can then simply be Any CPU and will fit in either the 32 or 64 bit runtimes.
Unfortunately for your second issue, the provided link is the way to solve it. There is nothing wrong with having an app.config in a project and you haven't stated why you don't want one.

The answer by Adam Houldsworth notwithstanding, I'd like to add that it is possible to do it without an app.config. However, this requires a tiny bit more work and potentially a proper understanding of COM interop. Whether it's worth the trouble is up to you of course ;).
You can set useLegacyV2RuntimeActivationPolicy programmatically by using the ICLRRuntimeInfo::BindAsLegacyV2Runtime method.
A quick rundown on how to do this is posted in this blogpost. Take note of his warning though, which might make you think twice in using this approach:
This approach works, but I would be very hesitant to use it in public
facing production code, especially for anything other than
initializing your own application. While this should work in a
library, using it has a very nasty side effect: you change the runtime
policy of the executing application in a way that is very hidden and
non-obvious.

I cannot use an app.config file because the assembly is loaded via COM from a native program.
I found the library that supports .net framework 4.0. here. In this scenario, no other solutions had worked for me.

Related

COM-Interop assembly not finding a native (.Net) dependancy when called from Vb

I have a C# COM-Interop assembly which I am calling from a Visual Basic 6 application. This assembly makes HTTP requests to send and retrieve JSON.
The assembly works fine when being testing with a C# test client.
However, when using it from with the VB6 app, the following error is returned:
"Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified."
The Newtonsoft.Json.dll is located within the same folder as the COM-Interop DLL (TLB).
Does the Newtonsoft.Json.dll need to be explicitly loaded? Or maybe placed in the GAC?
Hans provided a great explanation for why this happens. Let me offer a workaround for making this work without having to register the Json DLL in the GAC or copying it to the VB6 EXE directory.
In your COM-visible C# library, we can tell the .NET runtime environment to search for the Json DLL in the directory of the C# library instead of the "usual" paths. We do that by attaching our own handler to the AssemblyResolve event:
AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =>
{
// We only want this workaround for one particular DLL
if (e.Name != "Newtonsoft.Json")
return null;
var myLibraryFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var path = Path.Combine(myLibraryFolder, "Newtonsoft.Json.dll");
return Assembly.LoadFrom(path);
};
Notes about this workaround:
This code only works if it is executed in your C# library before doing anything that might cause the jitter to load the JSON library. For example, neither your library nor any other .NET library in your VB6 process must call any method referencing types from the JSON library before this code is executed.
You modify the the behaviour of the whole process, not just your library. If your VB6 process uses another library using JSON, your "redirect" affects the other library as well.
This is a standard DLL Hell problem, it is caused by using the /codepage option for Regasm.exe. Or, more commonly, the Project > Properties > Build tab > "Register for COM interop" checkbox. Both do the same thing, they write the path to the DLL into the registry. It is a very good option to use when you are busy developing and testing the project, it avoids having to re-register the DLL into the GAC every single time you make a change.
But what it does not do is help the CLR find any dependencies. The normal probing rules remain in effect, it looks for an appname.exe.config file in the directory where the EXE is stored. And first looks in the GAC, next in the EXE path for dependencies. Configuration remains under control of the usual victim of DLL Hell, whomever has to maintain the EXE. Frequently the end-user. So, explicitly, it does not look in the directory where your [ComVisible] DLL is stored.
It is the mild kind of DLL Hell, just a plain file-not-found mishap. Much milder than the nasty kind, finding a file with the right name but the wrong version. In general a strong problem with Newtonsoft.Json.dll, there are about 35 versions in the wild. Having so many versions and it being such a popular library also begets the other kind of nastiness, the program using another COM server that also uses the DLL. But almost inevitably a different version. Tends to happen long after you declared your project finished. One of them is going to lose, 50-50 odds that it is you. 100% odds for the end-user.
Yes, the GAC solves this problem. Each library gets the version they ask for. Ideally Newtonsoft would solve this problem for you with an installer that deploys the DLL into the GAC. But it is not the kind of commitment that open source library writers ever want to provide. They want (and need) to make it your problem. Microsoft does this, but they also have Windows Update to ensure that critical bug and security fixes get deployed. And have a large number of people working on making sure that any new revisions are always backwards compatible with the original release so the version number doesn't have to change.
Do note that you can take advantage of Microsoft's commitment. You can also use the DataContractJsonSerializer and JavascriptSerializer classes to get this job done. Part of the framework, they rarely get it wrong.
Meanwhile, do keep mind that is just a file-not-found problem. You don't have to use the GAC on your dev machine, and it is better if you don't, it is just as easy to copy the file into the right place to keep the CLR happy. Which is the same directory as your VB6 test program. And, extra quirk with VB6, into C:\Program Files (x86)\Visual Studio\VB6 if you want to use the VB6 debugger. Do use the GAC when you deploy.

Unable to load "lpsolve55.dll" in VS2015 on 64-bits OS

For a project I am working on, I need to solve a mathematical model. I chose to do this using Microsoft.Solver.Foundation and the SolverFoundation.Plugin.LpSolve plugin. Both associated .dll files for these extension seem to work fine, as VS2015 recognizes and references them without a problem and compiles and runs my program without errors.
This is however up untill I try to actually solve my optimization, which needs "lpsolve55.dll" to work. I have downloaded this dll and put it in my project's bin/Debug folder, but for some kind of reason VS2015 just doesn't recognize it. I.e.
I can't reference it by simply browsing to it from my "Add Reference" tab.
It's impossible to (un-)register it via the regsvr32 cmd-prompt application, as it doesn't have any DLL (Un-)registry entry points.
The TlbImp.exe cmd-prompt application can't handle it.
So basically, after discovering the above (after trying the most-common internet solutions), I still feel quite dissatisfied to get the error message while I try to solve the optimization -
Unable to load DLL 'lpsolve55.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
The wierd part is also that I have another project in which I solve a similar problem, where there are absolutely no problems at all using lpsolve55.dll....
Some quick facts:
I reference .NET framwork 4.5.2. I have changed it to 4.5 as well as 4.0, but this didn't change anyting.
For as far as I can tell, the bin/debug folder of my projects are identical.
I am working on a fully updated windows 10 OS, 64 bits, while using visual studio 2015.
My question would thus be whether or not some of you have encountered a similar problem and if you were able to solve it in some way.
Highly appreciated!
After some careful analysis, I have found the answer to the problem. To be honest, as most things are, it was quite simple in the end. The lpsolve55.dll wasn't recognized because I didn't have my new bin-folder in the Path, which I did have with my old project. I simply forgot.
On a further note however, after the lpsolve55.dll directory was added to the path, I still got an error telling me there was no model to be found that could solve my directive. Since the error occured when I was calling the LPSolverDirective(), some research landed me on the following page:
http://lpsolve.sourceforge.net/5.5/MSF.htm
Above page gives a complete and stable way of how to acces lpsolve55.dll using the LPSolverPlugin straight out of Microsoft.Solver.Foundation.dll. After following the method in the link that involves editing my projects' bin/Debug and bin/Release folders, I got the LP model up and running within no-time.
Morale of the story - read the documentation. I am a bit of a beginner in programming entire multi-project solutions and using customly-added dlls, but hopefully this helps someone else experiencing the same. In the end, I learned a lot by simply trying different methods of getting it to work, so no time was wasted.

Approach to obfuscate an embedded dll in a WPF application

I have a WPF application whose output is a.exe. This application is dependent on an external b.dll (whose source code I have access to).
Requirements:
The output should only be a.exe which should contain the dll. I don't want to provide my users with a separate dll (if it can be avoided)
I should be able to obfuscate the code. (I don't want anyone to be able to modify it).
Approaches tried:
I embedded b.dll inside a.exe, it worked. But I was not able to obfuscate the exe as it gave an error that it was unable to find b.dll.
I obfuscated a.exe and b.dll but it did not work. It was unable to find b.dll.
Alternate approach :
Is there any way that I can perhaps add the spruce code of b.dll to my project and have the dll be compiled to the exe itself rather than a separate dll.
Is it possible to make this alternate approach work or are there any other ways ?
If nothing works, I know that I can compile a and b separately, obfuscate a and provide b as a separate file (what I'm trying to avoid).
Apologies for the formatting issues, if any, I'm using the android app. Let me know if you need any details.
I have had great success with Eazfuscator.Net in the past.
http://www.gapotchenko.com/eazfuscator.net
To run it from the command line enter the following command:
Eazfuscator.Net.exe -n a.exe b.dll
It will combine the two files into a single exe. The main program will be able to access the dll.
You can even set up Visual Studio so that the command line above runs as a post compile event.
Assembly embedding may seem quite confusing, so here is how it's usually done:
The dependencies are obfuscated if needed.
The target assembly is obfuscated. At this point, the obfuscator is also instructed to embed certain dependencies as a part of obfuscation process.
As a result, the embedded assemblies are stored as a resource of the target assembly.
In order to load dependencies at runtime, obfuscators usually install a handler for AppDomain.AssemblyResolve event that is raised by CLR when it fails to resolve an assembly automatically.
The handler extracts and loads an embedded assembly from the resource.
That's it. A good obfuscation tool allows achieving that quite easily. I don't see why it wouldn't work in the case with WPF application. If there are problems, I would recommend contacting product support.
Another option is assembly merging. Unlike embedded, the merged assemblies become an inseparable part of the target assembly code. For this reason, the assembly merging often helps to achieve a better obfuscation coverage and application startup time comparing to embedding. Although it may look a better option, merging may sometimes break the application functionality.

Debugging "Could not load file or assembly" that only happens on some computers

So I recently updated my software and with the new version I supply a new dll-file, lets call it My.dll. Now, the old version works just fine on every computer I have tried.
The problems began with the new version. Specifically, so far on at least one computer, it states that "Could not load file or assembly My.dll". This even happens when I have dropped a copy of the software on a network drive and run the software directly from there. It works on every other computer but one, which still gives the exact same error where other computers work fine.
The dll in question is even in the same directory as the executable, so I'm really quite bummed here. I tried to google around a bit as well, but all the issues I found were related to ASP.NET specifically. Any ideas on how to go about finding the problem would be much appreciated.
It is possible that the computer in question has a DLL added to it's Global assembly cache. This would take priority over the DLL in the same folder.
More information about the GAC: http://msdn.microsoft.com/en-us/library/yf1d93sz(v=VS.100).aspx
Is there an old copy of the DLL lying around? Perhaps with a different name? I had a similar issue when I changed the name of a dll. Internally, the namespaces were the same.
In my case, an older version of the DLL was still there. .NET got confused with two assemblies in the bin directory having the exact same namespaces and classes, couldn't decide on which to load, and threw an exception.
Removing the older version of the dll solved the issue.
Use the Assembly binding log viewer and set it to log failures. This will give you some clues as to why it is not loading.
You could take a look at the error log using the Assembly Binding Log Viewer. First you have to turn on logging.
--Right Click on Project
--Goto Properties->Build tab
--Change Platform and Platform Target to Any CPU, Save and run

C# to C++/CLI to C DLL System.IO.FileNotFoundException

I'm getting System.IO.FileNotFoundException: The specified module could not be found when running C# code that calls a C++/CLI assembly which in turn calls a pure C DLL. It happens as soon as an object is instantiated that calls the pure C DLL functions.
BackingStore is pure C.
CPPDemoViewModel is C++/CLI calling BackingStore it has a reference to BackingStore.
I tried the simplest possible case - add a new C# unit test project that just tries to create an object defined in CPPDemoViewModel . I added a reference from the C# project to CPPDemoViewModel .
A C++/CLI test project works fine with just the added ref to CPPDemoViewModel so it's something about going between the languages.
I'm using Visual Studio 2008 SP1 with .Net 3.5 SP1. I'm building on Vista x64 but have been careful to make sure my Platform target is set to x86.
This feels like something stupid and obvious I'm missing but it would be even more stupid of me to waste time trying to solve it in private so I'm out here embarrassing myself!
This is a test for a project porting a huge amount of legacy C code which I'm keeping in a DLL with a ViewModel implemented in C++/CLI.
edit
After checking directories, I can confirm that the BackingStore.dll has not been copied.
I have the standard unique project folders created with a typical multi-project solution.
WPFViewModelInCPP
BackingStore
CPPViewModel
CPPViewModelTestInCS
bin
Debug
Debug
The higher-level Debug appears to be a common folder used by the C and C++/CLI projects, to my surprise.
WPFViewModelInCPP\Debug contains BackingStore.dll, CPPDemoViewModel.dll, CPPViewModelTest.dll and their associated .ilk and .pdb files
WPFViewModelInCPP\CPPViewModelTestInCS\bin\Debug contains CPPDemoViewModel and CPPViewModelTestInCS .dll and .pdb files but not BackingStore. However, manually copying BackingStore into that directory did not fix the error.
CPPDemoViewModel has the property Copy Local set which I assume is responsible for copying its DLL when if is referenced. I can't add a reference from a C# project to a pure C DLL - it just says A Reference to Backing Store could not be added.
I'm not sure if I have just one problem or two.
I can use an old-fashioned copying build step to copy the BackingStore.dll into any given C# project's directories, although I'd hoped the new .net model didn't require that.
DependencyWalker is telling me that the missing file is GPSVC.dll which has been suggested indicates security setting issues. I suspect this is a red herring.
edit2
With a manual copy of BackingStore.dll to be adjacent to the executable, the GUI now works fine. The C# Test Project still has problems which I suspect is due to the runtime environment of a test project but I can live without that for now.
Are the C and C++ DLLs in the same directory as the C# assembly that's executing?
You may have to change your project output settings so that the C# assembly and the other DLLs all end up in the same folder.
I've often used the Dependency Walker in cases like this; it's a sanity check that shows that all the dependencies can actually be found.
Once your app is running, you may also want to try out Process Monitor on the code you are running, to see which DLLs are being referenced, and where they are located.
The answer for the GUI, other than changing output settings, was the addition of a Pre-Build Step
copy $(ProjectDir)..\Debug\BackingStore.* $(TargetDir)
The answer for the Test projects was to add the missing DLL to the Deployment tab of the testrunconfig. You can either do so by directly editing the default LocalTestRun.testrunconfig (appears in Solution under Solution Items) or right-click the Solution and Add a new test run config, which will then appear under the main Test menu.
Thanks for the answers on this SO question on test configurations for leading me to the answer.
The reason why this happens is because you either are loading DLLMAIN from managed code, before the CRT has an opportunity to be initialized. You may not have any managed code, be executed DIRECTLY or INDERECTLY from an effect of DllMain notifications. (See: Expert C++/CLI: .Net for Visual C++ Programmers, chapter 11++).
Or you have no native entrypoint defined wahtsoever, yet you have linked to MSVCRT. The CLR is automatically initialized for you with /clr, this detail causes a lot of confusion and must be taken into account. A mixed mode DLL actually delay loads the CLR through the use of hot-patching all of the managed entry point vtables in your classes.
A number of class initialization issues surround this topic, loader lock and delay loading CLR are a bit trickey sometimes. Try to declare global's static and do not use #pragma managed/unmanaged, isolate your code with /clr per-file.
If you can not isolate your code from the managed code, and are having trouble, (after taking some of these steps), you can also look towards hosting the CLR yourself and perhaps going through the effort of creating a domain manager, that would ensure your fully "in-the-loop" of runtime events and bootstrapping.
This is exactally why, it has nothting todo with your search path, or initialization. Unfortunately the Fusion log viewer does not help that much (which is the usual place to look for .NET CLR assembly binding issues not dependency walker).
Linking statically has nothing todo with this either. You can NOT statically link a C++/CLI application which is mixed mode.
Place your DLLMAIN function into a file by itself.
Ensure that this file does NOT have /CLR set in the build options (file build options)
Make sure your linking with /MD or /MDd, and all your dependencies which you LINK use the exact same CRT.
Evaluate your linker's settings for /DEFAULTLIB and /INCLUDE to identify any possiable reference issues, you can declare a prototype in your code and use /INCLUDE to override default library link resolution.
Good luck, also check that book it's very good.
Make sure the target system has the correct MS Visual C runtime, and that you are not accidentally building the C dll with a debug runtime.
This is an interesting dilemma. I've never heard of a problem loading native .DLLs from C++/CLI after a call into it from C# before. I can only assume the problem is as #Daniel L suggested, and that your .DLL simply isn't in a path the assembly loader can find.
If Daniel's suggestion doesn't work out, I suggest you try statically linking the native C code to the C++/CLI program, if you can. That would certainly solve the problem, as the .DLL would then be entirely absorbed into the C++/CLI .DLL.
Had the same problem switching to 64-bit Vista. Our application was calling Win32 DLLs which was confusing the target build for the application. To resolve it we did the following:
Go to project properties;
Select Build tab;
Change 'Platform target:' option to x86;
Rebuild the application.
When I re-ran the application it worked.

Categories