C# Classes from Module could not be loaded - c#

I'm getting an internal compiler error:
System.Reflection.ReflectionTypeLoadException: The classes in the module cannot be loaded.
What would make them not load? The error offers no help and MSDN tell you about the class throwing when they can't be loaded, not why they wouldn't be able to be loaded.
There is literally no information on what would prevent classes from being loaded that I can find, help me out?
Edit: It doesn't actually tell me at which line the exception is thrown. Not all classes are public, some are internal, but the classes that need to be exposed in order for the system to work are public (no classes other than public are used in the calling code). The DLL was compiled in VS13, and the quick console application I made alongside that in VS for testing works fine - it recognises the namespace from the DLL, and makes use of the public classes available. When I bring the DLL out of a release build and into the program I'm using it with, however, that is when I run into this error.

It looks like a simple mistake: the target platform for using the DLL with is constantly updated, and does not specify a .NET version; one normally assumes this means that it uses 'up-to-date'. Oh no, rolling back through build targets for the DLL finally yielded a working DLL. Will post this to the author of the program as a request; it helps if you know what you're working with!
TL;DR:
Wrong target version of .NET, changing to 3.0 allowed the DLL to work, with no complaining.

Related

c# Monitor changes in critical method signatures during build

I stumbled into a cooperation project, where the other part references an interface library of mine and deploys a self compiled MEF Plugin for our tool. I know which methods those guys are using and I want to monitor our library during the the build process, if the method signatures have been changed (just to make sure, noone checked in stuff, which should lead to another interface version and impairs the plugins loadability).
Actually, I have a console project in mind, where the signatures are somehow hardcoded and checked via reflection - but maybe there is a more elegant or simple way.
Any hint would be great.
Thanks in advance!
Roslyn 2.3 introduces a feature for generating reference assemblies. That is an assembly containing only public types and members. When used together with the "deterministic" feature (=> reproducible builds), the generated reference assembly remains binary identical as long as no changes to the public interface is made (implementation changes and private/internal members don't matter).
So you can add this to your csproj:
<PropertyGroup>
<Deterministic>true</Deterministic>
<ProduceReferenceAssembly>true</ProduceReferenceAssembly>
</PropertyGroup>
Until VS 2017 15.5 comes out, I suggest adding <CompileUsingReferenceAssemblies>false</CompileUsingReferenceAssemblies> to all consuming projects because the IDE (e.g. "go to definition") has some problems with this feature unless you are using the "new project system" that is used for .NET Core and .NET Standard projects. (The idea would be that projects referencing the project are only rebuilt if the public interface changes - this speeds up incremental build for large solutions when only implementations change).
These changes will create a ref folder in your output. You can then check if the checksum of the assmbly in there matches a known cheksum on each build.
I ended up creating a small console application with a try catch block, using the same interface dll and the same objects as the project partner does - compiled with the last released interface library. During execution it falls into the catch branch if the signatures got invalid (discovered by the normal .NET processes) - then the exitcode is raised with -1.
Doing all this in the post build processes, cathcing the exit code as discribed this article and breaking build automatically.
Not very happy with that solution, but got it working ... Further ideas still wanted :-)

Managed C++ class cannot be referenced from C#

The problem I am currently encountering is really weird. I try to use a Managed C++ class from a C# project but the compiler cannot find the type.
Take a look at this screenshot:
The Managed C++ project (NGervill.Gervill.Native) is referenced and according to the Object Browser it contains all required namespaces and types. In my source code I've added the using and used the class but still I get a compile error.
Now the strangest part: The other types within the Managed C++ project can be referenced. In another C# class I access the methods of the PortMixerProviderNative class. That means target platform and .net framework version are correct (.net 4.5 - x86 build).
Is Visual Studio somehow caching an old version of the Managed C++ DLL or what else can cause such a problem?
PortMixerNative is a native C++ class, not a managed class. Native classes can be exposed in the assembly metadata in some cases, usually because they are the type of a private field in a managed class wrapper, but they are not usable in any way from a C# program. Only public ref class declarations in the C++/CLI project are usable.
It isn't clear what wrapper class you are supposed to use. Not PortMixerNative. Check the vendor's manual and/or code samples or contact them if you need more help.
I finally found the solution of this problem: For some reason the cpp file implementing the PortMixerNative class was not included in the project. After adding the PortMixerNative.cpp to the project again I finally could see that there were syntax errors in this file. After fixing the errors and recompiling the .Native project I could successfully reference the class.
The strange thing is that the .Native project successfully compiled even with methods without implementations. If anybody encounters this problem too, check if all methods of the class you try to use have an implementation.

How to create a custom .NET dll loadable for Lua(forWindows)?

We are doing a project in .NET framework and want to make most of its functionalities available later for Lua scripts. I thought I could compile a dll and load it to Lua script with the help of LuaInterface. But somehow it did not work.
What DID work is the following:
require 'luanet'
luanet.load_assembly("System.Windows.Forms")
Form = luanet.import_type("System.Windows.Forms.Form")
Button = luanet.import_type("System.Windows.Forms.Button")
form1 = Form()
button1 = Button()
As you can see, here I'm loading standard assembly and types, which didn't cause much problem.
However, if I have my own dll 'LuaTest' compiled under .NET 4.0 and try to load it in LUA. It did not work. I wrote something like,
require 'luanet'
luanet.load_assembly("LuaTest")
PlanetarySystem = luanet.import_type("LuaTest.PlanetarySystem")
solarSystem = PlanetarySystem()
where 'PlanetarySystem' is a class in LuaTest. If I run this piece of code, the interpreter would say: attempt to call global 'PlanetarySystem' (a nil value).
I also tried another way to load the dll:
package.path = package.path .. ";" .. "/?.dll"
require 'luanet'
require 'LuaTest'
After run, the interpreter throws: lua: error loading module 'LuaTest' from file '.\LuaTest.dll': The specified procedure could not be found.
I'm quite a newbie to .NET framework and LuaInterface. Perhaps I did something utterly wrong. Please help me on this. Many thanks!
Edit: Perhaps I should have an 'Entry Point' for Lua in my dll to indicate that this dll is LUA loadable???
Edit: Lua not LUA. No offense to Portuguese speaking people. The Lunanet I'm using must be compatible with .NET 4.0, otherwise the first piece of code would not work.
I believe you are confusing the assembly name with being a required part of the fully qualified name of the type that you are trying to import. The error indicates that the PlanetarySystem class is a "a nil value", meaning that it likely couldn't find a class by that fully qualified name. I would be certain on the namespace that your class was in.
Second, if my first recommendation doesn't work, you may need to make your classes ComVisible so that the Lua engine can see your classes.
http://msdn.microsoft.com/en-us/library/ms182157.aspx
Try this link. I posted a solution which works fine!
If your pc is well prepared (installed lua & C#2010 e.g.) then copy the C# code to a dll project and build it. Then make sure that your dll is located in a registered directory for your lua environment and execute the lua script which is shown in the same post.
An additional note for you: I needed to use .NET 3.5 framework. With .NET 4.0 LuaInterface did not work for me.

Errors trying to load an assembly in 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.

What kind of problem can cause a TypeLoadException?

I have a big and bloated software and I want to add a new GUI element to it. The GUI element was written using XAML and WPF. I created the UI element in a separate assembly, and reference it in the big software. The two projects compiled smoothly under VS2010, but when I run my application I get a TypeLoadException.
Looking into the exception with the debugger, I get the following message : Could not load type GUI.Dashboard from assembly GUI, blah, blah. There is no InnerException nor any further detail.
The .GNU documentation says that this message appears when there is no message passed to the constructor of the exception. I assume that the producer of the exception itself does not know how it happened.
I tried using the tool Fuslogvw.exe and it effectively showed me some minor missing dependencies which are unrelated. However, it cannot find any information on this very exception.
What kind of problem can possibly throw an imprecise exception like this one ? Is there a way to make Fuslogvw.exe aware of it to get some details ?
Thank you in advance,
Edit :
I effectively compiled my application with debugging symbols. The exception happens when I try to instanciate a class containing a reference to the problematic symbol. i.e.:
class SomeClass
{
GUI.Dashboard dashboard;
}
And the call trace looks loke this:
at SomeClass..ctor()
at MainClass.Main() din MainClass.cs:line 42
Possible issues include:
The assembly you reference is x64 only and your consumer is x86 or AnyCPU on a 32-Bit CLR
Your consumer assembly was compiled against a different version of the referenced assembly
You can try to use FusLogVW to turn on assembly binding logging and check the logfile for more information about what failed.
TypeLoadException is thrown when the common language runtime cannot find the assembly, the type within the assembly, or cannot load the type.
TypeLoadException uses the HRESULT COR_E_TYPELOAD, that has the value 0x80131522.
For a list of initial property values for an instance of TypeLoadException, see the TypeLoadException constructors.
Source: MSDN
Just to add another answer to this:
we had a C++ client calling a .NET COM dll.
The developer of the .NET dll renamed the namespace enclosing the C# classes, and although the progid remained the same in both the class attribute and in the C++ calling code, the runtime failed to load the object resulting in this error.
I finally found a reason for this bug : apparently, in some cases referencing a .exe file does not work properly. Some methods and classes loads OK but some fails. In another project, referencing this .exe file cause no problem.
Switching to the .dll format solved all linking problems. I think this is a bug in the CLR.

Categories