Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Hosting WCF services in a Windows Forms Application

, 8 Nov 2006
Demonstrates how to host serveral singleton services in a Windows Forms application.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Threading;
using ServiceHostUtility;

namespace DCCLocomotiveFactory
{
    public partial class MainForm : Form
    {
        const int LocoDictSize = 10;

        class ServerStatus
        {
            public const string
                Stopped = "Stopped",
                Running = "Running";
        }

        DataSet m_locomotives = new DataSet();
        Dictionary<string, ThreadedServiceHost<DCCLocomotiveService, IDCCLocomotiveContract>> m_locoDict =
            new Dictionary<string, ThreadedServiceHost<DCCLocomotiveService, IDCCLocomotiveContract>>(LocoDictSize);

        public MainForm()
        {
            InitializeComponent();

            btnPilotLoco.Enabled = false;

            try
            {
                m_locomotives.ReadXml(Properties.Settings.Default.LocoListFileb);

                DataTable locoTable = m_locomotives.Tables["Locomotive"];
                DataRowCollection dataRows = locoTable.Rows;
                for (int nI = 0; nI < dataRows.Count; nI++)
                {
                    LocoDataRow row = new LocoDataRow(dataRows[nI]);

                    locoListBox.Items.Add(row);
                }
            }
            catch (Exception ex)
            {
                toolStripStatusLabel.Text = ex.Message;
            }
        }


        class LocoDataRow 
        {
            DataRow m_row;

            public LocoDataRow(DataRow theRow)
            {
                m_row = theRow;
            }

            public override string ToString()
            {
                return m_row["Name"].ToString();
            }

            public object   this[string name]
            {
                get
                {
                    return m_row[name];
                }

                set
                {
                    m_row["Name"] = value;
                }
            }

            public DataRow Row
            {
                get
                {
                    return m_row;
                }
            }
        }

        private void locoListBox_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            try
            {
                // 1 - Get the data for that loco
                LocoDataRow locoData = (LocoDataRow)locoListBox.Items[e.Index];

                if (e.NewValue == CheckState.Checked)
                {
                    // Start the server for the given loco
                    StartLocoServer(locoData.Row);
                }
                else
                {
                    // Stop the server for the given loco
                    StopLocoServer(locoData.Row);
                }
            }
            catch (Exception ex)
            {
                toolStripStatusLabel.Text = ex.Message;
            }
        }


        private void StartLocoServer(DataRow locoData)
        {
            // Get the data
            string name = locoData[Constants.ColumnName.Name].ToString();;
            string address = locoData[Constants.ColumnName.Address].ToString();

            // Create the Host
            string serviceAddress = string.Format(Constants.LocoServerBaseAddress, address);
            ThreadedServiceHost<DCCLocomotiveService, IDCCLocomotiveContract> locoHost =
                new ThreadedServiceHost<DCCLocomotiveService, IDCCLocomotiveContract>(serviceAddress, address, new NetTcpBinding());

            // Add to dictionary of servers
            m_locoDict.Add(address, locoHost);

            SetLocoServiceInfo(locoData);
        }


        private void SetLocoServiceInfo(DataRow locoData)
        {
            string address = locoData[Constants.ColumnName.Address].ToString();
            textBoxAddress.Text = address;
            textBoxName.Text = locoData[Constants.ColumnName.Name].ToString();

            // Try to get the Service host
            if (m_locoDict.ContainsKey(address))
            {
                // Access to service to get current info
                textBoxStatus.Text = ServerStatus.Running;
                textBoxStatus.BackColor = Color.PaleGreen;
            }
            else
            {
                textBoxStatus.Text = ServerStatus.Stopped;
                textBoxStatus.BackColor = Color.LightPink;
            }

            toolStripStatusLabel.Text = string.Empty;
        }


        private void StopLocoServer(DataRow locodata)
        {
            // Get the loco server host,close and remove from dictionary
            string address = locodata[Constants.ColumnName.Address].ToString();
            m_locoDict[address].Stop();

            // Remove from dictionary servers
            m_locoDict.Remove(address);

            SetLocoServiceInfo(locodata);
        }

        private void btnPilotLoco_Click(object sender, EventArgs e)
        {
            try
            {
                LocoDataRow locoDataRow = (LocoDataRow)locoListBox.Items[locoListBox.SelectedIndex];
                LocoControlForm locoForm = new LocoControlForm(
                    locoDataRow.Row[Constants.ColumnName.Address].ToString(),
                    locoDataRow.Row[Constants.ColumnName.Name].ToString(),
                    true);

                locoForm.Show();
            }
            catch (Exception ex)
            {
                toolStripStatusLabel.Text = ex.Message;
            }
        }

        private void locoListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            int idx = locoListBox.SelectedIndex;

            btnPilotLoco.Enabled = locoListBox.GetItemChecked(idx);

            LocoDataRow locoDataRow = (LocoDataRow)locoListBox.Items[idx];

            SetLocoServiceInfo(locoDataRow.Row);
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            // Stop all the running Loco servers
            foreach (string key in m_locoDict.Keys)
            {
                try
                {
                    m_locoDict[key].Stop();
                }
                catch (Exception)
                {
                }
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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

About the Author

orouit
Architect Consistel - Singapore
Singapore Singapore
Software Architect, COM, .NET and Smartcard based security specialist.
 
I've been working in the software industry since I graduated in Electrical and Electronics Engineering. I chose software because I preferred digital to analog.
 
I started to program with 6802 machine code and evolved to the current .NET technologies... that was a long way.
 
For more than 20 years I have always worked in technical positions as I simply like to get my hands dirty and crack my brain when things don't go right!
 
After 12 years in the smart card industry I can claim a strong knowledge in security solutions based on those really small computers! I'm currently back in the business to design the licensing system for the enterprise solution I'm currenly working on, using a .NET smart card (yes they can run .NET CLR!)
 
View my profile on LinkedIn
 
You can contact me for professional consulting by using the forum.

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 8 Nov 2006
Article Copyright 2006 by orouit
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid