Log who subscribs to a event - c#

It it possible to retrive who is subscribing to a event in C#?
example
class MyClass
{
public string Name { get; set; }
}
class Syncronizer
{
public delegate void SynchronizatonEventHandler(MyClass myClass);
public event SynchronizatonEventHandler OnSyncFinished;
}
If i have something like that is it possible for me to see/use the myClass.Name string and use it for logging when the event is subscribed to?
What i want to accomplish is that i want to log every subscribe and unsubscribe from my Syncronizer class.

You can do the following:
class MyClass
{
public string Name { get; set; }
}
class Syncronizer
{
public delegate void SynchronizatonEventHandler(MyClass myClass);
internal event SynchronizatonEventHandler _onSyncFinished;
public event SynchronizatonEventHandler OnSyncFinished
{
add
{
// Perform some code before the subscription.
// Add the event.
_onSyncFinished += value;
// Perform some code after the subscription;
}
remove
{
// Perform some code before the subscription.
// Remove the event.
_onSyncFinished -= value;
// Peroform some code after the subscription.
}
}
}

Here's a working example:
class Syncronizer
{
public delegate void SynchronizatonEventHandler(MyClass myClass);
private event SynchronizatonEventHandler onSyncFinished;
public event SynchronizatonEventHandler OnSyncFinished
{
add
{
var method = new StackTrace().GetFrame(1).GetMethod();
Console.WriteLine("{0}.{1} subscribing", method.ReflectedType.Name, method.Name);
onSyncFinished += value;
}
remove
{
var method = new StackTrace().GetFrame(1).GetMethod();
Console.WriteLine("{0}.{1} unsubscribing", method.ReflectedType.Name, method.Name);
onSyncFinished -= value;
}
}
}
Note that you can not log myClass.Name, since that doesn't exist in the add and remove procedures. I have it logging (to Console.WriteLine) the class and method that subscribed to the event, which is, I think, what you were after.

You need to create an explicit event with your own accessors:
public event SynchronizatonEventHandler OnSyncFinished {
add { ... }
remove { ... }
}
add and remove take a value parameter containing the delegate instance being removed from or added to the event.
For logging purposes, you can get the Method and Target properties of the instance.

Sth. like this should solve your issue:
private event SynchronizatonEventHandler m_OnSyncFinished;
public event SynchronizatonEventHandler OnSyncFinished
{
add
{
// Custom code could be added here...
m_OnSyncFinished += value;
}
remove
{
// Custom code could be added here...
m_OnSyncFinished -= value;
}
}

Related

How to write a Trigger?

I want my C# code to call an event whenever a value is assigned to my object.
How exactly would I need to go about that?
class MyClass {
ManualResetEvent mre;
public MyClass() {
mre = new ManualResetEvent(false);
Data = null;
}
public object Data { get; set; }
void DataSet(object sender, EventArgs e) {
Console.WriteLine("object Data has been set.");
mre.Set();
}
}
Delegates don't seem to be what I need. An event, maybe? How would I write such an event, if so?
MyClass mc;
void processA() {
mc = new MyClass();
mc.Data = GetDataFromLongProcess();
}
private object data;
public object Data {
get { return data;}
set {
if(value != data) {
data = value;
OnDataChanged();
}
}
}
protected virtual void OnDataChanged() {
EventHandler handler = DataChanged;
if(handler != null) handler(this, EventArgs.Empty);
}
public event EventHandler DataChanged;
then hook any code to the DataChanged event. For example:
MyClass mc = ...
mc.DataChanged += delegate {
Console.WriteLine("new data! wow!");
};
If you want to fire an event when your property is set, you would do something like this:
public event Action OnDataChanged;
protected object _data = null;
public object Data
{
get { return _data; }
set
{
_data = value;
if(OnDataChanged != null)
OnDataChanged();
}
}
Then you would simply wire up event handlers to your object like so:
mc = new MyClass();
mc.OnDataChanged += delegate() { Console.WriteLine("It changed!"); };
mc.Data = SomeValue();
I think you're on the right track with an event-based model. Also take a look at the Observer pattern (which is the basis for .Net delegates and events underneath it all, as I understand):
http://www.dofactory.com/Patterns/PatternObserver.aspx
But the bottom line, as the other useful answer so far (Mr. Gravell's implementation) indicates, you're going to have to have code IN the setter to get it hooked up. The only alternative would be to poll the value for changes, which just smells bad to me.
you could implement INotifyPropertyChanged (this is more or less a event) or you could take your class a Action (Trigger) and call this, whenn the property changed.
Just don't use automatic properties but a concrete setter and call your event/trigger from there.
Conceptually, you would define an event in your class, and in your property set blocks, you would invoke the event with the necessary arguments to determine what just happened.
public event SomeDelegateThatTakesIntAsParameter myEvent;
void SetData(int data)
{
if(myEvent!= null)
myEvent(data)
}

What is the preferred way to bubble events?

I have three objects ObjectA has an ObjectB, ObjectB has an ObjectC. When ObjectC fires an event I need ObjectA to know about it, so this is what I've done...
public delegate void EventFiredEventHandler();
public class ObjectA
{
ObjectB objB;
public ObjectA()
{
objB = new ObjectB();
objB.EventFired += new EventFiredEventHandler(objB_EventFired);
}
private void objB_EventFired()
{
//Handle the event.
}
}
public class ObjectB
{
ObjectC objC;
public ObjectB()
{
objC = new ObjectC();
objC.EventFired += new EventFiredEventHandler(objC_EventFired);
objC.FireEvent();
}
public event EventFiredEventHandler EventFired;
protected void OnEventFired()
{
if(EventFired != null)
{
EventFired();
}
}
private void objC_EventFired()
{
//objC fired an event, bubble it up.
OnEventFired();
}
}
public class ObjectC
{
public ObjectC(){}
public void FireEvent()
{
OnEventFired();
}
public event EventFiredEventHandler EventFired;
protected void OnEventFired()
{
if(EventFired != null)
{
EventFired();
}
}
}
Is this the proper way to handle this, or is there a better way? I don't want ObjectA to know about ObjectC at all, only that it raised an event.
Another approach, is to wrap it using add/remove:
public class ObjectB
{
ObjectC objC;
public ObjectB()
{
objC = new ObjectC();
}
public event EventFiredEventHandler EventFired
{
add { this.objC.EventFired += value; }
remove { this.objC.EventFired -= value; }
}
}
That's the way I do it. however I would recommend change your firing mechanism to this to make it thread safe
protected void OnEventFired()
{
var tmpEvent = EventFired;
if(tmpEvent != null)
{
tmpEvent();
}
}
This keeps it from failing if EventFired becomes null between the null check and the firing.
Also it is somewhat of a standard to follow the EventHandler pattern for your event delegates.
protected virtual void OnEventFired(EventArgs e)
{
var tmpEvent = EventFired;
if(tmpEvent != null)
{
tmpEvent(this, EventArgs.e);
}
}
I was wrong about the threadsafe pattern, here is the full threadsafe event pattern
/// <summary>
/// Delegate backing the SomeEvent event.
/// </summary>
SomeEventHandler someEvent;
/// <summary>
/// Lock for SomeEvent delegate access.
/// </summary>
readonly object someEventLock = new object();
/// <summary>
/// Description for the event
/// </summary>
public event SomeEventHandler SomeEvent
{
add
{
lock (someEventLock)
{
someEvent += value;
}
}
remove
{
lock (someEventLock)
{
someEvent -= value;
}
}
}
/// <summary>
/// Raises the SomeEvent event
/// </summary>
protected virtual OnSomeEvent(EventArgs e)
{
SomeEventHandler handler;
lock (someEventLock)
{
handler = someEvent;
}
if (handler != null)
{
handler (this, e);
}
}
As other answers have stated, this is they way to do it.
But you can go beyond!!! I've just implemented a good data structure on it, and it's like to give you a spin on it.
Would be nice to have an automatic event bubbling? You could implement it using Reflection. My way is to define an Interface/Base class which declares an event (or a set of events). Then, the parameterless constructor of a base class will iterate other its properties/fields, and register automatically the members events for event propagation.
There are some restriction on design, but if you have a deep structure and/or many (structured) events, it could be nice to have everything setup without any additional line of code.
An initial base class could be:
class BaseObject {
public BaseObject() {
FieldInfo[] fInfos = this.GetType().GetFields(...);
foreach (FieldInfo fInfo in fInfos) {
object fInfoValue = fInfo.GetValue(this, null);
if (fInfoValue is BaseObject) {
BaseObject bMemberObject = (BaseObject)fInfoValue;
bMemberObject.MyEvent += new EventHandler(delegate() {
if (this.MyEvent != null)
MyEvent();
});
}
}
public event MyEvent = null;
}
Of course, as already suggested, follow the event delegate delegate(object sender, EventArgs args) (I've used a simpler event for clarity).
Naturally, is implicit that you classes A, B and C derives directly from BaseObject.
Note that any logic could be implemented to bind structured events (you could be the nested event registration using the name and/or other reflected properties.

How to make own event handler?

I am making a windows forms project in C#, in which I made a class LabelX which inherits System.Windows.Forms.Label, then added a property Mass of float type
Now, my question is how can I handle, when value of Mass is changed.
e.g.:
When user enter value zero or less than zero
I want to fire a message that "Mass can't be zero or negative"
If I am interpreting this correctly, there are two parts to this. First, you need to detect invalid values and throw exceptions. Second, you need to raise an event when the property changes. This can be achieved as follows.
private float mass;
public float Mass
{
get
{
return this.mass;
}
set
{
if (value <= 0.0F)
{
throw new ArgumentOutOfRangeException("Mass cannot be zero or negative.");
}
if (this.mass != value)
{
this.mass = value;
OnMassChanged(EventArgs.Empty);
}
}
}
public event EventHandler MassChanged;
protected virtual void OnMassChanged(EventArgs args)
{
var handler = this.MassChanged;
if (handler != null)
{
handler(this, args);
}
}
To show a message if an invalid entry is made, you should put a try \ catch block around the call to set Mass and catch the ArgumentOutOfRangeException.
Try the following:
// Created an empty form with a LabelX control on it.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Added this event from the property manager.
private void labelX1_MassChanged(object sender, EventArgs e)
{
var label = (LabelX)sender;
if (label.Mass <= 0.0)
MessageBox.Show("Mass is less than or equal to 0");
}
}
public class LabelX : Label
{
private float _mass;
public float Mass
{
get { return _mass; }
set
{
if (!value.Equals(_mass))
{
_mass = value;
OnMassChanged(EventArgs.Empty);
}
}
}
public event EventHandler MassChanged;
protected virtual void OnMassChanged(EventArgs e)
{
if (MassChanged != null)
MassChanged(this, e);
}
}
Outside of your LabelX class, create the following class:
public class MassChangedEventArgs : EventArgs
{
public float Mass { get; private set; }
public MassChangedEventArgs(float mass)
{
this.Mass = mass;
}
}
Also outside of your LabelX class, create the following delegate. This will be your event handler.
public delegate void MassChangedEventHandler(object sender, MassChangedEventArgs e);
Within your LabelX class, create an event to broadcast:
public class LabelX
{
public event MassChangedEventHandler MassChanged;
//the rest of your code here...
}
You'll also want to create a private instance method that will fire your event.
public class LabelX
{
public event MassChangedEventHandler MassChanged;
private void OnMassChanged()
{
if(MassChanged!=null)
this.MassChanged(this, new MassChangedEventArgs(this.Mass));
}
//the rest of your code here...
}
Finally, whenever your Mass property changes, call OnMassChanged. For instance:
public class LabelX
{
private float mass;
public float Mass
{
get
{
return mass;
}
set
{
mass = value;
OnMassChanged();
}
}
public event MassChangedEventHandler MassChanged;
private void OnMassChanged()
{
if(MassChanged!=null)
this.MassChanged(this, new MassChangedEventArgs(this.Mass));
}
//the rest of your code here...
}
When you want to handle that event on a per-instance basis, you just have to register a listener with the MassChanged event of your underlying object and perform whatever actions are necessary.
Events are a common pattern used in the framework. The process typically involves defining a delegate to be used as the event handlers, declaring the event using the handler, defining methods to raise the event, then hooking up to the properties the logic to raise the event.
The message you describe is better done as an Exception but here's an example to define the MassChanged event.
// Define event args if you have additional
// information to pass to your event handlers
public class MassChangedEventArgs : EventArgs
{
public MassChangedEventArgs(int oldMass)
{
OldMass = oldMass;
}
public int OldMass { get; private set; }
}
public class SomeObject
{
// There's a generic event handler delegate that can be
// used so you only need to define the event arguments.
public event EventHandler<MassChangedEventArgs> MassChanged;
// Convenience method to raise the event
protected virtual void OnMassChanged(MassChangedEventArgs e)
{
if (MassChanged != null)
MassChanged(this, e);
}
public int Mass
{
get
{
return mass;
}
set
{
// Your checks here
if (value <= 0)
throw new ArgumentOutOfRangeException("Mass", "Mass can't be zero or negative");
// Should only raise the event if the new value is different
if (value != mass)
{
// Change the mass
MassChangedEventArgs e = new MassChangedEventArgs(mass);
mass = value;
// Raise the event
OnMassChanged(e);
}
}
}
private int mass;
}
After that, it's just a matter of registering handlers to the event and going from there.
I am quite sure you you would like to 'fire' an exception in your case.
This more of a validation logic issue such AOP code contracts concept.
But if you really like to create an event for it you have to at least:
1) create an event storage variable in your label class
public event EventHandler MassChanged;
2) in your property (note that you loose the ability to use code gen functions of c# 3 for
which 'auto' implement the field to store your Mass property value)
public bool Mass
{
get { return _mass; }
set {
// check if value is invalid (0 or less) && that event subscribers exist
if(value<=0 && MassChanged != null) { MassChanged(this, null); }
else // otherwise assign ...
{
_mass = value;
}
}
}
3) create an event handler of type EventHandler
Best to read the msdn article for events: link text
Again I am pretty sure you are not handling exceptions properly in the app
if you need an event for this. I mean there is nothing wrong but events are
usually not used as means of value validations.

How to create Event Handler for my Class

I have following class
public class ButtonChange
{
private int _buttonState;
public void SetButtonState(int state)
{
_buttonState = state;
}
}
I want to fire an event whenever _buttonState value changes, finaly I want to define an event handler in ButtonChange
Will you guys help me please??
P.S : I dont want to use INotifyPropertyChanged
How about:
public class ButtonChange
{
// Starting off with an empty handler avoids pesky null checks
public event EventHandler StateChanged = delegate {};
private int _buttonState;
// Do you really want a setter method instead of a property?
public void SetButtonState(int state)
{
if (_buttonState == state)
{
return;
}
_buttonState = state;
StateChanged(this, EventArgs.Empty);
}
}
If you wanted the StateChanged event handler to know the new state, you could derive your own class from EventArgs, e.g. ButtonStateEventArgs and then use an event type of EventHandler<ButtonStateEventArgs>.
Note that this implementation doesn't try to be thread-safe.
Property based event raising:
public class ButtonChange
{
private int _buttonState;
public int ButtonState
{
get { return _buttonState; }
set
{
if (_buttonState == value)
return;
_buttonState = value;
OnButtonStateChanged();
}
}
public event EventHandler ButtonStateChanged;
private void OnButtonStateChanged()
{
if (this.ButtonStateChanged != null)
this.ButtonStateChanged(this, new EventArgs());
}
}
Help yourself with google "c# events msdn"
Events tutorial (C#) - MSDN if you are using plain c#. INotifyPropertyChanged is for WPF - you don't need it for POCO/simple type events

How to add an event to a class

Say I have a class named Frog, it looks like:
public class Frog
{
public int Location { get; set; }
public int JumpCount { get; set; }
public void OnJump()
{
JumpCount++;
}
}
I need help with 2 things:
I want to create an event named Jump in the class definition.
I want to create an instance of the Frog class, and then create another method that will be called when the Frog jumps.
public event EventHandler Jump;
public void OnJump()
{
EventHandler handler = Jump;
if (null != handler) handler(this, EventArgs.Empty);
}
then
Frog frog = new Frog();
frog.Jump += new EventHandler(yourMethod);
private void yourMethod(object s, EventArgs e)
{
Console.WriteLine("Frog has Jumped!");
}
Here is a sample of how to use a normal EventHandler, or a custom delegate. Note that ?. is used instead of . to insure that if the event is null, it will fail cleanly (return null)
public delegate void MyAwesomeEventHandler(int rawr);
public event MyAwesomeEventHandler AwesomeJump;
public event EventHandler Jump;
public void OnJump()
{
AwesomeJump?.Invoke(42);
Jump?.Invoke(this, EventArgs.Empty);
}
Note that the event itself is only null if there are no subscribers, and that once invoked, the event is thread safe. So you can also assign a default empty handler to insure the event is not null. Note that this is technically vulnerable to someone else wiping out all of the events (using GetInvocationList), so use with caution.
public event EventHandler Jump = delegate { };
public void OnJump()
{
Jump(this, EventArgs.Empty);
}

Categories

Resources