How to clone subscribtions to object's events is vs.net? - vb.net

I have a custom datagridviewcolumn in which i've added an event.
The problem is, I can't work out how to see who has subscribed to the current column object's event and add those subscriptions to the cloned column object.
I get around this problem by asking the calling program to pass the address of the handler to a delegate in the custom column, instead of adding a handler to the event.
Forgive my terminology, I hope you understand what i'm trying to say!
By receiving the reference to the method, the datagridviewcolumn now has control and can then easily clone that reference.
This is fine, but users of controls expect to be able to suscribe to events by selecting the event in visual studio - which creates a template of the method.

At least in C# you can have "adders" and "removers" for events, like getters and setters for properties.
Maybe you can use that to do some custom processing during the process of somebody adding an event handler to the event?
EDIT
I don't know much about VB.NET, but I googled a little and found the following snippet:
Public Delegate Sub WorkDone(ByVal completedWork As Integer )
Private handlers As New ArrayList()
Public Custom Event WorkCompleted As WorkDone
AddHandler (ByVal value As WorkDone)
If handlers.Count <= 5 Then
handlers.Add(value)
End If
End AddHandler
RemoveHandler(ByVal value As WorkDone)
handlers.Remove(value)
End RemoveHandler
RaiseEvent (ByVal completedWork As Integer)
If completedWork > 50 Then
For Each handler As WorkDone In handlers
handler.Invoke(completedWork)
Next
End If
End RaiseEvent
End Event
This should help you customize your event handler, so that you can "see" the delegates being added to the event from within your class.

For anyone interested, I chanced upon a way to perform this without the need for a custom event.
By suffixing the event name with Event, you have access to some properties and methods.
So in Thorsten's example, I would refer to the event as WorkCompletedEvent.
Specific to this question, there is the method GetInvocationList that returns a list of delegates attached to the event.
In addition to this, checking if WorkCompletedEvent IsNot Nothing, will tell you whether there are handlers for the event without having to retrieve the invocation list.

Related

Issues with Event Handlers not being removed (using RemoveHandler) when sender is part of another class

I have a system where a Class of "Automation Providers" is working with some Control objects to provide some advanced monitoring functionality to them (by dynamically monitoring events).
A part of my code; A class called Automation_Provider contains a function called Browser_Navigate that takes in a reference to a System.Windows.Forms.WebBrowser instance and performs a .Navigate operation with a URL.
The special functionality it provides is that it sets an Event Handler to the Browser.DocumentCompleted to perform some actions when the event is raised.
This part actually works. What doesn't work, is I'm trying to dynamically remove the handler that causes the Subroutine to be called in the first place, but it doesn't seem to remove the Handler and if I try to call the function again, it fires twice.
The code looks like this:
Public Class Automation_Functions
Public Function Browser_Navigate(ByRef Browser As WebBrowser, ByVal Address As String) As Function_Status
'-----------------------------------------------------------------------------------
' A bunch of URL checks are performed here to make sure the "Address" is a valid URL
'-----------------------------------------------------------------------------------
AddHandler Browser.DocumentCompleted, AddressOf Browser_Navigation_Callback
Browser.Navigate(Address)
End Function
Private Sub Browser_Navigation_Callback(sender As Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
'Get the browser object from the sender and remove the handler that initially called this function
Dim Browser As WebBrowser = CType(sender, WebBrowser)
RemoveHandler Browser.DocumentCompleted, AddressOf Browser_Navigation_Callback
'------------------------------------------------------------------------------------------
' A bunch of operations are performed here related to telling the caller of the original
' function about the performance of the web page - stuff like load time, etc.
'------------------------------------------------------------------------------------------
End Sub
End Class
However the Past Handlers are never actually removed from the Browser_Navigation_Callback function - I know this because calling the Browser_Navigate function a second time results in Browser_Navigation_Callback function being called twice, then if you call it a third time, it gets called Three times! - The Handlers just compound on top of each other since they never actually get removed.
I've been unable to find any reason as to why this is happening - I'm assuming it might have something to do with the fact that the WebBrowser object is actually inside of another class and casting the sender as a WebBrowser object doesn't refer it back to the original WebBrowser instance, but creates a new instance. However I have no idea on how to confirm that this is actually what is happening since I can't really see the attached event handlers in debug mode.
Other than that - this code should be working. Any help would be appreciated!
One of the features of VB when Option Strict is not set is that it will use "relaxed delegate conversion". This means that when a delegate argument does not exactly match the required signature but is compatible with it, VB will automagically insert an anonymous wrapper that converts from the provided delegate to the required signature.
This has a negative interaction with AddHandler and RemoveHandler. VB creates a new anonymous wrapper on each call, and each instance is distinct. As a practical matter, that means that it is impossible to remove a handler that has been added when relaxed delegate conversion is used.
With Option Strict on, relaxed delegate conversion is disabled, so it turns into a compiler error when the delegate argument does not exactly match the required signature. I have not found an individual compiler switch that will turn off relaxed delegate conversion, so the only way to deal with this is to turn on Option Strict for the file.

Access event in a user control created in code behind?

I'm trying to create a user control in my code behind, and then respond to events in that control. Presumably because the control doesn't exist at compile time, Visual Studio can't compile the handler subroutine I created to catch my control's event. Importantly, I want to decide the type of control at runtime (which is why I'm not just hard-coding it).
[before going on, the controls work correctly, including events and event handlers when used in the 'normal' way of creating the controls in XAML. I want to create the control instances in code behind so I can avoid duplicating pages that are 99% identical]
This 'works' (but doesn't give me the flexibility I need):
Public WithEvents AnswerPanel As MyControls.ScrollerControl
... (and the initialisation in the New() sub):
AnswerPanel = New MyControls.ScrollerControl
ItemStack3.Children.Add(AnswerPanel)
AddHandler AnswerPanel.GuessMade, AddressOf CheckAnswer
... (this is the handler sub responding to a custom event in the ScrollerControl)
Public Sub CheckAnswer(answer As String) Handles AnswerPanel.GuessMade
With the code above everything works as I expect: the control is created at runtime and its event is handled correctly.
What I want to achieve is to be able to choose a different user control when I initialise my control (e.g. ScrollerControl2, ScrollerControl3, etc.) I can create the controls this way by changing the first line to:
Public WithEvents AnswerPanel As UserControl
But once that change is made I can no longer reference the custom event in my handler as (presumably) the compiler sees it as a generic UserControl, which doesn't include my custom GuessMade event. The compiler errors on the event name and tells me it doesn't exist.
I'm sure I'm doing something wrong here. I think it's a theory/concept issue rather than my code.
Am I on the right track or going about this in the wrong way?
If I am reading this right, you have a user control that fires an event and you want the parent page to catch that even? If so, you need to raise the event, which will cause the event to bubble to the the parent. IE:
Partial Class user_controls_myControl
Inherits System.Web.UI.UserControl
Public Event DataChange As EventHandler
End Class
This creates a control with a public event called DataChange. Now, if you look at the code in the parent page that instantiates the user control, you will see that it has an event called "OnDataChange". Just like an onCLick event, you can assign this a method in the parent page. Now, you just need to raise the event in the user control. This can be added in some event in the control, like a button click or radio button change event:
RaiseEvent DataChange(Me, New EventArgs)
This takes two objects, the sender and event arguments. Typically I pass ME, which is the user control. This is great because you can use reflection to get all the controls public properties. You can also use this to cast objects to your control type. I rarely pass event arguments but you certainly could.
I answered a similar question here: Handling events of usercontrols within listview
If this is not what you had in mind, let me know
EDIT: To add a user control dynamically and attach the event:
First, in the page that will be using the control, you will need to add a place holder:
<asp:PlaceHolder ID="placeholder1" runat="server"></asp:PlaceHolder>
as well as a reference to the user control at the head of the page (depending on how the page is setup, you may not need this. If you get a page directive error, remove it):
<%# Reference="" Control="~/user_controls/myControl.ascx"%>
In the parent page, you can then create a user control and add it to the place holder. You must declare the user control with events like this:
Private WithEvents myNewControl As New user_controls_myControl
then, in some method you can add it to the page like this:
Dim getPh As New PlaceHolder
'create an instance of the user control
newMyControl = CType(LoadControl("~/user_controls/myControl.ascx"), user_controls_myControl)
'get a handle on the place holder
getPh = me.placeHolder1
'add the user control to the place holder
getPh.Controls.Add(newMyControl)
Then, make sure you have event method:
Protected Sub myEvent(ByVal sender As Object, ByVal e As EventArgs) Handles myNewControl.DataChange
End Sub
So, if you added the RaiseEvent to the user control like I suggested earlier, this should work for you.
I have an answer to this now. As I suspected I was sort of thinking about the problem from the wrong angle.
In a nutshell I was trying to raise an event from my user controls, but I needed to be raising the events in the base class and calling that from my user controls.
So my base class (which my user controls inherit from), now contains the following:
Public Event GuessMade(answer As String)
Protected Sub RaiseGuessEvent(answer As String)
RaiseEvent GuessMade(answer)
End Sub
Then, in my user control(s), when I need to raise the event, I simply call the RaiseGuessEvent sub like this:
Me.RaiseGuessEvent(CurrentValue)
And additionally, I had to remove the event from my subclasses/user controls, of course.

VB.NET: Add Cancel Event Handler From Other Class

I am trying to figure out a way to use events, handlers - to cancel an operation (a progress bar) from an asynchronous operation.
I have a class, ProgressBar, that is displaying the progress of an operation. It has a Cancel button (which is Friend WithEvents, typically generated, and has a Private Sub ButtonCancel_click). Nothing special.
The Cancel sets a public CancelButtonHasBeenPressed.
I want to be able to react to pressing Cancel, in another class.
I read about adding a handler to react to an event, and removing the handler at the end of the operation, which is what I should be doing.
Something like:
Public Function Mine(ByRef myProgress As ThatProgressWindow)
' some setup
AddHandler CancelEvent, AddressOf myProgress.ButtonCancel_Click
' create and call workers
RemoveHandler CancelEvent, AddressOf myProgress.ButtonCancel_Click
End Function
Public Event CancelEvent()
Private Function worker(ByVal state As Object) As Object
' do work
If ' how do I check for the event ? Then drop everything and run
End Function
The problems with the code/pseudocode above:
1) in the AddHandler, I should be adding an event that exists, something connected to the actual cancellation - but there is nothing in the ProgressBar, as is, to do that - how do I add a cancel ? I only have a Cancel button... So I had to make the button_click Public which is probably wrong...
Somehow, I was thinking that the user pressing Cancel would trigger that event... Is that not true ? I am truly new to this, and the web seems to assume, in all the examples, that the people looking at those examples are already experts.
2) How do I check that the event has been raised ?
As I tried to type "If" followed by an event name, in any form, Intellisense kept telling me that it was wrong.
Please, help me get started !
Thank you.
Have you considered using a BackgroundWorker? It supports progress events and cancellation.
As an aside, don't use ByRef in your Mine function. It is not required and could lead to subtle bugs down the road if someone maintaining your code doesn't realize the parameter is ByRef.

Is there any way to clear subscription to an event in VB.NET?

In C#, I took the habit on clearing every subscriptions to my custom events in Dispose() to avoid memory leaks of subscribers forgetting to unsubscribe from my events.
It was very simple to do, simply by calling MyEvent = null since the C# compiler automatically generates a delegate field. Unfortunately in VB.NET, there seems to be no simple way to do this. The only solution I came up with was to write a Custom Event, adding custom add and remove handlers calling Delegate.Combine / Delegate.Remove, basically what the C# compiler does. But having to do this for every event just to be able to clear the subscriptions seems a little 'overkill' to me.
Does anyone have another idea to solve this problem? Thanks.
It's exactly the same in VB.Net. The compiler automatically creates a delegate field for each event, just like the C# compiler, but in VB the field is hidden. However you can access the variable from your code - it's always named XXXEvent, where XXX is the event name.
So you can easily clear subscriptions to the event, just like in C#:
Public Class Class1
Implements IDisposable
Event MyEvent()
Sub Clear() Implements IDisposable.Dispose
Me.MyEventEvent = Nothing ' clear the hidden variable '
End Sub
End Class
I'm also thinking it should be possible to use reflection to automatically find all the hidden delegate variables, and clear them. Then they don't have to be listed in the Clear method.
I've got only vague knowledge of VB.NET, but what about AddHandler / RemoveHandler?

Force multi-threaded VB.NET class to display results on a single form

I have a windows form application that uses a Shared class to house all of the common objects for the application. The settings class has a collection of objects that do things periodically, and then there's something of interest, they need to alert the main form and have it update.
I'm currently doing this through Events on the objects, and when each object is created, I add an EventHandler to maps the event back to the form. However, I'm running into some trouble that suggests that these requests aren't always ending up on the main copy of my form. For example, my form has a notification tray icon, but when the form captures and event and attempts to display a bubble, no bubble appears. However, if I modify that code to make the icon visible (though it already is), and then display the bubble, a second icon appears and displays the bubble properly.
Has anybody run into this before? Is there a way that I can force all of my events to be captured by the single instance of the form, or is there a completely different way to handle this? I can post code samples if necessary, but I'm thinking it's a common threading problem.
MORE INFORMATION: I'm currently using Me.InvokeRequired in the event handler on my form, and it always returns FALSE in this case. Also, the second tray icon created when I make it visible from this form doesn't have a context menu on it, whereas the "real" icon does - does that clue anybody in?
I'm going to pull my hair out! This can't be that hard!
SOLUTION: Thanks to nobugz for the clue, and it lead me to the code I'm now using (which works beautifully, though I can't help thinking there's a better way to do this). I added a private boolean variable to the form called "IsPrimary", and added the following code to the form constructor:
Public Sub New()
If My.Application.OpenForms(0).Equals(Me) Then
Me.IsFirstForm = True
End If
End Sub
Once this variable is set and the constructor finishes, it heads right to the event handler, and I deal with it this way (CAVEAT: Since the form I'm looking for is the primary form for the application, My.Application.OpenForms(0) gets what I need. If I was looking for the first instance of a non-startup form, I'd have to iterate through until I found it):
Public Sub EventHandler()
If Not IsFirstForm Then
Dim f As Form1 = My.Application.OpenForms(0)
f.EventHandler()
Me.Close()
ElseIf InvokeRequired Then
Me.Invoke(New HandlerDelegate(AddressOf EventHandler))
Else
' Do your event handling code '
End If
End Sub
First, it checks to see if it's running on the correct form - if it's not, then call the right form. Then it checks to see if the thread is correct, and calls the UI thread if it's not. Then it runs the event code. I don't like that it's potentially three calls, but I can't think of another way to do it. It seems to work well, though it's a little cumbersome. If anybody has a better way to do it, I'd love to hear it!
Again, thanks for all the help - this was going to drive me nuts!
I think it is a threading problem too. Are you using Control.Invoke() in your event handler? .NET usually catches violations when you debug the app but there are cases it can't. NotifyIcon is one of them, there is no window handle to check thread affinity.
Edit after OP changed question:
A classic VB.NET trap is to reference a Form instance by its type name. Like Form1.NotifyIcon1.Something. That doesn't work as expected when you use threading. It will create a new instance of the Form1 class, not use the existing instance. That instance isn't visible (Show() was never called) and is otherwise dead as a doornail since it is running on thread that doesn't pump a message loop. Seeing a second icon appear is a dead give-away. So is getting InvokeRequired = False when you know you are using it from a thread.
You must use a reference to the existing form instance. If that is hard to come by (you usually pass "Me" as an argument to the class constructor), you can use Application.OpenForms:
Dim main As Form1 = CType(Application.OpenForms(0), Form1)
if (main.InvokeRequired)
' etc...
Use Control.InvokeRequired to determine if you're on the proper thread, then use Control.Invoke if you're not.
You should look at the documentation for the Invoke method on the Form. It will allow you to make the code that updates the form run on the thread that owns the form, (which it must do, Windows forms are not thread safe).
Something like
Private Delegate Sub UpdateStatusDelegate(ByVal newStatus as String)
Public sub UpdateStatus(ByVal newStatus as String)
If Me.InvokeRequired Then
Dim d As New UpdateStatusDelegate(AddressOf UpdateStatus)
Me.Invoke(d,new Object() {newStatus})
Else
'Update the form status
End If
If you provide some sample code I would be happy to provide a more tailored example.
Edit after OP said they are using InvokeRequired.
Before calling InvokeRequired, check that the form handle has been created, there is a HandleCreated property I belive. InvokeRequired always returns false if the control doesn't currently have a handle, this would then mean the code is not thread safe even though you have done the right thing to make it so. Update your question when you find out. Some sample code would be helpful too.
in c# it looks like this:
private EventHandler StatusHandler = new EventHandler(eventHandlerCode)
void eventHandlerCode(object sender, EventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(StatusHandler, sender, e);
}
else
{
//do work
}
}