Problem reflecting in ASP.net context - asp.net

I have a ASP.net application that is referencing a external assembly that I need to dynamically load and discover any types implementing a known interface. The problem I am having is that the type I reflect does not match the same interface that is running and so I cannot cast it.
Example:
This code is run in ASP.net app.
var assembly = Assembly.LoadFile(Path.Combine(HttpRuntime.BinDirectory, "ExternalAssembly.dll"));
var type = assembly.GetExportedTypes().First<Type>(x => x.Name == "AClass"); // AClass implements IAInterface
var reflectedInterface = type.GetInterface(typeof(IAmAInterface).ToString());
if (reflectedInterface != typeof(IAmAInterface))
throw new Exception("This makes me sad"); // This code gets run
The only difference I can see between the reflected interface I loaded from the bin and the interface returned from typeof is that the typeof assembly has a location in the temp ASP.net path (C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\08c43c8b\3adac8cf\assembly\dl3\eb7a4127\0235ea60_a3c8c901\ReflectionTest.DLL)
Thanks Paul Alexander I have changed the code to use the Assembly.Load method not Assembly.LoadFile which solves the problem.
wwilden: I also tried extracting the interface into it's own assembly and this does also solve the problem.

When you use LoadFile the assembly is not loaded into the same context as your other assemblies at runtime so to the CLR interface runtime types are different. You can read more in Suzanne Cook's Debugging Assembly Load Failures.
If the assembly that you're loading is already in the Bin directory - you can load it by name. You don't need to know the exact path as the Bin folder is already in the assembly probing path.

Where is your interface type defined? Does it exist both in the reflected assembly as well as in the application itself? Then you actually have two different interfaces, even though they have the same namespace and name.
What you need to do is extract the interface from the reflected assembly and put it into another assembly that you refer to both from the reflected assembly as well as your application. Then it should work.

Apart from your problem, if you have a lot of assemblies to dynamically load, remember that they will remain in memory until the ASP.NET worker process reloads. This could influence your server's performance.
You could load the assemblies in a separate AppDomain (the smallest unit that is possible to unload), load a proxy class in that AppDomain which you reference with .NET remoting. Once finished, you unload the AppDomain.

There is an interesting article over at CodeProject about a situation like this. Where you have a class that has a structure that is identical with an interface without implementing the interface itself. The article outlines a method of dynamically creating wrapper classes that implement the needed interface. It could be helpful in your situation.

Related

Loading all referenced assemblies .NET even if not used explicitly in code

We have a windows service which is using Autofac, when we try to load the referenced assemblies not all are listed as some contain objects we aren't using anywhere in the application but interface implementations are in there we need to be included. The following method loads the assemblies:
private IEnumerable<Assembly> GetReferencedAssemblies(Assembly assembly)
{
var assemblyNames = assembly.GetReferencedAssemblies();
List<Assembly> assemblies = new List<Assembly>();
assemblies.Add(assembly);
foreach (var item in assemblyNames)
{
var loadedAssembly = System.Reflection.Assembly.Load(item.FullName);
assemblies.Add(loadedAssembly);
}
return assemblies;
}
If we make a dummy reference to an object contained in the assembly then it loads the assembly and the types are built by autofac, if we remove the dummy object the assembly is no longer included.
Is there any way to include all referenced assemblies regardless of whether you are directly using an object in there (bearing in mind we still need it as the interface implementations are in there).
This works fine on ASP.NET as it just loads all DLLs in the bin.
If you do not actually reference a type in the assembly the compiler will remove the reference as it is assumed to be redundant. You need to manually load the required assemblies into the AppDomain using Assembly.Load(). How you determine the assemblies to load is up to you. You might choose to look through the files in a particular folder or you perhaps use a configuration file that contains the assemblies names.

Unable to load assembly in new appDomain

I have an mvc3 application.
I have a subfolder in my application project called "Plugins"
All of the dll's stored in that folder should be updateable during runtime, so then we an put down the appdomain and reload the new version of the dlls, so I am attemping to load all the plugin dll's in a different appDomain and set it's shadowCopy properties.
Looking through SO, msdn and some blogs, I got to this "solution". (this is called during my Application_Start)
static AppDomain pluginDomain;
static PluginHolder()
{
AppDomainSetup domainSetup = AppDomain.CurrentDomain.SetupInformation;
domainSetup.ApplicationName = "Plugins";
domainSetup.PrivateBinPathProbe = domainSetup.PrivateBinPath;
domainSetup.PrivateBinPath = GetPluginsDirectory();
domainSetup.ShadowCopyFiles = "true";
domainSetup.ShadowCopyDirectories = domainSetup.PrivateBinPath;
pluginDomain= AppDomain.CreateDomain("Plugins", null, domainSetup);
var item = pluginDomain.Load(File.ReadAllBytes(GetPluginsDirectory() + "Item.dll"));
}
"Item.dll" is the dll i am attemping to load. The last line throws a "Could not load file or assembly Item or one of its dependencies".
This seems to be the way other people have succeded with, but it just wont work for me.
I have no previous experience with AppDomains, so I am not sure on how to approach this problem, or if I am tackling it correctly.
Is my Assembly loading via the new AppDomain an ok approach?
To decypher these kind of error messages, you should use the Assembly Binding Log Viewer.
Also pay attention on the remarks section on the documentation page of AppDomain.Load(byte[]). If you want to load the assembly on the new AppDomain, then you should use CreateInstanceAndUnwrap instead.
If you want to implement a plugin engine in .NET, then you will need to understand AppDomains, assembly resolving and loading and a then choose on a mechanism for the communication between objects from different AppDomains. Most good books on .NET and CLR include a chapter or two on AppDomains and they will get you up to speed. Now as far as the cross-AppDomain communication is concerned, you could use WCF or .NET Remoting (MarshalByRefObject).
Good luck.

Is there a way to run code when an assembly loads?

I'm building an application that will load untrusted assemblies for inspection (i.e. retrieval of the assembly full name). For security reasons, I'm trying to think of a way that these assemblies could be written that would allow them to execute code when loaded. I haven't code up with a method yet, but wanted to throw it out here to see if anyone could.
I'm aware that I could load these assemblies into an untrusted app domain, effectively stopping them from doing almost anything, but I wanted to avoid the complexity if it's un-needed.
Specifically, I will be calling Assembly.Load and <LoadedAssebmly>.FullName. Maybe there's a better way to load the assembly name without using the Assembly class?
Thanks,
Matt
First of all, there's the AssemblyName class. It allows you to find the assembly's name without loading it. Second, you can load assemblies using Assembly.ReflectionOnlyLoad, which uses the reflection-only context -- no code can be executed from such an assembly.
Yes, it is possible: .Net: Running code when assembly is loaded
I suggest, you use a method to inspect the assembly, that doesn't load it, i.e. Mono.Cecil

ASP.NET page or control marked as internal doesn't work and gives "inaccessible due to its protection level" error

I know why this happens and I want to find a workaround it.
Example: a user control that exist in 2 assemblies, loaded at the same time.
namespace MyNamespace
{
internal class MyUserControl : UserControl
{
}
}
My situation - I want to be able to share user interface control between two web applications which are loaded at the same time in the same application pool. If my user interface class is marked public, then ASP.NET will not like it because it will be duplicated into memory ( CLR uses namespaces as full qualifier for class, and if the same class and namespace is met it more than one assembly, exception is thrown ). I do then mark the class as internal and of course I forget how UI compilation occurs, and I expect it to work. Of course it doesn't because ASP.NET compiles the UI into separate assembly which is dynamic and since I marked the class as internal, it is not visible to the main assembly...
The question that follows is: How can I make dynamic compiled assemblies that ASP.NET generates to view the main application assembly internals? It is very unfortunate that classes and methods I write into my UI controls must always be public! Has anyone met this obstacle in his daily work and found a workaround?
EDIT:
Precompilation is not possible here due to other circumstances.
You can share User Control markup between apps using a Virtual Path Provider (see
http://weblogs.asp.net/scottgu/archive/2005/11/27/431650.aspx and http://msdn.microsoft.com/en-us/library/system.web.hosting.virtualpathprovider.aspx).
You can pull the markup for the control from anywhere - SharePoint uses VPP to get markup from the database, and I use it in some projects to pull from a non-standard location on disk (which is shared between projects).
If your base class is internal, the derived class that ASP.NET generates at runtime will not be able to extend it.
However, I don't understand the issue that you're running into in the first place. Two distinct web applications will always run in different AppDomains (even if they're in the same app pool), and there should be no type conflicts between the AppDomains.
I probably need more details about what you are doing. e.g. what assembly are you compiling your base class into, and why does it end up in two different assemblies?

Checked install components

How can I check third-party components that is property installed before the web page start in web.config. And throw error before start.
Find something about the component that your code can test, then have the code test it. Best place for testing it would probably be the Application_Start event handler in global.asax.
What to test depends on what kind of component you are talking about. You could use reflection to attempt to locate information about a known assembly if the component is a compiled assembly referenced by your application, or you could use System.IO to check a physical file on the file system that should exist. You could possibly even call a constructor on some object from the component and verify that it instantiates correctly.

Resources