Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/build-github.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<Project>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<TargetFrameworks>net10.0;net11.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>

<AssemblyVersion>2.4.1</AssemblyVersion>
<AssemblyVersion>2.4.2</AssemblyVersion>

<BaseOutputPath>../../output/$(MSBuildProjectName)</BaseOutputPath>
<Deterministic>true</Deterministic>
Expand Down
145 changes: 143 additions & 2 deletions samples/Sample05.CommandStates/Program.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Demonstrates command states that request simulated device actions and wait
/// for their results in OnMessage before choosing the next state.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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<StateId>(eventAggregator: events)
.RegisterState<State1>(StateId.State1, onSuccess: StateId.State2)
.RegisterState<State2>(StateId.State2, onFailure: StateId.State3)
.RegisterState<State3>(StateId.State3, onSuccess: StateId.State4)
.RegisterState<State4>(StateId.State4, onError: StateId.State5)
.RegisterState<State5>(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<StateId>
{
public IReadOnlyCollection<Type> SubscribedMessageTypes => [typeof(ActionCompleted)];

protected abstract string Action { get; }

public Task OnEnter(Context<StateId> 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<StateId> context) => Task.CompletedTask;

public Task OnExit(Context<StateId> context)
{
Console.WriteLine($"{context.CurrentStateId}: exiting.");
return Task.CompletedTask;
}

public Task OnMessage(Context<StateId> 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<StateId> 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)";
}
}
6 changes: 5 additions & 1 deletion samples/Sample05.CommandStates/Sample05.CommandStates.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
Expand All @@ -7,4 +7,8 @@
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="../../source/Lite.StateMachine/Lite.StateMachine.csproj" />
</ItemGroup>

</Project>
30 changes: 28 additions & 2 deletions samples/Sample05.CommandStates/readme.md
Original file line number Diff line number Diff line change
@@ -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<StateId>` 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.
148 changes: 146 additions & 2 deletions samples/Sample06.PassingEvents/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>
/// Demonstrates passing typed order data through command states using the
/// built-in event aggregator and each state's OnMessage handler.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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<StateId>(eventAggregator: events)
.RegisterState<State1>(StateId.State1, onSuccess: StateId.State2)
.RegisterState<State2>(StateId.State2, onSuccess: StateId.State3)
.RegisterState<State3>(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<StateId>
{
public abstract IReadOnlyCollection<Type> SubscribedMessageTypes { get; }

public abstract Task OnEnter(Context<StateId> context);

public Task OnEntering(Context<StateId> context) => Task.CompletedTask;

public Task OnExit(Context<StateId> context) => Task.CompletedTask;

public abstract Task OnMessage(Context<StateId> context, object message);

public Task OnTimeout(Context<StateId> 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<Type> SubscribedMessageTypes => [typeof(OrderCreated)];

public override Task OnEnter(Context<StateId> context)
{
Console.WriteLine("State1: publishing OrderCreated for 3 notebooks.");
context.EventAggregator!.Publish(new OrderCreated("Notebook", 3));
return Task.CompletedTask;
}

public override Task OnMessage(Context<StateId> 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<Type> SubscribedMessageTypes => [typeof(PriceRequested)];

public override Task OnEnter(Context<StateId> 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<StateId> 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<Type> SubscribedMessageTypes => [typeof(OrderPriced)];

public override Task OnEnter(Context<StateId> 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<StateId> 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;
}
}
}
Loading
Loading