Skip to content

Instantly share code, notes, and snippets.

@aidapsibr
Created January 5, 2016 20:53
Show Gist options
  • Save aidapsibr/015623201dfd4abd86e1 to your computer and use it in GitHub Desktop.
Save aidapsibr/015623201dfd4abd86e1 to your computer and use it in GitHub Desktop.
Example of building a statemachine from configuration
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using Persistate.Repositories;
using Stateless;
using Susanoo;
namespace Persistate.Susanoo
{
public class PersistateRepository
: IPersistateRepository
{
public PersistateRepository(IDatabaseManagerPool databaseManagerPool, string apiKey)
{
DatabaseManagerPool = databaseManagerPool;
ApiKey = apiKey;
}
public string ApiKey { get; }
/// <summary>
/// Gets the database manager.
/// </summary>
/// <value>The database manager.</value>
protected IDatabaseManagerPool DatabaseManagerPool { get; }
public void Dispose()
{
DatabaseManagerPool.Dispose();
}
public IConfigurationRepository Configuration { get; }
public StateMachine<int, int> BuildMachine()
{
var machine = new StateMachine<int, int>(1);
var results = CommandManager.Instance
.DefineCommand(
"SELECT * FROM States WHERE MachineId = @machineId " +
"\r\n" +
"SELECT * FROM Triggers WHERE MachineId = @machineId " +
"\r\n" +
"SELECT Transitions.* FROM Transitions INNER JOIN States ON States.StateId = Transitions.StateId WHERE States.MachineId= @machineId " +
"\r\n" +
"SELECT IgnoreRules.* FROM IgnoreRules INNER JOIN States ON States.StateId = IgnoreRules.StateId WHERE States.MachineId= @machineId " +
"\r\n" +
"SELECT * FROM Machines WHERE MachineDefinitionId = @machineId"
, CommandType.Text)
.DefineResults(typeof(object), typeof(object), typeof(object), typeof(object), typeof(object))
.Realize()
.Execute(DatabaseManagerPool.DatabaseManager, new { machineId = 1 })
.ToArray();
var states = results[0];
var triggers = results[1];
var transitionResults = results[2];
var ignoreRuleResults = results[3];
var machineDefinition = results[4].Cast<dynamic>().Single();
var configurations = states
.Cast<dynamic>()
.GroupJoin(transitionResults.Cast<dynamic>(),
s => s.StateId, t => t.StateId,
(state, transitions) => new {State = state, Transitions = transitions})
.GroupJoin(ignoreRuleResults.Cast<dynamic>(),
o => o.State.StateId, i => i.StateId,
(o, ignoreRules) => new {o.State, o.Transitions, IgnoreRules = ignoreRules});
if(machineDefinition.AutoIgnoreNotConfiguredTriggers)
machine.OnUnhandledTrigger((i, i1) => {});
foreach (var configuration in configurations)
{
var stateConfiguration = machine.Configure((int)configuration.State.StateId);
foreach (var transition in configuration.Transitions)
{
stateConfiguration.Permit(transition.TriggerId, transition.ResultantStateId);
}
foreach (var ignoreRule in configuration.IgnoreRules)
{
stateConfiguration.Ignore(ignoreRule.TriggerId);
}
}
return machine;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment