3279921120_33a8baebc4_o

Frog in a Well & Event Handlers

Being a doctor who codes is not as romantic as you would think. You try hard to keep consistent with development but you end up in peaks and troughs of coding rather than a preferred consistent flow. The Surgery work is phenomenal and I’m frantically trying to clear the work load to spend time coding.

You have your baseline of surgery work eg clinics, paperwork, meetings, admin, baseline of your product work eg bug fixes, deployment issues, anomalies, managing clients, practice visits etc. And after this you have to find the time to move the code forward.  You also need to keep up to date with clinical knowledge and I’m always constantly learning new coding techniques.

More importantly I’m also constantly recapping on techniques already learnt. I have a baseline of coding which is in long term memory but I’m always trying to be better and rise to the next level. Due to these gaps in time between learning l feel like a frog in the well: you go 2 steps forward and one step back.

Living in both worlds does have its advantages though. There is nothing like looking at a problem and not only thinking about the solution but actually implementing it and supporting issues post release. It’s very empowering and exciting but also tiring and a lot of hard work. Luckily I’m still finding it so much fun.

These blogs are good for me as they help me consolidate my knowledge on aspects I’ve learnt for me too refer to at a later date if I need to. Selfish I know, but hopefully it might help others too.

Enough ranting lets get down to the topic of Event Handlers. I’ve discussed about delegates here but events are special kind of delegates used in the .Net Framework. This isn’t a talk about the ins and outs of events but just a practical example of how to use events, add extra accessors to event args, how to handle the subscription of events and creating event handlers.

Events are the essence of passing values from one place to another place or places depending on what subscribes to the event in question. They are a refined form of a delegate. I’m not going into detail around this and some of my code abstracts out to .net which you can look up elsewhere.

The Scenario

You’d like 2 unconnected Forms to talk to each other. You’d like a group box title bar updated from a Form it can’t see (doesn’t have a reference too). See this diagram

Diagram 1 - An Overview

Form 1 Instantiates Form2 and Form 3 but Form 2 and 3 don’t know about each other.

Solution Referencing Forms

You could pass a reference of Form 2 to Form 3. When you click on the Button in Form 3, you can update the message in Form 2. You will need to have accessors to the controls you require updating and it’s a very tightly coupled way of handling things. As a rule of thumb, if you can abstract out and get something else to handle actions you need to perform between objects the better.

Diagram 2 - The rubbish method

Solution Event Handling

Have you ever wondered how to create custom event args and pass these through events to be triggered and passed to the listener? I’ve found this solution the easiest to implement and is a good example for use in the future (for me if not anyone else).  As a rule of thumb in .net Events like to have the same basic signature which is (object sender, EventArgs (or objects inherited from EventArgs) e).

Think of Events as pipes through which you are passing objects to listeners or subscribers. To pass an event it has to be fired or triggered. Since the signature is void on the return, nothing is returned: they are fire and forget. We use the words Listeners or Subscribers interchangeably as they are synonymous with each other. This is also the case for Triggering or Firing .

Below is a diagram of the solution and then I’ll go through each step in turn. You can download the entire solution here  (Visual Studio 2013)

Diagram 3 - Using Events

 

Step 1. Create the Custom Event Args

Create a simple class which inherits from Event Args. Add your own custom properties which you would like sent down the pipe in the event

public class ChangeTitleEventArgs : System.EventArgs
{
    public string TitleName { get; set; }
}

This new class ChangeTitleEventArg is used in the creation of the event which will be used. There is a nice custom handler event creator which does some of the magic for us. See this line in the negotiator class

public event EventHandler<ChangeTitleEventArgs> TitleChanged;

This does the plumbing to create the signature of the event to take objects of type ChangeTitleEventArgs rather then just EventArgs so you can pass your bespoke objects through the event pipe.

Step 2 Create the Negotiator Class

We then need to create a static singleton class. I’m not going to go into what a static singleton class is but suffice to say it’s a class which stays in memory and only one instance of the object can be created. This is useful in this case as we need to have an object which is visible by all the other classes to handle the passage of messages from one to another.

The negotiator class houses the event and handles the firing of the event to the subscribers.

public event EventHandler<ChangeTitleEventArgs> TitleChanged;

public void OnTitleChanged(Object sender, String message)
{
    var titleChangeDelegate = TitleChanged as EventHandler<ChangeTitleEventArgs>;
    if (titleChangeDelegate != null)
    {
       titleChangeDelegate(sender, new ChangeTitleEventArgs { TitleName = message });
    }
}

I’ve already gone over the first line which creates the event with the ChangeTitleEventArgs as the Argument Object rather than EventArgs. This way you can pass the message through the second parameter of the Event as ChangeTitleEventArgs rather than just the boring EventArgs which doesn’t do much.

OnTitleChanged method takes an object and a message. With this it checks to see if there are any subsribers/listeners (if titleChangedDelegate !=null) and fires off the message wrapped in the ChangeTitleEventArgs to these listners/subscribers.

Step 3 Add Subscribers/Listeners to the Other Form

public Form2()
{
    InitializeComponent();
    Negotiator.GetInstance().TitleChanged +=  new EventHandler<ChangeTitleEventArgs>(titleChange);
}

private void titleChange(object sender, ChangeTitleEventArgs e)
{
   this.groupBox1.Text = e.TitleName;
}

A Subscriber is added to the event pointing to the method titleChange. Noticed the subscribed method has the same signature as the Event ( takes a basic object and a ChangeTitleEventArgs object and returns nothing)

With this method call the message is passed via the ChangeTitleEventArgs and can be used to update the title of the groupbox control.

Step 4 Fire/Trigger the Event from a Different Form

Negotiator.GetInstance().OnTitleChanged(this, textBox1.Text);

Linked to a button click, the textbox entry of the separate form is passed through the Negogiator Class to be pushed to any subscribers/listeners which are on the list of the TitleChanged Event. In this case it would be the method which will update the title of the groupbox in Form 2.

I’ve tried to keep it as simple as I can and with the above sample you should be able to create your own custom events within your .net projects

As stated all the source files can be found in my GitHub Repo here.

Until Next time…

Photo credit: h.koppdelaney / Foter / CC BY-ND