├── .github └── FUNDING.yml ├── SimpleStateMachineLibrary ├── SimpleStateMachine.png ├── Helpers │ ├── NamedObject.cs │ ├── LogExtension.cs │ └── Check.cs ├── States │ ├── StateWorkWithXML.cs │ ├── StateWorkWithTransitionsToThisState.cs │ ├── StateWorkWithTransitionsFromThisState.cs │ └── State.cs ├── SimpleStateMachineLibrary.csproj ├── StateMachines │ ├── InvokeParameters.cs │ ├── StateMachineWorkWithXML.cs │ ├── StateMachineWorkWithTransitionsForState.cs │ ├── StateMachineWorkWithData.cs │ ├── StateMachineWorkWithStates.cs │ ├── StateMachine.cs │ └── StateMachineWorkWithTransitions.cs ├── Data │ ├── DataWorkWithXML.cs │ └── Data.cs └── Transitions │ ├── TransitionWorkWithXML.cs │ └── Transition.cs ├── Tests ├── ForTest.cs ├── Tests.csproj ├── StateMachineTests.cs ├── DataTests.cs ├── StateTests.cs └── TransitionTests.cs ├── Examples ├── Examples.csproj └── Program.cs ├── azure-pipelines.yml ├── LICENSE ├── SimpleStateMachineLibrary.sln ├── .gitattributes ├── README.md └── .gitignore /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | custom: ['paypal.me/romansolovyov'] 4 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/SimpleStateMachine.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SimpleStateMachine/SimpleStateMachineLibrary/HEAD/SimpleStateMachineLibrary/SimpleStateMachine.png -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/Helpers/NamedObject.cs: -------------------------------------------------------------------------------- 1 | namespace SimpleStateMachineLibrary.Helpers 2 | { 3 | 4 | public abstract class NamedObject 5 | { 6 | public string Name { get; } 7 | 8 | public StateMachine StateMachine { get; } 9 | 10 | internal NamedObject(StateMachine stateMachine, string nameObject) 11 | { 12 | Name = Check.Name(nameObject, stateMachine?._logger); 13 | StateMachine = Check.Object(stateMachine, stateMachine?._logger); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/Helpers/LogExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace SimpleStateMachineLibrary.Helpers 7 | { 8 | static internal class LogExtension 9 | { 10 | static internal void LogDebugAndInformation(this ILogger logger, string message, params object[] args) 11 | { 12 | logger?.LogDebug(message, args); 13 | logger?.LogInformation(message, args); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Tests/ForTest.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | 7 | namespace Tests 8 | { 9 | public static class ForTest 10 | { 11 | 12 | static public StateMachine stateMachine = new StateMachine(); 13 | public static ILogger GetConsoleLogger() 14 | { 15 | var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole().AddDebug().SetMinimumLevel(LogLevel.Debug); }); 16 | return loggerFactory.CreateLogger(); 17 | } 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Examples/Examples.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | ..\SimpleStateMachineLibrary\bin\Release\netstandard2.1\SimpleStateMachineLibrary.dll 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Tests/Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | jobs: 2 | - job: Linux 3 | pool: 4 | vmImage: 'ubuntu-18.04' 5 | variables: 6 | buildConfiguration: 'Release' 7 | steps: 8 | - script: cd $(Build.SourcesDirectory) && dotnet build 9 | displayName: 'Linux Build and Tests' 10 | - task: PublishTestResults@2 11 | inputs: 12 | testRunner: VSTest 13 | testResultsFiles: '**/*.trx' 14 | 15 | - job: Windows 16 | pool: 17 | vmImage: 'windows-2019' 18 | variables: 19 | buildConfiguration: 'Release' 20 | steps: 21 | - task: DotNetCoreInstaller@0 22 | inputs: 23 | version: '3.1.302' 24 | - script: cd $(Build.SourcesDirectory) && dotnet build 25 | displayName: 'Windows Full Build and Tests' 26 | - task: PublishTestResults@2 27 | inputs: 28 | testRunner: VSTest 29 | testResultsFiles: '**/*.trx' 30 | - task: PublishCodeCoverageResults@1 31 | inputs: 32 | summaryFileLocation: $(Build.SourcesDirectory)\artifacts\coverage.cobertura.xml 33 | reportDirectory: $(Build.SourcesDirectory)\artifacts 34 | codecoverageTool: cobertura 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 SimpleStateMachine 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/States/StateWorkWithXML.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System.Xml.Linq; 4 | 5 | 6 | namespace SimpleStateMachineLibrary 7 | { 8 | public partial class State 9 | { 10 | internal static XElement ToXElement(State state, bool withLog) 11 | { 12 | Check.NamedObject(state, state?.StateMachine?._logger); 13 | XElement element = new XElement("State"); 14 | element.Add(new XAttribute("Name", state.Name)); 15 | 16 | if(withLog) 17 | state.StateMachine._logger.LogDebug("State \"{NameState}\" to XElement", state.Name); 18 | 19 | return element; 20 | } 21 | 22 | internal XElement ToXElement(bool withLog) 23 | { 24 | return State.ToXElement(this, withLog); 25 | } 26 | 27 | internal static State FromXElement(StateMachine stateMachine, XElement state, bool withLog) 28 | { 29 | string Name = state.Attribute("Name")?.Value; 30 | 31 | 32 | State stateObj = stateMachine._AddState(Name, null, null, out bool result, true, false); 33 | 34 | if ((result) && (withLog)) 35 | stateMachine?._logger.LogDebug("Initialization state \"{NameState}\" from XElement", Name); 36 | 37 | return stateObj; 38 | } 39 | 40 | 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/SimpleStateMachineLibrary.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | true 6 | SimpleStateMachine 7 | https://github.com/SimpleStateMachine/SimpleStateMachineLibrary 8 | 9 | MIT 10 | statemachine state-machine finite-state-machine 11 | https://github.com/SimpleStateMachine/SimpleStateMachineLibrary 12 | 2.1.1.0 13 | Library for SimpleStateMachine 14 | SimpleStateMachine.png 15 | 2.1.1.0 16 | 2.1.1.0 17 | add PreviousState and CurrentTransition 18 | Some fix for logging 19 | Microsoft.Extensions.Logging.Abstractions 3.1.5 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | True 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/StateMachines/InvokeParameters.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace SimpleStateMachineLibrary 6 | { 7 | public class InvokeParameters 8 | { 9 | internal InvokeParameters(StateMachine stateMachine) 10 | { 11 | StateMachine = stateMachine; 12 | } 13 | 14 | internal StateMachine StateMachine; 15 | } 16 | 17 | public static class InvokeParametersExtension 18 | { 19 | public static InvokeParameters AddParameter(this InvokeParameters invokeParameters, string nameParameter, object valueParameter) 20 | { 21 | 22 | if(invokeParameters.StateMachine._nextParameters ==null) 23 | { 24 | invokeParameters.StateMachine._nextParameters = new Dictionary(); 25 | } 26 | 27 | invokeParameters.StateMachine._nextParameters.Add(nameParameter, valueParameter); 28 | return invokeParameters; 29 | } 30 | 31 | public static InvokeParameters AddParameters(this InvokeParameters invokeParameters, Dictionary parameters) 32 | { 33 | 34 | if (invokeParameters.StateMachine._nextParameters == null) 35 | { 36 | invokeParameters.StateMachine._nextParameters = new Dictionary(); 37 | } 38 | 39 | foreach (var parameter in parameters) 40 | { 41 | invokeParameters.StateMachine._nextParameters.Add(parameter.Key, parameter.Value); 42 | } 43 | 44 | return invokeParameters; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/Data/DataWorkWithXML.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System.Xml.Linq; 4 | 5 | 6 | namespace SimpleStateMachineLibrary 7 | { 8 | public partial class Data 9 | { 10 | internal static XElement _ToXElement(Data data, bool withLog) 11 | { 12 | Check.NamedObject(data, data?.StateMachine?._logger); 13 | XElement element = new XElement("Data"); 14 | element.Add(new XAttribute("Name", data.Name)); 15 | element.Add(new XAttribute("Value", data.Value.ToString())); 16 | 17 | if(withLog) 18 | data.StateMachine._logger.LogDebug("Data \"{NameData}\" to XElement", data.Name); 19 | 20 | return element; 21 | } 22 | 23 | internal XElement _ToXElement(bool withLog) 24 | { 25 | return Data._ToXElement(this, withLog); 26 | } 27 | 28 | internal static Data _FromXElement(StateMachine stateMachine, XElement data, bool withLog) 29 | { 30 | stateMachine = Check.Object(stateMachine, stateMachine?._logger); 31 | data = Check.Object(data, stateMachine?._logger); 32 | 33 | string Name = data.Attribute("Name")?.Value; 34 | string Value = data.Attribute("Value")?.Value; 35 | 36 | Data dataObj = stateMachine._AddData(Name, Value, null, result: out bool result, exception:true, withLog: false); 37 | 38 | if((result)&&(withLog)) 39 | stateMachine?._logger.LogDebug("Initialization data \"{NameData}\" from XElement", Name); 40 | 41 | return dataObj; 42 | } 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/Data/Data.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System; 4 | 5 | namespace SimpleStateMachineLibrary 6 | { 7 | public partial class Data : NamedObject 8 | { 9 | private object _value; 10 | 11 | public object Value 12 | { get { return _value; } 13 | set 14 | { 15 | _onChange?.Invoke(this, value); 16 | _value = value; 17 | } 18 | } 19 | 20 | private Action _onChange; 21 | 22 | internal Data(StateMachine stateMachine, string nameData, object valueData, Action actionOnChange, bool withLog) : base(stateMachine, nameData) 23 | { 24 | Value = valueData; 25 | 26 | //stateMachine?._logger.LogDebug("Create data \"{NameData}\" ", nameData); 27 | 28 | stateMachine._AddData(this, out _, true, withLog); 29 | 30 | if (actionOnChange != null) 31 | { 32 | OnChange(actionOnChange); 33 | } 34 | } 35 | 36 | public Data Delete() 37 | { 38 | return this.StateMachine.DeleteData(this); 39 | } 40 | 41 | public Data TryDelete(out bool result) 42 | { 43 | return this.StateMachine.TryDeleteData(this, out result); 44 | } 45 | 46 | public Data OnChange(Action actionOnChange) 47 | { 48 | actionOnChange = Check.Object(actionOnChange, this.StateMachine?._logger); 49 | 50 | _onChange += actionOnChange; 51 | this.StateMachine._logger.LogDebug("Method \"{NameMethod}\" subscribe on change data \"{NameData}\"", actionOnChange.Method.Name, this.Name); 52 | return this; 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/States/StateWorkWithTransitionsToThisState.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | 5 | namespace SimpleStateMachineLibrary 6 | { 7 | public partial class State 8 | { 9 | public Dictionary GetTransitionsToThis() 10 | { 11 | return this.StateMachine.GetTransitionsToState(this); 12 | } 13 | 14 | public Dictionary TryGetTransitionsToThis(out bool result) 15 | { 16 | return this.StateMachine.TryGetTransitionsToState(this, out result); 17 | } 18 | 19 | public Transition AddTransitionToThis(string nameTransition, State stateFrom, Action> actionOnInvoke = null) 20 | { 21 | return this.StateMachine.AddTransition(nameTransition, stateFrom, this); 22 | } 23 | 24 | public Transition AddTransitionToThis(string nameTransition, string nameStateFrom, Action> actionOnInvoke = null) 25 | { 26 | return this.StateMachine.AddTransition(nameTransition, nameStateFrom, this); 27 | } 28 | 29 | public Transition TryAddTransitionToThis(out bool result, string nameTransition, State stateFrom, Action> actionOnInvoke = null) 30 | { 31 | return this.StateMachine.TryAddTransition(out result, nameTransition, stateFrom, this, actionOnInvoke); 32 | } 33 | 34 | public Transition TryAddTransitionToThis(out bool result, string nameTransition, string nameStateFrom, Action> actionOnInvoke = null) 35 | { 36 | return this.StateMachine.TryAddTransition(out result, nameTransition, nameStateFrom, this, actionOnInvoke); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/States/StateWorkWithTransitionsFromThisState.cs: -------------------------------------------------------------------------------- 1 | 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace SimpleStateMachineLibrary 6 | { 7 | public partial class State 8 | { 9 | public Dictionary GetTransitionsFromThis() 10 | { 11 | return this.StateMachine.GetTransitionsFromState(this); 12 | } 13 | 14 | public Dictionary TryGetTransitionsFromThis(out bool result) 15 | { 16 | return this.StateMachine.TryGetTransitionsFromState(this, out result); 17 | } 18 | 19 | public Transition AddTransitionFromThis(string nameTransition, State stateTo, Action> actionOnInvoke = null) 20 | { 21 | return this.StateMachine.AddTransition(nameTransition, this, stateTo, actionOnInvoke); 22 | } 23 | 24 | public Transition AddTransitionFromThis(string nameTransition, string nameStateTo, Action> actionOnInvoke = null) 25 | { 26 | return this.StateMachine.AddTransition(nameTransition, this, nameStateTo, actionOnInvoke); 27 | } 28 | 29 | public Transition TryAddTransitionFromThis(out bool result, string nameTransition, State stateTo, Action> actionOnInvoke = null) 30 | { 31 | return this.StateMachine.TryAddTransition(out result, nameTransition, this, stateTo, actionOnInvoke); 32 | } 33 | 34 | public Transition TryAddTransitionFromThis(out bool result, string nameTransition, string nameStateTo, Action> actionOnInvoke = null) 35 | { 36 | return this.StateMachine.TryAddTransition(out result, nameTransition, this, nameStateTo, actionOnInvoke); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/Transitions/TransitionWorkWithXML.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System.Xml.Linq; 4 | 5 | 6 | namespace SimpleStateMachineLibrary 7 | { 8 | public partial class Transition 9 | { 10 | internal static XElement _ToXElement(Transition transition, bool withLog) 11 | { 12 | Check.NamedObject(transition, transition?.StateMachine?._logger); 13 | XElement element = new XElement("Transition"); 14 | element.Add(new XAttribute("Name", transition.Name)); 15 | element.Add(new XAttribute("From", transition.StateFrom)); 16 | element.Add(new XAttribute("To", transition.StateTo)); 17 | 18 | if(withLog) 19 | transition.StateMachine._logger.LogDebug("Transition \"{NameTransition}\" to XElement", transition.Name); 20 | 21 | return element; 22 | } 23 | 24 | internal XElement _ToXElement(bool withLog) 25 | { 26 | return Transition._ToXElement(this, withLog); 27 | } 28 | 29 | internal static Transition _FromXElement(StateMachine stateMachine, XElement transition, bool withLog) 30 | { 31 | stateMachine = Check.Object(stateMachine, stateMachine?._logger); 32 | transition = Check.Object(transition, stateMachine?._logger); 33 | 34 | string Name = transition.Attribute("Name")?.Value; 35 | string From = transition.Attribute("From")?.Value; 36 | string To = transition.Attribute("To")?.Value; 37 | 38 | Transition transitionObj = stateMachine._AddTransition(Name, From, To, null, out bool result, true, false); 39 | if((result)&&(withLog)) 40 | stateMachine?._logger.LogDebug("Initialization transition \"{NameTransition}\" from XElement", Name); 41 | 42 | return transitionObj; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Examples/Program.cs: -------------------------------------------------------------------------------- 1 | using SimpleStateMachineLibrary; 2 | using System; 3 | using System.Collections.Generic; 4 | 5 | namespace Examples 6 | { 7 | class Program 8 | { 9 | static void Action1(State state, Dictionary parameters) 10 | { 11 | state.StateMachine.InvokeTransition("Transition1"); 12 | } 13 | static void Action2(State state, Dictionary parameters) 14 | { 15 | state.StateMachine.InvokeTransition("Transition2"); 16 | } 17 | static void Action3(State state, Dictionary parameters) 18 | { 19 | state.StateMachine.InvokeTransition("Transition3"); 20 | } 21 | static void Action4(State state, Dictionary parameters) 22 | { 23 | 24 | } 25 | 26 | static void Main(string[] args) 27 | { 28 | StateMachine stateMachine = new StateMachine(); 29 | 30 | //Add states 31 | State state1 = stateMachine.AddState("State1"); 32 | State state2 = stateMachine.AddState("State2"); 33 | State state3 = stateMachine.AddState("State3"); 34 | State state4 = stateMachine.AddState("State4"); 35 | 36 | //Add transitions three ways: 37 | 38 | //Standart way 39 | Transition transition1 = stateMachine.AddTransition("Transition1", state1, state2); 40 | 41 | //From state 42 | Transition transition2 = state2.AddTransitionFromThis("Transition2", state3); 43 | 44 | //To state 45 | Transition transition3 = state4.AddTransitionToThis("Transition3", state3); 46 | 47 | //Add action on entry or/and exit 48 | state1.OnExit(Action1); 49 | state2.OnEntry(Action2); 50 | state3.OnExit(Action3); 51 | state4.OnExit(Action4); 52 | 53 | //Set start state 54 | state1.SetAsStartState(); 55 | 56 | //Start work 57 | stateMachine.Start(); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29806.167 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleStateMachineLibrary", "SimpleStateMachineLibrary\SimpleStateMachineLibrary.csproj", "{047A9390-803D-4964-B512-546D19B62066}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tests", "Tests\Tests.csproj", "{F508DC28-A157-49D4-8C65-791FFD6AF719}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Examples", "Examples\Examples.csproj", "{032759D0-1C07-4996-BB9E-4A187D7D8F73}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {047A9390-803D-4964-B512-546D19B62066}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {047A9390-803D-4964-B512-546D19B62066}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {047A9390-803D-4964-B512-546D19B62066}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {047A9390-803D-4964-B512-546D19B62066}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {F508DC28-A157-49D4-8C65-791FFD6AF719}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {F508DC28-A157-49D4-8C65-791FFD6AF719}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {F508DC28-A157-49D4-8C65-791FFD6AF719}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {F508DC28-A157-49D4-8C65-791FFD6AF719}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {032759D0-1C07-4996-BB9E-4A187D7D8F73}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {032759D0-1C07-4996-BB9E-4A187D7D8F73}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {032759D0-1C07-4996-BB9E-4A187D7D8F73}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {032759D0-1C07-4996-BB9E-4A187D7D8F73}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {55F50111-8503-4708-8485-A684BB817C7C} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/Transitions/Transition.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | namespace SimpleStateMachineLibrary 7 | { 8 | public partial class Transition : NamedObject 9 | { 10 | public string StateFrom { get; private set; } 11 | 12 | public string StateTo { get; private set; } 13 | 14 | private Action> _onInvoke; 15 | 16 | internal Transition(StateMachine stateMachine, string nameTransition, string stateFrom, string stateTo, Action> actionOnInvoke, bool withLog) : base(stateMachine, nameTransition) 17 | { 18 | 19 | StateFrom = stateMachine._StateExists(stateFrom, out _, true, false); 20 | StateTo = stateMachine._StateExists(stateTo, out _, true, false); 21 | 22 | //stateMachine?._logger.LogDebug("Create transition \"{NameTransition}\" from state \"{NameStateFrom}\" to state \"{NameStateTo}\"", nameTransition, stateFrom, stateTo); 23 | 24 | stateMachine._AddTransition(this, out _, true, withLog); 25 | 26 | if (actionOnInvoke != null) 27 | { 28 | OnInvoke(actionOnInvoke); 29 | } 30 | } 31 | 32 | public Transition Delete() 33 | { 34 | return this.StateMachine.DeleteTransition(this); 35 | } 36 | 37 | public Transition TryDelete(out bool result) 38 | { 39 | return this.StateMachine.TryDeleteTransition(this, out result); 40 | } 41 | 42 | public Transition OnInvoke(Action> actionOnInvoke) 43 | { 44 | actionOnInvoke = Check.Object(actionOnInvoke, this.StateMachine?._logger); 45 | 46 | _onInvoke += actionOnInvoke; 47 | 48 | this.StateMachine._logger.LogDebug("Method \"{NameMethod}\" subscribe on invoke for transition \"{NameTransition}\"", actionOnInvoke.Method.Name, this.Name); 49 | 50 | return this; 51 | } 52 | 53 | public InvokeParameters Invoke(Dictionary parameters) 54 | { 55 | return StateMachine.InvokeTransition(this, parameters); 56 | } 57 | 58 | internal Transition _Invoking(Dictionary parameters) 59 | { 60 | _onInvoke?.Invoke (this, parameters); 61 | this.StateMachine._logger.LogDebug("Invoke transition \"{NameTransition}\"", this.Name); 62 | return this; 63 | } 64 | 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/States/State.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | namespace SimpleStateMachineLibrary 7 | { 8 | public partial class State : NamedObject 9 | { 10 | private Action> _onEntry; 11 | 12 | private Action> _onExit; 13 | 14 | internal State(StateMachine stateMachine, string nameState, Action> actionOnEntry, Action> actionOnExit, bool withLog) : base(stateMachine, nameState) 15 | { 16 | //stateMachine?._logger.LogDebug("Create state \"{NameState}\" ", nameState); 17 | 18 | StateMachine._AddState(this, out bool result, true, withLog); 19 | 20 | if (actionOnEntry != null) 21 | { 22 | OnEntry(actionOnEntry); 23 | } 24 | 25 | if (actionOnExit != null) 26 | { 27 | OnExit(actionOnExit); 28 | } 29 | 30 | } 31 | 32 | public State Delete() 33 | { 34 | return this.StateMachine.DeleteState(this); 35 | } 36 | 37 | public State TryDelete(out bool result) 38 | { 39 | return this.StateMachine.TryDeleteState(this, out result); 40 | } 41 | 42 | public State SetAsStartState() 43 | { 44 | this.StateMachine.SetStartState(this); 45 | return this; 46 | } 47 | 48 | public State OnEntry(Action> actionOnEntry) 49 | { 50 | 51 | actionOnEntry = Check.Object(actionOnEntry, this.StateMachine?._logger); 52 | 53 | _onEntry += actionOnEntry; 54 | this.StateMachine._logger.LogDebug("Method \"{NameMethod}\" subscribe on entry for state \"{NameState}\"", actionOnEntry.Method.Name, this.Name); 55 | return this; 56 | } 57 | 58 | public State OnExit(Action> actionOnExit) 59 | { 60 | actionOnExit = Check.Object(actionOnExit, this.StateMachine?._logger); 61 | 62 | _onExit += actionOnExit; 63 | this.StateMachine._logger.LogDebug("Method \"{NameMethod}\" subscribe on exit for state \"{NameState}\"", actionOnExit.Method.Name, this.Name); 64 | return this; 65 | } 66 | 67 | internal void _Entry(Dictionary parameters, bool withLog) 68 | { 69 | _onEntry?.Invoke (this, parameters); 70 | 71 | if(withLog) 72 | this.StateMachine._logger.LogDebug("Entry to state \"{NameState}\"", this.Name); 73 | } 74 | 75 | internal void _Exit(Dictionary parameters, bool withLog) 76 | { 77 | _onExit?.Invoke(this, parameters); 78 | 79 | if (withLog) 80 | this.StateMachine._logger.LogDebug("Exit from state \"{NameState}\"", this.Name); 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | [![NuGet Pre Release](https://img.shields.io/nuget/vpre/SimpleStateMachineLibrary.svg)](https://www.nuget.org/packages/SimpleStateMachineLibrary) [![](https://img.shields.io/github/stars/SimpleStateMachine/SimpleStateMachineLibrary)](https://github.com/SimpleStateMachine/SimpleStateMachineLibrary) [![NuGet Downloads](https://img.shields.io/nuget/dt/SimpleStateMachineLibrary)](https://www.nuget.org/packages/SimpleStateMachineLibrary) [![](https://img.shields.io/github/license/SimpleStateMachine/SimpleStateMachineLibrary)](https://github.com/SimpleStateMachine/SimpleStateMachineLibrary) [![](https://img.shields.io/github/languages/code-size/SimpleStateMachine/SimpleStateMachineLibrary)](https://github.com/SimpleStateMachine/SimpleStateMachineLibrary) 3 | [![]( https://img.shields.io/github/last-commit/SimpleStateMachine/SimpleStateMachineLibrary)](https://github.com/SimpleStateMachine/SimpleStateMachineLibrary) [![](https://img.shields.io/badge/chat-slack-blueviolet.svg)](https://join.slack.com/t/simplestatemachine/shared_invite/zt-fnfhvvsx-fTejcpPn~PPb2ojdG_MQBg) [![](https://img.shields.io/badge/chat-telegram-blue.svg)](https://t.me/joinchat/HMLJFkv9do6aDV188rhd0w) 4 | [![Build Status](https://dev.azure.com/GMIKE/SimpleStateMachineLibrary/_apis/build/status/SimpleStateMachine.SimpleStateMachineLibrary?branchName=master)](https://dev.azure.com/GMIKE/SimpleStateMachineLibrary/_build/latest?definitionId=2&branchName=master) 5 | # SimpleStateMachineLibrary 6 | A C# library for realization simple state-machine on .Net 7 | 8 | ## Give a Star! :star: 9 | If you like or are using this project please give it a star. Thanks! 10 | 11 | # Why SimpleStateMachine? 12 | Create state machine in **three** steps : 13 | 14 | **1.** Create scheme in [node editor🔗](https://github.com/SimpleStateMachine/SimpleStateMachineNodeEditor) and load it in your project using [this library📚](https://github.com/SimpleStateMachine/SimpleStateMachineLibrary) 15 | ```C# 16 | StateMachine stateMachine = new StateMachine("scheme.xml"); 17 | ``` 18 | **2.** Describe your app logic on events⚡ 19 | ```C# 20 | stateMachine.GetState("State1").OnExit(Action1); 21 | stateMachine.GetState("State2").OnEntry(Action2); 22 | stateMachine.GetTransition("Transition1").OnInvoke(Action3); 23 | stateMachine.OnChangeState(Action4); 24 | ``` 25 | **3.** Run the state machine🚘 26 | ```C# 27 | stateMachine.Start(); 28 | ``` 29 | ## Features💡 30 | 31 | State machine properties: 32 | * Start state 33 | * Entry/exit events for state 34 | * Invoke event for transition 35 | * Parameters for transitions 36 | * Parameters for entry/exit for state 37 | 38 | Useful extensions for work: 39 | * State changed event for state machine 40 | * Data for sharing between states 41 | * Change event for data 42 | * Export/Import to/from XML 43 | * Logging 44 | 45 | ## Getting Started📂 46 | Install from Nuget: 47 | ```sh 48 | Install-Package SimpleStateMachineLibrary 49 | ``` 50 | ## Documentation📄 51 | Documentation here: https://github.com/SimpleStateMachine/SimpleStateMachineLibrary/wiki 52 | 53 | ## FAQ❔ 54 | If you think you have found a bug, create a github [issue](https://github.com/SimpleStateMachine/SimpleStateMachineLibrary/issues). 55 | 56 | But if you just have questions about how to use: 57 | 58 | - [Slack channel](https://join.slack.com/t/simplestatemachine/shared_invite/zt-fnfhvvsx-fTejcpPn~PPb2ojdG_MQBg) 59 | - [Telegram channel](https://t.me/joinchat/HMLJFkv9do6aDV188rhd0w) 60 | 61 | ## License📑 62 | 63 | Copyright (c) SimpleStateMachine 64 | 65 | Licensed under the [MIT](LICENSE) license. 66 | 67 | -------------------------------------------------------------------------------- /Tests/StateMachineTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using SimpleStateMachineLibrary; 4 | using System; 5 | using System.Collections.Generic; 6 | 7 | namespace Tests 8 | { 9 | [TestClass] 10 | public class StateMachineTests 11 | { 12 | 13 | void Method1(State state, Dictionary parameters) 14 | { 15 | Assert.AreEqual(parameters["Data1"], "Test Data"); 16 | 17 | state.StateMachine.InvokeTransition("Transition1"); 18 | } 19 | void Method2(State state, Dictionary parameters) 20 | { 21 | state.StateMachine.InvokeTransition("Transition2"); 22 | } 23 | void Method3(State state, Dictionary parameters) 24 | { 25 | state.StateMachine.InvokeTransition("Transition3"); 26 | } 27 | void Method4(State state, Dictionary parameters) 28 | { 29 | 30 | } 31 | 32 | void ActionOnTransitionInvoke(Transition transition, Dictionary parameters) 33 | { 34 | 35 | } 36 | void ActionOnChangeState(State stateFrom, State stateTo) 37 | { 38 | 39 | } 40 | static Dictionary parametersForStart = new Dictionary() { { "Data1", "Test Data" } }; 41 | static Dictionary parametersForStart2 = new Dictionary() { { "string", "stroka" } }; 42 | [TestCategory("StateMachine")] 43 | [TestMethod] 44 | public void StateMachineFromCode() 45 | { 46 | var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole().AddDebug().SetMinimumLevel(LogLevel.Debug); }); 47 | var logger = loggerFactory.CreateLogger(); 48 | StateMachine stateMachine = new StateMachine(logger); 49 | State state1 = stateMachine.AddState("State1", actionOnExit: Method1); 50 | State state2 = stateMachine.AddState("State2"); 51 | State state3 = stateMachine.AddState("State3"); 52 | State state4 = stateMachine.AddState("State4"); 53 | 54 | Assert.IsTrue(stateMachine.StateExists("State1")); 55 | 56 | stateMachine.OnChangeState(ActionOnChangeState); 57 | 58 | Transition transition1 = state1.AddTransitionFromThis("Transition1", state2); 59 | Transition transition2 = stateMachine.AddTransition("Transition2", state2, state3); 60 | Transition transition3 = state4.AddTransitionToThis("Transition3", state3); 61 | 62 | Assert.IsTrue(stateMachine.TransitionExists("Transition1")); 63 | 64 | state1.SetAsStartState(); 65 | state2.OnExit(Method2); 66 | state3.OnExit(Method3); 67 | state4.OnExit(Method4); 68 | stateMachine.AddData("int1", 55); 69 | stateMachine.AddData("string1", "Roman"); 70 | stateMachine.AddData("double1", 1001.0005); 71 | 72 | Assert.IsTrue(stateMachine.DataExists("int1")); 73 | stateMachine.Start(parametersForStart); 74 | 75 | Assert.AreEqual(stateMachine.CurrentState.Name, "State4"); 76 | 77 | stateMachine.ToXDocument("text.xml"); 78 | 79 | } 80 | 81 | [TestCategory("StateMachine")] 82 | [TestMethod] 83 | public void StateMachineFromXML() 84 | { 85 | var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole().AddDebug().SetMinimumLevel(LogLevel.Debug); }); 86 | var logger = loggerFactory.CreateLogger(); 87 | 88 | StateMachine stateMachine = StateMachine.FromXDocument("text.xml", logger); 89 | 90 | stateMachine.GetState("State1").OnExit(Method1); 91 | stateMachine.GetState("State2").OnExit(Method2); 92 | stateMachine.GetState("State3").OnExit(Method3); 93 | 94 | stateMachine.OnChangeState(ActionOnChangeState); 95 | 96 | stateMachine.Start(parametersForStart); 97 | 98 | Assert.AreEqual(stateMachine.CurrentState.Name, "State4"); 99 | } 100 | 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/StateMachines/StateMachineWorkWithXML.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System.Linq; 4 | using System.Xml.Linq; 5 | 6 | 7 | namespace SimpleStateMachineLibrary 8 | { 9 | public partial class StateMachine 10 | { 11 | 12 | internal static XDocument _ToXDocument(StateMachine stateMachine, string nameFile, bool withLog) 13 | { 14 | Check.Object(stateMachine, stateMachine?._logger); 15 | Check.Name(nameFile, stateMachine?._logger); 16 | XDocument xDocument = new XDocument(); 17 | XElement stateMachineXElement = new XElement("StateMachine"); 18 | xDocument.Add(stateMachineXElement); 19 | stateMachine?._logger.LogDebug("StateMachine to XDocument"); 20 | XElement states = new XElement("States"); 21 | stateMachineXElement.Add(states); 22 | foreach(var state in stateMachine._states) 23 | { 24 | states.Add(state.Value.ToXElement(withLog)); 25 | } 26 | 27 | if (stateMachine?._startState != null) 28 | { 29 | XElement startState = new XElement("StartState"); 30 | stateMachineXElement.Add(startState); 31 | startState.Add(new XAttribute("Name", stateMachine._startState)); 32 | } 33 | 34 | XElement transitions = new XElement("Transitions"); 35 | stateMachineXElement.Add(transitions); 36 | 37 | foreach (var transition in stateMachine._transitions) 38 | { 39 | transitions.Add(transition.Value._ToXElement(withLog)); 40 | } 41 | 42 | XElement datas = new XElement("DATA"); 43 | stateMachineXElement.Add(datas); 44 | 45 | foreach (var data in stateMachine._data) 46 | { 47 | datas.Add(data.Value._ToXElement(withLog)); 48 | } 49 | 50 | xDocument.Save(nameFile); 51 | 52 | return xDocument; 53 | } 54 | 55 | public XDocument ToXDocument(string nameFile) 56 | { 57 | return StateMachine._ToXDocument(this, nameFile, true); 58 | } 59 | 60 | internal static StateMachine _FromXDocument(StateMachine stateMachine, XDocument xDocument, bool withLog) 61 | { 62 | XElement stateMachineXElement = Check.Object(xDocument, stateMachine?._logger).Element("StateMachine"); 63 | stateMachineXElement = Check.Object(stateMachineXElement, stateMachine?._logger); 64 | var States = stateMachineXElement.Element("States")?.Elements()?.ToList(); 65 | States?.ForEach(x => stateMachine._AddState(x, true)); 66 | var startState = stateMachineXElement.Element("StartState"); 67 | string nameStartState = startState?.Attribute("Name").Value; 68 | if (!string.IsNullOrEmpty(nameStartState)) 69 | stateMachine.SetStartState(nameStartState); 70 | 71 | var Transitions = stateMachineXElement.Element("Transitions")?.Elements()?.ToList(); 72 | Transitions?.ForEach(x => stateMachine._AddTransition(x, true)); 73 | 74 | var Datas = stateMachineXElement.Element("DATA")?.Elements()?.ToList(); 75 | Datas?.ForEach(x => stateMachine._AddData(x, true)); 76 | stateMachine?._logger.LogDebug("StateMachine from XDocument"); 77 | return stateMachine; 78 | } 79 | 80 | internal static StateMachine _FromXDocument(StateMachine stateMachine, string xDocumentPath, bool withLog) 81 | { 82 | xDocumentPath = Check.Name(xDocumentPath, stateMachine?._logger); 83 | XDocument xDocument = XDocument.Load(xDocumentPath); 84 | return _FromXDocument(stateMachine, xDocument, withLog); 85 | } 86 | 87 | public static StateMachine FromXDocument(XDocument xDocument, ILogger logger = null) 88 | { 89 | StateMachine stateMachine = new StateMachine(logger); 90 | return _FromXDocument(stateMachine, xDocument, true); 91 | } 92 | 93 | public static StateMachine FromXDocument(string xmlFilePath, ILogger logger = null) 94 | { 95 | StateMachine stateMachine = new StateMachine(logger); 96 | return _FromXDocument(stateMachine, xmlFilePath, true); 97 | } 98 | 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/StateMachines/StateMachineWorkWithTransitionsForState.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | 7 | namespace SimpleStateMachineLibrary 8 | { 9 | public partial class StateMachine 10 | { 11 | internal Dictionary _GetTransitionsFromState(string stateName, out bool result, bool exceptions, bool withLog) 12 | { 13 | result = Check.Contains(_states, stateName, this._logger, exceptions); 14 | var transitionsFromState = result ? Check.GetValuesWhere(_transitions, (Transition x) => x.StateFrom == stateName, this._logger, out result, exceptions): new Dictionary(); 15 | 16 | if(withLog) 17 | _logger.LogDebug("Get transitions from state \"{NameState}\" ", stateName); 18 | 19 | return transitionsFromState; 20 | } 21 | 22 | internal Dictionary _GetTransitionsFromState(State state, out bool result, bool exceptions, bool withLog) 23 | { 24 | result = Check.Contains(_states, state, this._logger, exceptions); 25 | var transitionsFromState = result ? Check.GetValuesWhere(_transitions, (Transition x) => x.StateFrom == state.Name, this._logger, out result, exceptions) : new Dictionary(); 26 | 27 | if(withLog) 28 | _logger.LogDebug("Get transitions from state \"{NameState}\" ", state.Name); 29 | 30 | return transitionsFromState; 31 | } 32 | 33 | public Dictionary GetTransitionsFromState(string stateName) 34 | { 35 | return _GetTransitionsFromState(stateName, out bool result, true, true); 36 | } 37 | 38 | public Dictionary GetTransitionsFromState(State state) 39 | { 40 | return _GetTransitionsFromState(state, out bool result, true, true); 41 | } 42 | 43 | public Dictionary TryGetTransitionsFromState(string stateName, out bool result) 44 | { 45 | return _GetTransitionsFromState(stateName, out result, false, true); 46 | } 47 | 48 | public Dictionary TryGetTransitionsFromState(State state, out bool result) 49 | { 50 | return _GetTransitionsFromState(state, out result, false, true); 51 | } 52 | 53 | 54 | 55 | internal Dictionary _GetTransitionsToState(string stateName, out bool result, bool exceptions, bool withLog) 56 | { 57 | result = Check.Contains(_states, stateName, this._logger, exceptions); 58 | var transitionsToState = result ? Check.GetValuesWhere(_transitions, (Transition x) => x.StateTo == stateName, this._logger, out result, exceptions): new Dictionary(); 59 | 60 | if(withLog) 61 | _logger.LogDebug("Get transitions to state \"{NameState}\" ", stateName); 62 | 63 | return transitionsToState; 64 | } 65 | 66 | internal Dictionary _GetTransitionsToState(State state, out bool result, bool exceptions, bool withLog) 67 | { 68 | result = Check.Contains(_states, state, this._logger, exceptions); 69 | var transitionsToState = result ? Check.GetValuesWhere(_transitions, (Transition x) => x.StateTo == state.Name, this._logger, out result, exceptions) : new Dictionary(); 70 | 71 | if(withLog) 72 | _logger.LogDebug("Get transitions to state \"{NameState}\" ", state.Name); 73 | 74 | return transitionsToState; 75 | } 76 | 77 | public Dictionary GetTransitionsToState(string stateName) 78 | { 79 | return _GetTransitionsToState(stateName, out bool result, true, true); 80 | } 81 | 82 | public Dictionary GetTransitionsToState(State state) 83 | { 84 | return _GetTransitionsToState(state, out bool result, true, true); 85 | } 86 | 87 | public Dictionary TryGetTransitionsToState(string stateName, out bool result) 88 | { 89 | return _GetTransitionsToState(stateName, out result, false, true); 90 | } 91 | 92 | public Dictionary TryGetTransitionsToState(State state, out bool result) 93 | { 94 | return _GetTransitionsToState(state, out result, false, true); 95 | } 96 | 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/StateMachines/StateMachineWorkWithData.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System; 4 | using System.Xml.Linq; 5 | 6 | namespace SimpleStateMachineLibrary 7 | { 8 | public partial class StateMachine 9 | { 10 | 11 | internal Data _GetData(string nameData, out bool result, bool exception, bool withLog) 12 | { 13 | var data_ = Check.GetElement(_data, nameData, this._logger, out result, exception); 14 | 15 | if (withLog) 16 | { 17 | if (exception) 18 | _logger.LogDebug("Get data \"{NameData}\"", nameData); 19 | else 20 | _logger.LogDebug("Try get data \"{NameData}\"", nameData); 21 | } 22 | 23 | return data_; 24 | } 25 | 26 | internal string _DataExists(string nameData, out bool result, bool exeption, bool withLog) 27 | { 28 | return Check.Contains(_data, nameData, this._logger, out result, exeption); 29 | } 30 | 31 | public bool DataExists(string nameData) 32 | { 33 | nameData = _DataExists(nameData, out bool result, false, true); 34 | return result; 35 | } 36 | 37 | public Data GetData(string nameData) 38 | { 39 | return _GetData(nameData, out bool result, true, true); 40 | } 41 | 42 | public Data TryGetData(string nameData, out bool result) 43 | { 44 | return _GetData(nameData, out result, false, true); 45 | } 46 | 47 | internal Data _AddData(string nameData, object valueData, Action actionOnChange, out bool result, bool exception, bool withLog) 48 | { 49 | //throw that element already contains 50 | result = Check.NotContains(_data, nameData, this._logger, exception); 51 | 52 | if (!result) 53 | return null; 54 | 55 | return new Data(this, nameData, valueData, actionOnChange, withLog); 56 | } 57 | 58 | internal Data _AddData(Data data, out bool result, bool exception, bool withLog) 59 | { 60 | //throw that element already contains 61 | result = Check.NotContains(_data, data, this._logger, exception); 62 | 63 | if (!result) 64 | return null; 65 | 66 | _data.Add(data.Name, data); 67 | if (withLog) 68 | { 69 | if (exception) 70 | _logger.LogDebug("Add data \"{NameData}\"", data.Name); 71 | else 72 | _logger.LogDebug("Try add data \"{NameData}\"", data.Name); 73 | } 74 | 75 | return data; 76 | } 77 | 78 | internal Data _AddData(XElement xElement, bool withLog) 79 | { 80 | return Data._FromXElement(this, Check.Object(xElement, this._logger), withLog); 81 | } 82 | 83 | 84 | public Data AddData(string nameData, object valueData = default(object), Action actionOnChange = null) 85 | { 86 | return _AddData(nameData, valueData, actionOnChange, out bool result, true, true); 87 | } 88 | 89 | public Data TryAddData(out bool result, string nameData, object valueData = default(object), Action actionOnChange = null) 90 | { 91 | return _AddData(nameData, valueData, actionOnChange, out result, false, true); 92 | } 93 | 94 | 95 | 96 | private Data _DeleteData(Data data, out bool result, bool exception, bool withLog) 97 | { 98 | var data_ = Check.Remove(_data, data, this._logger, out result, exception); 99 | 100 | if (withLog) 101 | { 102 | if (exception) 103 | _logger.LogDebug("Delete data \"{NameData}\"", data.Name); 104 | else 105 | _logger.LogDebug("Try delete data \"{NameData}\"", data.Name); 106 | } 107 | 108 | return data_; 109 | } 110 | 111 | private Data _DeleteData(string dataName, out bool result, bool exception, bool withLog) 112 | { 113 | var data_ = Check.Remove(_data, dataName, this._logger, out result, exception); 114 | 115 | if (withLog) 116 | { 117 | if (exception) 118 | _logger.LogDebug("Delete data \"{NameData}\"", dataName); 119 | else 120 | _logger.LogDebug("Try delete data \"{NameData}\"", dataName); 121 | } 122 | 123 | 124 | return data_; 125 | } 126 | 127 | 128 | public Data DeleteData(string nameData) 129 | { 130 | return _DeleteData(nameData, out bool result, true, true); 131 | } 132 | 133 | public Data DeleteData(Data data) 134 | { 135 | return _DeleteData(data, out bool result, true, true); 136 | } 137 | 138 | public Data TryDeleteData(string nameData, out bool result) 139 | { 140 | return _DeleteData(nameData, out result, false, true); 141 | } 142 | 143 | public Data TryDeleteData(Data data, out bool result) 144 | { 145 | return _DeleteData(data, out result, false, true); 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/StateMachines/StateMachineWorkWithStates.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Xml.Linq; 6 | 7 | namespace SimpleStateMachineLibrary 8 | { 9 | public partial class StateMachine 10 | { 11 | 12 | internal string _StateExists(string nameState, out bool result, bool exeption, bool withLog) 13 | { 14 | return Check.Contains(_states, nameState, this._logger, out result, exeption); 15 | } 16 | 17 | public bool StateExists(string nameState) 18 | { 19 | nameState = _StateExists(nameState, out bool result, false, true); 20 | return result; 21 | } 22 | 23 | internal State _GetState(string nameState, out bool result, bool exception, bool withLog) 24 | { 25 | var _state = Check.GetElement(_states, nameState, this._logger, out result, exception); 26 | 27 | if (withLog) 28 | { 29 | if (exception) 30 | _logger.LogDebug("Get state \"{NameState}\"", nameState); 31 | else 32 | _logger.LogDebug("Try get state \"{NameState}\"", nameState); 33 | } 34 | 35 | return _state; 36 | } 37 | 38 | public State GetState(string nameState) 39 | { 40 | return _GetState(nameState, out bool result, true, true); 41 | } 42 | 43 | public State TryGetState(string nameState, out bool result) 44 | { 45 | return _GetState(nameState, out result, false, true); 46 | } 47 | 48 | internal State _AddState(string nameState, Action> actionOnEntry, Action> actionOnExit, out bool result, bool exception, bool withLog) 49 | { 50 | //throw that element already contains 51 | result = Check.NotContains(_states, nameState, this._logger, exception); 52 | 53 | 54 | if (!result) 55 | return null; 56 | 57 | return new State(this, nameState, actionOnEntry, actionOnExit, withLog); 58 | } 59 | 60 | internal State _AddState(State state, out bool result, bool exception, bool withLog) 61 | { 62 | //throw that element already contains 63 | result = Check.NotContains(_states, state, this._logger, exception); 64 | 65 | if (!result) 66 | return null; 67 | 68 | _states.Add(state.Name, state); 69 | 70 | if (withLog) 71 | { 72 | if (exception) 73 | _logger.LogDebug("Add state \"{NameState}\"", state.Name); 74 | else 75 | _logger.LogDebug("Try add state \"{NameState}\"", state.Name); 76 | } 77 | 78 | return state; 79 | } 80 | 81 | internal State _AddState(XElement xElement, bool withLog) 82 | { 83 | return State.FromXElement(this, Check.Object(xElement, this._logger), withLog); 84 | } 85 | 86 | 87 | public State AddState(string nameState, Action> actionOnEntry = null, Action> actionOnExit = null) 88 | { 89 | return _AddState(nameState, actionOnEntry, actionOnExit, out bool result, true, true); 90 | } 91 | 92 | public State TryAddState(out bool result, string nameState, Action> actionOnEntry = null, Action> actionOnExit = null) 93 | { 94 | return _AddState(nameState, actionOnEntry, actionOnExit, out result, false, true); 95 | } 96 | 97 | 98 | 99 | internal State _DeleteState(State state, out bool result, bool exception, bool withLog) 100 | { 101 | 102 | var _state = Check.Remove(_states, state, this._logger, out result, exception); 103 | 104 | if (withLog) 105 | { 106 | if (exception) 107 | _logger.LogDebug("Delete state \"{NameState}\"", state.Name); 108 | else 109 | _logger.LogDebug("Try delete state \"{NameState}\"", state.Name); 110 | } 111 | 112 | return _state; 113 | } 114 | 115 | internal State _DeleteState(string stateName, out bool result, bool exception, bool withLog) 116 | { 117 | var _state = Check.Remove(_states, stateName, this._logger, out result, exception); 118 | 119 | if (withLog) 120 | { 121 | if (exception) 122 | _logger.LogDebug("Delete state \"{NameState}\"", stateName); 123 | else 124 | _logger.LogDebug("Try delete state \"{NameState}\"", stateName); 125 | } 126 | 127 | return _state; 128 | } 129 | 130 | 131 | public State DeleteState(State state) 132 | { 133 | return _DeleteState(state, out bool result, true, true); 134 | } 135 | 136 | public State DeleteState(string stateName) 137 | { 138 | return _DeleteState(_GetState(stateName, out bool result, true, false), out result, true, true); 139 | } 140 | 141 | public State TryDeleteState(State state, out bool result) 142 | { 143 | return _DeleteState(state, out result, false, true); 144 | } 145 | 146 | public State TryDeleteState(string stateName, out bool result) 147 | { 148 | return _DeleteState(stateName, out result, false, true); 149 | } 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb 341 | 342 | CodeMap1.dgml 343 | 344 | SimpleStateMachine.png -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/StateMachines/StateMachine.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Xml.Linq; 3 | using System; 4 | using SimpleStateMachineLibrary.Helpers; 5 | using System.Data.Common; 6 | using System.Linq; 7 | using Microsoft.Extensions.Logging.Abstractions; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace SimpleStateMachineLibrary 11 | { 12 | 13 | public partial class StateMachine 14 | { 15 | 16 | private Dictionary _states = new Dictionary(); 17 | 18 | private Dictionary _transitions = new Dictionary(); 19 | 20 | private Dictionary _data = new Dictionary(); 21 | 22 | public string CurrentStateName { get; private set; } 23 | 24 | public string PreviousStateName{ get; private set; } 25 | public string CurrentTransitionName { get; private set; } 26 | 27 | internal string _nextTransition; 28 | internal string _startState { get; private set; } 29 | 30 | internal Dictionary _currentParameters; 31 | 32 | internal Dictionary _nextParameters; 33 | 34 | internal Action _onChangeState; 35 | 36 | public State CurrentState { get { return _GetState(CurrentStateName, out _, true, false); } } 37 | public Transition CurrentTransition { get { return _GetTransition(CurrentTransitionName, out _, true, false); } } 38 | public State PreviousState { get { return _GetState(PreviousStateName, out _, true, false); } } 39 | 40 | 41 | 42 | 43 | internal ILogger _logger; 44 | 45 | public ILogger SetLogger(ILogger logger) 46 | { 47 | _logger = logger ?? NullLogger.Instance; 48 | 49 | return logger; 50 | } 51 | 52 | public StateMachine(ILogger logger=null) 53 | { 54 | SetLogger(logger); 55 | _logger.LogDebug("Create state machine"); 56 | } 57 | 58 | public StateMachine(XDocument xDocument, ILogger logger = null) : this(logger) 59 | { 60 | _FromXDocument(this, xDocument, true); 61 | 62 | } 63 | 64 | public StateMachine(string xDocumentPath, ILogger logger = null): this(logger) 65 | { 66 | _FromXDocument(this, xDocumentPath, true); 67 | } 68 | 69 | public StateMachine OnChangeState(Action actionOnChangeState) 70 | { 71 | _onChangeState += actionOnChangeState; 72 | _logger.LogDebug("Method \"{NameMethod}\" subscribe on change state for State Machine", actionOnChangeState.Method.Name); 73 | return this; 74 | } 75 | 76 | public State SetStartState(State state) 77 | { 78 | _startState = _StateExists(state.Name, out _, true, false); 79 | 80 | _logger.LogDebug("State \"{NameState}\" set as start", state.Name); 81 | 82 | return state; 83 | } 84 | 85 | public State SetStartState(string stateName) 86 | { 87 | State state = _GetState(stateName, out bool result, true, false); 88 | _startState = state.Name; 89 | 90 | if(result) 91 | _logger.LogDebug("State \"{NameState}\" set as start", stateName); 92 | 93 | return state; 94 | } 95 | 96 | public InvokeParameters InvokeTransition(string nameTransition, Dictionary parameters=null) 97 | { 98 | _nextTransition = _TransitionExists(nameTransition, out _,true, false); 99 | 100 | _CheckBeforeInvoke(this._logger, true); 101 | 102 | InvokeParameters invokeParameters = new InvokeParameters(this); 103 | if(parameters!=null) 104 | invokeParameters.AddParameters(parameters); 105 | return invokeParameters; 106 | } 107 | 108 | internal void _CheckBeforeInvoke(ILogger logger, bool withLog) 109 | { 110 | Transition transition = _GetTransition(_nextTransition, out _, true, false); 111 | if (transition.StateFrom!= CurrentStateName) 112 | { 113 | object[] args = { _nextTransition, CurrentStateName }; 114 | string message = "Transition \"{0}\" not available from state \"{0}\""; 115 | var exception = new ArgumentException(message: String.Format(message, args)); 116 | _logger.LogError(exception, message, args); 117 | 118 | throw exception; 119 | } 120 | 121 | if(withLog) 122 | _logger.LogDebug("Transition \"{NameTransition}\" set as next", _nextTransition); 123 | } 124 | 125 | public InvokeParameters InvokeTransition(Transition transition, Dictionary parameters = null) 126 | { 127 | return InvokeTransition(transition?.Name, parameters); 128 | } 129 | 130 | 131 | internal StateMachine _InvokeTransition() 132 | { 133 | 134 | //Mark nextParameters as current 135 | _currentParameters = _nextParameters; 136 | _nextParameters = null; 137 | 138 | //Mark nextTransition as current 139 | CurrentTransitionName = _nextTransition; 140 | _nextTransition = null; 141 | 142 | //Mark currentState as previous 143 | PreviousStateName = CurrentStateName; 144 | CurrentStateName = null; 145 | 146 | Transition currentTransition = _GetTransition(CurrentTransitionName, out _, true, false); 147 | currentTransition._Invoking(_currentParameters); 148 | CurrentStateName = currentTransition.StateTo; 149 | CurrentTransitionName = null; 150 | 151 | return this; 152 | } 153 | 154 | internal StateMachine _ChangeState() 155 | { 156 | State currentState = _GetState(CurrentStateName, out bool result, true, false); 157 | currentState._Entry(_currentParameters, true); 158 | State previousState = null; 159 | List obj = new List(); 160 | string message; 161 | 162 | if (string.IsNullOrEmpty(PreviousStateName)) 163 | { 164 | obj.Add(CurrentStateName); 165 | message = "State \"{StateNew}\" was set"; 166 | } 167 | else 168 | { 169 | obj.Add(PreviousStateName); 170 | obj.Add(CurrentStateName); 171 | message = "State \"{StateOld}\" change on \"{StateNew}\""; 172 | previousState = _GetState(PreviousStateName, out _, true, false); 173 | } 174 | 175 | _onChangeState?.Invoke(previousState, currentState); 176 | _logger.LogDebug(message, obj.ToArray()); 177 | currentState._Exit(_currentParameters, true); 178 | 179 | return this; 180 | } 181 | 182 | internal void _CheckStartState() 183 | { 184 | string message; 185 | if (string.IsNullOrEmpty(_startState)) 186 | { 187 | message = "Start state not set"; 188 | var exception = new NullReferenceException(message: message); 189 | _logger.LogError(exception, message); 190 | throw exception; 191 | } 192 | _startState = _StateExists(_startState, out _, true, false); 193 | CurrentStateName = _startState; 194 | } 195 | 196 | public void Start(Dictionary startParameters = null) 197 | { 198 | _CheckStartState(); 199 | 200 | _logger.LogInformation("Start work state machine"); 201 | _currentParameters = startParameters; 202 | 203 | _ChangeState(); 204 | 205 | while (_nextTransition != null) 206 | { 207 | _InvokeTransition(); 208 | 209 | _ChangeState(); 210 | } 211 | _logger.LogInformation("End work state machine"); 212 | 213 | } 214 | 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /Tests/DataTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using SimpleStateMachineLibrary; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | namespace Tests 7 | { 8 | [TestClass] 9 | public class DataTests 10 | { 11 | 12 | [TestMethod] 13 | [TestCategory("Data")] 14 | public void AllTestsWithLogger() 15 | { 16 | ForTest.stateMachine = new StateMachine(ForTest.GetConsoleLogger()); 17 | AllTests(); 18 | } 19 | 20 | [TestMethod] 21 | [TestCategory("Data")] 22 | public void AllTestsWithoutLogger() 23 | { 24 | ForTest.stateMachine = new StateMachine(); 25 | AllTests(); 26 | } 27 | 28 | public void AllTests() 29 | { 30 | AddDataTest(); 31 | GetDataTest(); 32 | DeleteDataTest(); 33 | ChangeDataTest(); 34 | } 35 | 36 | [TestMethod] 37 | [TestCategory("Data")] 38 | public void AddDataTest() 39 | { 40 | StateMachine stateMachine = ForTest.stateMachine; 41 | string dataName = "Data1"; 42 | Assert.IsFalse(stateMachine.DataExists(dataName)); 43 | 44 | Data data1 = stateMachine.AddData(dataName); 45 | Assert.IsNotNull(data1); 46 | 47 | Assert.IsTrue(stateMachine.DataExists(dataName)); 48 | 49 | Assert.ThrowsException(() => 50 | { 51 | data1 = stateMachine.AddData(dataName); 52 | }); 53 | 54 | data1 = stateMachine.TryAddData(out bool result, dataName); 55 | Assert.IsNull(data1); 56 | Assert.IsFalse(result); 57 | 58 | stateMachine.DeleteData(dataName); 59 | } 60 | 61 | [TestMethod] 62 | [TestCategory("Data")] 63 | public void GetDataTest() 64 | { 65 | StateMachine stateMachine = ForTest.stateMachine; 66 | string dataName = "Data1"; 67 | Data data1; 68 | bool result; 69 | Assert.IsFalse(stateMachine.DataExists(dataName)); 70 | 71 | //get data 72 | data1 = stateMachine.AddData(dataName); 73 | data1 = stateMachine.GetData(dataName); 74 | Assert.IsNotNull(data1); 75 | Assert.IsTrue(stateMachine.DataExists(dataName)); 76 | stateMachine.DeleteData(dataName); 77 | Assert.ThrowsException(() => 78 | { 79 | data1 = stateMachine.GetData(dataName); 80 | }); 81 | 82 | //try get data 83 | data1 = stateMachine.AddData(dataName); 84 | data1 = stateMachine.TryGetData(dataName, out result); 85 | Assert.IsNotNull(data1); 86 | Assert.IsTrue(result); 87 | Assert.IsTrue(stateMachine.DataExists(dataName)); 88 | stateMachine.DeleteData(dataName); 89 | data1 = stateMachine.TryGetData(dataName, out result); 90 | Assert.IsNull(data1); 91 | Assert.IsFalse(result); 92 | } 93 | 94 | [TestMethod] 95 | [TestCategory("Data")] 96 | public void DeleteDataTest() 97 | { 98 | StateMachine stateMachine = ForTest.stateMachine; 99 | string dataName = "Data1"; 100 | Data data1; 101 | bool result; 102 | 103 | //delete data by name 104 | data1 = stateMachine.AddData(dataName); 105 | data1 = stateMachine.DeleteData(dataName); 106 | Assert.IsNotNull(data1); 107 | Assert.IsFalse(stateMachine.DataExists(dataName)); 108 | Assert.ThrowsException(() => 109 | { 110 | data1 = stateMachine.DeleteData(dataName); 111 | }); 112 | 113 | //delete data by object 114 | data1 = stateMachine.AddData(dataName); 115 | data1 = stateMachine.DeleteData(data1); 116 | Assert.IsNotNull(data1); 117 | Assert.IsFalse(stateMachine.DataExists(dataName)); 118 | Assert.ThrowsException(() => 119 | { 120 | data1 = stateMachine.DeleteData(data1); 121 | }); 122 | 123 | //try delete data by name 124 | data1 = stateMachine.AddData(dataName); 125 | data1 = stateMachine.TryDeleteData(dataName, out result); 126 | Assert.IsNotNull(data1); 127 | Assert.IsTrue(result); 128 | data1 = stateMachine.TryDeleteData(dataName, out result); 129 | Assert.IsNull(data1); 130 | Assert.IsFalse(result); 131 | 132 | //try delete data by object 133 | data1 = stateMachine.AddData(dataName); 134 | data1 = stateMachine.TryDeleteData(data1, out result); 135 | Assert.IsNotNull(data1); 136 | Assert.IsTrue(result); 137 | data1 = stateMachine.TryDeleteData(data1, out result); 138 | Assert.IsNull(data1); 139 | Assert.IsFalse(result); 140 | 141 | //delete data from object 142 | data1 = stateMachine.AddData(dataName); 143 | data1 = data1.Delete(); 144 | Assert.IsNotNull(data1); 145 | Assert.IsFalse(stateMachine.DataExists(dataName)); 146 | Assert.ThrowsException(() => 147 | { 148 | data1 = data1.Delete(); 149 | }); 150 | 151 | //try delete data from object 152 | data1 = stateMachine.AddData(dataName); 153 | data1 = data1.TryDelete(out result); 154 | Assert.IsNotNull(data1); 155 | Assert.IsTrue(result); 156 | Assert.IsFalse(stateMachine.DataExists(dataName)); 157 | data1 = data1.TryDelete(out result); 158 | Assert.IsNull(data1); 159 | Assert.IsFalse(result); 160 | 161 | } 162 | 163 | [TestMethod] 164 | [TestCategory("Data")] 165 | public void ChangeDataTest() 166 | { 167 | StateMachine stateMachine = ForTest.stateMachine; 168 | int eventCount = 0; 169 | string dataName = "Data1"; 170 | int newDataValue = 5; 171 | Data data1; 172 | 173 | eventCount = 0; 174 | data1 = stateMachine.AddData(dataName); 175 | data1.Value = 5; 176 | Assert.AreEqual(eventCount, 0); 177 | stateMachine.DeleteData(dataName); 178 | 179 | eventCount = 0; 180 | data1 = stateMachine.AddData(dataName, 10, MethodOnChange); 181 | Assert.AreEqual(eventCount, 0); 182 | stateMachine.DeleteData(dataName); 183 | 184 | eventCount = 0; 185 | data1 = stateMachine.AddData(dataName, 10).OnChange(MethodOnChange); 186 | Assert.AreEqual(eventCount, 0); 187 | stateMachine.DeleteData(dataName); 188 | 189 | eventCount = 0; 190 | data1 = stateMachine.AddData(dataName); 191 | data1.OnChange(MethodOnChange); 192 | data1.Value = 5; 193 | Assert.AreEqual(eventCount, 1); 194 | stateMachine.DeleteData(dataName); 195 | 196 | eventCount = 0; 197 | data1 = stateMachine.AddData(dataName, actionOnChange:MethodOnChange); 198 | data1.Value = 5; 199 | Assert.AreEqual(eventCount, 1); 200 | stateMachine.DeleteData(dataName); 201 | 202 | eventCount = 0; 203 | data1 = stateMachine.AddData(dataName).OnChange(MethodOnChange); 204 | data1.Value = 5; 205 | Assert.AreEqual(eventCount, 1); 206 | stateMachine.DeleteData(dataName); 207 | 208 | eventCount = 0; 209 | data1 = stateMachine.AddData(dataName, actionOnChange:MethodOnChange).OnChange(MethodOnChange).OnChange(MethodOnChange); 210 | data1.OnChange(MethodOnChange); 211 | data1.OnChange(MethodOnChange); 212 | data1.Value = 5; 213 | Assert.AreEqual(eventCount, 5); 214 | stateMachine.DeleteData(dataName); 215 | 216 | void MethodOnChange(Data data, object newValue) 217 | { 218 | Assert.AreEqual(data.Name, dataName); 219 | Assert.AreEqual(newValue, newDataValue); 220 | eventCount++; 221 | } 222 | 223 | } 224 | 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/StateMachines/StateMachineWorkWithTransitions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using SimpleStateMachineLibrary.Helpers; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Xml.Linq; 6 | 7 | 8 | namespace SimpleStateMachineLibrary 9 | { 10 | public partial class StateMachine 11 | { 12 | internal string _TransitionExists(string nameTransition, out bool result, bool exeption, bool withLog) 13 | { 14 | return Check.Contains(_transitions, nameTransition, this._logger, out result, exeption); 15 | } 16 | 17 | public bool TransitionExists(string nameTransition) 18 | { 19 | nameTransition = _TransitionExists(nameTransition,out bool result, false, true); 20 | return result; 21 | } 22 | 23 | internal Transition _GetTransition(string nameTransition, out bool result, bool exception, bool withLog) 24 | { 25 | var _transition = Check.GetElement(_transitions, nameTransition, this._logger, out result, exception); 26 | 27 | if (withLog) 28 | { 29 | if (exception) 30 | _logger.LogDebug("Get transition \"{NameTransition}\"", nameTransition); 31 | else 32 | _logger.LogDebug("Try get transition \"{NameTransition}\"", nameTransition); 33 | } 34 | 35 | return _transition; 36 | } 37 | 38 | public Transition GetTransition(string nameTransition) 39 | { 40 | return _GetTransition(nameTransition, out bool result, true, true); 41 | } 42 | 43 | public Transition TryGetTransition(string nameTransition, out bool result) 44 | { 45 | return _GetTransition(nameTransition, out result, false, true); 46 | } 47 | 48 | 49 | internal Transition _AddTransition(string nameTransition, string stateFrom, string stateTo, Action> actionOnInvoke, out bool result, bool exception, bool withLog) 50 | { 51 | //throw that element already contains 52 | result = Check.NotContains(_transitions, nameTransition, this._logger, exception); 53 | 54 | if (!result) 55 | return null; 56 | 57 | return new Transition(this, nameTransition, stateFrom, stateTo, actionOnInvoke, withLog); 58 | } 59 | 60 | internal Transition _AddTransition(Transition transition, out bool result, bool exception, bool withLog) 61 | { 62 | //throw that element already contains 63 | result = Check.NotContains(_transitions, transition, this._logger, exception); 64 | 65 | if (!result) 66 | return null; 67 | 68 | _transitions.Add(transition.Name, transition); 69 | if (withLog) 70 | { 71 | if (exception) 72 | _logger.LogDebug("Add transition \"{NameTransition}\" from state \"{NameStateFrom}\" to state \"{NameStateTo}\"", transition.Name, transition.StateFrom, transition.StateTo); 73 | else 74 | _logger.LogDebug("Try add transition \"{NameTransition}\" from state \"{NameStateFrom}\" to state \"{NameStateTo}\"", transition.Name, transition.StateFrom, transition.StateTo); 75 | } 76 | 77 | return transition; 78 | } 79 | 80 | internal Transition _AddTransition(XElement xElement, bool withLog) 81 | { 82 | return Transition._FromXElement(this, Check.Object(xElement, this._logger), true); 83 | } 84 | 85 | 86 | public Transition AddTransition(string nameTransition, State stateFrom, State stateTo, Action> actionOnInvoke = null) 87 | { 88 | return _AddTransition(nameTransition, stateFrom?.Name, stateTo?.Name, actionOnInvoke, out bool result, true, true); 89 | } 90 | 91 | public Transition AddTransition(string nameTransition, State stateFrom, string nameStateTo, Action> actionOnInvoke = null) 92 | { 93 | return _AddTransition(nameTransition, stateFrom?.Name, nameStateTo, actionOnInvoke, out bool result, true, true); 94 | } 95 | 96 | public Transition AddTransition(string nameTransition, string nameStateFrom, State stateTo, Action> actionOnInvoke = null) 97 | { 98 | return _AddTransition(nameTransition, nameStateFrom, stateTo?.Name, actionOnInvoke, out bool result, true, true); 99 | } 100 | 101 | public Transition AddTransition(string nameTransition, string nameStateFrom, string nameStateTo, Action> actionOnInvoke = null) 102 | { 103 | return _AddTransition(nameTransition, nameStateFrom, nameStateTo, actionOnInvoke, out bool result, true, true); 104 | } 105 | 106 | public Transition TryAddTransition(out bool result, string nameTransition, State stateFrom, State stateTo, Action> actionOnInvoke = null) 107 | { 108 | return _AddTransition(nameTransition, stateFrom?.Name, stateTo?.Name, actionOnInvoke, out result, false, true); 109 | } 110 | 111 | public Transition TryAddTransition(out bool result, string nameTransition, State stateFrom, string nameStateTo, Action> actionOnInvoke = null) 112 | { 113 | return _AddTransition(nameTransition, stateFrom?.Name, nameStateTo, actionOnInvoke, out result, false, true); 114 | } 115 | 116 | public Transition TryAddTransition(out bool result, string nameTransition, string nameStateFrom, State stateTo, Action> actionOnInvoke = null) 117 | { 118 | return _AddTransition(nameTransition, nameStateFrom, stateTo?.Name, actionOnInvoke, out result, false, true); 119 | } 120 | 121 | public Transition TryAddTransition(out bool result, string nameTransition, string nameStateFrom, string nameStateTo, Action> actionOnInvoke = null) 122 | { 123 | return _AddTransition(nameTransition, nameStateFrom, nameStateTo, actionOnInvoke, out result, false, true); 124 | } 125 | 126 | 127 | 128 | 129 | internal Transition _DeleteTransition(Transition transition, out bool result, bool exception, bool withLog) 130 | { 131 | var _transition = Check.Remove(_transitions, transition, this._logger,out result, exception); 132 | 133 | if (withLog) 134 | { 135 | if (exception) 136 | _logger.LogDebug("Delete transition \"{NameTransition}\"", transition.Name); 137 | else 138 | _logger.LogDebug("Try delete transition \"{NameTransition}\"", transition.Name); 139 | } 140 | 141 | return _transition; 142 | } 143 | 144 | internal Transition _DeleteTransition(string transitionName, out bool result, bool exception, bool withLog) 145 | { 146 | var _transition = Check.Remove(_transitions, transitionName, this._logger, out result, exception); 147 | 148 | if (withLog) 149 | { 150 | if (exception) 151 | _logger.LogDebug("Delete transition \"{NameTransition}\"", transitionName); 152 | else 153 | _logger.LogDebug("Try delete transition \"{NameTransition}\"", transitionName); 154 | } 155 | 156 | return _transition; 157 | } 158 | 159 | 160 | public Transition DeleteTransition(Transition transition) 161 | { 162 | return _DeleteTransition(transition, out bool result, true, true); 163 | } 164 | 165 | public Transition DeleteTransition(string transitionName) 166 | { 167 | return _DeleteTransition(transitionName, out bool result, true, true); 168 | } 169 | 170 | public Transition TryDeleteTransition(Transition transition, out bool result) 171 | { 172 | return _DeleteTransition(transition, out result, false, true); 173 | } 174 | 175 | public Transition TryDeleteTransition(string transitionName, out bool result) 176 | { 177 | return _DeleteTransition(transitionName, out result, false, true); 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /Tests/StateTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using SimpleStateMachineLibrary; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Runtime.CompilerServices; 6 | 7 | namespace Tests 8 | { 9 | [TestClass] 10 | public class StateTests 11 | { 12 | [TestMethod] 13 | [TestCategory("State")] 14 | public void AllTestsWithLogger() 15 | { 16 | ForTest.stateMachine = new StateMachine(ForTest.GetConsoleLogger()); 17 | AllTests(); 18 | } 19 | [TestMethod] 20 | [TestCategory("State")] 21 | public void AllTestsWithoutLogger() 22 | { 23 | ForTest.stateMachine = new StateMachine(); 24 | AllTests(); 25 | } 26 | public void AllTests() 27 | { 28 | AddStateTest(); 29 | GetStateTest(); 30 | DeleteStateTest(); 31 | EntryExitStateTest(); 32 | } 33 | 34 | [TestMethod] 35 | [TestCategory("State")] 36 | public void AddStateTest() 37 | { 38 | StateMachine stateMachine = ForTest.stateMachine; 39 | string stateName = "State1"; 40 | Assert.IsFalse(stateMachine.StateExists(stateName)); 41 | 42 | State state1 = stateMachine.AddState(stateName); 43 | Assert.IsNotNull(state1); 44 | 45 | Assert.IsTrue(stateMachine.StateExists(stateName)); 46 | 47 | Assert.ThrowsException(() => 48 | { 49 | state1 = stateMachine.AddState(stateName); 50 | }); 51 | 52 | state1 = stateMachine.TryAddState(out bool result, stateName); 53 | Assert.IsNull(state1); 54 | Assert.IsFalse(result); 55 | 56 | stateMachine.DeleteState(stateName); 57 | 58 | } 59 | 60 | [TestMethod] 61 | [TestCategory("State")] 62 | public void GetStateTest() 63 | { 64 | StateMachine stateMachine = ForTest.stateMachine; 65 | string stateName = "State1"; 66 | State state1; 67 | bool result; 68 | 69 | Assert.IsFalse(stateMachine.StateExists(stateName)); 70 | 71 | //get state 72 | state1 = stateMachine.AddState(stateName); 73 | state1 = stateMachine.GetState(stateName); 74 | Assert.IsNotNull(state1); 75 | Assert.IsTrue(stateMachine.StateExists(stateName)); 76 | stateMachine.DeleteState(stateName); 77 | Assert.ThrowsException(() => 78 | { 79 | state1 = stateMachine.GetState(stateName); 80 | }); 81 | 82 | //try get state 83 | state1 = stateMachine.AddState(stateName); 84 | state1 = stateMachine.TryGetState(stateName, out result); 85 | Assert.IsNotNull(state1); 86 | Assert.IsTrue(result); 87 | Assert.IsTrue(stateMachine.StateExists(stateName)); 88 | stateMachine.DeleteState(stateName); 89 | state1 = stateMachine.TryGetState(stateName, out result); 90 | Assert.IsNull(state1); 91 | Assert.IsFalse(result); 92 | } 93 | 94 | [TestMethod] 95 | [TestCategory("State")] 96 | public void DeleteStateTest() 97 | { 98 | StateMachine stateMachine = ForTest.stateMachine; 99 | string stateName = "State1"; 100 | State state1; 101 | bool result; 102 | 103 | //delete state by name 104 | state1 = stateMachine.AddState(stateName); 105 | state1 = stateMachine.DeleteState(stateName); 106 | Assert.IsNotNull(state1); 107 | Assert.IsFalse(stateMachine.StateExists(stateName)); 108 | Assert.ThrowsException(() => 109 | { 110 | state1 = stateMachine.DeleteState(stateName); 111 | }); 112 | 113 | //delete state by object 114 | state1 = stateMachine.AddState(stateName); 115 | state1 = stateMachine.DeleteState(state1); 116 | Assert.IsNotNull(state1); 117 | Assert.IsFalse(stateMachine.StateExists(stateName)); 118 | Assert.ThrowsException(() => 119 | { 120 | state1 = stateMachine.DeleteState(state1); 121 | }); 122 | 123 | //try delete state by name 124 | state1 = stateMachine.AddState(stateName); 125 | state1 = stateMachine.TryDeleteState(stateName, out result); 126 | Assert.IsNotNull(state1); 127 | Assert.IsTrue(result); 128 | state1 = stateMachine.TryDeleteState(stateName, out result); 129 | Assert.IsNull(state1); 130 | Assert.IsFalse(result); 131 | 132 | //try delete state by object 133 | state1 = stateMachine.AddState(stateName); 134 | state1 = stateMachine.TryDeleteState(state1, out result); 135 | Assert.IsNotNull(state1); 136 | Assert.IsTrue(result); 137 | state1 = stateMachine.TryDeleteState(state1, out result); 138 | Assert.IsNull(state1); 139 | Assert.IsFalse(result); 140 | 141 | //delete state from object 142 | state1 = stateMachine.AddState(stateName); 143 | state1 = state1.Delete(); 144 | Assert.IsNotNull(state1); 145 | Assert.IsFalse(stateMachine.StateExists(stateName)); 146 | Assert.ThrowsException(() => 147 | { 148 | state1 = state1.Delete(); 149 | }); 150 | 151 | //try delete state from object 152 | state1 = stateMachine.AddState(stateName); 153 | state1 = state1.TryDelete(out result); 154 | Assert.IsNotNull(state1); 155 | Assert.IsTrue(result); 156 | Assert.IsFalse(stateMachine.StateExists(stateName)); 157 | state1 = state1.TryDelete(out result); 158 | Assert.IsNull(state1); 159 | Assert.IsFalse(result); 160 | } 161 | 162 | [TestMethod] 163 | [TestCategory("State")] 164 | public void EntryExitStateTest() 165 | { 166 | StateMachine stateMachine = ForTest.stateMachine; 167 | int eventCont; 168 | string stateName1 = "State1"; 169 | State state1; 170 | 171 | state1 = stateMachine.AddState(stateName1); 172 | eventCont = 0; 173 | state1.SetAsStartState(); 174 | stateMachine.Start(); 175 | Assert.AreEqual(eventCont, 0); 176 | stateMachine.DeleteState(stateName1); 177 | 178 | 179 | state1 = stateMachine.AddState(stateName1); 180 | eventCont = 0; 181 | state1.OnEntry(MethodOnEntry); 182 | state1.OnExit(MethodOnExit); 183 | state1.SetAsStartState(); 184 | stateMachine.Start(); 185 | Assert.AreEqual(eventCont, 2); 186 | stateMachine.DeleteState(stateName1); 187 | 188 | state1 = stateMachine.AddState(stateName1, MethodOnEntry, MethodOnExit); 189 | eventCont = 0; 190 | state1.SetAsStartState(); 191 | stateMachine.Start(); 192 | Assert.AreEqual(eventCont, 2); 193 | stateMachine.DeleteState(stateName1); 194 | 195 | state1 = stateMachine.AddState(stateName1).OnEntry(MethodOnEntry).OnExit(MethodOnExit); 196 | eventCont = 0; 197 | state1.SetAsStartState(); 198 | stateMachine.Start(); 199 | Assert.AreEqual(eventCont, 2); 200 | stateMachine.DeleteState(stateName1); 201 | 202 | state1 = stateMachine.AddState(stateName1, MethodOnEntry, MethodOnExit).OnEntry(MethodOnEntry).OnExit(MethodOnExit).OnEntry(MethodOnEntry).OnExit(MethodOnExit); 203 | eventCont = 0; 204 | state1.OnEntry(MethodOnEntry); 205 | state1.OnEntry(MethodOnEntry); 206 | state1.OnExit(MethodOnExit); 207 | state1.OnExit(MethodOnExit); 208 | state1.SetAsStartState(); 209 | stateMachine.Start(); 210 | Assert.AreEqual(eventCont, 10); 211 | stateMachine.DeleteState(stateName1); 212 | 213 | 214 | void MethodOnEntry(State state, Dictionary parameters) 215 | { 216 | Assert.AreEqual(state.Name, stateName1); 217 | eventCont++; 218 | } 219 | void MethodOnExit(State state, Dictionary parameters) 220 | { 221 | Assert.AreEqual(state.Name, stateName1); 222 | eventCont++; 223 | } 224 | } 225 | 226 | } 227 | } 228 | 229 | -------------------------------------------------------------------------------- /SimpleStateMachineLibrary/Helpers/Check.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace SimpleStateMachineLibrary.Helpers 7 | { 8 | internal class Check 9 | { 10 | public static string Name(string name, ILogger logger) 11 | { 12 | if (String.IsNullOrEmpty(name)) 13 | { 14 | string message = "Name must be not Empty"; 15 | var ex = new ArgumentNullException(message: message, paramName:"Name"); 16 | logger?.LogError(ex, message); 17 | throw ex; 18 | } 19 | 20 | return name; 21 | } 22 | 23 | public static TObject Object(TObject objectRequested, ILogger logger) 24 | { 25 | if (Equals(objectRequested, default(TObject))) 26 | { 27 | object[] args = { typeof(TObject).Name }; 28 | string message = "Object of type \"{0}\" must be not null"; 29 | var ex = new ArgumentNullException(message: String.Format(message, args), paramName: typeof(TObject).Name); 30 | logger?.LogError(ex, message, args); 31 | throw ex; 32 | } 33 | 34 | 35 | return objectRequested; 36 | } 37 | 38 | public static TObject NamedObject(TObject objectRequested, ILogger logger) where TObject : NamedObject 39 | { 40 | Check.Object(objectRequested, logger); 41 | Check.Name(objectRequested.Name, logger); 42 | return objectRequested; 43 | } 44 | 45 | 46 | public static bool Contains(Dictionary dictionary, string nameObject, ILogger logger, bool exception = true) where TObject : NamedObject 47 | { 48 | nameObject = Contains(dictionary, nameObject, logger, out bool result, exception); 49 | return result; 50 | } 51 | public static bool Contains(Dictionary dictionary, TObject objectRequested, ILogger logger, bool exception = true) where TObject : NamedObject 52 | { 53 | objectRequested = Contains(dictionary, objectRequested, logger, out bool result, exception); 54 | return result; 55 | } 56 | public static string Contains(Dictionary dictionary, string nameObject, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject 57 | { 58 | dictionary = Check.Object(dictionary, logger); 59 | nameObject = Check.Name(nameObject, logger); 60 | result = dictionary.ContainsKey(nameObject); 61 | 62 | if ((exception) && (!result)) 63 | { 64 | object[] args = { nameObject }; 65 | string message = "Element with name \"{0}\" is not found"; 66 | var ex = new KeyNotFoundException(message: String.Format(message, args)); 67 | logger?.LogError(ex, message, args); 68 | throw ex; 69 | } 70 | 71 | return nameObject; 72 | } 73 | public static TObject Contains(Dictionary dictionary, TObject objectRequested, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject 74 | { 75 | dictionary = Check.Object(dictionary, logger); 76 | objectRequested = Check.Object(objectRequested, logger); 77 | 78 | result = dictionary.ContainsValue(objectRequested); 79 | 80 | if ((exception) && (!result)) 81 | { 82 | object[] args = { objectRequested.Name }; 83 | string message = "Element with name \"{0}\" is not found"; 84 | var ex = new KeyNotFoundException(message: String.Format(message, args)); 85 | logger?.LogError(ex, message, args); 86 | throw ex; 87 | } 88 | 89 | return objectRequested; 90 | } 91 | 92 | 93 | public static bool NotContains(Dictionary dictionary, string nameObject, ILogger logger, bool exception = true) where TObject : NamedObject 94 | { 95 | nameObject = NotContains(dictionary, nameObject, logger, out bool result, exception); 96 | return result; 97 | } 98 | public static bool NotContains(Dictionary dictionary, TObject objectRequested, ILogger logger, bool exception = true) where TObject : NamedObject 99 | { 100 | objectRequested = NotContains(dictionary, objectRequested, logger, out bool result, exception); 101 | return result; 102 | } 103 | public static string NotContains(Dictionary dictionary, string nameObject, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject 104 | { 105 | dictionary = Check.Object(dictionary, logger); 106 | nameObject = Check.Name(nameObject, logger); 107 | result = !dictionary.ContainsKey(nameObject); 108 | 109 | if ((exception) && (!result)) 110 | { 111 | object[] args = { nameObject }; 112 | string message = "Element with name \"{0}\" already exists"; 113 | var ex = new ArgumentException(message: String.Format(message, args)); 114 | logger?.LogError(ex, message, args); 115 | throw ex; 116 | } 117 | 118 | return nameObject; 119 | } 120 | public static TObject NotContains(Dictionary dictionary, TObject objectRequested, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject 121 | { 122 | dictionary = Check.Object(dictionary, logger); 123 | objectRequested = Check.Object(objectRequested, logger); 124 | result = !dictionary.ContainsValue(objectRequested); 125 | 126 | if ((exception) && (!result)) 127 | { 128 | object[] args = { objectRequested.Name }; 129 | string message = "Element with name \"{0}\" already exists"; 130 | var ex = new ArgumentException(message: String.Format(message, args)); 131 | logger?.LogError(ex, message, args); 132 | throw ex; 133 | } 134 | 135 | return objectRequested; 136 | } 137 | 138 | 139 | public static TObject Remove(Dictionary dictionary, string nameObject, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject 140 | { 141 | result = false; 142 | dictionary = Check.Object(dictionary, logger); 143 | nameObject = Check.Name(nameObject, logger); 144 | 145 | TObject removedObj = default(TObject); 146 | dictionary?.TryGetValue(nameObject, out removedObj); 147 | 148 | if (removedObj == default(TObject)) 149 | { 150 | if (exception) 151 | { 152 | object[] args = { nameObject }; 153 | string message = "Element with name \"{0}\" is not deleted because not found"; 154 | var ex = new KeyNotFoundException(String.Format(message, args)); 155 | logger?.LogError(ex, message, args); 156 | throw ex; 157 | } 158 | 159 | else 160 | return default(TObject); 161 | } 162 | 163 | dictionary.Remove(nameObject); 164 | result = true; 165 | return removedObj; 166 | } 167 | public static TObject Remove(Dictionary dictionary, TObject obj, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject 168 | { 169 | result = false; 170 | dictionary = Check.Object(dictionary, logger); 171 | obj = Check.NamedObject(obj, logger); 172 | 173 | TObject removedObj = default(TObject); 174 | dictionary?.TryGetValue(obj.Name, out removedObj); 175 | 176 | if (removedObj == default(TObject)) 177 | { 178 | if (exception) 179 | { 180 | object[] args = { obj.Name }; 181 | string message = "Element with name \"{0}\" is not deleted because not found"; 182 | var ex = new KeyNotFoundException(String.Format(message, args)); 183 | logger?.LogError(ex, message, args); 184 | throw ex; 185 | } 186 | 187 | else 188 | return default(TObject); 189 | } 190 | 191 | dictionary.Remove(obj.Name); 192 | result = true; 193 | return removedObj; 194 | } 195 | 196 | 197 | public static TObject GetElement(Dictionary dictionary, string nameObject, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject 198 | { 199 | result = Contains(dictionary, nameObject, logger, exception); 200 | return result ? dictionary[nameObject] : default(TObject); 201 | } 202 | public static TObject GetElement(Dictionary dictionary, TObject obj, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject 203 | { 204 | result = Contains(dictionary, obj, logger, exception); 205 | return result ? obj : default(TObject); 206 | } 207 | 208 | 209 | public static Dictionary GetValuesWhere(Dictionary dictionary, Func action, ILogger logger, out bool result, bool exception = true) where TObject : NamedObject 210 | { 211 | dictionary = Check.Object(dictionary, logger); 212 | Dictionary foundElements = dictionary.Values.Where(action).ToDictionary(x => x.Name, x => x); 213 | result = foundElements.Count > 1; 214 | if ((exception) && (!result)) 215 | { 216 | object[] args = { }; 217 | string message = "Elements aren't found"; 218 | var ex = new KeyNotFoundException(message: String.Format(message, args)); 219 | logger?.LogError(ex, message, args); 220 | throw ex; 221 | } 222 | 223 | return foundElements; 224 | } 225 | 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /Tests/TransitionTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using SimpleStateMachineLibrary; 3 | using System; 4 | using System.Collections.Generic; 5 | 6 | namespace Tests 7 | { 8 | [TestClass] 9 | public class TransitionTests 10 | { 11 | [TestMethod] 12 | [TestCategory("Transition")] 13 | public void AllTestsWithLogger() 14 | { 15 | ForTest.stateMachine = new StateMachine(ForTest.GetConsoleLogger()); 16 | AllTests(); 17 | } 18 | [TestMethod] 19 | [TestCategory("Transition")] 20 | public void AllTestsWithoutLogger() 21 | { 22 | AllTests(); 23 | } 24 | public void AllTests() 25 | { 26 | AddTransitionTest(); 27 | GetTransitionTest(); 28 | DeleteTransitionTest(); 29 | InvokeTransitionTest(); 30 | TransitionParametersTest(); 31 | } 32 | [TestMethod] 33 | [TestCategory("Transition")] 34 | public void AddTransitionTest() 35 | { 36 | StateMachine stateMachine = ForTest.stateMachine; 37 | string transitionName = "Transition1"; 38 | string stateName1 = "State1"; 39 | string stateName2 = "State2"; 40 | bool result; 41 | State state1 = stateMachine.AddState(stateName1); 42 | State state2 = stateMachine.AddState(stateName2); 43 | Assert.IsFalse(stateMachine.TransitionExists(transitionName)); 44 | 45 | //add transition from two objects 46 | Transition transition1 = stateMachine.AddTransition(transitionName, state1, state2); 47 | Assert.IsNotNull(transition1); 48 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 49 | Assert.ThrowsException(() => 50 | { 51 | transition1 = stateMachine.AddTransition(transitionName, state1, state2); 52 | }); 53 | stateMachine.DeleteTransition(transitionName); 54 | 55 | //add transition from name and object 56 | transition1 = stateMachine.AddTransition(transitionName, stateName1, state2); 57 | Assert.IsNotNull(transition1); 58 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 59 | Assert.ThrowsException(() => 60 | { 61 | transition1 = stateMachine.AddTransition(transitionName, stateName1, state2); 62 | }); 63 | stateMachine.DeleteTransition(transitionName); 64 | 65 | //add transition from object and name 66 | transition1 = stateMachine.AddTransition(transitionName, state1, stateName2); 67 | Assert.IsNotNull(transition1); 68 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 69 | Assert.ThrowsException(() => 70 | { 71 | transition1 = stateMachine.AddTransition(transitionName, state1, stateName2); 72 | }); 73 | stateMachine.DeleteTransition(transitionName); 74 | 75 | //add transition from two names 76 | transition1 = stateMachine.AddTransition(transitionName, stateName1, stateName2); 77 | Assert.IsNotNull(transition1); 78 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 79 | Assert.ThrowsException(() => 80 | { 81 | transition1 = stateMachine.AddTransition(transitionName, stateName1, stateName2); 82 | }); 83 | stateMachine.DeleteTransition(transitionName); 84 | 85 | //try add transition from two objects 86 | transition1 = stateMachine.TryAddTransition(out result, transitionName, state1, state2); 87 | Assert.IsNotNull(transition1); 88 | Assert.IsTrue(result); 89 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 90 | transition1 = stateMachine.TryAddTransition(out result, transitionName, state1, state2); 91 | Assert.IsNull(transition1); 92 | Assert.IsFalse(result); 93 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 94 | stateMachine.DeleteTransition(transitionName); 95 | 96 | //try add transition from name and object 97 | transition1 = stateMachine.TryAddTransition(out result, transitionName, stateName1, state2); 98 | Assert.IsNotNull(transition1); 99 | Assert.IsTrue(result); 100 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 101 | transition1 = stateMachine.TryAddTransition(out result, transitionName, stateName1, state2); 102 | Assert.IsNull(transition1); 103 | Assert.IsFalse(result); 104 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 105 | stateMachine.DeleteTransition(transitionName); 106 | 107 | //try add transition from object and name 108 | transition1 = stateMachine.TryAddTransition(out result, transitionName, state1, stateName2); 109 | Assert.IsNotNull(transition1); 110 | Assert.IsTrue(result); 111 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 112 | transition1 = stateMachine.TryAddTransition(out result, transitionName, state1, stateName2); 113 | Assert.IsNull(transition1); 114 | Assert.IsFalse(result); 115 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 116 | stateMachine.DeleteTransition(transitionName); 117 | 118 | //try add transition from two names 119 | transition1 = stateMachine.TryAddTransition(out result, transitionName, stateName1, stateName2); 120 | Assert.IsNotNull(transition1); 121 | Assert.IsTrue(result); 122 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 123 | transition1 = stateMachine.TryAddTransition(out result, transitionName, stateName1, stateName2); 124 | Assert.IsNull(transition1); 125 | Assert.IsFalse(result); 126 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 127 | stateMachine.DeleteTransition(transitionName); 128 | 129 | //add transition from this state and object 130 | transition1 = state1.AddTransitionFromThis(transitionName, state2); 131 | Assert.IsNotNull(transition1); 132 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 133 | Assert.ThrowsException(() => 134 | { 135 | transition1 = state1.AddTransitionFromThis(transitionName, state2); 136 | }); 137 | stateMachine.DeleteTransition(transitionName); 138 | 139 | //add transition from this state and name 140 | transition1 = state1.AddTransitionFromThis(transitionName, stateName2); 141 | Assert.IsNotNull(transition1); 142 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 143 | Assert.ThrowsException(() => 144 | { 145 | transition1 = state1.AddTransitionFromThis(transitionName, stateName2); 146 | }); 147 | stateMachine.DeleteTransition(transitionName); 148 | 149 | //try add transition from this state and object 150 | transition1 = state1.TryAddTransitionFromThis(out result, transitionName, state2); 151 | Assert.IsNotNull(transition1); 152 | Assert.IsTrue(result); 153 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 154 | transition1 = state1.TryAddTransitionFromThis(out result, transitionName, state2); 155 | Assert.IsNull(transition1); 156 | Assert.IsFalse(result); 157 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 158 | stateMachine.DeleteTransition(transitionName); 159 | 160 | //try add transition from this state and name 161 | transition1 = state1.TryAddTransitionFromThis(out result, transitionName, stateName2); 162 | Assert.IsNotNull(transition1); 163 | Assert.IsTrue(result); 164 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 165 | transition1 = state1.TryAddTransitionFromThis(out result, transitionName, stateName2); 166 | Assert.IsNull(transition1); 167 | Assert.IsFalse(result); 168 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 169 | stateMachine.DeleteTransition(transitionName); 170 | 171 | //add transition to this state and object 172 | transition1 = state2.AddTransitionToThis(transitionName, state1); 173 | Assert.IsNotNull(transition1); 174 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 175 | Assert.ThrowsException(() => 176 | { 177 | transition1 = state1.AddTransitionFromThis(transitionName, state1); 178 | }); 179 | stateMachine.DeleteTransition(transitionName); 180 | 181 | //add transition to this state and name 182 | transition1 = state2.AddTransitionToThis(transitionName, stateName1); 183 | Assert.IsNotNull(transition1); 184 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 185 | Assert.ThrowsException(() => 186 | { 187 | transition1 = state1.AddTransitionFromThis(transitionName, stateName1); 188 | }); 189 | stateMachine.DeleteTransition(transitionName); 190 | 191 | //try add transition to this state and object 192 | transition1 = state2.TryAddTransitionToThis(out result, transitionName, state1); 193 | Assert.IsNotNull(transition1); 194 | Assert.IsTrue(result); 195 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 196 | transition1 = state2.TryAddTransitionToThis(out result, transitionName, state1); 197 | Assert.IsNull(transition1); 198 | Assert.IsFalse(result); 199 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 200 | stateMachine.DeleteTransition(transitionName); 201 | 202 | //try add transition to this state and name 203 | transition1 = state2.TryAddTransitionToThis(out result, transitionName, stateName1); 204 | Assert.IsNotNull(transition1); 205 | Assert.IsTrue(result); 206 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 207 | transition1 = state2.TryAddTransitionToThis(out result, transitionName, stateName1); 208 | Assert.IsNull(transition1); 209 | Assert.IsFalse(result); 210 | Assert.IsTrue(stateMachine.TransitionExists(transitionName)); 211 | stateMachine.DeleteTransition(transitionName); 212 | 213 | stateMachine.DeleteState(stateName1); 214 | stateMachine.DeleteState(stateName2); 215 | 216 | } 217 | 218 | [TestMethod] 219 | [TestCategory("Transition")] 220 | public void GetTransitionTest() 221 | { 222 | StateMachine stateMachine = ForTest.stateMachine; 223 | string transitionName1 = "Transition1"; 224 | string transitionName2 = "Transition2"; 225 | string stateName1 = "State1"; 226 | string stateName2 = "State2"; 227 | bool result; 228 | Transition transition1; 229 | Transition transition2; 230 | Dictionary transitions; 231 | State state1 = stateMachine.AddState(stateName1); 232 | State state2 = stateMachine.AddState(stateName2); 233 | Assert.IsFalse(stateMachine.TransitionExists(transitionName1)); 234 | 235 | //get transition 236 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 237 | transition1 = stateMachine.GetTransition(transitionName1); 238 | Assert.IsNotNull(transition1); 239 | Assert.IsTrue(stateMachine.TransitionExists(transitionName1)); 240 | stateMachine.DeleteTransition(transitionName1); 241 | Assert.ThrowsException(() => 242 | { 243 | transition1 = stateMachine.GetTransition(transitionName1); 244 | }); 245 | 246 | //try get transition 247 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 248 | transition1 = stateMachine.TryGetTransition(transitionName1, out result); 249 | Assert.IsNotNull(transition1); 250 | Assert.IsTrue(result); 251 | Assert.IsTrue(stateMachine.TransitionExists(transitionName1)); 252 | stateMachine.DeleteTransition(transitionName1); 253 | transition1 = stateMachine.TryGetTransition(transitionName1, out result); 254 | Assert.IsNull(transition1); 255 | Assert.IsFalse(result); 256 | 257 | 258 | //get all transitions from state by object 259 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 260 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 261 | transitions = stateMachine.GetTransitionsFromState(state1); 262 | Assert.IsNotNull(transitions); 263 | Assert.AreEqual(transitions.Count, 2); 264 | stateMachine.DeleteTransition(transitionName1); 265 | stateMachine.DeleteTransition(transitionName2); 266 | Assert.ThrowsException(() => 267 | { 268 | transitions = stateMachine.GetTransitionsFromState(state1); 269 | }); 270 | 271 | //get all transitions from state by name 272 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 273 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 274 | transitions = stateMachine.GetTransitionsFromState(stateName1); 275 | Assert.IsNotNull(transitions); 276 | Assert.AreEqual(transitions.Count, 2); 277 | stateMachine.DeleteTransition(transitionName1); 278 | stateMachine.DeleteTransition(transitionName2); 279 | Assert.ThrowsException(() => 280 | { 281 | transitions = stateMachine.GetTransitionsFromState(stateName1); 282 | }); 283 | 284 | //try get all transitions from state by object 285 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 286 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 287 | transitions = stateMachine.TryGetTransitionsFromState(state1, out result); 288 | Assert.IsNotNull(transitions); 289 | Assert.IsTrue(result); 290 | Assert.AreEqual(transitions.Count, 2); 291 | stateMachine.DeleteTransition(transitionName1); 292 | stateMachine.DeleteTransition(transitionName2); 293 | transitions = stateMachine.TryGetTransitionsFromState(state1, out result); 294 | Assert.IsNotNull(transitions); 295 | Assert.IsFalse(result); 296 | Assert.AreEqual(transitions.Count, 0); 297 | 298 | //try get all transitions from state by name 299 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 300 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 301 | transitions = stateMachine.TryGetTransitionsFromState(stateName1, out result); 302 | Assert.IsNotNull(transitions); 303 | Assert.IsTrue(result); 304 | Assert.AreEqual(transitions.Count, 2); 305 | stateMachine.DeleteTransition(transitionName1); 306 | stateMachine.DeleteTransition(transitionName2); 307 | transitions = stateMachine.TryGetTransitionsFromState(stateName1, out result); 308 | Assert.IsNotNull(transitions); 309 | Assert.IsFalse(result); 310 | Assert.AreEqual(transitions.Count, 0); 311 | 312 | //get all transitions from state from object 313 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 314 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 315 | transitions = state1.GetTransitionsFromThis(); 316 | Assert.IsNotNull(transitions); 317 | Assert.AreEqual(transitions.Count, 2); 318 | stateMachine.DeleteTransition(transitionName1); 319 | stateMachine.DeleteTransition(transitionName2); 320 | Assert.ThrowsException(() => 321 | { 322 | transitions = state1.GetTransitionsFromThis(); 323 | }); 324 | 325 | //try get all transitions from state from object 326 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 327 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 328 | transitions = state1.TryGetTransitionsFromThis(out result); 329 | Assert.IsNotNull(transitions); 330 | Assert.IsTrue(result); 331 | Assert.AreEqual(transitions.Count, 2); 332 | stateMachine.DeleteTransition(transitionName1); 333 | stateMachine.DeleteTransition(transitionName2); 334 | transitions = state1.TryGetTransitionsFromThis(out result); 335 | Assert.IsNotNull(transitions); 336 | Assert.IsFalse(result); 337 | Assert.AreEqual(transitions.Count, 0); 338 | 339 | //get all transitions to state by object 340 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 341 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 342 | transitions = stateMachine.GetTransitionsToState(state2); 343 | Assert.IsNotNull(transitions); 344 | Assert.AreEqual(transitions.Count, 2); 345 | stateMachine.DeleteTransition(transitionName1); 346 | stateMachine.DeleteTransition(transitionName2); 347 | Assert.ThrowsException(() => 348 | { 349 | transitions = stateMachine.GetTransitionsToState(state2); 350 | }); 351 | 352 | //get all transitions to state by name 353 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 354 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 355 | transitions = stateMachine.GetTransitionsToState(stateName2); 356 | Assert.IsNotNull(transitions); 357 | Assert.AreEqual(transitions.Count, 2); 358 | stateMachine.DeleteTransition(transitionName1); 359 | stateMachine.DeleteTransition(transitionName2); 360 | Assert.ThrowsException(() => 361 | { 362 | transitions = stateMachine.GetTransitionsToState(stateName2); 363 | }); 364 | 365 | //try get all transitions to state by object 366 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 367 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 368 | transitions = stateMachine.TryGetTransitionsToState(state2, out result); 369 | Assert.IsNotNull(transitions); 370 | Assert.IsTrue(result); 371 | Assert.AreEqual(transitions.Count, 2); 372 | stateMachine.DeleteTransition(transitionName1); 373 | stateMachine.DeleteTransition(transitionName2); 374 | transitions = stateMachine.TryGetTransitionsToState(state2, out result); 375 | Assert.IsNotNull(transitions); 376 | Assert.IsFalse(result); 377 | Assert.AreEqual(transitions.Count, 0); 378 | 379 | //try get all transitions to state by name 380 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 381 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 382 | transitions = stateMachine.TryGetTransitionsToState(stateName2, out result); 383 | Assert.IsNotNull(transitions); 384 | Assert.IsTrue(result); 385 | Assert.AreEqual(transitions.Count, 2); 386 | stateMachine.DeleteTransition(transitionName1); 387 | stateMachine.DeleteTransition(transitionName2); 388 | transitions = stateMachine.TryGetTransitionsToState(stateName2, out result); 389 | Assert.IsNotNull(transitions); 390 | Assert.IsFalse(result); 391 | Assert.AreEqual(transitions.Count, 0); 392 | 393 | //get all transitions to state from object 394 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 395 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 396 | transitions = state2.GetTransitionsToThis(); 397 | Assert.IsNotNull(transitions); 398 | Assert.AreEqual(transitions.Count, 2); 399 | stateMachine.DeleteTransition(transitionName1); 400 | stateMachine.DeleteTransition(transitionName2); 401 | Assert.ThrowsException(() => 402 | { 403 | transitions = state2.GetTransitionsToThis(); 404 | }); 405 | 406 | //try get all transitions to state from object 407 | transition1 = stateMachine.AddTransition(transitionName1, state1, state2); 408 | transition2 = stateMachine.AddTransition(transitionName2, state1, state2); 409 | transitions = state2.TryGetTransitionsToThis(out result); 410 | Assert.IsNotNull(transitions); 411 | Assert.IsTrue(result); 412 | Assert.AreEqual(transitions.Count, 2); 413 | stateMachine.DeleteTransition(transitionName1); 414 | stateMachine.DeleteTransition(transitionName2); 415 | transitions = state2.TryGetTransitionsToThis(out result); 416 | Assert.IsNotNull(transitions); 417 | Assert.IsFalse(result); 418 | Assert.AreEqual(transitions.Count, 0); 419 | 420 | stateMachine.DeleteState(stateName1); 421 | stateMachine.DeleteState(stateName2); 422 | 423 | } 424 | 425 | [TestMethod] 426 | [TestCategory("Transition")] 427 | public void DeleteTransitionTest() 428 | { 429 | StateMachine stateMachine = ForTest.stateMachine; 430 | string transitionName = "Transition1"; 431 | string stateName1 = "State1"; 432 | string stateName2 = "State2"; 433 | bool result; 434 | Transition transition1; 435 | State state1 = stateMachine.AddState(stateName1); 436 | State state2 = stateMachine.AddState(stateName2); 437 | 438 | //delete transition by name 439 | transition1 = stateMachine.AddTransition(transitionName, state1, state2); 440 | transition1 = stateMachine.DeleteTransition(transitionName); 441 | Assert.IsNotNull(transition1); 442 | Assert.IsFalse(stateMachine.TransitionExists(transitionName)); 443 | Assert.ThrowsException(() => 444 | { 445 | transition1 = stateMachine.DeleteTransition(transitionName); 446 | }); 447 | 448 | //delete transition by object 449 | transition1 = stateMachine.AddTransition(transitionName, state1, state2); 450 | transition1 = stateMachine.DeleteTransition(transition1); 451 | Assert.IsNotNull(transition1); 452 | Assert.IsFalse(stateMachine.TransitionExists(transitionName)); 453 | Assert.ThrowsException(() => 454 | { 455 | transition1 = stateMachine.DeleteTransition(transition1); 456 | }); 457 | 458 | //try delete transition by name 459 | transition1 = stateMachine.AddTransition(transitionName, state1, state2); 460 | transition1 = stateMachine.TryDeleteTransition(transitionName, out result); 461 | Assert.IsNotNull(transition1); 462 | Assert.IsTrue(result); 463 | transition1 = stateMachine.TryDeleteTransition(transitionName, out result); 464 | Assert.IsNull(transition1); 465 | Assert.IsFalse(result); 466 | 467 | //try delete transition by object 468 | transition1 = stateMachine.AddTransition(transitionName, state1, state2); 469 | transition1 = stateMachine.TryDeleteTransition(transition1, out result); 470 | Assert.IsNotNull(transition1); 471 | Assert.IsTrue(result); 472 | transition1 = stateMachine.TryDeleteTransition(transition1, out result); 473 | Assert.IsNull(transition1); 474 | Assert.IsFalse(result); 475 | 476 | //delete transition from object 477 | transition1 = stateMachine.AddTransition(transitionName, state1, state2); 478 | transition1 = transition1.Delete(); 479 | Assert.IsNotNull(transition1); 480 | Assert.IsFalse(stateMachine.TransitionExists(transitionName)); 481 | Assert.ThrowsException(() => 482 | { 483 | transition1 = transition1.Delete(); 484 | }); 485 | 486 | //try delete transition from object 487 | transition1 = stateMachine.AddTransition(transitionName, state1, state2); 488 | transition1 = transition1.TryDelete(out result); 489 | Assert.IsNotNull(transition1); 490 | Assert.IsTrue(result); 491 | Assert.IsFalse(stateMachine.TransitionExists(transitionName)); 492 | transition1 = transition1.TryDelete(out result); 493 | Assert.IsNull(transition1); 494 | Assert.IsFalse(result); 495 | 496 | stateMachine.DeleteState(stateName1); 497 | stateMachine.DeleteState(stateName2); 498 | 499 | } 500 | 501 | [TestMethod] 502 | [TestCategory("Transition")] 503 | public void InvokeTransitionTest() 504 | { 505 | StateMachine stateMachine = ForTest.stateMachine; 506 | int eventCount = 0; 507 | 508 | string transitionName = "Transition1"; 509 | string stateName1 = "State1"; 510 | string stateName2 = "State2"; 511 | Transition transition1; 512 | State state1 = stateMachine.AddState(stateName1, MethodOnEntry); 513 | State state2 = stateMachine.AddState(stateName2); 514 | 515 | 516 | eventCount = 0; 517 | transition1 = stateMachine.AddTransition(transitionName, state1, state2); 518 | state1.SetAsStartState(); 519 | stateMachine.Start(); 520 | Assert.AreEqual(eventCount, 0); 521 | stateMachine.DeleteTransition(transitionName); 522 | 523 | 524 | eventCount = 0; 525 | transition1 = stateMachine.AddTransition(transitionName, state1, state2, MethodOnInvoke); 526 | state1.SetAsStartState(); 527 | stateMachine.Start(); 528 | Assert.AreEqual(eventCount, 1); 529 | stateMachine.DeleteTransition(transitionName); 530 | 531 | eventCount = 0; 532 | transition1 = stateMachine.AddTransition(transitionName, state1, state2).OnInvoke(MethodOnInvoke); 533 | state1.SetAsStartState(); 534 | stateMachine.Start(); 535 | Assert.AreEqual(eventCount, 1); 536 | stateMachine.DeleteTransition(transitionName); 537 | 538 | eventCount = 0; 539 | transition1 = stateMachine.AddTransition(transitionName, state1, state2); 540 | transition1.OnInvoke(MethodOnInvoke); 541 | state1.SetAsStartState(); 542 | stateMachine.Start(); 543 | Assert.AreEqual(eventCount, 1); 544 | stateMachine.DeleteTransition(transitionName); 545 | 546 | 547 | eventCount = 0; 548 | transition1 = stateMachine.AddTransition(transitionName, state1, state2, MethodOnInvoke).OnInvoke(MethodOnInvoke).OnInvoke(MethodOnInvoke); 549 | transition1.OnInvoke(MethodOnInvoke); 550 | transition1.OnInvoke(MethodOnInvoke); 551 | state1.SetAsStartState(); 552 | stateMachine.Start(); 553 | Assert.AreEqual(eventCount, 5); 554 | stateMachine.DeleteTransition(transitionName); 555 | 556 | stateMachine.DeleteState(stateName1); 557 | stateMachine.DeleteState(stateName2); 558 | 559 | void MethodOnInvoke(Transition transition, Dictionary parameters) 560 | { 561 | Assert.AreEqual(transition.Name, transitionName); 562 | eventCount++; 563 | } 564 | void MethodOnEntry(State state, Dictionary parameters) 565 | { 566 | state.StateMachine.InvokeTransition(transitionName); 567 | } 568 | } 569 | 570 | [TestMethod] 571 | [TestCategory("Transition")] 572 | public void TransitionParametersTest() 573 | { 574 | StateMachine stateMachine = ForTest.stateMachine; 575 | int eventCount = 0; 576 | string transitionName = "Transition1"; 577 | string stateName1 = "State1"; 578 | string stateName2 = "State2"; 579 | string intName = "Int"; 580 | string doubleName = "Double"; 581 | string stringName = "String"; 582 | string boolName = "Bool"; 583 | Dictionary parameters1 = new Dictionary() { { intName, 15 }}; 584 | Dictionary parameters2 = new Dictionary() { { doubleName, 15.5 } }; 585 | Dictionary parameters3 = new Dictionary() { { stringName, "string" } }; 586 | Transition transition1; 587 | State state1 = stateMachine.AddState(stateName1, MethodOnEntry1); 588 | State state2 = stateMachine.AddState(stateName2, MethodOnEntry2); 589 | 590 | eventCount = 0; 591 | transition1 = stateMachine.AddTransition(transitionName, state1, state2, MethodOnInvoke); 592 | state1.SetAsStartState(); 593 | stateMachine.Start(parameters1); 594 | Assert.AreEqual(eventCount, 1); 595 | stateMachine.DeleteTransition(transitionName); 596 | 597 | stateMachine.DeleteState(stateName1); 598 | stateMachine.DeleteState(stateName2); 599 | 600 | void MethodOnInvoke(Transition transition, Dictionary parameters) 601 | { 602 | Assert.AreEqual(transition.Name, transitionName); 603 | eventCount++; 604 | } 605 | void MethodOnEntry1(State state, Dictionary parameters) 606 | { 607 | Assert.AreEqual(state.Name, stateName1); 608 | Assert.IsTrue(parameters.ContainsKey(intName)); 609 | Assert.AreEqual(parameters.Count, 1); 610 | state.StateMachine.InvokeTransition(transitionName, parameters2).AddParameter(boolName, true).AddParameters(parameters3); 611 | } 612 | void MethodOnEntry2(State state, Dictionary parameters) 613 | { 614 | Assert.IsFalse(parameters.ContainsKey(intName)); 615 | Assert.IsTrue(parameters.ContainsKey(doubleName)); 616 | Assert.IsTrue(parameters.ContainsKey(stringName)); 617 | Assert.IsTrue(parameters.ContainsKey(boolName)); 618 | Assert.AreEqual(parameters.Count, 3); 619 | Assert.AreEqual(state.Name, stateName2); 620 | } 621 | 622 | 623 | } 624 | 625 | } 626 | } 627 | --------------------------------------------------------------------------------