C# exception not being thrown/caught - c#

I am trying to load dlls into my program at runtime that match a specific assembly attribute that I have set. In order to make sure that the dll is loadable before I check its flag I have written the following method:
private bool IsValidDll(string dll) {
try {
System.Reflection.Assembly.LoadFrom(dll);
return true;
} catch (Exception ex) { return false; }
}
I can loop through dlls in my current directory and call this method to see if it will be safe to load the dll and check its assembly attributes. However, I am hitting a dll that is not throwing/catching an Exception and is still just directly crashing the program. The relevant output window information is as follows:
LoaderException: System.IO.FileLoadException: Mixed mode assembly is built against
version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information. - Adapters.Spryware.SprywareAdapter
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
I have tried catching the specific Exception (System.IO.FileLoadException) but the catch block is still skipped over and I still crash. Any thoughts?
Also, I find that this is a pretty heavy handed way of checking for my assembly attribute. Is there a way to check for my flag without having to load the dll with Reflection first?

Have to confess, I dont see why your code doesnt work either:
I made a .net 4 thing and ran and mine did catch it:
private void button1_Click(object sender, EventArgs e)
{
// foreach (String file in Directory.GetFiles("c:\\windows", "*.dll"))
String file = #"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Data.dll";
{
try
{
//System.Reflection.Assembly.ReflectionOnlyLoadFrom(file);
System.Reflection.Assembly.LoadFrom(file);
}
catch (Exception ee)
{
textBox1.Text += ee.Message + Environment.NewLine;
}
}
}
On clicking the text box reads:
Could not load file or assembly 'file:///C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Data.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format.

You can probably solve this problem and be less heavy handed by loading the assemblies into the reflection-only context.
Basically, instead of fully loading the assembly, this gives you the ability to reflect over the assembly without the ability to do things like instantiate objects. This expressly allows you to look at assemblies that are built against different .NET framework versions than the one on which your application is running.
A thorough treatment is available on MSDN: http://msdn.microsoft.com/en-us/library/ms172331.aspx

Related

Embedding SQLite.Interop.dll in C#

I have an application that has all the DLL files it needs embedded into it so that it is a standalone exe. Here is how I am loading everything now:
public static Assembly ExecutingAssembly = Assembly.GetExecutingAssembly();
public static string[] EmbeddedLibraries = ExecutingAssembly.GetManifestResourceNames().Where(x => x.EndsWith(".dll")).ToArray();
public static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
// Get assembly name
var assemblyName = new AssemblyName(args.Name).Name + ".dll";
// Get resource name
var resourceName = EmbeddedLibraries.FirstOrDefault(x => x.EndsWith(assemblyName));
if (resourceName == null) {
return null;
}
// Load assembly from resource
using (var stream = ExecutingAssembly.GetManifestResourceStream(resourceName)) {
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
return Assembly.Load(bytes);
}
}
public static void Main(string[] arg) {
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
RealMain();
}
So the first interesting thing I noticed is that it only loads the DLL files that are used in the first page. It isn't enough to put using System.Data.SQLite; at the top to get it to include System.Data.SQLite.dll, you also have to do something that touches that namespace right away.
The next issue involves SQLite.Interop.dll which it won't load into the assembly. When you try you get the following error:
Exception thrown: 'System.BadImageFormatException' in mscorlib.dll
An unhandled exception of type 'System.BadImageFormatException' occurred in mscorlib.dll
The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)
Now I could unpack the DLL and copy it to the c:\Windows\System32 directory, but since everything else is self contained, it would be nice if this was as well. I noticed this SDK that claims to be able to create it as a virtual file:
https://www.boxedapp.com/boxedappsdk/usecases/embed_system.data.sqlite.dll_dependencies.html
Is there a way to do this without the extra SDK? Or as an alternative, is there another way of creating and using SQLite databases without that DLL using a different package? I tried 3-4 different packages yesterday and didn't get anywhere.
SOLUTION
Ok, so this is disappointing that it is so easy, and yet nowhere else did I see the solution in dozens of other SO questions. On the SQLite.org website, there are a couple different downloads to choose from. When you use the NuGet package manager, you get the wrong version if what you want to do is embed everything.
To do it right, go to: https://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
On that page you will want to download the BUNDLE version. In my case that was sqlite-netFx46-static-binary-bundle-Win32-2015-1.0.112.0.zip
Manually add that as a resource, include in your application as an Embedded Resource (Those are 2 separate steps), set it to not copy to output directory and use the code from the question to have it added.

How to trigger "BadImageFormatException'?

I need to create a "BadimageFormatException" in my local to test some cacheing issue. How to create "BadImageFormatException"?
As already specified in the comments, you can just create and throw this exception:
throw new BadImageFormatException();
If you want to cause this exception naturally, then as per MSDN documentation,
This exception is thrown when the file format of a dynamic link library (.dll file) or an executable (.exe file) doesn't conform to the format that the common language runtime expects
It means that you can cause it by trying to load an invalid assembly file:
string tempPath = Path.GetTempFileName();
using (var file = File.OpenWrite(tempPath))
using (var sw = new StreamWriter(file))
{
sw.WriteLine("I am not an assembly");
}
Assembly.LoadFile(tempPath);
Thanks to #Xiaoy312 for the advice. There is a much simpler way to do this using Assembly.Load:
Assembly.Load(new byte[] { 0 });
If new to this, then one way also is to load an unmanaged assembly for example notepad.exe.
try
{
// path to notepad.exe.
string path = Environment.ExpandEnvironmentVariables("%windir%") + #"\System32\notepad.exe";
Assembly assembly = Assembly.LoadFile(path);
}
catch (System.BadImageFormatException exception)
{
// catch an exception.
}
As Notepad is unmanaged and not compiled with .Net, .net isnt very happy and throws the exception.
For interesting trivia, BadImageFormatException has nothing to do with bad image format like gifs or jpegs but its an exception when .Net attempts to load a DLL or exe which isnt compatible with CLR.
Also, all exceptions are derived from System.Exception. BadImageFormatException is just inherited from System.Exception.

why reflection.assembly loadfile doesn't load all dlls?

I am using LoadFrom(), to load dlls, but for some reason this load function doesn't work on all dlls,
i want to load 3000 dlls to get from each one the copyright attribute.
my code :
class ReverseDLL
{
private Assembly assembly;
private AssemblyDescriptionAttribute desc;
private AssemblyTitleAttribute title;
private AssemblyCopyrightAttribute copyRight;
public string getCopyright(string path)
{
try
{
//assembly = System.Reflection.Assembly.Load(System.IO.File.ReadAllBytes(path));
assembly = System.Reflection.Assembly.LoadFrom(path);//"C:\\Windows\\winsxs\\x86_microsoft.vc90.debugcrt_1fc8b3b9a1e18e3b_9.0.30729.1_none_bb1f6aa1308c35eb\\msvcm90d.dll");//path);// LoadFrom(path);
desc = (AssemblyDescriptionAttribute)
AssemblyDescriptionAttribute.GetCustomAttribute(
assembly, typeof(AssemblyDescriptionAttribute));
title = (AssemblyTitleAttribute)
AssemblyTitleAttribute.GetCustomAttribute(
assembly, typeof(AssemblyTitleAttribute));
copyRight = (AssemblyCopyrightAttribute)AssemblyCopyrightAttribute.GetCustomAttribute(assembly, typeof(AssemblyCopyrightAttribute));
}
catch
{
this.copyRight = new AssemblyCopyrightAttribute("");
}
if (this.copyRight == null)
this.copyRight = new AssemblyCopyrightAttribute("");
return copyRight.Copyright;
}
}
I don't know about the reflection problem without you providing more info (such as the error), but you could also try access the file itself:
string copyright = FileVersionInfo.GetVersionInfo(path).LegalCopyright;
This accesses the file-system meta-data (like you would see in explorer), and has the advantage of working for both managed and unmanaged dlls; but it requires that meta-data to exist (it doesn't look at the attribute).
Edit: a quick check indicates that (as expected) the compiler does check for this attribute and populate the file meta-data correctly.
Have you tried stopping on exceptions? Ctrl + Alt + E, stop on framework exceptions when they are thrown. The exception message should give you some information as to why the DLL couldn't be loaded.
Using reflection is not the optimal approach, as some of the dll may have dependencies you don't have.
Using a metadata parser can give you the things you want,
http://ccimetadata.codeplex.com/
http://www.mono-project.com/Cecil
The way Marc mentioned does not work for most .NET specific metadata.

Assembly.GetTypes() - ReflectionTypeLoadException

We implement a plugin framework for our application and load plugin assemblies using Assembly.Loadfrom. We then use GetTypes() and further examine the types with each plugin file for supported Interfaces.
A path for the plugins is provided by the user and we cycle through each of the files in the folder to see if it (the plugin) supports our plugin interface. If it does, we create an instance, if not we move onto the next file.
We build two versions of software from the one code base (appA_1 and appA_2).
Loading the plugins works well when the plugins are loaded by the application that was built at the same time as the plugin file. However if we build appA_2 and point to the plugin folder of appA_1, we get an exception when GetTypes() is called.
A basic version of our code is;
var pluginAssembly = Assembly.LoadFrom(FileName);
foreach (var pluginType in pluginAssembly.GetTypes())
{
We get a "ReflectionTypeLoadException" exception.
This is concerning because we want our application to be able to load the types of any plugin, built by anyone. Is there something we are missing?
EDIT:
After iterating through the LoaderExceptions we have discovered that there is a single file libPublic.dll that generates a System.IO.FileNotFoundException exception. The strange thing is that this file resides in the application directory and the plugin is referenced to the project file.
EDIT 2:
In the exception log we find the following
"Comparing the assembly name resulted in the mismatch: Revision Number"
A few things:
Make sure you don't have duplicate assemblies in the plugin directory (i.e. assemblies that you're already loading in your main app from your app directory.) Otherwise, when you load your plugin, it may load an additional copy of the same assembly. This can lead to fun exceptions like:
Object (of type 'MyObject') is not of type 'MyObject'.
If you're getting the exception when instantiating a type, you may need to handle AppDomain.AssemblyResolve:
private void App_Startup(object sender, StartupEventArgs e)
{
// Since we'll be dynamically loading assemblies at runtime,
// we need to add an appropriate resolution path
// Otherwise weird things like failing to instantiate TypeConverters will happen
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var domain = (AppDomain) sender;
foreach (var assembly in domain.GetAssemblies())
{
if (assembly.FullName == args.Name)
{
return assembly;
}
}
return null;
}
I realize it's a bit strange to have to tell the CLR that, in order to resolve an assembly, find the assembly with the name we're using to resolve, but I've seen odd things happen without it. For example, I could instantiate types from a plugin assembly, but if I tried to use TypeDescriptor.GetConverter, it wouldn't find the TypeConverter for the class, even though it could see the Converter attribute on the class.
Looking at your edits, this is probably not what's causing your current exception, though you may run into these issues later as you work with your plugins.
Thanks to this post I could solve the ReflectionTypeLoadException that I was getting in a UITypeEditor. It's a designer assembly (a winforms smart-tag used at design-time) of a custom class library, that scan for some types.
/// <summary>
/// Get the types defined in the RootComponent.
/// </summary>
private List<Type> getAssemblyTypes(IServiceProvider provider)
{
var types = new List<Type>();
try
{
IDesignerHost host = (IDesignerHost)provider.GetService(typeof(IDesignerHost));
ITypeResolutionService resolution = (ITypeResolutionService)provider.GetService(typeof(ITypeResolutionService));
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
foreach (var assembly in ((AppDomain)sender).GetAssemblies())
{
if (assembly.FullName == args.Name)
{
return assembly;
}
}
return null;
};
Type rootComponentType = resolution.GetType(host.RootComponentClassName, false);
types = rootComponentType.Assembly.GetTypes().ToList();
}
catch
{
}
return types;
}
You are getting an assembly version mismatch. Since your plugins refer to this libPublic.dll, you must version it carefully and in particular not bump its revision/build/etc. numbers at every compile.

InvalidCastException for two Objects of the same type

I have this weird problem that I cannot handle myself. A class in the model of my mvp-project designed as singleton causes an InvalidCastException.
The source of error is found in this code line where the deserialised object is assigned to the instance variable of the class: engineObject = (ENGINE)xSerializer.Deserialize(str);. It occurs whenever I try to add one of my UserControls to a Form or to a different UC. All of my UCs have a special presenter that accesses the above mentioned instance variable of the singleton class.
This is what I get when trying to add a UC somewhere:
'System.TypeInitializationException: The type initializer for 'MVP.Model.EngineData' threw an exception. ---->
System.InvalidCastException: [A]Engine cannot be cast to [B]Engine. Type A originates from 'MVP.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither'
at location '[...]\AppData\Roaming\Microsoft\VisualStudio\9.0\ProjectAssemblies\uankw1hh01\MVP.Model.dll'.
Type B originates from 'MVP.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither'
at location '[...]\AppData\Roaming\Microsoft\VisualStudio\9.0\ProjectAssemblies\u_hge2de01\MVP.Model.dll'
...
So I somehow have two assemblies and they are not accessed from my project folder, but from a VS temp folder? I googled a lot and only found this: IronPython Exception: [A]Person cannot be cast to [B]Person. There is a solution offered, but it concerns IronPhyton and I don't know where to use it within my project.
Types are per-assembly; if you have "the same" assembly loaded twice, then types in each "copy" of the assembly are not considered to be the same type.
These issues normally crop up when the two assemblies are in the Load and LoadFrom contexts. See
Difference between LoadFile and LoadFrom with .NET Assemblies?
and the link to suzcook's blog for details on that issue.
Also, consider using the fusion log viewer to help diagnose the problem.
http://msdn.microsoft.com/en-us/library/e74a18c4%28VS.71%29.aspx
Judging by the context in which the assembly is getting loaded (the context is "LoadNeither"), some developers may be doing something like loading an assembly that has been internally packaged as a resource with your application. If you do this, you will be using the AppDomain.CurrentDomain.AssemblyResolve event handler, so that your application can specify where .NET should get any particular assembly that it needs.
My answer will not explain the machinations of how to do that - but I'm mentioning it because this process led directly to the same exact error encountered by the original poster. As Eric Lippert mentions, types are per-assembly. So if you load an individual assembly more than once, the same defined class will appear as different classes - even though visual inspection shows that they appear to be the same.
We've seen instances in which .NET will call the ResolveEventHandler more than once for the same DLL. I'm not sure why .NET sometimes does this (it happened on some machines, but not all machines). But to resolve the problem, we needed keep a global list of handles to loaded assemblies, so that if .NET wanted to load the assembly again, we returned a handle to the same Assembly that was originally loaded, instead of loading another copy into memory.
I have included the code that caused the issue for us, and notes about how to handle it properly.
public void AppStartup (object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
public System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");
dllName = dllName.Replace(".", "_");
if (dllName.EndsWith("_resources")) return null;
System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
byte[] bytes = null;
try
{
bytes = (byte[])rm.GetObject(dllName);
}
catch (Exception ex)
{
}
if (bytes != null)
{
// the following call will return a newly loaded assembly
// every time it is called
// if this function is called more than once for the same
// assembly, you'll load more than one copy into memory
// this can cause the InvalidCastException
// instead of doing this, you keep a global list of loaded
// assemblies, and return the previously loaded assembly
// handle, instead of loading it again
return System.Reflection.Assembly.Load(bytes);
}
return null;
}
My situation involved two copies of the same dll. One was in the bin folder and one was in a sub-folder of the same bin folder. Both were loaded, amazingly some things worked fine, but some things didn't and that's when this error message appeared:
System.InvalidOperationException; There was an error generating the XML document.; Source: System.Xml; TargetSite: Void Serialize(System.Xml.XmlWriter, System.Object, System.Xml.Serialization.XmlSerializerNamespaces, System.String, System.String);
Hidden in this was the following inner exception (this was to do with Microsoft Dynamics CRM 4.0, but could relate to anything)
System.InvalidCastException; [A]XXX.CRMCustomCode.YYY.CreateCompanyRequest cannot be cast to [B]XXX.CRMCustomCode.YYY.CreateCompanyRequest. Type A originates from 'XXX.CRMCustomCode, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadFrom' at location 'C:\Program Files\Microsoft CRM\Server\bin\assembly\XXX.CRMCustomCode.dll'. Type B originates from 'XXX.CRMCustomCode, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\Program Files\Microsoft CRM\Server\bin\XXX.CRMCustomCode.dll'.;
I simply deleted the duplicate dll (in C:\Program Files\Microsoft CRM\Server\bin) and the error went away.
My particular case - class library referenced in web application was renamed and rebuilt. Older version of library was still in bin folder under old name. The framework loads whatever in bin folder (both libraries) and emits this error. So it happens not only when assemblies are loaded explicitly.
The obvious solution in my case is to clean bin folder.
I got it working when I tried changing this cast:
var t = (TeacherWebPages)Session["TeachersAD"];
To this:
var t = Session["TeachersAD"] as TeacherWebPages;
However the assembly/session/memcache was different and no data got back but no error occurred. So later I still had to delete specific temporary files every time source page was changed from the folder it was complaining about which would require me to kill IIS process from task manager. Or in my case I can just logout and it clears the session state.

Categories

Resources