473,836 Members | 1,429 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Assembly.Load(b yte[]) - how does it work? I get TargetInvocatio nException. Source code included...

My problem:

I load an some assemblies (strong named) from a byte array using
Assembly.Load(b yte[]). They load fine. But one one of them is actually
accessed, it's referenced assemblies can't be found on disk and I get a
TargetInvocatio nExeption.

For example, let's say I have a C# win forms application called Prog.

Prog.exe uses Assembly.Load(b yte[]) to load two C# class library assemblies,
ClassLib1 and ClassLib2. Both are strong named. ClassLib1.dll and
ClassLib2.dll are NOT on disk. However, they were created in VS.NET in the
same solution, and ClassLib1 has a reference to ClassLib2 in VS.NET.

The problem is that when my Prog.exe calls a static method on a class in
ClassLib1, I get a TargetInvocatio nException with the details:
Unhandled Exception: System.Reflecti on.TargetInvoca tionException: Exception
has been thrown by the target of an invocation. --->
System.IO.FileN otFoundExceptio n: File or assembly name ClassLib2, or one of
its dependencies, was not found.

There are additional details that show that the framework is trying to load
ClassLib2.dll from disk, from the debug (or release) directory where
Prog.exe was started.

In fact, if I do put ClassLib2.dll on disk there, then there is no exception
because it finds it and loads it. Which means it has been loaded twice,
once by me with the Assembly.Load, and once due to the reference from
ClassLib1.

WHY? Why oh why? I've already loaded it!

So how do I make the framework "realize" that it is already loaded? I
thought strong naming would have do the trick, but it didn't make a
difference... it still wants to load it from disk because of the reference
from ClassLib1. Argghhh!

Any help would be GREATLY appreciated...

Thanks!

Greg Patrick

Source code is below if you want to try it out. You just make a VS.NET C#
Win Forms app solution and use Form1 from below. Then make two C# class
library projects ClassLibrary1, and ClassLibrary2. Don't reference either
class library from the main application project. Build. Copy
ClassLibrary1\b in\debug\ClassL ibrary1.dll to <application>\b in\debug\C1.dll .
Similarly for ClassLibrary2.d ll - copy to C2.dll.

----------------------------------------------------------------------------
-------------------------------

ClassLibrary2

using System;
namespace ClassLibrary2
{
public class Class2
{
public Class2()
{
}
}
}

ClassLibrary1 (Note, in VS.NET, has a reference to ClassLibrary2):

using System;
using System.Windows. Forms;
using ClassLibrary2;
namespace ClassLibrary1
{
public class Class1
{
public static Class2 class2 = new Class2();

public Class1()
{
}

public static void Hello()
{
MessageBox.Show ("Hello!");
}
}
}

Prog.exe's Form1:

using System;
using System.Drawing;
using System.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;
using System.Data;
using System.IO;
using System.Reflecti on;
namespace WinApp
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows. Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r components = null;

private Assembly LoadAss(string filename)
{
FileStream fin = new FileStream("c1. dll", FileMode.Open,
FileAccess.Read );
byte[] bin = new byte[16384];
long rdlen = 0;
long total= fin.Length;
int len;
MemoryStream memStream = new MemoryStream((i nt)total);
rdlen = 0;
while(rdlen < total)
{
len = fin.Read(bin, 0, 16384);
memStream.Write (bin, 0, len);
rdlen = rdlen + len;
}
// done with input file
fin.Close();
return Assembly.Load(m emStream.ToArra y());
}

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeCompo nent();
Assembly c1 = this.LoadAss("c 1.dll");
this.LoadAss("c 2.dll");
Type t = c1.GetType("Cla ssLibrary1.Clas s1");
MethodInfo m = t.GetMethod("He llo");
m.Invoke(null, new object[]{});
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Disp ose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.components = new System.Componen tModel.Containe r();
this.Size = new System.Drawing. Size(300,300);
this.Text = "Form1";
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run (new Form1());
}
}
}
Nov 16 '05 #1
1 15964
You have to manage AssemblyResolve and make sure to return your dynamic
assembly whenever a request for your second strongly typed assembly is made.
What I would recommend is using Assembly.Load(b yte[]), and then inserting
the Assembly references into a Hashtable that you can index later.

I have some information on this on my blog. Note, that because your assemblies
are strong named, you might not want to use basic name resolving and instead use
a more complete resolving based on the full name. That is completely up to your
discretion.

http://weblogs.asp.net/justin_rogers...07/149964.aspx

--
Justin Rogers
DigiTec Web Consultants, LLC.
Blog: http://weblogs.asp.net/justin_rogers

"Greg Patrick" <pr*****@privat e.com> wrote in message
news:WlJyc.1204 $0A.9411@localh ost...
My problem:

I load an some assemblies (strong named) from a byte array using
Assembly.Load(b yte[]). They load fine. But one one of them is actually
accessed, it's referenced assemblies can't be found on disk and I get a
TargetInvocatio nExeption.

For example, let's say I have a C# win forms application called Prog.

Prog.exe uses Assembly.Load(b yte[]) to load two C# class library assemblies,
ClassLib1 and ClassLib2. Both are strong named. ClassLib1.dll and
ClassLib2.dll are NOT on disk. However, they were created in VS.NET in the
same solution, and ClassLib1 has a reference to ClassLib2 in VS.NET.

The problem is that when my Prog.exe calls a static method on a class in
ClassLib1, I get a TargetInvocatio nException with the details:
Unhandled Exception: System.Reflecti on.TargetInvoca tionException: Exception
has been thrown by the target of an invocation. --->
System.IO.FileN otFoundExceptio n: File or assembly name ClassLib2, or one of
its dependencies, was not found.

There are additional details that show that the framework is trying to load
ClassLib2.dll from disk, from the debug (or release) directory where
Prog.exe was started.

In fact, if I do put ClassLib2.dll on disk there, then there is no exception
because it finds it and loads it. Which means it has been loaded twice,
once by me with the Assembly.Load, and once due to the reference from
ClassLib1.

WHY? Why oh why? I've already loaded it!

So how do I make the framework "realize" that it is already loaded? I
thought strong naming would have do the trick, but it didn't make a
difference... it still wants to load it from disk because of the reference
from ClassLib1. Argghhh!

Any help would be GREATLY appreciated...

Thanks!

Greg Patrick

Source code is below if you want to try it out. You just make a VS.NET C#
Win Forms app solution and use Form1 from below. Then make two C# class
library projects ClassLibrary1, and ClassLibrary2. Don't reference either
class library from the main application project. Build. Copy
ClassLibrary1\b in\debug\ClassL ibrary1.dll to <application>\b in\debug\C1.dll .
Similarly for ClassLibrary2.d ll - copy to C2.dll.

----------------------------------------------------------------------------
-------------------------------

ClassLibrary2

using System;
namespace ClassLibrary2
{
public class Class2
{
public Class2()
{
}
}
}

ClassLibrary1 (Note, in VS.NET, has a reference to ClassLibrary2):

using System;
using System.Windows. Forms;
using ClassLibrary2;
namespace ClassLibrary1
{
public class Class1
{
public static Class2 class2 = new Class2();

public Class1()
{
}

public static void Hello()
{
MessageBox.Show ("Hello!");
}
}
}

Prog.exe's Form1:

using System;
using System.Drawing;
using System.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;
using System.Data;
using System.IO;
using System.Reflecti on;
namespace WinApp
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows. Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r components = null;

private Assembly LoadAss(string filename)
{
FileStream fin = new FileStream("c1. dll", FileMode.Open,
FileAccess.Read );
byte[] bin = new byte[16384];
long rdlen = 0;
long total= fin.Length;
int len;
MemoryStream memStream = new MemoryStream((i nt)total);
rdlen = 0;
while(rdlen < total)
{
len = fin.Read(bin, 0, 16384);
memStream.Write (bin, 0, len);
rdlen = rdlen + len;
}
// done with input file
fin.Close();
return Assembly.Load(m emStream.ToArra y());
}

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeCompo nent();
Assembly c1 = this.LoadAss("c 1.dll");
this.LoadAss("c 2.dll");
Type t = c1.GetType("Cla ssLibrary1.Clas s1");
MethodInfo m = t.GetMethod("He llo");
m.Invoke(null, new object[]{});
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Disp ose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.components = new System.Componen tModel.Containe r();
this.Size = new System.Drawing. Size(300,300);
this.Text = "Form1";
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run (new Form1());
}
}
}

Nov 16 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
1520
by: Mitchell Vincent | last post by:
I'm sure this has been discussed here plenty of times before (feel free to point me to the thread!) but I want to learn as much as possible about the single most talked about issue with .NET development. Disassembly into source code and preventing that from happening! Thinstall (thinstall.com) - I own it from previous projects (non - .NET) but don't have faith that it can single handedly protect my source code. What can I do to help,...
8
11230
by: Michael Dekson | last post by:
Hello, Can I exe file made in Microsoft Visual C++ decompile into source code. If it is possibly please tell me how. Thanks
19
3587
by: Martin Oddman | last post by:
Hi, I have a compiling problem. Please take a look at the code below. I have an application that is built upon three tiers: one data tier (Foo.DataManager), one business tier (Foo.Kernel) and one web presentation tier (Foo.WebFiles). The data tier shall only be accessible thru the business tier so I do NOT want a reference to the data tier in the presentation tier. In the business tier I have a class with the name CategoryItem that...
1
1806
by: mathlec | last post by:
I'm struggling with an odd problem and I want to validate something. What is the right way to load an assembly from bytes? Is this code correct? : .... Private Function loadBytes(filename as string) as Byte() Dim fs As New FileStream(filename, FileMode.Open) Dim buffer(CInt(fs.Length)) As Byte
3
1208
by: Peter | last post by:
I have a VB.net exe ----> I want to load in more VB.net Source code into my VB app ---> and then compile a new EXE file from within my original program. Has anyone done this? I'm looking for some well documented source code or general tutorial. -Peter
5
1450
by: iamcs1983 | last post by:
Can I load a assembly from memory by Assembly.Load(string) ?
6
44492
by: Steve | last post by:
I'm playing with late binding and trying a very simple test to load an assembly In my "Host" application I have this code: <code> string modulePath = @"C:\PMDRepository\Tools\ManfBusProcMgr\Modules\TestModule\bin\Debug\TestModule"; Assembly a = Assembly.Load(modulePath); </code>
0
1391
by: Boni | last post by:
Dear all, the Assembly.load(ByteArray() ) function works very slow for me (sometimes about 10 sec for 1 MB assembly). Is there any chance for speed up? --- Overloads Public Shared Function Load( _ ByVal rawAssembly() As Byte _ ) As Assembly ------
1
1157
by: =?Utf-8?B?QU1lcmNlcg==?= | last post by:
I have a vb.net program that needs to display a few fragments of its source code, typically one to five lines for each fragment, and each line contains one assignment statement. I need to do this in a few places (about 10) in a medium size program (about 10k lines). In the old C days, I would use the stringize operator to capture a few source fragments. No such thing in VB (too bad, actually). I need this to work in both debug and...
0
9825
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9671
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10854
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10257
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7794
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6981
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5829
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4459
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.