473,881 Members | 1,611 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Beginner question about Reflection & code snippet.

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.Creat eInstance() it always fails. However if I walk my assembly and get a type value, the call to
Activator.Creat eInstance() will always succeed.

My next question, is why can't I cast the return value from the Invoke() call to a DataSet. I thought it returned an object. Am I
missing something? The test method returns a DataSet.

Finally, I got some advice to use Type.InvokeMemb er() in this forum, but I had to unwrap the return and then needed to use typed
values to complete the call and I want to be able to build this entirely from strings from a database.

If my approach is way off, could someone please point me in the right direction?

Thanks. My code snippet is below.

MethodInfo myMethodEX = null;
Type myTypeEX = null;
Assembly assembly1 = Assembly.Load( "Ripple.Home.Bu sinessLayer" );
Type[] types = assembly1.GetTy pes();
foreach( Type definedType in types )
{
sClass = definedType.Nam e;
if ( sClass == "Role" )
{
myTypeEX = definedType;
MethodInfo[] myMethod = definedType.Get Methods();
foreach( MethodInfo nextMethod in myMethod )
{
sMethod = nextMethod.Name ;
if ( sMethod == "ListAll" )
{
myMethodEX = nextMethod;
break;
}
}
}
if ( sClass == "Role" )
{
break;
}
}

// This always succeeds
Object obj = Activator.Creat eInstance( myTypeEX );

// This ALWAYS Fails
// Object obj = Activator.Creat eInstance( "Ripple.Home.Bu sinessLayer", "Role" );

// The cast fails. How do I get my return value?
DataSet ds = (DataSet) myMethodEX.Invo ke( obj, null );

Nov 15 '05 #1
1 2629
Jeffrey,

Thanks for your insight. My problem with Activator.Creat eInstance() was that I was not using the full name in the second parameter.

I have an additional question that I could use your insight into. My approach now involves walking an entire assembly to get a
MethodInfo variable to do an Invoke() on. Is there a better, or more efficient way to use reflection to call a specific method in
an assembly if you already know the assembly name, the type and the method? I will be storing these values as strings in a database
log. Someone told me to use Type.InvokeMemb er(). How does that figure in to all of this?

Finally, if this is the best way to do this, can you give me a small example of how to format the parameter[] for the second
parameter of Invoke()? I will be wanting to call methods with parameters eventually.

Thanks.

Mike Malter
"Jeffrey Tan[MSFT]" <v-*****@online.mi crosoft.com> wrote in message news:GE******** ******@cpmsftng xa06.phx.gbl...

Hi Mike,

The Activator.Creat eInstance(assem blyname,typenam e) function return
ObjectHandle type which wrapped the
object type.
So you should use UnWrap() method to get the object that was wrapped.
Also, I did not get any error on casting object to dataset.

Sample code listed below:

using System;
using System.Reflecti on;
using System.Runtime. Remoting ;
using System.Data ;

namespace reflectiontest
{
public class Role
{
public DataSet ListAll()
{
Console.WriteLi ne ("Role.ListAll( )");
return new DataSet ();
}
}
class Class1
{

[STAThread]
static void Main(string[] args)
{
try
{
string sClass;
string sMethod;
MethodInfo myMethodEX = null;
Type myTypeEX = null;
Assembly assembly1 = Assembly.Load( "reflectiontest " );
Type[] types = assembly1.GetTy pes();
foreach( Type definedType in types )
{
sClass = definedType.Nam e;
if ( sClass == "Role" )
{
myTypeEX = definedType;
MethodInfo[] myMethod = definedType.Get Methods();
foreach( MethodInfo nextMethod in myMethod )
{
sMethod = nextMethod.Name ;
if ( sMethod == "ListAll" )
{
myMethodEX = nextMethod;
break;
}
}
}
if ( sClass == "Role" )
{
break;
}
}

//Object obj1= Activator.Creat eInstance( myTypeEX );
ObjectHandle obj2 = Activator.Creat eInstance(
"reflectiontest ","reflectionte st.Role" );
Object obj3=obj2.Unwra p();

DataSet ds=(DataSet)myM ethodEX.Invoke( obj3, null );//no error generate

}
catch(Exception e)
{
Console.WriteLi ne (e.Message );
}
Console.Read ();
}
}
}

If you have anything unclear, please feel free to let me know.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

--------------------
| From: "Mike Malter" <mi********@nos pam.com>
| Subject: Beginner question about Reflection & code snippet.
| Date: Mon, 25 Aug 2003 17:30:06 -0700
| Lines: 55
| X-Priority: 3
| X-MSMail-Priority: Normal
| X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
| X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
| Message-ID: <O0************ **@TK2MSFTNGP09 .phx.gbl>
| Newsgroups: microsoft.publi c.dotnet.langua ges.csharp
| NNTP-Posting-Host: adsl-64-175-22-129.dsl.snfc21. pacbell.net 64.175.22.129
| Path: cpmsftngxa06.ph x.gbl!TK2MSFTNG P08.phx.gbl!TK2 MSFTNGP09.phx.g bl
| Xref: cpmsftngxa06.ph x.gbl microsoft.publi c.dotnet.langua ges.csharp:1792 92
| X-Tomcat-NG: microsoft.publi c.dotnet.langua ges.csharp
|
| 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.Creat eInstance() it always fails. However if I walk my
assembly and get a type value, the call to
| Activator.Creat eInstance() will always succeed.
|
| My next question, is why can't I cast the return value from the Invoke()
call to a DataSet. I thought it returned an object. Am I
| missing something? The test method returns a DataSet.
|
| Finally, I got some advice to use Type.InvokeMemb er() in this forum, but
I had to unwrap the return and then needed to use typed
| values to complete the call and I want to be able to build this entirely
from strings from a database.
|
| If my approach is way off, could someone please point me in the right
direction?
|
| Thanks. My code snippet is below.
|
| MethodInfo myMethodEX = null;
| Type myTypeEX = null;
| Assembly assembly1 = Assembly.Load( "Ripple.Home.Bu sinessLayer" );
| Type[] types = assembly1.GetTy pes();
| foreach( Type definedType in types )
| {
| sClass = definedType.Nam e;
| if ( sClass == "Role" )
| {
| myTypeEX = definedType;
| MethodInfo[] myMethod = definedType.Get Methods();
| foreach( MethodInfo nextMethod in myMethod )
| {
| sMethod = nextMethod.Name ;
| if ( sMethod == "ListAll" )
| {
| myMethodEX = nextMethod;
| break;
| }
| }
| }
| if ( sClass == "Role" )
| {
| break;
| }
| }
|
| // This always succeeds
| Object obj = Activator.Creat eInstance( myTypeEX );
|
| // This ALWAYS Fails
| // Object obj = Activator.Creat eInstance( "Ripple.Home.Bu sinessLayer",
"Role" );
|
| // The cast fails. How do I get my return value?
| DataSet ds = (DataSet) myMethodEX.Invo ke( obj, null );
|
|
|
|

Nov 15 '05 #2

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

Similar topics

44
4309
by: lester | last post by:
a pre-beginner's question: what is the pros and cons of .net, compared to ++ I am wondering what can I get if I continue to learn C# after I have learned C --> C++ --> C# ?? I think there must be many know the answer here. thanks
6
2853
by: Laser Lu | last post by:
HI, all, I just want to invoke an internal method named 'ResolveClientUrl', which is defined in class System.Web.UI.Control, using an instance object of a type that derives from Control. Let's see the following code snippet (class MyControl is a sub class that derives directly from System.Web.UI.Control): //... MyControl instance = new MyControl(); Type type = instance.GetType();
2
3573
by: Carl Rosenberger | last post by:
Hi all, I would like to create an instance of a struct with reflection. The way I am used to doing this with classes: - get a ConstructorInfo from the Type - call Invoke() However, if a struct does not have a constructor
2
1296
by: Jim Bancroft | last post by:
Hi all, I'm writing an exception handler for one of my VB.Net methods and wondered how best to dynamically put the class and method name in my message string. My code looks like this currently: Catch ex as Exception
2
1050
by: Miro | last post by:
I am a pure beginner and reading 3 books at the same time trying to learn vb. I have created 2 forms in my "Solution" No where can I see in any of the books how you load / call one form from the other. So how do you: A) Load 1 form from the other.
7
2372
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....
1
2627
by: =?Utf-8?B?VGltIFBhY2w=?= | last post by:
I am new to Reflection. I am building a windows app that navigates the control tree of a Windows form and creates XAML representing the form. I am using reflection to get the properties of each control to create the XmlAttributes for the Control's XAML node. The problem is, regardless of how I set the 'Visible' property for a control in the form, its value is always read as "False" through reflection. Here is a snippet of my code: Type...
5
4305
by: Klaudiusz Bryja | last post by:
Hi, This is for NetCF 2.0. I need to create event handling code which using reflection. I have some parameters in XML which describe how event should be handled. I have code to create delegate: public class DelegateEx {
2
3531
by: nicholas08 | last post by:
I am new to programming and trying to work on a simple console app. I am making a simple Library Management system where the user/admin can manage members and item. Attaching the menu so it's clear to understand what I am saying. http://i475.photobucket.com/albums/rr116/nicholasCsharp/Untitled.jpg So far I have only looked at Item and Member Management (option 1 and 2) Few question I had: 1. In terms of the design approach I am taking. One...
0
9927
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
9776
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
11098
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
10717
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10814
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
9552
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...
1
4597
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
2
4196
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3223
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.