From 6d171adc70e31384317ad1e5f1dda2313031ada4 Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sat, 14 Nov 2026 20:32:12 -0500 Subject: [PATCH 1/3] support .net 11 --- Directory.Build.props | 4 ++-- source/Lite.StateMachine/Lite.StateMachine.csproj | 5 ----- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 3a3a01b..3707c69 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,10 +1,10 @@ - net10.0 + net10.0;net11.0 latest True - 2.4.1 + 2.4.2 ../../output/$(MSBuildProjectName) true diff --git a/source/Lite.StateMachine/Lite.StateMachine.csproj b/source/Lite.StateMachine/Lite.StateMachine.csproj index c02812e..902e73b 100644 --- a/source/Lite.StateMachine/Lite.StateMachine.csproj +++ b/source/Lite.StateMachine/Lite.StateMachine.csproj @@ -1,9 +1,4 @@  - - - net10.0 - - Lite State Machine Flexible lightweight finite state machine (FSM) for .NET supporting shared context for passing parameters, composite (sub) states, command states, lazy-loading and thread safe. Cross-platform and optimized for speed for use in enterprise, robotic and even tiny applications. From f439661da81cb0b7f895fa36d7a3bb292efd03eb Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sat, 14 Nov 2026 20:42:41 -0500 Subject: [PATCH 2/3] Added Command State and PassingEvents samples --- samples/Sample05.CommandStates/Program.cs | 145 ++++++++++++++++- .../Sample05.CommandStates.csproj | 6 +- samples/Sample05.CommandStates/readme.md | 30 +++- samples/Sample06.PassingEvents/Program.cs | 148 +++++++++++++++++- .../Sample06.PassingEvents.csproj | 6 +- samples/Sample06.PassingEvents/readme.md | 33 +++- 6 files changed, 358 insertions(+), 10 deletions(-) diff --git a/samples/Sample05.CommandStates/Program.cs b/samples/Sample05.CommandStates/Program.cs index fd3bfc6..0ab3b80 100644 --- a/samples/Sample05.CommandStates/Program.cs +++ b/samples/Sample05.CommandStates/Program.cs @@ -1,12 +1,153 @@ // Copyright Xeno Innovations, Inc. 2026 // See the LICENSE file in the project root for more information. +using Lite.StateMachine; + namespace Sample05.CommandStates; +/// +/// Demonstrates command states that request simulated device actions and wait +/// for their results in OnMessage before choosing the next state. +/// +/// +/// State1 connects successfully; +/// State2 deliberately fails to start the device; +/// State3 recovers by closing its safety door; +/// State4 simulates a sensor error; +/// and State5 cleans up and disconnects. +/// +/// Console output explains each action, result, and transition +/// through the success, failure, and error paths. +/// +/// All states and the simulated worker are defined in this file; no hardware is required. +/// internal class Program { - private static void Main(string[] args) + private enum StateId + { + State1, + State2, + State3, + State4, + State5, + } + + private static async Task Main() + { + Console.WriteLine("Command states: perform actions and follow their results."); + Console.WriteLine("Expected: State1 --Success--> State2 --Failure--> State3 --Success--> State4 --Error--> State5."); + var events = new EventAggregator(); + + // A stand-in for a device or application service. Failures are deliberate + // so every run demonstrates success, expected failure, and error handling. + using var worker = events.Subscribe(message => + { + if (message is not ActionCommand command) + return; + + var result = command.State switch + { + StateId.State2 => Result.Failure, + StateId.State4 => Result.Error, + _ => Result.Success, + }; + Console.WriteLine($" Worker: {command.Action} => {result}"); + events.Publish(new ActionCompleted(command.State, result)); + }, + typeof(ActionCommand)); + + var machine = new StateMachine(eventAggregator: events) + .RegisterState(StateId.State1, onSuccess: StateId.State2) + .RegisterState(StateId.State2, onFailure: StateId.State3) + .RegisterState(StateId.State3, onSuccess: StateId.State4) + .RegisterState(StateId.State4, onError: StateId.State5) + .RegisterState(StateId.State5); + + using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await machine.RunAsync(StateId.State1, cancellation.Token); + + if (machine.Context.CurrentStateId != StateId.State5 || + !machine.Context.ParameterAsBool("Completed")) + { + throw new InvalidOperationException("The sample did not complete its expected actions."); + } + + Console.WriteLine("Done: success, failure recovery, and error cleanup were demonstrated."); + } + + private sealed record ActionCommand(StateId State, string Action); + + private sealed record ActionCompleted(StateId State, Result Result); + + // Shared command plumbing; each numbered state below defines its action. + private abstract class CommandState : ICommandState + { + public IReadOnlyCollection SubscribedMessageTypes => [typeof(ActionCompleted)]; + + protected abstract string Action { get; } + + public Task OnEnter(Context context) + { + Console.WriteLine($"{context.CurrentStateId}: requesting '{Action}'. Waiting for ActionCompleted in OnMessage."); + context.EventAggregator!.Publish(new ActionCommand(context.CurrentStateId, Action)); + + // Returning from OnEnter does not advance a command state. + // OnMessage must call NextState after receiving the action's result. + return Task.CompletedTask; + } + + public Task OnEntering(Context context) => Task.CompletedTask; + + public Task OnExit(Context context) + { + Console.WriteLine($"{context.CurrentStateId}: exiting."); + return Task.CompletedTask; + } + + public Task OnMessage(Context context, object message) + { + if (message is ActionCompleted completed && completed.State == context.CurrentStateId) + { + Console.WriteLine($"{context.CurrentStateId}.OnMessage: action returned {completed.Result}."); + if (context.CurrentStateId == StateId.State5 && completed.Result == Result.Success) + context.Parameters["Completed"] = true; + + context.NextState(completed.Result); + } + + return Task.CompletedTask; + } + + public Task OnTimeout(Context context) + { + Console.WriteLine($"{context.CurrentStateId}: no action result arrived; ending with Error."); + context.NextState(Result.Error); + return Task.CompletedTask; + } + } + + private sealed class State1 : CommandState + { + protected override string Action => "Connect to the device (success expected)"; + } + + private sealed class State2 : CommandState + { + protected override string Action => "Start the device while its safety door is open (failure expected)"; + } + + private sealed class State3 : CommandState + { + protected override string Action => "Recover from State2's failure by closing the safety door (success expected)"; + } + + private sealed class State4 : CommandState + { + protected override string Action => "Read a sensor with a simulated communication fault (error expected)"; + } + + private sealed class State5 : CommandState { - Console.WriteLine("Coming Soon!"); + protected override string Action => "Clean up after State4's error and disconnect (success expected)"; } } diff --git a/samples/Sample05.CommandStates/Sample05.CommandStates.csproj b/samples/Sample05.CommandStates/Sample05.CommandStates.csproj index ed9781c..4e9e710 100644 --- a/samples/Sample05.CommandStates/Sample05.CommandStates.csproj +++ b/samples/Sample05.CommandStates/Sample05.CommandStates.csproj @@ -1,4 +1,4 @@ - + Exe @@ -7,4 +7,8 @@ enable + + + + diff --git a/samples/Sample05.CommandStates/readme.md b/samples/Sample05.CommandStates/readme.md index 936c98f..a51822c 100644 --- a/samples/Sample05.CommandStates/readme.md +++ b/samples/Sample05.CommandStates/readme.md @@ -1,5 +1,31 @@ # Sample 05 - Command States -_Coming Soon_ +All states (`State1` through `State5`), messages, and the simulated worker are in +`Program.cs`. Each state implements `ICommandState` through a small shared +`CommandState` base class that handles subscriptions, results, and timeouts. -See, Unit Tests, for an example of how to use Command States for now. +Run from the repository root: + +```powershell +dotnet run --project samples/Sample05.CommandStates --framework net10.0 +``` + +| State | Intended action | Result | Next state | +| --- | --- | --- | --- | +| State1 | Connect to a device | Success | State2 | +| State2 | Try starting with the safety door open | Failure | State3 | +| State3 | Recover by closing the door | Success | State4 | +| State4 | Read a sensor with a simulated communication fault | Error | State5 | +| State5 | Clean up and disconnect | Success | End | + +`OnEnter` publishes an `ActionCommand` to a simulated device service using the +built-in event aggregator. The service prints its action and publishes an +`ActionCompleted` result. The active state's `OnMessage` checks the state ID and +calls `context.NextState(result)` to select `onSuccess`, `onFailure`, or `onError`. +Returning from `OnEnter` alone does not advance a command state. + +The worker deliberately returns `Failure` for State2 and `Error` for State4 so +every run demonstrates all three outcomes. No hardware or external service is +required. Each state logs its request, received result, and exit. Missing results +use the machine's default command timeout; the executable also has a ten-second +cancellation guard and verifies that cleanup completed. diff --git a/samples/Sample06.PassingEvents/Program.cs b/samples/Sample06.PassingEvents/Program.cs index 78417fe..47c06f9 100644 --- a/samples/Sample06.PassingEvents/Program.cs +++ b/samples/Sample06.PassingEvents/Program.cs @@ -2,13 +2,157 @@ // See the LICENSE file in the project root for more information. using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Lite.StateMachine; namespace Sample06.PassingEvents; +/// +/// Demonstrates passing typed order data through command states using the +/// built-in event aggregator and each state's OnMessage handler. +/// +/// +/// State1 creates an order for three notebooks; +/// State2 awaits a simulated price lookup and calculates the total; +/// State3 prints the receipt. +/// +/// The shared context holds each outgoing payload until the next state subscribes and publishes it, +/// because the aggregator does not queue events for future states. +/// +/// Console output traces the messages and their data. +/// All states and message types are defined in this file. +/// internal class Program { - private static void Main(string[] args) + private enum StateId { - Console.WriteLine("Coming Soon!"); + State1, + State2, + State3, + } + + private static async Task Main() + { + Console.WriteLine("Passing events: State1 creates an order, State2 prices it, State3 prints the receipt."); + var events = new EventAggregator(); + var machine = new StateMachine(eventAggregator: events) + .RegisterState(StateId.State1, onSuccess: StateId.State2) + .RegisterState(StateId.State2, onSuccess: StateId.State3) + .RegisterState(StateId.State3); + + using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await machine.RunAsync(StateId.State1, cancellation.Token); + + if (!machine.Context.ParameterAsBool("Completed")) + throw new InvalidOperationException("The sample did not produce its receipt."); + + Console.WriteLine("Done: each state received its typed payload through OnMessage."); + } + + private sealed record OrderCreated(string Product, int Quantity); + + private sealed record PriceRequested(string Product, int Quantity); + + private sealed record OrderPriced(string Product, int Quantity, decimal Total); + + // The aggregator only delivers to the current command state; it does not + // queue events for future states. Context carries each outgoing payload until + // the next state's OnEnter publishes it after that state's subscription exists. + private abstract class EventState : ICommandState + { + public abstract IReadOnlyCollection SubscribedMessageTypes { get; } + + public abstract Task OnEnter(Context context); + + public Task OnEntering(Context context) => Task.CompletedTask; + + public Task OnExit(Context context) => Task.CompletedTask; + + public abstract Task OnMessage(Context context, object message); + + public Task OnTimeout(Context context) + { + Console.WriteLine($"{context.CurrentStateId}: timed out waiting for its event."); + context.NextState(Result.Error); + return Task.CompletedTask; + } + } + + private sealed class State1 : EventState + { + public override IReadOnlyCollection SubscribedMessageTypes => [typeof(OrderCreated)]; + + public override Task OnEnter(Context context) + { + Console.WriteLine("State1: publishing OrderCreated for 3 notebooks."); + context.EventAggregator!.Publish(new OrderCreated("Notebook", 3)); + return Task.CompletedTask; + } + + public override Task OnMessage(Context context, object message) + { + if (message is OrderCreated order) + { + Console.WriteLine($"State1.OnMessage: received {order.Product}, quantity {order.Quantity}; passing data to State2."); + context.Parameters["NextMessage"] = new PriceRequested(order.Product, order.Quantity); + context.NextState(Result.Success); + } + + return Task.CompletedTask; + } + } + + private sealed class State2 : EventState + { + public override IReadOnlyCollection SubscribedMessageTypes => [typeof(PriceRequested)]; + + public override Task OnEnter(Context context) + { + Console.WriteLine("State2: publishing the PriceRequested payload passed from State1."); + context.EventAggregator!.Publish((PriceRequested)context.Parameters["NextMessage"]!); + return Task.CompletedTask; + } + + public override async Task OnMessage(Context context, object message) + { + if (message is not PriceRequested order) + return; + + Console.WriteLine($"State2.OnMessage: looking up the price for {order.Product}..."); + + await Task.Delay(100); // Simulate an asynchronous price lookup. + + var total = order.Quantity * 4.50m; + Console.WriteLine($"State2.OnMessage: {order.Quantity} x 4.50 = {total:F2}; passing data to State3."); + context.Parameters["NextMessage"] = new OrderPriced(order.Product, order.Quantity, total); + context.NextState(Result.Success); + } + } + + private sealed class State3 : EventState + { + public override IReadOnlyCollection SubscribedMessageTypes => [typeof(OrderPriced)]; + + public override Task OnEnter(Context context) + { + Console.WriteLine("State3: publishing the OrderPriced payload passed from State2."); + context.EventAggregator!.Publish((OrderPriced)context.Parameters["NextMessage"]!); + return Task.CompletedTask; + } + + public override Task OnMessage(Context context, object message) + { + if (message is OrderPriced order) + { + Console.WriteLine($"State3.OnMessage: receipt - {order.Quantity} x {order.Product}, total {order.Total:F2}."); + context.Parameters.Remove("NextMessage"); + context.Parameters["Completed"] = true; + context.NextState(Result.Success); + } + + return Task.CompletedTask; + } } } diff --git a/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj b/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj index 2f6f13c..50d9689 100644 --- a/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj +++ b/samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj @@ -1,4 +1,4 @@ - + Exe @@ -7,4 +7,8 @@ enable + + + + diff --git a/samples/Sample06.PassingEvents/readme.md b/samples/Sample06.PassingEvents/readme.md index 2e2811c..9e450ec 100644 --- a/samples/Sample06.PassingEvents/readme.md +++ b/samples/Sample06.PassingEvents/readme.md @@ -1,5 +1,34 @@ # Sample 06 - Event Aggregator for Passing Events -_Coming Soon_ +All states (`State1`, `State2`, and `State3`) and message records are in `Program.cs`. +This sample uses the built-in `Lite.StateMachine.EventAggregator` with typed +subscriptions on command states. -See, Unit Tests, for an example of how to use Event Aggregator for Passing Events for now. +Run from the repository root: + +```powershell +dotnet run --project samples/Sample06.PassingEvents --framework net10.0 +``` + +1. State1 publishes `OrderCreated` for three notebooks. Its `OnMessage` receives + the product and quantity and prepares a `PriceRequested` payload for State2. +2. State2 publishes that payload after entering. Its `OnMessage` awaits a + simulated price lookup, calculates `3 x 4.50 = 13.50`, and prepares an + `OrderPriced` payload for State3. +3. State3 publishes the priced payload after entering. Its `OnMessage` prints + the receipt and completes the flow. + +Each state's `SubscribedMessageTypes` declares the exact message type it accepts. +The shared `EventState` base class provides the empty lifecycle hooks and timeout +handling so the numbered states focus on sending and receiving data. + +The aggregator delivers immediately to current subscribers and does not buffer +messages for future states. To pass data safely between states, each `OnMessage` +stores the next payload in `context.Parameters["NextMessage"]` before advancing. +The next state's `OnEnter` republishes it after the machine has subscribed that +state. This keeps the handoff explicit and avoids losing events during transitions. + +`Publish` returns without awaiting asynchronous `OnMessage` work. State2 calls +`NextState(Result.Success)` only after its awaited work and payload preparation +finish. The program awaits `RunAsync`, uses a ten-second cancellation guard, and +verifies that State3 produced its receipt. From 2980da7a3cec65588c6291e453f6e1e879eb83e4 Mon Sep 17 00:00:00 2001 From: Damian Suess Date: Sat, 14 Nov 2026 20:51:13 -0500 Subject: [PATCH 3/3] Build script support for .NET 11 --- .github/workflows/build-github.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-github.yml b/.github/workflows/build-github.yml index a5d01eb..ed26324 100644 --- a/.github/workflows/build-github.yml +++ b/.github/workflows/build-github.yml @@ -32,7 +32,10 @@ jobs: - name: 2) Setup .NET SDK uses: actions/setup-dotnet@v4 with: - dotnet-version: '10.0.x' # Change to your target version + # Match the target frameworks in Directory.Build.props. + dotnet-version: | + 10.0.x + 11.0.x # 3. Restore dependencies - name: 3) Restore dependencies