Click here to Skip to main content
Click here to Skip to main content
Articles » Languages » C# » General » Downloads
 
Add your own
alternative version

A .NET State Machine Toolkit - Part III

, 26 Oct 2006 CPOL
Using code generation with the .NET state machine toolkit.
statemachinetoolkitpartiii_demo.zip
StateMachineToolkit
StateMachineBuilderDemo
App.ico
StateMachineBuilderDemo.csproj.user
StateMachineDemo
App.ico
StateMachineDemo.csproj.user
StateMachineMaker
App.ico
StateMachineMaker.csproj.user
StateMachineToolkit
bin
Debug
LSCollections.dll
CodeGeneration
StateMachineBuilder
StateMachineToolkit.csproj.user
statemachinetoolkitpartiii_src.zip
StateMachineToolkitPartIII_src
CodeGeneration
/*
 * Created by: Leslie Sanford
 * 
 * Contact: jabberdabber@hotmail.com
 * 
 * Last modified: 09/19/2005
 */

using System;
using System.CodeDom;
using System.Data;
using System.IO;
using System.Reflection;
using System.Xml;

namespace StateMachineToolkit
{
	/// <summary>
	/// Generates code for state machine base classes.
	/// </summary>
	public class StateMachineBuilder : IDisposable
	{
        #region StateMachineBuilder Members

        #region Fields

        // The collection of tables that holds the state machine data.
        private DataSet stateMachineDataSet;

        // The name of the namespace in which the state machine resides.
        private string namespaceName = "YourNamespace";

        // The name of the state machine.
        private string stateMachineName = "YourStateMachine";

        // The initial state of the state machine.
        private string initialState = string.Empty;

        // Builds the constructor.
        ConstructorBuilder constructorBuilder;

        // Builds the fields.
        FieldBuilder fieldBuilder;

        // Builds the methods.
        MethodBuilder methodBuilder;

        // Builds the event type.
        EventTypeBuilder eventTypeBuilder;

        // The result of building the state machine.
        private CodeNamespace result = new CodeNamespace();

        #endregion

        #region Construction

		public StateMachineBuilder()
		{
            stateMachineDataSet = new DataSet("StateMachine"); 

            #region State Table

            DataTable stateTable = new DataTable("State");
            stateTable.Columns.Add("Name");
            stateTable.Columns["Name"].Unique = true;
            stateTable.Columns.Add("HistoryType");
            stateTable.PrimaryKey = new DataColumn[] { stateTable.Columns["Name"] };
            stateTable.RowDeleted += new DataRowChangeEventHandler(StateDeletedHandler);
            stateMachineDataSet.Tables.Add(stateTable);

            #endregion

            #region Event Table

            DataTable eventTable = new DataTable("Event");
            eventTable.Columns.Add("Name");
            eventTable.Columns["Name"].Unique = true;
            eventTable.PrimaryKey = new DataColumn[] { eventTable.Columns["Name"] };
            stateMachineDataSet.Tables.Add(eventTable);

            #endregion

            #region Guard Table

            DataTable guardTable = new DataTable("Guard");
            guardTable.Columns.Add("Name");
            guardTable.Columns["Name"].Unique = true;
            guardTable.PrimaryKey = new DataColumn[] { guardTable.Columns["Name"] };
            stateMachineDataSet.Tables.Add(guardTable);

            #endregion

            #region Action Table

            DataTable actionTable = new DataTable("Action");
            actionTable.Columns.Add("Name");
            actionTable.Columns["Name"].Unique = true;
            actionTable.PrimaryKey = new DataColumn[] { actionTable.Columns["Name"] };
            stateMachineDataSet.Tables.Add(actionTable);

            #endregion

            #region State Transition Table

            DataTable stateTransitionTable = new DataTable("StateTransition");
            stateTransitionTable.Columns.Add("Source");
            stateTransitionTable.Columns["Source"].AllowDBNull = false;
            stateTransitionTable.Columns.Add("Event");
            stateTransitionTable.Columns["Event"].AllowDBNull = false;
            stateTransitionTable.Columns.Add("Guard");
            stateTransitionTable.Columns.Add("Action");
            stateTransitionTable.Columns.Add("Target");
            stateMachineDataSet.Tables.Add(stateTransitionTable);

            ForeignKeyConstraint constraint = new ForeignKeyConstraint("SourceForeignKey",
                stateTable.Columns["Name"], stateTransitionTable.Columns["Source"]);

            stateTransitionTable.Constraints.Add(constraint);

            constraint = new ForeignKeyConstraint("EventForeignKey",
                eventTable.Columns["Name"], stateTransitionTable.Columns["Event"]);

            stateTransitionTable.Constraints.Add(constraint);

            DataRelation relation = new DataRelation("TransitionGuardRelation",
                guardTable.Columns["Name"], stateTransitionTable.Columns["Guard"]);

            stateMachineDataSet.Relations.Add(relation);

            relation = new DataRelation("TransitionActionRelation",
                actionTable.Columns["Name"], stateTransitionTable.Columns["Action"]);

            stateMachineDataSet.Relations.Add(relation);

            relation = new DataRelation("TransitionTargetRelation",
                stateTable.Columns["Name"], stateTransitionTable.Columns["Target"]);

            stateMachineDataSet.Relations.Add(relation);

            #endregion            

            #region Relationship Table

            DataTable relationshipTable = new DataTable("Relationship");
            relationshipTable.Columns.Add("Substate");    
            relationshipTable.Columns.Add("Superstate");                    
            stateMachineDataSet.Tables.Add(relationshipTable);

            constraint = new ForeignKeyConstraint("RelationshipConstraint",
                stateTable.Columns["Name"], relationshipTable.Columns["Substate"]);

            relationshipTable.Constraints.Add(constraint);

            relationshipTable.Columns["Substate"].Unique = true;

            relation = new DataRelation("RelationshipSuperstateRelation",
                stateTable.Columns["Name"], relationshipTable.Columns["Superstate"]);

            stateMachineDataSet.Relations.Add(relation);

            #endregion

            #region Initial State Table

            DataTable initialStateTable = new DataTable("InitialState");
            initialStateTable.Columns.Add("State");
            initialStateTable.Columns.Add("InitialState");
            stateMachineDataSet.Tables.Add(initialStateTable);

            constraint = new ForeignKeyConstraint("InitialStateConstraint",
                stateTable.Columns["Name"], initialStateTable.Columns["State"]);

            initialStateTable.Constraints.Add(constraint);

            initialStateTable.Columns["State"].Unique = true;

            relation = new DataRelation("InitialStateRelation",
                stateTable.Columns["Name"], initialStateTable.Columns["InitialState"]);

            stateMachineDataSet.Relations.Add(relation);

            #endregion             

            constructorBuilder = new ConstructorBuilder();
            fieldBuilder = new FieldBuilder(stateTable, guardTable, actionTable);
            methodBuilder = new MethodBuilder(stateTable, eventTable, guardTable, 
                actionTable, stateTransitionTable, relationshipTable, initialStateTable);
            eventTypeBuilder = new EventTypeBuilder(eventTable);
        }

        #endregion

        #region Methods

        /// <summary>
        /// Builds the state machine.
        /// </summary>
        public void Build()
        {            
            result = new CodeNamespace(NamespaceName);

            CodeTypeDeclaration stateMachineClass = 
                new CodeTypeDeclaration(StateMachineName);

            stateMachineClass.BaseTypes.Add(typeof(StateMachine));
            stateMachineClass.IsClass = true;
            stateMachineClass.TypeAttributes = 
                TypeAttributes.Abstract | 
                TypeAttributes.Public;

            eventTypeBuilder.Build();
            stateMachineClass.Members.Add(eventTypeBuilder.Result);

            constructorBuilder.InitialState = InitialState;
            constructorBuilder.Build();
            stateMachineClass.Members.Add(constructorBuilder.Result);            

            fieldBuilder.Build();

            foreach(CodeMemberField field in fieldBuilder.Result)
            {
                stateMachineClass.Members.Add(field);
            }            
            
            methodBuilder.Build();

            foreach(CodeMemberMethod method in methodBuilder.Result)
            {
                stateMachineClass.Members.Add(method);
            }
            
            result.Types.Add(stateMachineClass);            
        }

        /// <summary>
        /// Reads XML state machine data into the builder.
        /// </summary>
        /// <param name="fileName">
        /// The filename (including the path) from which to read. 
        /// </param>
        public void ReadXml(string fileName)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(fileName);

            NamespaceName = doc.DocumentElement.GetAttribute("namespaceName");
            StateMachineName = doc.DocumentElement.GetAttribute("stateMachineName");
            
            stateMachineDataSet.Clear();
            stateMachineDataSet.ReadXml(fileName, XmlReadMode.IgnoreSchema);

            InitialState = doc.DocumentElement.GetAttribute("initialState");
        }

        /// <summary>
        /// Writes XML data representing the state machine to the specified file.
        /// </summary>
        /// <param name="fileName">
        /// The file name (including the path) to which to write.
        /// </param>
        public void WriteXml(string fileName)
        {
            StringReader reader = new StringReader(stateMachineDataSet.GetXml());
            XmlDocument doc = new XmlDocument();

            doc.Load(reader);

            doc.DocumentElement.SetAttribute("namespaceName", NamespaceName);
            doc.DocumentElement.SetAttribute("stateMachineName", StateMachineName);
            doc.DocumentElement.SetAttribute("initialState", InitialState);

            StreamWriter writer = new StreamWriter(fileName);

            doc.Save(writer);

            writer.Close();
        }

        // Handles the StateDeleted event from the state table.
        private void StateDeletedHandler(object sender, DataRowChangeEventArgs e)
        {
            // If the initial state is the state that was deleted.
            if(initialState == e.Row["State"].ToString())
            {
                // Reset initial state.
                initialState = string.Empty;
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the result of building the state machine.
        /// </summary>
        public CodeNamespace Result
        {
            get
            {
                return result;
            }
        }

        /// <summary>
        /// Gets the state table.
        /// </summary>
        /// <remarks>
        /// The state table represents the collection of states that make up 
        /// the state machine.
        /// </remarks>
        public DataTable StateTable
        {
            get
            {
                return stateMachineDataSet.Tables["State"];
            }
        }

        /// <summary>
        /// Gets the event table.
        /// </summary>
        /// <remarks>
        /// The event table represents the collection of events that the
        /// state machine can receive.
        /// </remarks>
        public DataTable EventTable
        {
            get
            {
                return stateMachineDataSet.Tables["Event"];
            }
        }

        /// <summary>
        /// Gets the guard table.
        /// </summary>
        /// <remarks>
        /// The guard table represents the collection of guards transitions
        /// use to determine whether or not they should fire.
        /// </remarks>
        public DataTable GuardTable
        {
            get
            {
                return stateMachineDataSet.Tables["Guard"];
            }
        }

        /// <summary>
        /// Gets the action table.
        /// </summary>
        /// <remarks>
        /// The action table represents the collection of actions transitions
        /// perform when they fire.
        /// </remarks>
        public DataTable ActionTable
        {
            get
            {
                return stateMachineDataSet.Tables["Action"];
            }
        }

        /// <summary>
        /// Gets the state transition table.
        /// </summary>
        /// <remarks>
        /// The state transition table represents the collection of state 
        /// transitions that can take place when the state machine receives 
        /// events.
        /// </remarks>
        public DataTable StateTransitionTable
        {
            get
            {
                return stateMachineDataSet.Tables["StateTransition"];
            }
        } 

        /// <summary>
        /// Gets the relationship table.
        /// </summary>
        /// <remarks>
        /// The RelationshipTable represents the substate/superstate 
        /// relationship between states.
        /// </remarks>
        public DataTable RelationshipTable
        {
            get
            {
                return stateMachineDataSet.Tables["Relationship"];
            }
        }

        /// <summary>
        /// Gets the initial states table.
        /// </summary>
        /// <remarks>
        /// The InitialStateTable property represents the initial states of
        /// the superstates. 
        /// </remarks>
        public DataTable InitialStateTable
        {
            get
            {
                return stateMachineDataSet.Tables["InitialState"];
            }
        }

        /// <summary>
        /// Gets or sets the name of the namespace in which the state machine
        /// resides.
        /// </summary>
        public string NamespaceName
        {
            get
            {
                return namespaceName;
            }
            set
            {
                namespaceName = value;
            }
        }

        /// <summary>
        /// Gets or sets the name of the state machine.
        /// </summary>
        public string StateMachineName
        {
            get
            {
                return stateMachineName;
            }
            set
            {
                stateMachineName = value;
            }
        }
    
        /// <summary>
        /// Gets or sets the initial state of the state machine.
        /// </summary>
        /// <exception cref="ArgumentException">
        /// The initial state does not exist.
        /// </exception>
        /// <remarks>
        /// The initial state must have already have been added to the state
        /// table.
        /// </remarks>
        public string InitialState
        {
            get
            {
                return initialState;
            }
            set
            {
                DataTable stateTable = stateMachineDataSet.Tables["State"];

                if(stateTable.Rows.Find(value) == null)
                {
                    throw new ArgumentException("Unknown state.");
                }

                initialState = value;
            }
        }

        #endregion

        #endregion

        #region IDisposable Members

        /// <summary>
        /// Disposes of the StateMachineBuilder.
        /// </summary>
        public void Dispose()
        {
            stateMachineDataSet.Dispose();
        }

        #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)

Share

About the Author

Leslie Sanford

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.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150302.1 | Last Updated 26 Oct 2006
Article Copyright 2005 by Leslie Sanford
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid