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
16 changes: 12 additions & 4 deletions .github/workflows/build-github.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ env:
BASE_VERSION: "2.1"
PATH_SLNX: "Lite.StateMachine.slnx"
PATH_LIB: "source\\Lite.StateMachine\\Lite.StateMachine.csproj"
PATH_DOTGRAPH: "source\\Lite.StateMachine.DotGraph\\Lite.StateMachine.DotGraph.csproj"
PATH_ARTIFACTS: ${{github.workspace}}\artifacts

jobs:
Expand Down Expand Up @@ -82,9 +83,16 @@ jobs:
if ($prerelease) { Write-Host "Version suffix=$prerelease" }

# 7. Pack NuGet
- name: 7) Pack NuGet
- name: 7) Pack NuGet Packages
# Optionally, "--include-symbols"
run: dotnet pack ${{env.PATH_LIB}} --configuration Release --no-build --output ${{env.PATH_ARTIFACTS}}
shell: pwsh
run: |
foreach ($project in @($env:PATH_LIB, $env:PATH_DOTGRAPH)) {
dotnet pack $project --configuration Release --no-build --output $env:PATH_ARTIFACTS -m:1
if ($LASTEXITCODE -ne 0) {
throw "NuGet packing failed for $project"
}
}
# dotnet pack source/Lite.StateMachine/Lite.StateMachine.csproj --configuration Release --no-build --output ./artifacts
#- name: Pack NuGet
# shell: pwsh
Expand Down Expand Up @@ -125,13 +133,13 @@ jobs:
## steps:

## 10) Publish to NuGet.org (master branch, push events only)
- name: 8) NuGet Push Package
- name: 8) NuGet Push Packages
env:
NUGET_API_URL: "https://api.nuget.org/v3/index.json"

## Optionally pass, `--skip-duplicate` if a pkg version already exists on NuGet.org
if: github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/')
run: dotnet nuget push ${{env.PATH_ARTIFACTS}}\*.nupkg -k ${{secrets.NUGET_AUTH_TOKEN}} -s ${{env.NUGET_API_URL}}
run: dotnet nuget push ${{env.PATH_ARTIFACTS}}\*.nupkg -k ${{secrets.NUGET_AUTH_TOKEN}} -s ${{env.NUGET_API_URL}} --skip-duplicate

#- name: Publish to NuGet.org
# if: github.ref_name == 'master' && github.event_name == 'push'
Expand Down
42 changes: 42 additions & 0 deletions .github/workflows/dotgraph.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: DOT rendering on Windows, Linux, and macOS

on:
push:
branches: [master, develop]
pull_request:
branches: [master, develop]

jobs:
render:
strategy:
fail-fast: false
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: |
10.0.x
11.0.x
- name: Install Graphviz on Windows
if: runner.os == 'Windows'
run: choco install graphviz --no-progress -y
- name: Install Graphviz on Linux
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y graphviz
- name: Install Graphviz on macOS
if: runner.os == 'macOS'
run: brew install graphviz
- name: Test rendering
shell: pwsh
run: |
if ($IsWindows) {
$env:GRAPHVIZ_DOT = 'C:\Program Files\Graphviz\bin\dot.exe'
} else {
$env:GRAPHVIZ_DOT = 'dot'
}
dotnet test source/Lite.StateMachine.DotGraph.Tests -c Release --verbosity normal
- name: Pack standalone renderer
run: dotnet pack source/Lite.StateMachine.DotGraph -c Release --no-build
3 changes: 3 additions & 0 deletions Lite.StateMachine.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<Project Path="samples/Sample05.CommandStates/Sample05.CommandStates.csproj" Id="cd6b33b8-ac4a-4ec7-a3a8-5cdf14c03847" />
<Project Path="samples/Sample06.PassingEvents/Sample06.PassingEvents.csproj" Id="01a1903a-9da0-4cd2-a811-356822569e03" />
<Project Path="samples/Sample10.UsingEventIPC/Sample10.UsingEventIPC.csproj" Id="f89325bb-17ff-4db9-9647-92bad4e2f974" />
<Project Path="samples/Sample11.GenerateDotGraph/Sample11.GenerateDotGraph.csproj" />
</Folder>
<Folder Name="/Solution Items/">
<File Path=".github/workflows/build-github.yml" />
Expand All @@ -20,8 +21,10 @@
<File Path="Directory.Packages.props" />
</Folder>
<Folder Name="/Tests/">
<Project Path="source/Lite.StateMachine.DotGraph.Tests/Lite.StateMachine.DotGraph.Tests.csproj" />
<Project Path="source/Lite.Statemachine.BenchmarkTests/Lite.StateMachine.BenchmarkTests.csproj" Id="de19a850-9787-485a-b4d2-4620ca204969" />
<Project Path="source/Lite.StateMachine.Tests/Lite.StateMachine.Tests.csproj" Id="9644caac-1ac7-49b2-a502-896ca82f7b74" />
</Folder>
<Project Path="source/Lite.StateMachine/Lite.StateMachine.csproj" />
<Project Path="source/Lite.StateMachine.DotGraph/Lite.StateMachine.DotGraph.csproj" />
</Solution>
17 changes: 16 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,24 @@ public class BasicState3() : BaseState
### Generate DOT Graph (GraphViz)

```cs
var uml = machine.ExportUml(includeSubmachines: true);
var uml = machine.ExportUml();
```

To generate SVG or PNG files from DOT, use the optional
[Lite.StateMachine.DotGraph](source/Lite.StateMachine.DotGraph/readme.md) package:

```cs
using Lite.StateMachine.DotGraph;

var renderer = new GraphvizRenderer();
await renderer.RenderAsync(machine.ExportUml(), "machine.svg");
await renderer.RenderFileAsync("machine.dot", "machine.png", DotGraphFormat.Png);
```

The renderer requires an installed or application-supplied [Graphviz](https://graphviz.org/download/)
executable. It is independent of the core library and uses portable .NET process APIs
for Windows, Linux, and macOS. See the package README for deployment requirements.

![Sample Composite State Image](https://raw.githubusercontent.com/SuessLabs/Lite.StateMachine/develop/docs/SampleGraphviz-1080.png)

### Composite States
Expand Down
3 changes: 3 additions & 0 deletions samples/Sample11.GenerateDotGraph/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
*.png
*.svg
*.dot
66 changes: 66 additions & 0 deletions samples/Sample11.GenerateDotGraph/Generate-Diagrams.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<#
.SYNOPSIS
Builds the sample, loads its DLL, and renders the same diagrams as the console app.
.EXAMPLE
./Generate-Diagrams.ps1 -DotPath 'C:/Program Files/Graphviz/bin/dot.exe'
#>
#Requires -Version 7.0

[CmdletBinding()]
param(
[string] $OutputDirectory = (Join-Path $PSScriptRoot 'diagrams'),
[string] $DotPath = 'dot',
[ValidateSet('Debug', 'Release')]
[string] $Configuration = 'Release',
[switch] $SkipBuild
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if ([Environment]::Version.Major -lt 10) {
throw 'Use PowerShell hosted on .NET 10 or later (for example PowerShell 7.6). Windows PowerShell 5.1 is not supported.'
}

$project = Join-Path $PSScriptRoot 'Sample11.GenerateDotGraph.csproj'
if (-not $SkipBuild) {
dotnet build $project -c $Configuration -f net10.0
if ($LASTEXITCODE -ne 0) {
throw 'Sample build failed.'
}
}

# Matches this repository's Directory.Build.props output layout.
$assemblyDirectory = [IO.Path]::GetFullPath(
(Join-Path $PSScriptRoot "../../output/Sample11.GenerateDotGraph/$Configuration/net10.0"))

foreach ($assemblyName in @('Lite.StateMachine.dll', 'Lite.StateMachine.DotGraph.dll', 'Sample11.GenerateDotGraph.dll'))
{
$assemblyPath = Join-Path $assemblyDirectory $assemblyName
if (-not (Test-Path -LiteralPath $assemblyPath -PathType Leaf)) {
throw "Assembly not found: $assemblyPath. Build the sample first or omit -SkipBuild."
}
[void][Reflection.Assembly]::LoadFrom($assemblyPath)
}

$OutputDirectory = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputDirectory)
[void][IO.Directory]::CreateDirectory($OutputDirectory)
$renderer = [Lite.StateMachine.DotGraph.GraphvizRenderer]::new($DotPath, [TimeSpan]::FromSeconds(30))
$token = [Threading.CancellationToken]::None

foreach ($includeLegend in @($false, $true)) {
$name = if ($includeLegend) { 'machine-legend' } else { 'machine' }

# This calls a public DLL method, not the console application's entry point.
$dot = [Sample11.GenerateDotGraph.WorkflowDiagram]::ExportDot($includeLegend)

[IO.File]::WriteAllText((Join-Path $OutputDirectory "$name.dot"), $dot)

[void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.svg"),
[Lite.StateMachine.DotGraph.DotGraphFormat]::Svg, $token).GetAwaiter().GetResult()

[void]$renderer.RenderAsync($dot, (Join-Path $OutputDirectory "$name.png"),
[Lite.StateMachine.DotGraph.DotGraphFormat]::Png, $token).GetAwaiter().GetResult()

Write-Output "Generated $name.dot, $name.svg, and $name.png in $OutputDirectory"
}
48 changes: 48 additions & 0 deletions samples/Sample11.GenerateDotGraph/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright Xeno Innovations, Inc. 2026
// See the LICENSE file in the project root for more information.

using System;
using System.IO;
using System.Threading.Tasks;
using Lite.StateMachine.DotGraph;

namespace Sample11.GenerateDotGraph;

internal static class Program
{
private static async Task<int> Main(string[] args)
{
if (args.Length > 2)
{
Console.Error.WriteLine("Usage: Sample11.GenerateDotGraph [output-directory] [dot-executable]");
return 1;
}

var outputDirectory = Path.GetFullPath(args.Length > 0
? args[0]
: Path.Combine(AppContext.BaseDirectory, "diagrams"));

var renderer = new GraphvizRenderer(args.Length > 1
? args[1]
: "dot");

Directory.CreateDirectory(outputDirectory);

foreach (var includeLegend in new[] { false, true })
{
var name = includeLegend ? "machine-legend" : "machine";

// Create state machine and export DOT graph without running any states.
var dot = SampleStateMachine.ExportDot(includeLegend);
var dotPath = Path.Combine(outputDirectory, name + ".dot");

await File.WriteAllTextAsync(dotPath, dot);
await renderer.RenderAsync(dot, Path.Combine(outputDirectory, name + ".svg"));
await renderer.RenderAsync(dot, Path.Combine(outputDirectory, name + ".png"), DotGraphFormat.Png);

Console.WriteLine($"Generated {name}.dot, {name}.svg, and {name}.png in {outputDirectory}");
}

return 0;
}
}
14 changes: 14 additions & 0 deletions samples/Sample11.GenerateDotGraph/Sample11.GenerateDotGraph.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<IsPackable>false</IsPackable>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" />
<ProjectReference Include="../../source/Lite.StateMachine/Lite.StateMachine.csproj" />
<ProjectReference Include="../../source/Lite.StateMachine.DotGraph/Lite.StateMachine.DotGraph.csproj" />
</ItemGroup>
</Project>
59 changes: 59 additions & 0 deletions samples/Sample11.GenerateDotGraph/SampleStateMachine.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright Xeno Innovations, Inc. 2026
// See the LICENSE file in the project root for more information.

using System;
using Lite.StateMachine;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Sample11.GenerateDotGraph;

/// <summary>Exports the same topology as DiMsTests.Basic_GeneratesExportUml_SuccessTestAsync.</summary>
public static class SampleStateMachine
{
/// <summary>Builds the configured machine and exports DOT without running any states.</summary>
/// <param name="includeLegend">Whether to add the Graphviz legend.</param>
/// <returns>DOT text with Entry as the initial state.</returns>
public static string ExportDot(bool includeLegend)
{
// Configure DI
using var services = new ServiceCollection()
.AddLogging(builder => builder.AddSimpleConsole())
.AddSingleton<IEventAggregator, EventAggregator>()
.AddTransient<EntryState>()
.AddTransient<ParentState>()
.AddTransient<ParentSub_FetchState>()
.AddTransient<ParentSub_WaitMessageState>()
.AddTransient<DoneState>()
.AddTransient<ErrorState>()
.AddTransient<FailureState>()
.BuildServiceProvider();

// Factory uses DI to construct states
var aggregator = services.GetRequiredService<IEventAggregator>();
Func<Type, object?> factory = type => ActivatorUtilities.CreateInstance(services, type);

// Create State Machine
var machine = new StateMachine<CompositeMsgStateId>(factory, aggregator);

machine.RegisterState<EntryState>(CompositeMsgStateId.Entry, CompositeMsgStateId.Parent);
machine.RegisterComposite<ParentState>(
stateId: CompositeMsgStateId.Parent,
initialChildStateId: CompositeMsgStateId.Parent_Fetch,
onSuccess: CompositeMsgStateId.Done,
onError: CompositeMsgStateId.Error,
onFailure: CompositeMsgStateId.Failure);

//// Substates of ParentState
machine.RegisterSubState<ParentSub_FetchState>(CompositeMsgStateId.Parent_Fetch, CompositeMsgStateId.Parent, CompositeMsgStateId.Parent_WaitMessage);
machine.RegisterSubState<ParentSub_WaitMessageState>(CompositeMsgStateId.Parent_WaitMessage, CompositeMsgStateId.Parent);

// End of substates
machine.RegisterState<DoneState>(CompositeMsgStateId.Done);
machine.RegisterState<ErrorState>(CompositeMsgStateId.Error, CompositeMsgStateId.Parent);
machine.RegisterState<FailureState>(CompositeMsgStateId.Failure, CompositeMsgStateId.Parent);

// Export the DOT graph with Entry as the initial state.
return machine.ExportUml([CompositeMsgStateId.Entry], includeLegend: includeLegend);
}
}
65 changes: 65 additions & 0 deletions samples/Sample11.GenerateDotGraph/WorkflowStates.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright Xeno Innovations, Inc. 2026
// See the LICENSE file in the project root for more information.

using System.Threading.Tasks;
using Lite.StateMachine;
using Microsoft.Extensions.Logging;

namespace Sample11.GenerateDotGraph;

#pragma warning disable SA1402 // Keep the small diagram-only state definitions together.
#pragma warning disable SA1649 // File groups related state definitions.

/// <summary>State identifiers matching the composite export test.</summary>
public enum CompositeMsgStateId
{
Entry,
Parent,
Parent_Fetch,
Parent_WaitMessage,
Done,
Error,
Failure,
}

public sealed class EntryState(ILogger<DiagramState> logger) : DiagramState(logger);

public sealed class ParentState(ILogger<DiagramState> logger) : DiagramState(logger);

public sealed class ParentSub_FetchState(ILogger<DiagramState> logger) : DiagramState(logger);

public sealed class ParentSub_WaitMessageState(ILogger<DiagramState> logger)
: DiagramState(logger), ICommandState<CompositeMsgStateId>
{
public Task OnMessage(Context<CompositeMsgStateId> context, object message) => Task.CompletedTask;

public Task OnTimeout(Context<CompositeMsgStateId> context)
{
context.NextState(Result.Failure);
return Task.CompletedTask;
}
}

public sealed class DoneState(ILogger<DiagramState> logger) : DiagramState(logger);

public sealed class ErrorState(ILogger<DiagramState> logger) : DiagramState(logger);

public sealed class FailureState(ILogger<DiagramState> logger) : DiagramState(logger);

/// <summary>Minimal state behavior; diagram generation never executes these handlers.</summary>
public abstract class DiagramState(ILogger<DiagramState> logger) : IState<CompositeMsgStateId>
{
public Task OnEnter(Context<CompositeMsgStateId> context)
{
logger.LogInformation("Entered {StateId}", context.CurrentStateId);
context.NextState(Result.Success);
return Task.CompletedTask;
}

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

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

#pragma warning restore SA1649 // File groups related state definitions.
#pragma warning restore SA1402 // Keep the small diagram-only state definitions together.
Loading
Loading