I use this code to embed all dlls to app exe file but this code can embed only one dll. i search for other code but all are same that.
public App()
{
AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
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 = (byte[])rm.GetObject(dllName);
return System.Reflection.Assembly.Load(bytes);
}
to use ILmerge i have problem wuth my dlls. so i cant use this.
how can i do this?
This open source tool should help you
http://madebits.com/netz/
A possible approach is to add all your DLLs to resources (manually). Then, at the program's startup, use File.WriteAllBytes to write those resource byte streams to files.
NOTE : In this case you cannot use DllImport, since it requires constant string path. Instead, you will use what so called "dynamic P\Invoke". Learn more.
Using GetManifestResourceStream should work better.
When the dlls are embedded as resources the resource names are prefixed with the default name space for you project, so you will need to fill that in.
eg
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string defaultNameSpace = "...";
string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");
string resourceName = String.Format("{0}.{1}.dll", defaultNameSpace , dllName);
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
if (stream == null)
return null;
byte[] data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
return Assembly.Load(data);
}
}
Related
Trying to find the path to my file after adding it to properties is not working very well. In my properties the file looks like this:
internal static System.Drawing.Bitmap one {
get {
object obj = ResourceManager.GetObject("one", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
How can I find the path to this file?
And then I try to use it like this:
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file =
thisExe.GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.one");
this.pictureBox1.Image = Image.FromStream(file);
When I run this code:
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
string [] resources = thisExe.GetManifestResourceNames();
string list = "";
// Build the string of resources.
foreach (string resource in resources)
list += resource + "\r\n";
It gives me the following paths: "WFA1.Form1.resources" and "WFA1.Properties.Resources.resources"
Can add that my recourses are embedded.
If you need any more info please let me know.
So what I want is a path to my file, or info on HOW I can find the path. After looking around they say this should work:
System.IO.Stream file =
thisExe.GetManifestResourceStream("[WindowsFormsApplication1.Form1.resources].[a.jpg]");
IE:
System.IO.Stream file =
thisExe.GetManifestResourceStream("[Namespace].[file and extension]");
So it seems Im getting my namespace wrong cus it still returns null at this line:
this.pictureBox1.Image = Image.FromStream(file);
I have had a look at this and I don't believe that there's a way to get the path without some serious string building/manipulation. Which of course could lead to bigger issues.
I presume this code will not suffice:
var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.one);
pictureBox1.Image = bmp;
Instead of this one:
var thisExe = Assembly.GetExecutingAssembly();
var file = thisExe.GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.one");
if (file != null) pictureBox1.Image = Image.FromStream(file);
Option 2:
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
var stream = assembly.GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.one.jpg");
var tempPath = Path.GetTempPath();
File.Save(stream, tempPath);
i'm building a class library for SQLite , when i build the project the System.Data.SQLite.dll comes as a standalone dll file and i need it to be merged with my class library in a single dll file
i added System.Data.SQLite.dll as a ressource then , add / existing item , and then adding it as an embedded resource
then i drop this static constractor in the start of my namespace
static SimpleClass()
{
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
if (new AssemblyName(args.Name).Name.ToLowerInvariant() == "System.Data.SQLite")
{
String resourceName = "SQLlite." + new AssemblyName(args.Name).Name + ".dll";
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
Byte[] assemblyData = new Byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}
else
{
return null;
}
};
}
This is giving me errors like error CS1518: Expected class, delegate, enum, interface, or struct
appreciate any help from you guys
If you want to make one assembly from two, you can try ILMerge.
This will ultimately fail. System.Data.SQLite is a PInvoke wrapper for SQLite.Interop.dll, which is an unmanaged dll, which is not resolved in .net.
I am rather new to c# and .NET, and trying to create an asp.net web application that dynamically loads assembly.
Initially, I've used Activator.CreateInstance to dynamically load assemblies, but it seems to lock the assembly DLL file. Because I am making frequent changes to the assembly it's become quite a pain. I also need to share the assembly with other apps, so it may become a problem later.
It appears that most people recommend creating a separate AppDomain and loading the assembly into it, then unload the appdomain after I'm done. However, my app and the assembly also depends on session context and all the session is lost once I send it over to the app domain; the assembly crashes because it cannot find session context.
Is there any way to pass on my session context to the AppDomain? Or is there any way for me to load the assembly without locking the DLL file? I've tried streaming the file as some suggested, but it still locks the DLL.
Edit: I've tried the following code as Davide Piras suggested, but the DLL file is still locked
private static T CreateInstance<T>(string fileName, string typeName)
{
if (!File.Exists(fileName)) throw new FileNotFoundException(string.Format("Cannot find assembly '{0}'.", fileName));
try
{
Assembly assembly = Assembly.LoadFrom(fileName);
if (assembly != null)
{
List<Type> assemblyTypes = assembly.GetTypes().ToList();
Type assemblyType =
assemblyTypes.FirstOrDefault(asmType => typeof(T).IsAssignableFrom(asmType));
T instance = (T) Activator.CreateInstance(assemblyType);
if (instance != null) return instance;
}
// Trouble if the above doesn't work!
throw new NullReferenceException(string.Format("Could not create type '{0}'.", typeName));
}
catch (Exception exp1)
{
throw new Exception("Cannot create instance from " + fileName + ", with type " + typeName + ": " + exp1.Message + exp1.Source, exp1.InnerException);
}
}
to load the assemblies in the same AppDomain but not lock the files after load just use the LoadFrom method in this way:
Assembly asm = Assembly.LoadFrom( “mydll.dll” );
in this way you are done and Session will be available.
there will be an issue with the debugger because symbols (*.pdb) will not get loaded so no breakpoint and no debugging available, to be able to debug you should really load the .pdb files in memory as well, for example using FileStream.
Edit: The way you can do to also load symbols and not lock the files is to use proper overload of Assembly.Load, the one that gets two byte[] one for the assembly and the other for the assembly' symbols file (.pdb file):
public static Assembly Load(
byte[] rawAssembly,
byte[] rawSymbolStore
)
in fact you should first load the bytes with a stream then call Assembly.Load and pass the byte[]
EDIT 2:
here a full example to load the assemblies in your current domain, including the symbol file and not having the files locks.
it's a full example found online, it reflect everything you need including the handling of AppDomain.AssemblyResolve...
public static void Main() {
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolver);
}
static void InstantiateMyType(AppDomain domain) {
try {
// You must supply a valid fully qualified assembly name here.
domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyType");
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
// Loads the content of a file to a byte array.
static byte[] loadFile(string filename) {
FileStream fs = new FileStream(filename, FileMode.Open);
byte[] buffer = new byte[(int) fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
return buffer;
}
static Assembly MyResolver(object sender, ResolveEventArgs args) {
AppDomain domain = (AppDomain) sender;
// Once the files are generated, this call is
// actually no longer necessary.
EmitAssembly(domain);
byte[] rawAssembly = loadFile("temp.dll");
byte[] rawSymbolStore = loadFile("temp.pdb");
Assembly assembly = domain.Load(rawAssembly, rawSymbolStore);
return assembly;
}
I'm following http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx
I've added WPFToolkit.Extended.dll to my solution, and set its Build Action to Embedded Resource.
In App.OnStartup(StartupEventArgs e) I have the following code:
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
String resourceName = "AssemblyLoadingAndReflection." + new AssemblyName(args.Name).Name + ".dll";
String assemblyName = Assembly.GetExecutingAssembly().FullName;
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
using (stream)
{
Byte[] assemblyData = new Byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
};
The debugger hits this block of code twice.
First time:
resourceName is "AssemblyLoadingAndReflection.StatusUtil.resources.dll"
assemblyName is "StatusUtil, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
stream is null
Second time:
resourceName is "AssemblyLoadingAndReflection.WPFToolkit.Extended.resources.dll"
assemblyName is "StatusUtil, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
stream is null
The code throws an exception when it hits stream.Length, since it's null.
I can't use ILMerge because it's a WPF project.
You have to change the string "AssemblyLoadingAndReflection" to the name of your application assembly.
One thing you can do to make this code more generic by using some more reflection:
Assembly.GetExecutingAssembly().FullName.Split(',').First()
Don't forget to append a dot. This will of course not work if the dll is not in the resources of the application assembly.
The answer by H.B. is actually not quite right. The prefix we need is not the name of the assembly, but the default namespace of the project. This is probably impossible to get entirely reliably, but the following code would be much more reliable than assuming it's the same as the assembly name.
Assembly thisAssembly = Assembly.GetEntryAssembly();
String resourceName = string.Format("{0}.{1}.dll",
thisAssembly.EntryPoint.DeclaringType.Namespace,
new AssemblyName(args.Name).Name);
Nathan Philip's Answer worked like a charm for me..
This is the entire method that worked for me
(and it works for multiple dlls also)
public MainWindow()
{
InitializeComponent();
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
Assembly thisAssembly = Assembly.GetEntryAssembly();
String resourceName = string.Format("{0}.{1}.dll",
thisAssembly.EntryPoint.DeclaringType.Namespace,
new AssemblyName(args.Name).Name);
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
Byte[] assemblyData = new Byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
};
}
I tried all of the above answers and they did not work for me. I found this post and it worked like a charm.
Post: http://www.digitallycreated.net/Blog/61/combining-multiple-assemblies-into-a-single-exe-for-a-wpf-application
I found that the .csproj file also needs to be edited. The post explains how to do everything.
I have a full explanation of how to dynamically load embedded assemblies in StackOverflow question VB.NET embedded DLL in another DLL as embedded resource?
I've got a situation where I have a DLL I'm creating that uses another third party DLL, but I would prefer to be able to build the third party DLL into my DLL instead of having to keep them both together if possible.
This with is C# and .NET 3.5.
The way I would like to do this is by storing the third party DLL as an embedded resource which I then place in the appropriate place during execution of the first DLL.
The way I originally planned to do this is by writing code to put the third party DLL in the location specified by System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()
minus the last /nameOfMyAssembly.dll. I can successfully save the third party .DLL in this location (which ends up being
C:\Documents and Settings\myUserName\Local Settings\Application
Data\assembly\dl3\KXPPAX6Y.ZCY\A1MZ1499.1TR\e0115d44\91bb86eb_fe18c901
), but when I get to the part of my code requiring this DLL, it can't find it.
Does anybody have any idea as to what I need to be doing differently?
Once you've embedded the third-party assembly as a resource, add code to subscribe to the AppDomain.AssemblyResolve event of the current domain during application start-up. This event fires whenever the Fusion sub-system of the CLR fails to locate an assembly according to the probing (policies) in effect. In the event handler for AppDomain.AssemblyResolve, load the resource using Assembly.GetManifestResourceStream and feed its content as a byte array into the corresponding Assembly.Load overload. Below is how one such implementation could look like in C#:
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
var resName = args.Name + ".dll";
var thisAssembly = Assembly.GetExecutingAssembly();
using (var input = thisAssembly.GetManifestResourceStream(resName))
{
return input != null
? Assembly.Load(StreamToBytes(input))
: null;
}
};
where StreamToBytes could be defined as:
static byte[] StreamToBytes(Stream input)
{
var capacity = input.CanSeek ? (int) input.Length : 0;
using (var output = new MemoryStream(capacity))
{
int readLength;
var buffer = new byte[4096];
do
{
readLength = input.Read(buffer, 0, buffer.Length);
output.Write(buffer, 0, readLength);
}
while (readLength != 0);
return output.ToArray();
}
}
Finally, as a few have already mentioned, ILMerge may be another option to consider, albeit somewhat more involved.
In the end I did it almost exactly the way raboof suggested (and similar to what dgvid suggested), except with some minor changes and some omissions fixed. I chose this method because it was closest to what I was looking for in the first place and didn't require using any third party executables and such. It works great!
This is what my code ended up looking like:
EDIT: I decided to move this function to another assembly so I could reuse it in multiple files (I just pass in Assembly.GetExecutingAssembly()).
This is the updated version which allows you to pass in the assembly with the embedded dlls.
embeddedResourcePrefix is the string path to the embedded resource, it will usually be the name of the assembly followed by any folder structure containing the resource (e.g. "MyComapny.MyProduct.MyAssembly.Resources" if the dll is in a folder called Resources in the project). It also assumes that the dll has a .dll.resource extension.
public static void EnableDynamicLoadingForDlls(Assembly assemblyToLoadFrom, string embeddedResourcePrefix) {
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { // had to add =>
try {
string resName = embeddedResourcePrefix + "." + args.Name.Split(',')[0] + ".dll.resource";
using (Stream input = assemblyToLoadFrom.GetManifestResourceStream(resName)) {
return input != null
? Assembly.Load(StreamToBytes(input))
: null;
}
} catch (Exception ex) {
_log.Error("Error dynamically loading dll: " + args.Name, ex);
return null;
}
}; // Had to add colon
}
private static byte[] StreamToBytes(Stream input) {
int capacity = input.CanSeek ? (int)input.Length : 0;
using (MemoryStream output = new MemoryStream(capacity)) {
int readLength;
byte[] buffer = new byte[4096];
do {
readLength = input.Read(buffer, 0, buffer.Length); // had to change to buffer.Length
output.Write(buffer, 0, readLength);
}
while (readLength != 0);
return output.ToArray();
}
}
There's a tool called IlMerge that can accomplish this: http://research.microsoft.com/~mbarnett/ILMerge.aspx
Then you can just make a build event similar to the following.
Set Path="C:\Program Files\Microsoft\ILMerge"
ilmerge /out:$(ProjectDir)\Deploy\LevelEditor.exe $(ProjectDir)\bin\Release\release.exe $(ProjectDir)\bin\Release\InteractLib.dll $(ProjectDir)\bin\Release\SpriteLib.dll $(ProjectDir)\bin\Release\LevelLibrary.dll
I've had success doing what you are describing, but because the third-party DLL is also a .NET assembly, I never write it out to disk, I just load it from memory.
I get the embedded resource assembly as a byte array like so:
Assembly resAssembly = Assembly.LoadFile(assemblyPathName);
byte[] assemblyData;
using (Stream stream = resAssembly.GetManifestResourceStream(resourceName))
{
assemblyData = ReadBytesFromStream(stream);
stream.Close();
}
Then I load the data with Assembly.Load().
Finally, I add a handler to AppDomain.CurrentDomain.AssemblyResolve to return my loaded assembly when the type loader looks it.
See the .NET Fusion Workshop for additional details.
You can achieve this remarkably easily using Netz, a .net NET Executables Compressor & Packer.
Instead of writing the assembly to disk you can try to do Assembly.Load(byte[] rawAssembly) where you create rawAssembly from the embedded resource.