473,626 Members | 3,974 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reflection / Casting Question

Hi guys,

I'm trying to load a class instance dynamically, and then cast it to it's
base type so I can use it in my app.

More specifically, I'm dynamically instantiating a
System.Web.UI.W ebControls.Requ iredFieldValida tor and attempting to cast it
into an IValidator and/or a BaseValidator. Both casting attempts have
failed miserably, throwing an InvalidCastExce ption ... how can it be i
cannot cast to the base class of my instance ???

More specifically, I load the Assembly directly from the System.Web.dll, and
create the RequiredFieldVa lidator instance using .CreateInstance (string
strClassName) on the Assembly.

I get back a perfectly good object, for which I'm using reflection to set
some properties before I cast it to it's base type (BaseValidator) and
return it from a method to the caller. upon casting it to the base type, I
get the InvalidCastExce ption. This shouldn't be happening normally, and i'm
bangin' my head against a wall to find out what could be causing it ...

Could it be that the application uses a reference to the System.Web.dll, and
my own loader loads another instance of the assembly ? If this is it, how
could I work around it ?

Thanks a million,

Angel
O:]
Jul 21 '05 #1
2 1780
Loading System.Web.dll should not load another instance of the assembly, once
an assembly is loaded into memory, you cannot load additional instances of
it. Please post an example of what your code. I would also try to create a
simple test app to isolate the code you are having a problem with.

"Angelos Karantzalis" wrote:
Hi guys,

I'm trying to load a class instance dynamically, and then cast it to it's
base type so I can use it in my app.

More specifically, I'm dynamically instantiating a
System.Web.UI.W ebControls.Requ iredFieldValida tor and attempting to cast it
into an IValidator and/or a BaseValidator. Both casting attempts have
failed miserably, throwing an InvalidCastExce ption ... how can it be i
cannot cast to the base class of my instance ???

More specifically, I load the Assembly directly from the System.Web.dll, and
create the RequiredFieldVa lidator instance using .CreateInstance (string
strClassName) on the Assembly.

I get back a perfectly good object, for which I'm using reflection to set
some properties before I cast it to it's base type (BaseValidator) and
return it from a method to the caller. upon casting it to the base type, I
get the InvalidCastExce ption. This shouldn't be happening normally, and i'm
bangin' my head against a wall to find out what could be causing it ...

Could it be that the application uses a reference to the System.Web.dll, and
my own loader loads another instance of the assembly ? If this is it, how
could I work around it ?

Thanks a million,

Angel
O:]

Jul 21 '05 #2
Here's what I did in my code initially ...

public System.Web.UI.W ebControls.Base Validator[] GetValidators() {
System.Web.UI.W ebControls.Base Validator[] validators = new
System.Web.UI.W ebControls.Base Validator[this.ValidatorD escriptors.Leng th];
for(int i=0; i<this.Validato rDescriptors.Le ngth; i++){

ValidatorDescri ptor validator = this.ValidatorD escriptors[i];

ObjectHandle objHndl = Activator.Creat eInstance("Syst em.Web",
validator.Class Name);

object instance = objHndl.Unwrap( );

foreach(Propert y prop in validator.Prope rties)

TypeInspector.S etPropertyValue (prop.Name, prop.Value, instance);
try{

validators[i] = (System.Web.UI. WebControls.Bas eValidator)inst ance;

}catch(Exceptio n e){

throw new InvalidCastExce ption("Cannot cast to IValidator for class
"+instance.GetT ype().ToString( )+" original : "+validator.Cla ssName);

}

}

return validators;
}

... this is executed inside a Web Appliation, so the System.Web assembly
*should* be available to the Activator .. however, I get an exception saying
that the ASP.NET runtime cannot load the System.Web assembly !!! (Weird ?)

So, I changed the code:

ObjectHandle objHndl = Activator.Creat eInstance("Syst em.Web",
validator.Class Name);

object instance = objHndl.Unwrap( );

... to use a class I'd created on my own ...

object instance =
DynamicClassLoa der.GetInstance ().Load(validat or.ClassName);

what the DynamicClassLoa der does, is locate the class name in it's
configuration file, read the asembly it belongs to from there, and then:

... in the initialization method ...

AssemblyDescrip tor ad = (AssemblyDescri ptor)lstAssembl ies[i];

try{

Assembly objAssembly = Assembly.LoadFr om(ad.CodeBase) ;

... . in the Load(strClassna me) method

return objAssembly.Cre ateInstance(str ClassName);

....

That code works ok, and returns an instance of the class I'm asking for, the
RequiredFieldVa lidator. However, when I cast it to a BaseValidator, I get
the InvalidCastExce ption ...

... and that's my problem right there. I get some weird exception in both
attempts, either using dynamic assembly loading, or not :(

Angel

O:]

"Jorge Matos" <Jo********@dis cussions.micros oft.com> wrote in message
news:7B******** *************** ***********@mic rosoft.com...
Loading System.Web.dll should not load another instance of the assembly, once an assembly is loaded into memory, you cannot load additional instances of
it. Please post an example of what your code. I would also try to create a simple test app to isolate the code you are having a problem with.

"Angelos Karantzalis" wrote:
Hi guys,

I'm trying to load a class instance dynamically, and then cast it to it's base type so I can use it in my app.

More specifically, I'm dynamically instantiating a
System.Web.UI.W ebControls.Requ iredFieldValida tor and attempting to cast it into an IValidator and/or a BaseValidator. Both casting attempts have
failed miserably, throwing an InvalidCastExce ption ... how can it be i
cannot cast to the base class of my instance ???

More specifically, I load the Assembly directly from the System.Web.dll, and create the RequiredFieldVa lidator instance using .CreateInstance (string
strClassName) on the Assembly.

I get back a perfectly good object, for which I'm using reflection to set some properties before I cast it to it's base type (BaseValidator) and
return it from a method to the caller. upon casting it to the base type, I get the InvalidCastExce ption. This shouldn't be happening normally, and i'm bangin' my head against a wall to find out what could be causing it ...

Could it be that the application uses a reference to the System.Web.dll, and my own loader loads another instance of the assembly ? If this is it, how could I work around it ?

Thanks a million,

Angel
O:]

Jul 21 '05 #3

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

Similar topics

1
2611
by: Mike Malter | last post by:
I am just starting to work with reflection and I want to create a log that saves relevant information if a method call fails so I can call that method again later using reflection. I am experimenting a bit with what I need to do this and have the following code snippet. But first if I pass the assembly name and type to Activator.CreateInstance() it always fails. However if I walk my assembly and get a type value, the call to...
1
1690
by: Roman Muntyanu | last post by:
Hi all, I created object of MyClass : ISomeInterface Then I created object of this class using reflection mechanism. ISomeInterface instance = (ISomeInterface)constructorInfo.Invoke(new Object ); This casting works fine. But When I try
2
6366
by: cv | last post by:
Hi, I want to create an object from a class I load from an assembly. Then I want to cast that object to a class (an interface) 'known' to the program in order to pass it to other methods that work with that interface. The casting is invalid but I can't see why, as the class I load from the assembly really is of the type I cast it to. Command a = (Command) t.GetConstructor(new...
2
358
by: Angelos Karantzalis | last post by:
Hi guys, I'm trying to load a class instance dynamically, and then cast it to it's base type so I can use it in my app. More specifically, I'm dynamically instantiating a System.Web.UI.WebControls.RequiredFieldValidator and attempting to cast it into an IValidator and/or a BaseValidator. Both casting attempts have failed miserably, throwing an InvalidCastException ... how can it be i cannot cast to the base class of my instance ???
7
2359
by: Paul Hadfield | last post by:
Hi, I'm running into one problem with trying to call "Type.GetCustomAttributes(...)" on my reflected code. Basically - I can't trap my own custom attribute - I can only catch / identify system "Custom Attributes" by type. The output below identifies that I can catch the "DefaultMemberAttribute", but I can not catch my own "DirectoryVersionAttribute". Cany anyone throw any light on this as it is driving mad Thanks in Advance, - Paul....
9
3844
by: Kuberan Naganathan | last post by:
Hello all Does anyone know of a good way to use reflection in c++? I don't mean simply using rtti or dynamic casting. I'm talking about java/c# style reflection where an actual instance of an object can be constructed through reflection and method calls can be made via the reflection apis.
5
1854
by: | last post by:
I am having problems with casting or converting a class to to an interface from which it derives. I'm certain that it's due to how it's being loaded, but I'm not sure how to get past the problem. Here's a general outline of the architecture. It's oversimplified, but I think it's enough info to help: Assembly A.dll { interface IMyBase {}
2
1300
by: Matt | last post by:
Hi, Is it possible to write a method which can take both a normal instansiated type and reflection instansiated type? For example, the following code doesn't work. It throws a casting exception claiming that a type cannot be converted to another type (they are both the same reported type - RoundedRectangle): ///code that sets classThatImplementsFactorySuppliedInterface by
11
6388
by: =?Utf-8?B?dG9iaXdhbl9rZW5vYmk=?= | last post by:
The following code is in a custom deserializer: object value = (int) 1; string nameToParse = Enum.GetName(field.FieldType, value); value = Enum.Parse(field.FieldType, nameToParse); Currently we follow the path below: intValue --enum name --enum value
0
8266
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
8705
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...
1
8365
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8505
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...
0
7196
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5574
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
4198
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1811
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1511
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.