Solved

c# event handling

Posted on 2011-02-23
13
320 Views
Last Modified: 2013-12-17
Hi,

I inherit this class:

class test
{
  public enum NotificationMessages  
    {
        Aborted,
        WaitingToConnect,
        Connected,
}
       public delegate void NotificationMessageDelegate(object sender, NotificationMessages);
       private event NotificationMessageDelegate m_NotificationMessage;
 
       public event NotificationMessageDelegate NotificationMessage
        {
            add { m_NotificationMessage += new NotificationMessageDelegate(value); }
            remove { m_NotificationMessage -= new NotificationMessageDelegate(value); }
        }


      private void SendNotifiation(NotificationMessages m)
        {
            if (m_NotificationMessage != null)
            {
                // send notification message out
                m_NotificationMessage(this, m);
            } // if
        }
      public processSerialPort()
     {
          ...
           SendNotifiation(NotificationMessages.DownloadFlashStart);
          ...
      }

}

Now in the client of test, how can I get this message?

{
...
Test t  = new Test();

          t.NotificationMessage += new Class1.NotificationMessageDelegate(c1_NotificationMessage);     // i register event handler

       //??? how can subscribe event
..
}

    void c1_NotificationMessage(object sender, Class1.NotificationMessages m)
        {
            //????
        }
 

Thanks,
JT
0
Comment
Question by:jtran007
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 3
13 Comments
 
LVL 22

Expert Comment

by:p_davis
ID: 34967066
if i understand your layout, this should do it..(using invoke)

private void SendNotifiation(NotificationMessages m)
        {
            if (m_NotificationMessage != null)
            {
                // send notification message out
                m_NotificationMessage.Invoke(this, m);
            } // if
        }
0
 
LVL 6

Accepted Solution

by:
ViceroyFizzlebottom earned 500 total points
ID: 34967885
So, I rewrote your code a little to conform to Microsoft's "best practices" as far as defining and using events. The code below can be copy/pasted into a simple console application and ran, achieving what you need. I'm using EventHandler<T> instead of defining a separate delegate, but it achieves the same thing.

Here is the MSDN documentation on events, refer to the 'Related Sections' portion for links on publishing events, and the link on subscribing to events. The code sample below uses those guidelines.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SampleEvents
{
    class Program
    {
        static void Main(string[] args)
        {
            var t = new Test();
            t.NotificationMessage += t_NotificationMessage;

            // This method will raise event that will be handled in t_NotificationMessage
            t.ProcessSerialPort();

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        static void t_NotificationMessage(object sender, NotificationMessages e)
        {
            Console.WriteLine("Current status is: " + e.CurrentStatus);
        }
    }

    public class NotificationMessages : EventArgs
    {
        [Flags]
        public enum Message
        {
            Aborted,
            WaitingToConnect,
            Connected
        }

        public Message CurrentStatus { get; set; }
    }

    public class Test
    {

        public event EventHandler<NotificationMessages> NotificationMessage;

        private void OnSendNotification(NotificationMessages messages)
        {
            if (NotificationMessage != null)
            {
                NotificationMessage(this, messages);
            }
        }

        public void ProcessSerialPort()
        {
            // Do stuff

            // Fire event
            OnSendNotification(new NotificationMessages()
                                   {
                                       CurrentStatus = NotificationMessages.Message.WaitingToConnect
                                   });
        }
    }
}

Open in new window

0
 
LVL 6

Expert Comment

by:ViceroyFizzlebottom
ID: 34967888
Uh, forgot to link the MSDN article above:

http://msdn.microsoft.com/en-us/library/awbftdfh.aspx
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:jtran007
ID: 34969005
Hi p_davis,

Thanks for your suggestion.

Once I register event like:

Test t  = new Test();

          t.NotificationMessage += new Class1.NotificationMessageDelegate(c1_NotificationMessage);

how do i subscribe it, so that the function c1_NofiticationMessage can be called?

Thanks,
JT
0
 

Author Comment

by:jtran007
ID: 34969039
Hi,

Thanks for your assistance. The thing is that during process data coming from serial port,
the class Test use SendNotification(...) as listed above notifies client by its message. I'd like to capture message sent by SendNotification. How my client do it?

Thanks,
JT
0
 

Author Comment

by:jtran007
ID: 34969056
Hi,

I mean how do I raise event from client to receive message from SendNotification. Since the
object Test() use many SendNotification during the course of processing serial port.

Thanks,
JT
0
 

Author Comment

by:jtran007
ID: 34969182
Hi vicery,

What does it mean ^Flags in your codeÉ

Thanks,
JT
0
 

Author Comment

by:jtran007
ID: 34969206
Hi vicery,

How do I remove message once it was launchedÉ Is it necessary to remove the messageÉ

Thanks,
JT
0
 
LVL 6

Expert Comment

by:ViceroyFizzlebottom
ID: 34971544
jtran007,

The [Flags] is simply an attribute indicating that the enum can be used as a bit field (basically it allows more than one value to be selected). Actually, it's just force of habit for me and you don't have to have it there. You could safely remove it if you wanted. Here's the MSDN for the FlagsAttribute: http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx

Also, events are based on a publisher/subscriber model in that the class which publishes the event knows nothing about any consumers. Therefore, you can't raise the event from a client (subscriber), you can only respond to the event once it's been raised. If you wanted to take action on the Test class instance from your client, you would need to expose a method or property from your Test class which the client could call of check to determine the current status like:

public void ClientMethod()
{
    Test t = new Test();
    // Do some stuff
    NotificationMessage m = t.GetCurrentStatus();
}

In the case above, there would be no need to even have the event(s) in your Test class.

Finally, I'm not sure I understand what you mean by removing the message. Can you elaborate on that?
0
 

Author Comment

by:jtran007
ID: 34971704
Hi,
 How do I use MethodInvoker to call event since I enherited a class with big codes handling
seriort?
Thanks,
JT
0
 

Author Comment

by:jtran007
ID: 34971950
Hi,
I try this:

                t.NotificationMessage += new NotificationMessageDelegate(t_NotificationMessage);
...
     void Adt42To45_NotificationMessage(object sender, NotificationMessages m)
        {
              if (textBox1.InvokeRequired)
            {
                textBox1.BeginInvoke(new MethodInvoker(delegate() { t_NotificationMessage(sender, m); }));

            }
              textBox1.Text = m.ToString();
              textBox1.Refresh();
              textBox1.Update();

        }

But it is not working. Could you help?
Thanks,
JT
0
 

Author Comment

by:jtran007
ID: 34971967
Hi
sorry
  void t_NotificationMessage(object sender, NotificationMessages m)
 instead of

  void Adt42To45_NotificationMessage(object sender, NotificationMessages m)
 JT
0
 

Author Closing Comment

by:jtran007
ID: 35380733
Thanks,'
JT
0

Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question