473,667 Members | 2,562 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to hook up EventHandler or Delegate to UserControl thru Reflec

Hi

I have an Assembly that has various usercontrols that all implemnet
an Interface

The Interface

public interface ISettings
{
bool SaveSettings();
}
I then have a test pgm that will loop thru the asssmbly and find all classes
that implement the ISettings interface. I then display all the UserControls
on a Form

Assembly asm = Assembly.LoadFr om(@"C:\myUserC ontro.dll");
// Walk through each type in the assembly looking for our
class
foreach (Type type in asm.GetTypes())
{
if (type.IsClass == true )
{
bClass = false;
foreach (Type interfaceType in type.GetInterfa ces())
{
if (interfaceType. FullName.Contai ns("ISettings") )
{
bClass = true;
break;
}
}

if(bClass)
{
Control control = Activator.Creat eInstance(type)
as Control;
xtraTabControl1 .TabPages.Add() ;

xtraTabControl1 .TabPages[xtraTabControl1 .TabPages.Count - 1].Text =
type.FullName;

xtraTabControl1 .TabPages[xtraTabControl1 .TabPages.Count-1].Controls.Add(c ontrol);
}
}
This is all fine
The question is on the form where I create the UserControls I have a "SAVE"
button. When I hit the SAVE button I want to fire all the interface method
"SaveSettin gs" from all the UserControls.

What is the best way to do that???

Thanks
Sep 4 '08 #1
22 2413
On Thu, 04 Sep 2008 14:21:01 -0700, sippyuconn
<si********@new sgroup.nospamwr ote:
[...]
The question is on the form where I create the UserControls I have a
"SAVE"
button. When I hit the SAVE button I want to fire all the interface
method
"SaveSettin gs" from all the UserControls.

What is the best way to do that???
I don't think reflection as anything to do with the question. As far as
what's the "best way", that's not for us to say. But one option might be
to create a delegate and add the SaveSettings() method for each
implementor to the delegate. For example:

private Func<boolSaveSe ttingsHandlers;

// when adding a UserControl:
UserControl control = ...;
ISettings settings = (ISettings)cont rol;

SaveSettingsHan dlers += settings.SaveSe ttings;

// when you want all the settings to be saved, invoke the delegate:
SaveSettingsHan dlers();

Of course, it begs the question as to why the method returns a bool. If
you actually want to use that in some way, you'll want to change the
invocation. For example:

foreach (Func<boolhandl er in
SaveSettingsHan dlers.GetInvoca tionList())
{
if (!handler())
{
// return/display error, whatever
}
}

Pete
Sep 4 '08 #2
On Sep 4, 2:41*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Thu, 04 Sep 2008 14:21:01 -0700, sippyuconn *
I don't think reflection as anything to do with the question. *As far as *
what's the "best way", that's not for us to say. *But one option might be *
to create a delegate and add the SaveSettings() method for each *
implementor to the delegate. *For example:
Of course, it begs the question as to why the method returns a bool. *If *
you actually want to use that in some way, you'll want to change the *
invocation. *For example:
yeah I guess I second Peter on this. I find that a delegate is like a
super "GOTO" statement, that you can 'throw' to call another function
that's not even aware of what's going on in the code that throws. A
global GOTO.

The other option, equally bad but easier to write, is of course to use
the old standby of a 'global' boolean (to the namespace, as C# has no
true global variables). When the global boolean is changed, an if
statement somewhere in your active code takes over. And of course the
related solution of using enums and case statements, which is how
classic Windows works.

I think the problem though is that in C# Winforms code and data and
not separated. I'm looking forward to studying WPF in a few months
and seeing how they supposedly solved the problem by separating code
and data.

RL
Sep 4 '08 #3
I mention reflection because the interface is in a third party assemble that
I don't have access to code so I needed to use reflection to get at the
interface and Method

But I am stuck - how to tie the Class or Methods of Class using relection to
extract - to then tie to Delegate
public delegate bool CustomSaveHandl er();
Assembly asm = Assembly.LoadFr om(@"C:\myassem bly.dll");
// Walk through each type in the assembly looking for our
class
foreach (Type type in asm.GetTypes())
{
if (type.IsClass == true )
{
bClass = false;
foreach (Type interfaceType in type.GetInterfa ces())
{
if (interfaceType. FullName.Contai ns("ISettings") )
{
bClass = true;
break;
}
}

if(bClass)
{
Control control = Activator.Creat eInstance(type)
as Control;
xtraTabControl1 .TabPages.Add() ;

xtraTabControl1 .TabPages[xtraTabControl1 .TabPages.Count - 1].Text =
type.FullName;

xtraTabControl1 .TabPages[xtraTabControl1 .TabPages.Count-1].Controls.Add(c ontrol);

MethodInfo typemethod =
type.GetMethod( "SaveSettings") ;

?????

"raylopez99 " wrote:
On Sep 4, 2:41 pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Thu, 04 Sep 2008 14:21:01 -0700, sippyuconn
I don't think reflection as anything to do with the question. As far as
what's the "best way", that's not for us to say. But one option might be
to create a delegate and add the SaveSettings() method for each
implementor to the delegate. For example:
Of course, it begs the question as to why the method returns a bool. If
you actually want to use that in some way, you'll want to change the
invocation. For example:

yeah I guess I second Peter on this. I find that a delegate is like a
super "GOTO" statement, that you can 'throw' to call another function
that's not even aware of what's going on in the code that throws. A
global GOTO.

The other option, equally bad but easier to write, is of course to use
the old standby of a 'global' boolean (to the namespace, as C# has no
true global variables). When the global boolean is changed, an if
statement somewhere in your active code takes over. And of course the
related solution of using enums and case statements, which is how
classic Windows works.

I think the problem though is that in C# Winforms code and data and
not separated. I'm looking forward to studying WPF in a few months
and seeing how they supposedly solved the problem by separating code
and data.

RL
Sep 5 '08 #4
On Thu, 04 Sep 2008 19:38:02 -0700, sippyuconn
<si********@new sgroup.nospamwr ote:
I mention reflection because the interface is in a third party assemble
that
I don't have access to code so I needed to use reflection to get at the
interface and Method

But I am stuck - how to tie the Class or Methods of Class using
relection to
extract - to then tie to Delegate
As demonstrated in my code example, once you have an instance of the class
(in my example, a UserControl that implements the interface...in your own
example, you've simply got the type Control) just cast it to the interface
and use the method from that.

In fact, since you named your Control instance variable the same as I
named my UserControl instance variable, the code is basically the same.

Pete
Sep 5 '08 #5
Dear sippyuconn,

You can call the Type.GetInterfa ce() method to retrieve the interface, and
call Type.GetMethod( ) method to retrieve the "SaveSettin gs" method, then
call the Invoke() method to invoke the "SaveSettin gs" method.

For example, you can do something like this(I use a List<Control>
collection to store the UserControls in this example):

List<Controlctl sFromAsm = new List<Control>() ;

private void button1_Click(o bject sender, EventArgs e)
{
foreach (Control c in this.ctlsFromAs m)
{

c.GetType().Get Interface("ISet tings").GetMeth od("SaveSetting s").Invoke(c ,
null);
}
}

If any of this is unclear, please feel free to let me know.

Sincerely,
Zhi-Xin Ye
Microsoft Managed Newsgroup Support Team

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsof t.com.

=============== =============== =============== =====
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subs...#notifications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://support.microsoft.com/select/...tance&ln=en-us.
=============== =============== =============== =====
This posting is provided "AS IS" with no warranties, and confers no rights.

Sep 5 '08 #6
Reading these replies makes me wonder: is it possible to use
reflection to extract methods from .exe files? Not .DLL but
executables? I doubt it, because it would defeat the purpose of the
obfuscator, and/or why people distribute binary rather than source
code (to protect the IP in the source code), but I could be wrong.

Just curious.

RL
Zhi-Xin Ye [MSFT] wrote:
Dear sippyuconn,

You can call the Type.GetInterfa ce() method to retrieve the interface, and
call Type.GetMethod( ) method to retrieve the "SaveSettin gs" method, then
call the Invoke() method to invoke the "SaveSettin gs" method.
Sep 5 '08 #7
On Sep 5, 9:27*am, raylopez99 <raylope...@yah oo.comwrote:
Reading these replies makes me wonder: *is it possible to use
reflection to extract methods from .exe files?
Yes.
>*Not .DLL but executables? *I doubt it, because it would defeat the purpose of the
obfuscator, and/or why people distribute binary rather than source
code (to protect the IP in the source code), but I could be wrong.
Not everyone wants to have to compile code before using it. Note that
using reflection to find methods isn't the same as decompilation,
although both are feasible on executables. Download RedGate Reflector
and have a look.

http://www.red-gate.com/products/reflector/

Jon
Sep 5 '08 #8
"raylopez99 " <ra********@yah oo.comwrote in message
news:a9******** *************** ***********@a70 g2000hsh.google groups.com...
Reading these replies makes me wonder: is it possible to use
reflection to extract methods from .exe files? Not .DLL but
executables? I doubt it, because it would defeat the purpose of the
obfuscator, and/or why people distribute binary rather than source
code (to protect the IP in the source code), but I could be wrong.
For the record, there isn't much difference between .NET .exe and .dll
assemblies. For example, you can actually reference an .exe assembly from a
project as if it were a .dll library, and use the public classes/methods
within it as usual.
Sep 5 '08 #9
This is where my problem is - I cannot cast the Method because it is a
ThirdParty Assemble
public delegate bool CustomSaveHandl er();
....

MethodInfo typemethod = type.GetMethod( "SaveSettings") ;

I am trying to add the method to delegate by
but won't compile
Error 3 'typemethod' is a 'variable' but is used like a 'method'
CustomSaveHandl er a = new CustomSaveHandl er(typemethod);

or

CustomSaveHandl er b;
b += new CustomSaveHandl er(typemethod);

What is the way around this if I cannot cast the method ???

Thanks

"Peter Duniho" wrote:
On Thu, 04 Sep 2008 19:38:02 -0700, sippyuconn
<si********@new sgroup.nospamwr ote:
I mention reflection because the interface is in a third party assemble
that
I don't have access to code so I needed to use reflection to get at the
interface and Method

But I am stuck - how to tie the Class or Methods of Class using
relection to
extract - to then tie to Delegate

As demonstrated in my code example, once you have an instance of the class
(in my example, a UserControl that implements the interface...in your own
example, you've simply got the type Control) just cast it to the interface
and use the method from that.

In fact, since you named your Control instance variable the same as I
named my UserControl instance variable, the code is basically the same.

Pete
Sep 5 '08 #10

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

Similar topics

2
2679
by: Sandor Heese | last post by:
Question, When using BeginInvoke (on a From to marshal to the UI thread) with the EventHandler delegate I see some strange behaviour. The problem is that I call the UpdateTextBox method with a class derived from EventArgs ( i.e. MyEventArgs) and when the BeginInvoke is called and the UpdateTextBox methode is call on the UI thread the parameter e (EventArgs) does not contain the derived MyEventArgs object but a EventArgs object. The...
3
3338
by: Matias Szulman | last post by:
Hi! I need to know if an event (i.e. button1_click) has an eventhandler associated. Is this possible in c#? Thanks, Matias
5
624
by: Torben | last post by:
For test purposes I attach an event to a control, say a TextBox TextChanged event. At another time the same event delegate is attached to some other control, maybe a listbox. Same event function every where. The event function should happen only once for that control (and then, maybe again if it is attached to the control again). Could I make that deattachment operation general? could the function find out what event it is attaced?...
6
6012
by: Robert Werner | last post by:
I want to write one general purpose set of code that will handle the population (where required) of all controls on a form. Though I'm new to C# my instinct is to somehow hook into the Load event of the Control class, as this should get inherited down to all of the controls. Two questions: 1. Is this possible? 2. What's the simplest, most elegant way to do it?
9
3080
by: Christopher Weaver | last post by:
Can anyone tell me how I could iterate through a collection of controls on a form while assigning their event handlers to another identical collection of controls on the same form. So far, thanks to another programmer, I've got this working out quite nicely for the properties: Type ctrlType = subject.GetType(); ConstructorInfo cInfo = ctrlType.GetConstructor(Type.EmptyTypes); Control retControl = (Control)cInfo.Invoke(null);
13
9778
by: jac | last post by:
Hae, I have a windows form with a ComboBox an other things. On that combobox I have an eventhandler on de selectedindexchanged. But somewhere in my code want to do excecute the same code that is writen in the eventhandler. Is it posible to call that eventhandler from the code (not from a real selectedindexchanged on the form). So, I don't have to call that code twice.
0
2486
by: zeng.hui.stephen | last post by:
I download the demo http://msdn.microsoft.com/msdnmag/issues/02/10/cuttingedge/. I inherite the demo, and write my code. I want to use Hook to monitor C++ Edit change. I use a C# form containing a Edit(textbox) and button to test at first. When I change text in Edit or press button to setText value, I want to monitor the change event. But the event code always return 0, why?
2
8531
by: markliam | last post by:
I have auto-generated some code for a button by double clicking it. By default, the code is created with a return type of void and assigned to a click event. Now, I want the function to return a DialogResult instead, so I go and replace 'void' with DialogResult in the function header, but then I get an error stating it's the wrong return type. Double clicking the error in Visual Studio takes me to where the EventHandler is assigned to...
1
7640
by: Blip | last post by:
private void SerialPortLog(LogMsgType msgtype, string msg) { { txtReadData.Invoke(new EventHandler(delegate { txtReadData.SelectedText = string.Empty; txtReadData.SelectionFont = new Font(txtReadData.SelectionFont, FontStyle.Bold); txtReadData.SelectionColor =
0
8365
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
8883
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
8788
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...
0
8646
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
7390
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
5675
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
4200
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
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2776
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.