Click here to Skip to main content
15,888,323 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Use Custom Events from your WCF ServiceHost

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
26 Jan 2011CPOL 37.3K   9   5
When you need to communicate with the app that contains your ServiceHost object, use custom events
While working on an article for CodeProject, I happened on a requirement to create a WCF service using NamedPipe binding. The client application (a Windows Service) would be sending periodic messages, and if the sever (a SysTray application) was listening, it would insert those messages into a ListBox (I have no need to write the messages to disk anywhere - I just want to show them in a ListBox). This tip involves allowing the ServiceHost instance communicating to the host application that it had received a message from the client by way of a custom event.

First, you need your custom event:

C#
//////////////////////////////////////////////////////////////////////////////////////
public class MyHostEventArgs
{
    public string   Message { get; set; }
    public DateTime Date    { get; set; }
    public MyHostEventArgs(string msg, DateTime datetime)
    {
        this.Message = msg;
        this.Date    = datetime;
    }
}

public delegate void MyHostEventHandler(object sender, MyHostEventArgs e);


Next, you need to define your service (and this is where most of the tip lies):

C#
//////////////////////////////////////////////////////////////////////////////////////
[ServiceContract]
public interface IMyService
{
    [OperationContract]
    void SendStatusMessageEx(string msg, DateTime datetime);
}

//////////////////////////////////////////////////////////////////////////////////////
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, IncludeExceptionDetailInFaults=true)]
public class MyService : IMyService
{
    public event MyHostEventHandler MyHostEvent = delegate{};

    public MyService()
    {
    }

    //--------------------------------------------------------------------------------
    public void SendStatusMessageEx(string msg, DateTime datetime)
    {
        MyHostEvent(this, new MyHostEventArgs(msg, datetime));
    }
}


Notice the ServiceBehavior attribute. When you set the InstanceContextMode to Single, you can then do the following in your application:

C#
// create and open an instance of the host in our form object
Uri                 BaseAddress      = new Uri("net.pipe://localhost/MyService");
NetNamedPipeBinding NamedPipeBinding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
MyService           svc              = new MyService();
SvcHost                              = new ServiceHost(svc, BaseAddress);
SvcHost.AddServiceEndpoint(typeof(IMyService), NamedPipeBinding, "");
SvcHost.Open();

// now we can add an event handler
(SvcHost.SingletonInstance as MyService).MyHostEvent += new MyHostEventHandler(Form1_MyHostEvent);


An alternative to doing this is to set up delegates inside the ServiceHost object, but that requires a tighter coupling between the object that contains the ServiceHost object, and the ServiceHost object itself.

Note: Special thanks goes out to Nish for showing me the appropriate ServiceBehavior attribute

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paddedwall Software
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

 
QuestionHow to handle wcf custom event under windows form in client project Pin
Farzad Niknam B7-Nov-14 4:20
professionalFarzad Niknam B7-Nov-14 4:20 
Hello dear friend,
Thanks for your useful article. That was very useful and very interesting to me.

I have another problem.
My project is Attendance Device. In this project I have 2 card reader that read card info from com port and transfer them to server and save in database, by using WCF Service. WCF listen the port and when card reader read a card, raised event and save data in database. Also i created my custome event in WCF service like this

C#
public delegate void PortInfoReceivedEventHandler(string portInfo);


C#
public class CardReaderWCFService : ICardReaderWCFService
    {

        CardReaderData CardReaderData = new CardReaderData();

public event PortInfoReceivedEventHandlerPortInfoReceived = delegate { };

public void Connect()
        {
            SetPortInfo();
        }

private void SetPortInfo(string portName, int buadRate, System.IO.Ports.Parity parity, int dataBits)
        {
            port = new SerialPort("COM4", 38400, System.IO.Ports.Parity.Odd, 8);
            //port = new SerialPort(portName, buadRate, parity, dataBits);
            port.Handshake = Handshake.XOnXOff;
            //port.DtrEnable = true;
            //port.RtsEnable = true;

            try
            {
                port.Open();
 
            }
            catch (Exception exp)
            {
                throw exp;
            }
 
            port.DataReceived += new
            SerialDataReceivedEventHandler(port_DataReceived);
 
        }

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
 
            try
            {
 
                Thread.Sleep(500);
                string portInfo = port.ReadExisting();
 
                if (portInfo != "")
                {
                    DateTime readingDate = DateTime.Now;
 

 
                    int index = 0;
                    index = portInfo .IndexOf("$");
                    string strPortNumber = portInfo.Substring(index + 1, 3);
                    int portNumber = Convert.ToInt32(strPortNumber);
 

                    int endIndexOfCardNumber = 0;
                    endIndexOfCardNumber = portInfo.IndexOf("**");
                    string strCardNumber = portInfo.Substring(index + 4, endIndexOfCardNumber - 4);
 

 

                    string strDate = readingDate.Year.ToString() + "/" + (readingDate.Month < 10 ? "0" + readingDate.Month.ToString() : readingDate.Month.ToString()) + "/"
                                                                       + (readingDate.Day < 10 ? "0" + readingDate.Day.ToString() : readingDate.Day.ToString());// readingDate.Date.ToString().Substring(0, 10);
                    string strTime = readingDate.TimeOfDay.ToString().Substring(0, 8);
 
                    //

 
                    portInfo = strPortNumber + "," + strCardNumber + "," + portNumber + "," + strDate + "," + strTime;
 

 
                    if (PortInfoReceived_Handler != null)
                    {
                        this.PortInfoReceived_Handler(portInfo);
                    }
                }
 
            }
            catch (Exception exp)
            {
                port.Close();
            }
        }



in the last event 'port_DataReceived' i put my custom event 'this.PortInfoReceived_Handler(portInfo)'
this event create a string of all of data after reading card. This staring will show in listbox in windowsform.


this code work good. But i want handle my custom event in another project under windows form.
I have windows project thet refrenced to WCF (web service).
when i get instance from WCF service i can get created web method and iterface.
How can i get my custom event 'PortInfoReceived_Handler' and handle it under my form.

In Windows Form :

C#
CardReader_WCF.CardReaderWCFServiceClient crWCFService = new CardReader_WCF.CardReaderWCFServiceClient();


I want impelement custom event like this :

C#
crWCFService.PortInfoReceived_Handler += crFacade_PortInfoReceived_Event;

public void crFacade_PortNameReceived_Event(string portInfo)
        {
            try
            {
                SetText(portInfo);
            }
            catch (Exception exp)
            {
                
                throw exp;
            }
        }

delegate void SetTextCallback(string text);

private void SetText(string text)
        {
            if (this.lstReceivedMessage.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.lstReceivedMessage.Items.Add(text);
                this.lstBuffer.Items.Add(text);
            }
        }



Would you please help me how can i do it?
Thank you so much
QuestionHow would this work when the ServiceHost is running in a separate thread? Pin
johnbMA21-Apr-13 13:25
johnbMA21-Apr-13 13:25 
GeneralThank you, Thank You, THANK YOU! Pin
percidae14-Feb-11 3:55
percidae14-Feb-11 3:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.