how to call an dll file dynamically from code behind(.cs) - asp.net

i have an microsoft .office.interop.excel(dll) located at an directory d:\abc. now i do not want to add them as an web reference in my projet and call them
rather call the dll dynamically from my code behind(.cs)
is ther any way we can do dynmically
anyhelp would be great
thank you

Yes, but you will need to use reflection because if you don't add the assembly as reference it won't be known at compile time. Take a look at LoadFrom method.
var assembly = Assembly.LoadFrom(#"d:\abc\microsoft.office.interop.excel.dll");
var someType = assembly.GetType("Namespace.Type");
var instance = Activator.CreateInstance(type);
someType.InvokeMember(... // the reflection pain goes on

Take a look in Assembly.Load() method.

I want to discourage you from doing that. It can definitely be done if read the dll into a byte[] and call AppDomain.CurrentDomain.Load(byte[]). However you will find that you can only work with the types of that assembly through reflection. Otherwise your code behind file will not compile. So if at all possible you should add a reference (not a web reference) to the dll.

Related

How do I register types in assemblies that haven't been loaded with Unity?

I want to load all the types of an Interface so I can call a method on it. However, the assemblies are not referenced a compile time. They will be in the bin folder.
Is this something I can do easily with Unity?
So for example I have code sort of like:
using (var container = new UnityContainer())
{
container.RegisterType<IModule>();
var modules = container.ResolveAll(typeof(IModule));
foreach (IModule module in modules) { module.Logon(); }
Console.WriteLine("Done...");
Console.ReadLine();
}
Of course, modules resolves to nothing because the assemblies have been just dropped into the bin folder. They are not statically referenced in my current assembly.
Or, do I have to do some type of Assemblies.LoadAssembly(). I'd like this to be as dynamic as possible. I don't have to have to specify assembly names in a config file or code if possible.
Thanks in advance.
Unity does not, by itself, load any assemblies. It works off Type objects and lets the CLR load those types however it wants to.
To do dynamic discovery like you want, you'll need to write a little code to spin through the assemblies in the bin directory, load them into memory, and then spin through them looking for the types you're interested in. It's pretty trivial if you're familiar with the reflection APIs.
Here's some code you can use to loop through the bin directory and make sure every assembly there is loaded:
private static bool ForceLoadAssemblies()
{
foreach (var fileName in Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll"))
{
string assemblyName = Path.GetFileNameWithoutExtension(fileName);
if (assemblyName != null)
{
Assembly.Load(assemblyName);
}
}
return true;
}
Another option would be to look at MEF instead. MEF was explicitly designed for the dynamic discovery case, while Unity is more built around internal dependency management.

Using embedded WebResources throughout Webresource.axd

The question's simple: how could one use embedded resources in asp.net applications? What are the steps to include a resource in the assembly, and how to reference it? What are the gotchas that could be encountered?
Edit: For a version without referencing Page and ClientScript, see What is the right way to handle Embedded Resources on a Razor View?
After spending a half of a day I've learned these:
to embed a resource one needs to set it's Build Action to Embedded Resource (in VS Solution Explorer rightclick the file -> Properties)
next AsssemblyInfo.vb must be modified to make this resources available for WebResource queries. Add [Assembly: System.Web.UI.WebResource("MyWebResourceProj.Test.css", "text/css")] to AssemblyInfo.vb located in MyProject folder of the project.
The name consists of root namespace/assembly name +'.'+filename. To be 100% sure of the name, use the following code snippet to look it up:
Dim resNames = Assembly.LoadFile("YourDll.dll").GetManifestResourceNames()
Note that the assembly's Root Namespace must be the same as the Assembly Name (this took me about 4 hours to realize. At least with .Net v4 that is the case)
If there are references inside the css ( <%=WebResource("NS.image.jpg")%> ) than pass PerformSubstitution:=true for that css's WebResource attribute.
Referencing the resource can be done with Page.ClientScript.GetWebResourceUrl(GetType(MyWebResourceProj.ConssumingPage), "MyWebResourceProj.Test.css")
Note that instead of GetType(Typename) one could use Me.GetType(), but again, that won't work if the class is inherited, so beware!
Resources:
Debugging ASP.NET 2.0 Web Resources: Decrypting the URL and Getting the Resource Name
Using embedded resources through WebResource.axd is a pain in the neck, as you can see from your own answer. You have to keep assemblyinfo.vb|cs in sync, and it always seems damn near impossible to get all the namespace & assembly names right in all the right places.
When you finally get it to work, your reward is an include script line that that looks like a core memory dump.
I suggest an alternative. Write yourself a very simple web handler (e.g. MyResourceLoader.ashx. Then add a method to your class that simply serves it's own embedded resources, in whatever way you think is meaningful. You can use reflection to get the classes, like WebResource does, or just hardcode whatever you need into your loader, if it's just for a specific purpose. A public method in your class might look like:
public static Stream GetResource(string resourceName) {
// get the resource from myself, which is easy and doesn't require
// anything in assemblyinfo, and return it as a stream. As a bonus,
// you can parse it dynamically or even return things that aren't
// just embedded, but generated completely in code!
}
Or if you decide to make something more general purpose, you can get all fancy and return more data using a class, e.g.
class ResourceInfo
{
public Stream Data;
public string MimeType;
public string FileName;
}
Now you have the ability to serve up your embedded resources any way you want, e.g.
<script language="javascript" src="/MyResourceLoader.ashx/MyControlScript.js">
I think MS made a mess of that WebResource business. Luckily its' pretty straightforward to do your own thing.

internal ToMVCHmlString in TagBuilder

I am looking to write a few helpers in my own assembly modeled after the helpers in System.web.mvc. My problem is that I cannot use the call to Tagbuilder.ToMvcHtlString since it is internal. So if I return a string it wont be ready for asp.net 4 when it comes.
I dont want to add anything to system.web.mvc as that is a given dll.
return MvcHtmlString.Create(tagBuilder.ToString());

How do I access GetGlobalResourceObject function from a class that is not a page?

I have a class in my asp.net proj, I would like to get access GetGlobalResourceObject (that page exposes), from anywhere in the site, possible?
In other words I wanna access the global resources from a class that is not a page I don't care how.
Answer:
Yes, as following pseudo:
Resources.<The name of the resources file name>.<your resource key>;
Example:
lblTitle.Text = Resources.MySettings.WebsiteTitle;
Resources is an Visual-Studio auto generated namespace that exposes all the global resource classes and props in the project.
You should use
HttpContext.GetGlobalResourceObject("myResourceKey")
...because that way it will still work when using a custom ResourceProvider. The default type-generator for Resource files explicitely uses the Resx provider and won't work if you implement something like a database provider.
On some farms you'll need to wrap the call to
HttpContext.GetGlobalResourceObject("myResourceKey")
inside a try/catch block to get it over the "Could not find any resources appropriate for the specified culture or the neutral culture" error.
If you are in the site you have access to HttpContext and can use:
HttpContext.GetGlobalResourceObject("myResourceKey")
I kinda took this from the resource designer,
ResourceManager temp =
new ResourceManager("Resources.<<resource name>>",
System.Reflection.Assembly.Load("App_GlobalResources"));

How to use reflection to create a class in app_code?

I have a class Customer in app_code folder in asp.net web site, how can I create an instance using reflection, for example using Activator.CreateInstance(assemblyName, typeName)? Because the app_code is dynamically compiled, I don't know the assembly in design time?
Thanks
Fred
The question is should be how get a full name of type in design time, I want to put it in web.config. I have ConfigSection type, it is in app_code folder, I need to declare it in configSection. Thanks
You should be able to use "App_Code" or "__Code" as the assembly name in the web.config
I think you can use Assembly.GetExecutingAssembly() to get a reference to the current assembly.
I have solved a similar problem in this way:
Type[] appCodeTypes = System.Reflection.Assembly.Load("App_Code").GetTypes();
You can also use GetType().Assembly if you know that it will be the same assembly as your currently executing code.

Resources