Click here to Skip to main content
15,884,177 members
Articles / Programming Languages / C#

A .NET State Machine Toolkit - Part III

Rate me:
Please Sign up or sign in to vote.
4.91/5 (43 votes)
26 Oct 2006CPOL11 min read 223.6K   1.2K   135  
Using code generation with the .NET state machine toolkit.
/*
 * Created by: Leslie Sanford
 * 
 * Contact: jabberdabber@hotmail.com
 * 
 * Last modified: 09/24/2005
 */

using System;
using System.Collections;

namespace StateMachineToolkit
{
	/// <summary>
	/// Represents the base class for all state machines.
	/// </summary>
	public abstract class StateMachine
	{
        #region StateMachine Members

        #region Fields

        // The EventQueue for sending events to.
        private EventQueue queue = null;

        // The current state.
        private State currentState = null;

        #endregion

        #region Events

        /// <summary>
        /// Occurs when an exception takes place in the StateMachine.
        /// </summary>
        public event ExceptionEventHandler ExceptionOccurred;

        #endregion

        #region Construction

        /// <summary>
        /// Initializes a new instance of the StateMachine class.
        /// </summary>
        public StateMachine()
        {
        }

        /// <summary>
        /// Initializes a new instance of the StateMachine class with the 
        /// specified EventQueue.
        /// </summary>
        /// <param name="queue">
        /// The EventQueue for sending events to.
        /// </param>
		public StateMachine(EventQueue queue)
		{
            this.queue = queue;
		}

        #endregion

        #region Methods

        /// <summary>
        /// Sends an event to the StateMachine.
        /// </summary>
        /// <param name="eventID">
        /// The event ID.
        /// </param>
        /// <param name="args">
        /// The data accompanying the event.
        /// </param>
        public void Send(int eventID, params object[] args)
        {
            if(queue != null)
            {
                queue.Send(this, eventID, args);
            }
            else
            {
                Dispatch(eventID, args);
            }
        }

        protected void SendPriority(int eventID, params object[] args)
        {
            if(queue != null)
            {
                queue.SendPriority(this, eventID, args);
            }
            else
            {
                Dispatch(eventID, args);
            }
        }

        /// <summary>
        /// Initializes the StateMachine's initial state.
        /// </summary>
        /// <param name="initialState">
        /// The state that will initially receive events from the StateMachine.
        /// </param>
        protected void Initialize(State initialState)
        {           
            State s = initialState;
            State superstate = initialState.Superstate;
            Stack superstateStack = new Stack();

            currentState = initialState;

            // If the initial state is a substate, travel up the state 
            // hierarchy in order to descend from the top state to the initial
            // state.
            while(superstate != null)
            {
                superstateStack.Push(superstate);
                superstate = superstate.Superstate;
            }

            // While there are superstates to traverse.
            while(superstateStack.Count > 0)
            {
                superstate = (State)superstateStack.Pop();
                superstate.Entry();
            } 

            // While the lowest state has not been reached.
            while(s != null)
            {
                // Enter the state.
                s.Entry();

                // Move to the initial state.
                s = s.InitialState;

                // If there is an initial state.
                if(s != null)
                {
                    // Make the current state the last initial state.
                    currentState = s;
                }
            }
        }

        /// <summary>
        /// Dispatches events to the current state.
        /// </summary>
        /// <param name="eventID">
        /// The event ID.
        /// </param>
        /// <param name="args">
        /// The data accompanying the event.
        /// </param>
        internal void Dispatch(int eventID, object[] args)
        {
            currentState = currentState.Dispatch(currentState, eventID, args);
        }

        /// <summary>
        /// Raises an event indicating that an exception has occurred.
        /// </summary>
        /// <param name="ex">
        /// The exception object representing information about the exception.
        /// </param>
        protected virtual void OnExceptionOccurred(Exception ex)
        {
            ExceptionEventHandler handler = ExceptionOccurred;

            if(handler != null)
            {
                handler(this, new ExceptionEventArgs(ex));
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the EventQueue used by the StateMachine.
        /// </summary>
        protected EventQueue EventQueue
        {
            get
            {
                return queue;
            }
            set
            {
                queue = value;
            }
        }

        #endregion

        #endregion
	}
}

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)


Written By
United States United States
Aside from dabbling in BASIC on his old Atari 1040ST years ago, Leslie's programming experience didn't really begin until he discovered the Internet in the late 90s. There he found a treasure trove of information about two of his favorite interests: MIDI and sound synthesis.

After spending a good deal of time calculating formulas he found on the Internet for creating new sounds by hand, he decided that an easier way would be to program the computer to do the work for him. This led him to learn C. He discovered that beyond using programming as a tool for synthesizing sound, he loved programming in and of itself.

Eventually he taught himself C++ and C#, and along the way he immersed himself in the ideas of object oriented programming. Like many of us, he gotten bitten by the design patterns bug and a copy of GOF is never far from his hands.

Now his primary interest is in creating a complete MIDI toolkit using the C# language. He hopes to create something that will become an indispensable tool for those wanting to write MIDI applications for the .NET framework.

Besides programming, his other interests are photography and playing his Les Paul guitars.

Comments and Discussions