### Build and Deploy Docker Container Source: https://github.com/akkadotnet/akka.net/blob/dev/src/examples/Cluster/ClusterSharding/ClusterSharding.Node/README.md Run this script to build the Docker container and start the Docker Compose setup for local deployment. ```powershell PS> ./start.cmd ``` -------------------------------- ### Akka.NET Headless Service Setup Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/deployment/headless-service.md Configures and starts the Akka.NET system as a background service. This involves setting up the ActorSystem and potentially other services. ```csharp using Akka.Actor; using Akka.Configuration; using Akka.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace AkkaHeadlesssService { public class AkkaService : BackgroundService { private readonly ILogger _logger; private ActorSystem _actorSystem; public AkkaService(ILogger logger) { _logger = logger; } public override Task StartAsync(CancellationToken cancellationToken) { // Configuration for Akka.NET, including remote capabilities if needed var config = ConfigurationFactory.ParseString(@" akka { actor { provider = "Akka.Actor.LocalActorRefProvider" } // Add other Akka configurations here } "); // Initialize ActorSystem using Akka.Hosting _actorSystem = ActorSystem.Create("MyAkkaHeadlessActorSystem", config); // You can create actors or set up other Akka.NET components here // _actorSystem.ActorOf("headlessActor"); _logger.LogInformation("Akka.NET Actor System started."); return base.StartAsync(cancellationToken); } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { // This method is called when the service starts // You can perform background tasks here or manage actor lifecycles while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } public override async Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Akka.NET Actor System stopping."); // Gracefully shut down the ActorSystem if (_actorSystem != null) { await _actorSystem.Terminate(); await _actorSystem.WhenTerminated; } _logger.LogInformation("Akka.NET Actor System stopped."); await base.StopAsync(cancellationToken); } } } ``` -------------------------------- ### Combine HOCON and Setup with BootstrapSetup Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/configuration/config.md Use BootstrapSetup to store HOCON configuration and merge it with other Setup objects to create an ActorSystemSetup. ```csharp var bootstrapSetup = new BootstrapSetup(ConfigurationFactory.ParseString("akka.actor.provider = \"Akka.Actor.LocalActorRefProvider\"")); var serializationSetup = new SerializationSetup(new[] { new RegisterSerializer(typeof(MyCustomSerializer), "custom", "my-custom-serializer") }); var actorSystemSetup = bootstrapSetup.And(serializationSetup); var system = ActorSystem.Create("MyActorSystem", ActorSystemSetup.Empty.WithSetup(actorSystemSetup)); ``` -------------------------------- ### Actor System Setup and Message Sending Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/actors/untyped-actor-api.md This snippet demonstrates how to create an ActorSystem, instantiate an actor, and send messages to it. It's a basic setup for interacting with actors. ```csharp static void Main(string[] args) { var system = ActorSystem.Create("MySystem"); var swapper = system.ActorOf(); swapper.Tell(Swapper.Swap.Instance); swapper.Tell(Swapper.Swap.Instance); swapper.Tell(Swapper.Swap.Instance); swapper.Tell(Swapper.Swap.Instance); swapper.Tell(Swapper.Swap.Instance); swapper.Tell(Swapper.Swap.Instance); Console.ReadLine(); } ``` -------------------------------- ### Install Akka.NET Project Templates Source: https://github.com/akkadotnet/akka.net/blob/dev/README.md Install the Akka.NET project templates using the dotnet CLI. This makes templates available via `dotnet new` and within .NET IDEs. ```bash dotnet new install "Akka.Templates::*" ``` -------------------------------- ### ShardingProducerController.Start Source: https://github.com/akkadotnet/akka.net/blob/dev/src/core/Akka.API.Tests/verify/CoreAPISpec.ApproveClusterSharding.Net.verified.txt A command to start the ShardingProducerController. ```APIDOC ## ShardingProducerController.Start ### Description Sent to the `ShardingProducerController` to initiate its operation. It specifies the producer actor that will be sending messages. ### Properties * `Producer` (IActorRef) - The actor reference of the producer. ``` -------------------------------- ### ProducerController.Start Source: https://github.com/akkadotnet/akka.net/blob/dev/src/core/Akka.API.Tests/verify/CoreAPISpec.ApproveCore.Net.verified.txt Command to start a producer with the ProducerController. ```APIDOC ## ProducerController.Start ### Description Command to start a producer with the ProducerController. ### Constructor `public Start(Akka.Actor.IActorRef producer)` ### Properties - `Producer` (Akka.Actor.IActorRef) - The actor reference of the producer to start. ``` -------------------------------- ### Basic TestKit Setup Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/actors/testing-actor-systems.md This snippet demonstrates the minimal setup for testing actors using Akka.TestKit. It initializes the TestKit, which provides the `Sys` member for accessing the ActorSystem and `TestActor` for message assertions. ```csharp [Fact] public void IntroSample_0() { // Arrange var testKit = new TestKit(ActorSystem.Create("TestSys")); // Act // Assert testKit.Dispose(); } ``` -------------------------------- ### Install Akka.FSharp Support Source: https://github.com/akkadotnet/akka.net/blob/dev/README.md Run this command in the Package Manager Console to install the Akka.FSharp NuGet package for F# support. ```powershell PM> Install-Package Akka.FSharp ``` -------------------------------- ### Install Akka.NET Hosting Package Source: https://github.com/akkadotnet/akka.net/blob/dev/README.md Use this command in the Package Manager Console to install the Akka.Hosting NuGet package. This package includes the base Akka package and integrates with Microsoft.Extensions for configuration, logging, hosting, and dependency injection. ```powershell PM> Install-Package Akka.Hosting ``` -------------------------------- ### Starting Akka.Management for Receptionist Nodes Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/clustering/cluster-client.md Code to start Akka.Management on receptionist nodes if ClusterBootstrap is not being used. This is necessary for the Cluster Client discovery mechanism to function correctly. ```csharp services.AddAkka("ReceptionistSys", (builder, provider) => { builder.AddStartup(async (system, registry) => { await AkkaManagement.Get(system).Start(); }); }); ``` -------------------------------- ### Producer Controller Start Command Source: https://github.com/akkadotnet/akka.net/blob/dev/src/core/Akka.API.Tests/verify/CoreAPISpec.ApproveCore.Net.verified.txt Command to start the Producer Controller, requiring an IActorRef for the producer. Implements IProducerCommand. ```csharp public sealed class Start : Akka.Delivery.ProducerController.IProducerCommand { public Start(Akka.Actor.IActorRef producer) { } public Akka.Actor.IActorRef Producer { get; } ``` -------------------------------- ### Install Akka.Cluster NuGet Package Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/clustering/cluster-overview.md Install the Akka.Cluster NuGet package using the Package Manager Console in Visual Studio. ```powershell PM> Install-Package Akka.Cluster ``` -------------------------------- ### ProducerController.Start Source: https://github.com/akkadotnet/akka.net/blob/dev/src/core/Akka.API.Tests/verify/CoreAPISpec.ApproveCore.DotNet.verified.txt Command to start the ProducerController, providing an actor reference for the producer. ```APIDOC ## ProducerController.Start ### Description Command to start the ProducerController, providing an actor reference for the producer. ### Method Signature `public Start(Akka.Actor.IActorRef producer)` ### Properties - **Producer** (Akka.Actor.IActorRef) - The actor reference for the producer. ``` -------------------------------- ### Starting a Sharding Region (Proxy) in Program.cs Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/clustering/cluster-sharding.md Starts a sharding region actor, specifically a proxy coordinator, on the frontend node. This actor is responsible for routing messages to the correct sharded actors on backend nodes without hosting them directly. ```csharp var system = ActorSystem.Create("MyActorSystem"); // Initialize ClusterSharding extension ClusterSharding.Get(system); // Start the sharding region proxy on the frontend node var shardingRegion = ClusterSharding.Get(system).StartProxy("customers", "backend", Props.Create(() => new CustomerActorProxy())); Console.WriteLine("Frontend node started with sharding region proxy."); // ... rest of the setup ``` -------------------------------- ### ShardingProducerController.Start Source: https://github.com/akkadotnet/akka.net/blob/dev/src/core/Akka.API.Tests/verify/CoreAPISpec.ApproveClusterSharding.DotNet.verified.txt A command to start the ShardingProducerController, providing the producer's ActorRef. ```APIDOC ## Akka.Cluster.Sharding.Delivery.ShardingProducerController.Start ### Description A command to start the ShardingProducerController, providing the producer's ActorRef. ### Class Definition `public sealed class Start : Akka.Cluster.Sharding.Delivery.ShardingProducerController.IShardingProducerControllerCommand` ### Properties - **Producer** (Akka.Actor.IActorRef) - The ActorRef of the producer. ``` -------------------------------- ### Configure Startup with Service Bindings Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/actors/dependency-injection.md Set up your application's Startup class to configure services using Microsoft.Extensions.DependencyInjection. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddAkka(ActorSystem.Create(ActorSystem.DefaultName, Configuration.Default.WithFallback(Akka.Actor.ActorSystem.DefaultConfiguration)), "myActorSystem"); services.AddSingleton(); services.AddTransient(); } ``` -------------------------------- ### Merge Setups and Create ActorSystem Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/serialization/serialization.md Combine `SerializationSetup` with `BootstrapSetup` to configure the `ActorSystem` with both HOCON settings and programmatic serialization bindings. ```csharp var bootstrapSetup = BootstrapSetup.Create().WithConfig(ConfigurationFactory.ParseString("akka.actor.provider = remote")); var actorSystemSetup = bootstrapSetup.And(serializationSetup); var system = ActorSystem.Create("SerializationDocSpec", actorSystemSetup); // Verification can be done here... ``` -------------------------------- ### Combining MergeHub and BroadcastHub for Publish-Subscribe Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/streams/stream-dynamic.md Connect a MergeHub and a BroadcastHub to create a basic publish-subscribe channel. This example demonstrates the initial setup of the channel. ```csharp var mergeHubSink = MergeHub.Sink(); var broadcastHubSource = BroadcastHub.Source(); var (sink, source) = ActorSystem.Use().Create((mergeHubSink, broadcastHubSource)); ``` -------------------------------- ### Build Documentation on Windows Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/community/contributing/documentation-guidelines.md Execute this command in the root of the Akka.NET repository to build the documentation on a Windows system. ```batch build.cmd docfx ``` -------------------------------- ### MultiNodeSpec Configuration Example Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/testing/multi-node-testing.md A typical MultiNodeSpec setup, demonstrating the structure required for multi-node testing in Akka.NET. It includes the necessary constructors and field declarations. ```csharp [MultiNodeFact] public async Task ShouldRestartNode2() { // ... test logic ... } ``` ```csharp public class RestartNode2SpecConfig : MultiNodeConfig { public RoleName Seed1 { get; } = "seed1"; public RoleName Seed2 { get; } = "seed2"; public RestartNode2SpecConfig() { // Default configuration for all nodes in the test CommonConfig = new DebugSwapper().And(ConfigurationFactory.ParseString( $"akka.cluster.roles = [{Seed1}, {Seed2}]\n" + "akka.remote.log-remote-lifecycle-events = off")); // Specify configuration for individual nodes NodeConfig(new List { Seed1 }, new List { ConfigurationFactory.ParseString("akka.cluster.roles = [\"seed1\"]") }); NodeConfig(new List { Seed2 }, new List { ConfigurationFactory.ParseString("akka.cluster.roles = [\"seed2\"]") }); } } ``` ```csharp public class RestartNode2Spec : TestKit { private readonly RestartNode2SpecConfig _config; // Public constructor required by XUnit public RestartNode2Spec() : this(new RestartNode2SpecConfig()) { } // Protected constructor for base class initialization protected RestartNode2Spec(RestartNode2SpecConfig config) : base(config) { _config = config; // Ensure all nodes are started and ready before proceeding Sys.WhenTerminated.Wait(TimeSpan.FromSeconds(10)); } // ... test methods ... } ``` ```csharp public RoleName Seed1 { get; } = "seed1"; public RoleName Seed2 { get; } = "seed2"; ``` ```csharp public RestartNode2Spec() : this(new RestartNode2SpecConfig()) { } ``` ```csharp protected RestartNode2Spec(RestartNode2SpecConfig config) : base(config) { _config = config; Sys.WhenTerminated.Wait(TimeSpan.FromSeconds(10)); } ``` ```csharp [MultiNodeFact] public async Task ShouldRestartNode2() { // ... test logic ... } ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/community/contributing/documentation-guidelines.md Run this script from the repository root to serve the built documentation locally, enabling JavaScript components to function correctly in the browser. ```shell serve-docs.cmd ``` -------------------------------- ### Snapshot Store Startup Sequence Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/persistence/custom-persistence-provider.md Implement this to allow users to auto-initialize their backend event source from a blank slate by stashing incoming messages during table creation. ```csharp public class SqliteSnapshotStore : SnapshotStore { private readonly ILoggingAdapter _log = Context.GetLogger(); public SqliteSnapshotStore(Akka.Configuration.Config config) { // This is the constructor that will be used by Akka.NET // when creating the snapshot store actor. // The config parameter contains the configuration for this snapshot store. } public override async Task GetSnapshotAsync(string persistenceId, SnapshotSelectionCriteria criteria) { // Implementation for retrieving snapshots return null; // Placeholder } public override async Task SaveSnapshotAsync(SnapshotMetadata metadata, object snapshot) { // Implementation for saving snapshots await Task.CompletedTask; } public override async Task DeleteAsync(string persistenceId) { // Implementation for deleting snapshots for a given persistenceId await Task.CompletedTask; } public override async Task DeleteAsync(string persistenceId, SnapshotSelectionCriteria criteria) { // Implementation for deleting snapshots based on criteria await Task.CompletedTask; } // Example of how to handle auto-initialization protected override void PreStart() { // Simulate creating tables or other initialization logic _log.Info("Initializing SqliteSnapshotStore..."); // In a real implementation, you would perform database initialization here. // For demonstration, we'll just log and then become unstashable. Context.Become(Ready, discardOld: false); BecomeStacked(); // Ensure this actor can be unstashed later if needed } private void Ready() { // Once initialization is complete, become unstashable // and process any stashed messages. _log.Info("SqliteSnapshotStore initialized and ready."); UnbecomeStacked(); } } ``` -------------------------------- ### Incorrect Timer Registration in PreRestart() Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/debugging/rules/AK1007.md This example demonstrates the incorrect placement of timer registration within the PreRestart() lifecycle method. Timers started here will not be honored. ```csharp using System; using Akka.Actor; public sealed class MyActor : ReceiveActor, IWithTimers { private sealed class TimerKey { public static readonly TimerKey Instance = new(); private TimerKey() { } } private sealed class TimerMessage { public static readonly TimerMessage Instance = new(); private TimerMessage() { } } public MyActor() { Receive(_ => { // Timer callback code will never be executed }); } public ITimerScheduler Timers { get; set; } protected override void PreRestart(Exception reason, object message) { base.PreRestart(reason, message); // This timer will never be fired Timers.StartSingleTimer( key: TimerKey.Instance, msg: TimerMessage.Instance, timeout: TimeSpan.FromSeconds(3)); } } ``` -------------------------------- ### Start Stream Processing from a Source Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/streams/basics.md Shows how to initiate stream processing by defining a Source with transformations and then connecting it to a Sink. ```csharp // Starting from a Source var source = Source.From(Enumerable.Range(1, 6)).Select(x => x * 2); source.To(Sink.ForEach(x => Console.WriteLine(x.ToString()))); ``` -------------------------------- ### Akka.NET Sample Actor Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/deployment/windows-service.md A basic Akka.NET actor example. This actor can be used as a starting point for defining custom actor behavior within the Akka.NET framework. ```csharp using Akka.Actor; namespace AkkaWindowsService; public class MyActor : ReceiveActor { public MyActor() { Receive(message => { // Handle string messages Context.Sender.Tell($"Received: {message}", Self); }); } } ``` -------------------------------- ### Register Producer with Typed Actors in C# Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/clustering/cluster-sharding-delivery.md Register a producer with the ShardingProducerController using strongly-typed messages. This example demonstrates how to start typed actors for message production. ```csharp var producerProps = Props.Create(() => new MyProducerActor()); var producerRegistration = new ShardingProducerController.Register( producerId: "my-producer-id", producerProps: producerProps, // Optional: A function to extract the ShardKey from the message // If not provided, the ShardKey will be extracted from the message itself (if it implements IShardingMessage) shardKeyExtractor: message => message.ShardKey ); // Send the registration message to the ShardingProducerController shardingProducerController.Tell(producerRegistration); ``` -------------------------------- ### Akka.NET Windows Service Program Setup Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/deployment/windows-service.md Sets up the main entry point for an Akka.NET application to run as a Windows Service. This includes configuring the host builder and registering the AkkaService. ```csharp using Akka.Actor; using Akka.Configuration; using Akka.Hosting; using Microsoft.Extensions.Hosting; var builder = Host.CreateDefaultBuilder(args); builder.ConfigureServices(services => { // Add Akka.NET services services.AddAkka("MyActorSystem", (configurationBuilder, actorSystemOptions) => { // Load configuration from appsettings.json configurationBuilder.AddConfig(ConfigurationLoader.FromDefault()); // Register actors actorSystemOptions.WithActorsFromAssembly(typeof(MyActor).Assembly); }); }); // Register the Windows Service builder.UseWindowsService(); var host = builder.Build(); host.Run(); ``` -------------------------------- ### Persistent Actor Example with Akka.NET Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/persistence/event-sourcing.md Demonstrates a basic persistent actor that handles commands, generates events, and updates its state. Use this as a starting point for implementing event-sourced actors. ```csharp public class PersistentActor : UntypedPersistentActor { public override string PersistenceId { get; } private ExampleState State { get; set; } = new ExampleState(); public PersistentActor(string persistenceId) { PersistenceId = persistenceId; } protected override void OnRecover(object message) { switch (message) { case Evt evt: // Replay events Apply(evt); break; case RecoveryCompleted _: // Recovery finished Console.WriteLine("Recovery completed."); break; case SnapshotOffer snapshotOffer: if (snapshotOffer.Snapshot is ExampleState state) { State = state; } break; } } protected override void OnCommand(object message) { switch (message) { case Cmd cmd: // Validate command and generate events var events = GenerateEvents(cmd); // Persist events Persist(events, Apply); break; } } private IEnumerable GenerateEvents(Cmd cmd) { // Logic to generate events from command yield return new Evt($"Event for {cmd.Data}"); yield return new Evt($"Another event for {cmd.Data}"); } private void Apply(Evt evt) { State.Add(evt.Data); Console.WriteLine($"Applied event: {evt.Data}"); } // ExampleState and Cmd/Evt definitions would be here public class ExampleState { private readonly List _data = new List(); public void Add(string data) { _data.Add(data); } public IReadOnlyList Data => _data; } public record Cmd(string Data); public record Evt(string Data); } ``` -------------------------------- ### Sample Subscriber Actor Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/clustering/distributed-publish-subscribe.md An example of a subscriber actor that registers to the 'content' topic and receives messages. Ensure this actor is started on multiple nodes in the cluster to receive published messages. ```csharp public class SampleSubscriber : UntypedActor { public SampleSubscriber() { DistributedPubSub.Get(Context.System).Mediator.Tell(new DistributedPubSubMediator.Subscribe("content", Self)); } protected override void OnReceive(object message) { if (message is DistributedPubSubMediator.SubscribeAck) { Console.WriteLine("Subscribed to content topic"); } else if (message is string) { Console.WriteLine($"Received message: {message}"); } else { Unhandled(message); } } } ``` -------------------------------- ### Using IWithTimers for Automatic Cancellation Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/debugging/rules/AK1004.md This example shows the recommended approach using `IWithTimers` to manage scheduled messages. Timers started this way are automatically tied to the actor's lifecycle and cleaned up. ```csharp using Akka.Actor; using System.Threading.Tasks; using System; public sealed class MyActor : ReceiveActor, IWithTimers { private sealed class TimerKey { public static readonly TimerKey Instance = new(); private TimerKey() { } } private sealed class TimerMessage { public static readonly TimerMessage Instance = new(); private TimerMessage() { } } public MyActor() { Timers.StartPeriodicTimer( key: TimerKey.Instance, msg: TimerMessage.Instance, initialDelay: TimeSpan.FromSeconds(3), interval: TimeSpan.FromSeconds(3)); } public ITimerScheduler Timers { get; set; } = null!; } ``` -------------------------------- ### Programmatic Mutual TLS Setup Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/remoting/security.md Use this programmatic approach for advanced security configurations like certificate pinning, subject/issuer validation, or custom logic. This example demonstrates setting up mutual TLS programmatically. ```csharp public static ActorSystemSetup ProgrammaticMutualTlsSetup(X509Certificate2 serverCertificate, X509Certificate2 clientCertificate) => ActorSystemSetup.Create().WithRemote( // Configure TLS for the remote transport RemoteConfigFactory.Transport( "dot-netty.tcp", new DotNettyTransportSettings { // Enable SSL/TLS Ssl = new SslSettings { Enabled = true, // Require clients to authenticate themselves ClientAuth = ClientAuth.Need, // Use the server's certificate for the server KeyStore = serverCertificate, // Use the client's certificate for the client TrustStore = clientCertificate } } ) ); ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/community/contributing/build-process.md Scripts to serve the generated documentation locally. `./serve-docs.cmd` is for Windows, and `./serve-docs.ps1` works cross-platform. ```bash ./serve-docs.cmd ./serve-docs.ps1 ``` -------------------------------- ### Install Akka.Logger.Serilog Package Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/utilities/serilog.md Install the Akka.Logger.Serilog NuGet package to enable Serilog integration. This command also installs necessary Serilog dependencies. ```console PM> Install-Package Akka.Logger.Serilog ``` -------------------------------- ### Install Akka.DistributedData NuGet Package Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/clustering/distributed-data.md Install the Akka.DistributedData package using the NuGet package manager. ```console install-package Akka.DistributedData ``` -------------------------------- ### Application Entry Point with Actor System Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/intro/getting-started/tutorial-1.md Sets up the Akka.NET Actor System and provides the main entry point for the application. It demonstrates basic actor system creation. ```csharp public class IotApp { public static void Main(string[] args) { var configuration = ConfigurationFactory.ParseString(@"akka.actor.provider = \"Akka.Actor.LocalActorRefProvider\""); var actorSystem = ActorSystem.Create("IotSystem", configuration); Console.WriteLine("Starting application..."); actorSystem.ActorOf("iot-supervisor"); Console.WriteLine("Application started. Press ENTER to exit."); Console.ReadLine(); CoordinatedShutdown.Get(actorSystem).Exit( শক.Normal).Wait(); } } ``` -------------------------------- ### Install Akka.Remote NuGet Package Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/remoting/index.md Use the Package Manager Console to install the Akka.Remote NuGet package. ```powershell PS> Install-Package Akka.Remote ``` -------------------------------- ### Install Akka.DependencyInjection via NuGet Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/actors/dependency-injection.md Install the Akka.DependencyInjection package using the NuGet Package Manager Console. ```console PS> Install-Package Akka.DependencyInjection ``` -------------------------------- ### Run Aggregate on Source Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/streams/custom-stream-processing.md This example demonstrates how to run an aggregate operation on a source, taking the first 100 elements and summing them up. Requires an ActorMaterializer. ```scala // Returns 5050 var result2Task = mySource.Take(100).RunAggregate(0, (sum, next) => sum + next, materializer); ``` -------------------------------- ### Build Documentation on Linux/OSX Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/community/contributing/documentation-guidelines.md Execute this command in the root of the Akka.NET repository to build the documentation on Linux or macOS. ```shell build.sh docfx ``` -------------------------------- ### Build a Specific Project Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/community/contributing/build-process.md To build a single project, provide its `.csproj` file path. Use `-c Release` for a release configuration. ```bash dotnet build src/core/Akka/Akka.csproj dotnet build src/core/Akka/Akka.csproj -c Release ``` -------------------------------- ### PersistentFSM Snapshotting Example Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/persistence/persistent-fsm.md Example of manually saving a snapshot of the FSM's state data. This is useful for optimizing recovery time. ```csharp Stop().Applying(OrderDiscarded.Instance).AndThen(cart => { reportActor.Tell(ShoppingCardDiscarded.Instance); SaveStateSnapshot(); }); ``` -------------------------------- ### Create ActorSystemSetup with Log Filtering Rules Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/utilities/logging.md Integrate custom logger setup with filtering rules into the `ActorSystemSetup` for programmatic ActorSystem configuration. ```csharp ActorSystemSetup completeSetup = CustomLoggerSetup(); ``` -------------------------------- ### Install markdownlint CLI Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/community/contributing/documentation-guidelines.md Installs markdownlint-cli and the titlecase rule globally using npm. This is required for running markdown linting checks locally. ```bash npm install -g markdownlint-cli@0.31.0 markdownlint-rule-titlecase@0.1.0 ``` -------------------------------- ### Obtaining Lease Implementation Reference Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/utilities/lease.md Demonstrates how to get a reference to a Lease implementation using LeaseProvider. Requires lease name, owner name, configuration path, and retry interval. ```csharp var leaseName = "my-distributed-lock"; var ownerName = "my-actor-or-node"; var configPath = "akka.coordination.lease.kubernetes"; // Or akka.coordination.lease.azure var retryInterval = TimeSpan.FromSeconds(5); var lease = LeaseProvider.Get(Context.System).GetLease(leaseName, ownerName, configPath, retryInterval); ``` -------------------------------- ### Constructing and Testing a Protocol Stack Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/streams/workingwithgraphs.md Demonstrates how to combine a codec and a framing BidiFlow to create a protocol stack. The stack is then tested by joining it with its inverse and a ping-pong flow, simulating a bidirectional communication. ```csharp /* construct protocol stack * +------------------------------------+ * | stack | * | | * | +-------+ +---------+ | * ~> O~~o | ~> | o~~O ~> * Message | | codec | ByteString | framing | | ByteString * <~ O~~o | <~ | o~~O <~ * | +-------+ +---------+ | * +------------------------------------+ */ var stack = codec.Atop(framing); // test it by plugging it into its own inverse and closing the right end var pingpong = Flow.Create().Collect(message => { var ping = message as Ping; return ping != null ? new Pong(ping.Id) as IMessage : null; }); var flow = stack.Atop(stack.Reversed()).Join(pingpong); var result = Source.From(Enumerable.Range(0, 10)) .Select(i => new Ping(i) as IMessage) .Via(flow) .Limit(20) .RunWith(Sink.Seq(), materializer); result.Wait(TimeSpan.FromSeconds(1)).Should().BeTrue(); result.Result.ShouldAllBeEquivalentTo(Enumerable.Range(0, 10)); ``` -------------------------------- ### Install Serilog Console Sink Package Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/utilities/serilog.md Install the Serilog.Sinks.Console NuGet package to direct log output to the console. This is a common sink for development and debugging. ```console PM> Install-Package Serilog.Sinks.Console ``` -------------------------------- ### Setting up Dependency Resolver and Actor System Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/actors/dependency-injection.md Illustrates the initial setup for integrating a DI container with Akka.NET using a custom `DependencyResolver`. This involves creating the DI container, the ActorSystem, and the resolver instance. ```csharp // Create your DI container of preference var someContainer = ... ; // Create the actor system var system = ActorSystem.Create("MySystem"); // Create the dependency resolver for the actor system IDependencyResolver resolver = new XyzDependencyResolver(someContainer, system); ``` -------------------------------- ### Intersperse Flow Operator (Start, Inject, End) Source: https://github.com/akkadotnet/akka.net/blob/dev/src/core/Akka.API.Tests/verify/CoreAPISpec.ApproveStreams.Net.verified.txt Intersperse elements with optional 'start', 'inject', and 'end' elements. This provides more control over the interspersed sequence. ```csharp public static Akka.Streams.Dsl.Flow Intersperse(this Akka.Streams.Dsl.Flow flow, TOut start, TOut inject, TOut end) { } ``` -------------------------------- ### Log Filter Setup Source: https://github.com/akkadotnet/akka.net/blob/dev/src/core/Akka.API.Tests/verify/CoreAPISpec.ApproveCore.DotNet.verified.txt Represents the setup for a log filter, containing an array of `LogFilterBase` objects. The `CreateEvaluator` method generates a `LogFilterEvaluator` based on these filters. ```csharp public LogFilterSetup(Akka.Event.LogFilterBase[] filters) { } ``` ```csharp public Akka.Event.LogFilterBase[] Filters { get; } ``` ```csharp public Akka.Event.LogFilterEvaluator CreateEvaluator() { } ``` -------------------------------- ### Create Console Host Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/deployment/console.md Sets up the Akka.NET actor system and the console application's entry point. It creates the actor system, spawns the `GreetingActor`, and sends it a `Greet` message. ```csharp public class Program { public static void Main(string[] args) { var system = ActorSystem.Create("HelloAkkaSystem"); var hello = system.ActorOf("hello"); hello.Tell(new Greet("World")); Console.CancelKeyPress += (sender, e) => system.Terminate(); system.WhenTerminated.Wait(); } } ``` -------------------------------- ### Example Serilog OutputTemplate Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/utilities/serilog.md An example of a Serilog OutputTemplate demonstrating the use of built-in properties like Timestamp, Level, ActorPath, SourceContext, Message, and Exception. ```console [{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] [{ActorPath}] [{SourceContext}] {Message}{NewLine}{Exception} ``` -------------------------------- ### PersistentFSM Side Effects Example Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/persistence/persistent-fsm.md Example of using the AndThen block to define side effects after an event is persisted. Note that these actions are not executed during recovery. ```csharp GoTo(Paid.Instance).Applying(DomainEvents.OrderExecuted).AndThen(cart => { if (cart is NonEmptyShoppingCart nonShoppingCart) { reportActor.Tell(new PurchaseWasMade(nonShoppingCart.Items)); } }); ``` -------------------------------- ### Actor System Setup and Message Sending Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/actors/receive-actor-api.md Sets up an Akka.NET ActorSystem and demonstrates sending messages to a `Swapper` actor to trigger its stacked behavior. Includes a `Console.ReadLine` to keep the application running. ```csharp static void Main(string[] args) { var system = ActorSystem.Create("MySystem"); var swapper = system.ActorOf(); swapper.Tell(Swapper.SWAP); swapper.Tell(Swapper.SWAP); swapper.Tell(Swapper.SWAP); swapper.Tell(Swapper.SWAP); swapper.Tell(Swapper.SWAP); swapper.Tell(Swapper.SWAP); Console.ReadLine(); } ``` -------------------------------- ### Starting a Subscriber Actor Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/clustering/distributed-publish-subscribe.md This code demonstrates how to start a subscriber actor within the Akka.NET cluster. It ensures the actor is properly initialized and ready to subscribe to topics. ```csharp public static class Program { public static void Main(string[] args) { var system = ActorSystem.Create("ClusterSystem"); system.ActorOf(Props.Create(() => new SampleSubscriber()), "subscriber"); Console.Read(); } } ``` -------------------------------- ### Akka.NET ActorSystem with Windsor Dependency Injection Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/actors/di-core.md Demonstrates setting up an ActorSystem with Windsor dependency injection, registering actors, and sending messages via a router. Ensure the Windsor container and dependency resolver are correctly configured before creating the ActorSystem. ```csharp IWindsorContainer container = new WindsorContainer(); container.Register(Component.For().ImplementedBy()); container.Register(Component.For().Named("TypedWorker").LifestyleTransient()); // Create the ActorSystem using (var system = ActorSystem.Create("MySystem")) { // Create the dependency resolver IDependencyResolver resolver = new WindsorDependencyResolver(container, system); // Register the actors with the system system.ActorOf(system.DI().Props(), "Worker1"); system.ActorOf(system.DI().Props(), "Worker2"); // Create the router IActorRef router = system.ActorOf(Props.Empty.WithRouter(new ConsistentHashingGroup(config))); // Create the message to send TypedActorMessage message = new TypedActorMessage { Id = 1, Name = Guid.NewGuid().ToString() }; // Send the message to the router router.Tell(message); } ``` -------------------------------- ### Create Props for Actors Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/actors/receive-actor-api.md Demonstrates various ways to create `Props` instances for actor creation, including specifying the actor type and passing constructor arguments. ```csharp Props props1 = Props.Create(typeof(MyActor)); Props props2 = Props.Create(() => new MyActorWithArgs("arg")); Props props3 = Props.Create(); Props props4 = Props.Create(typeof(MyActorWithArgs), "arg"); ``` -------------------------------- ### Loading and Using Service Discovery Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/discovery/index.md C# code demonstrating how to load the Akka.Discovery extension and perform a service lookup. ```APIDOC ## Loading and Using Service Discovery ```csharp using Akka.Actor; using Akka.Discovery; ... var system = ActorSystem.Create("example"); var serviceDiscovery = Discovery.Get(system).Default; ``` This code snippet shows how to get an instance of the default `ServiceDiscovery` implementation for an `ActorSystem`. ``` -------------------------------- ### Verify Local Machine Certificates Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/remoting/security.md List certificates installed in the local machine's 'My' certificate store. Useful for verifying if a certificate is correctly installed and accessible. ```powershell Get-ChildItem Cert:\LocalMachine\My ``` -------------------------------- ### Generate Documentation (FAKE to .NET CLI) Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/community/contributing/build-process.md Equivalent .NET CLI command for the FAKE build script 'build.cmd DocFx', used for generating documentation. ```bash dotnet docfx build ./docs/docfx.json ``` -------------------------------- ### Start Cluster Sharding Region Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/clustering/cluster-sharding.md Registers an actor type as a sharded entity and obtains an IActorRef to the shard region. Recommended to wait for the node to fully join the cluster before starting. ```csharp var region = await ClusterSharding.Get(system).StartAsync( typeName: "my-actor", entityPropsFactory: s => Props.Create(() => new MyActor(s)), settings: ClusterShardingSettings.Create(system), messageExtractor: new MessageExtractor()); region.Tell(new ShardEnvelope(shardId: 1, entityId: 1, message: "hello")) ``` -------------------------------- ### Start ProducerController with Durable Queue Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/actors/reliable-delivery.md This C# code demonstrates how to start a ProducerController using EventSourcedProducerQueue for durable message delivery. This ensures that unacknowledged messages are persisted to the Akka.Persistence Journal. ```csharp var producerId = "producer-1"; var producer = Context.ActorOf(Producer.Create(producerId, producerId, "consumer-1"), $"{producerId}-producer"); // Use EventSourcedProducerQueue for durable message delivery. // This will persist unacknowledged messages to the Akka.Persistence Journal. var producerController = Context.ActorOf( ProducerController.Create( producerId, producer, // Use EventSourcedProducerQueue for durable delivery. // This requires Akka.Persistence to be configured and referenced. EventSourcedProducerQueue.Create(producerId) ).WithProducerLogic(new MyProducerLogic()), $"{producerId}-producer-controller" ); ``` -------------------------------- ### Convert Flow to Processor and Run Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/streams/integration.md Demonstrates converting a Flow into a Processor and running it, allowing direct subscription to both the input publisher and the output subscriber. ```csharp var processor = authors.ToProcessor().Run(materializer); tweets.Subscribe(processor); processor.Subscribe(storage); ``` -------------------------------- ### Build Akka.NET Solution Source: https://github.com/akkadotnet/akka.net/blob/dev/CLAUDE.md Standard commands to build the Akka.NET solution. Use `-c Release` for release builds. Use `-warnaserror` for CI validation to treat warnings as errors. ```bash # Standard build dotnet build dotnet build -c Release ``` ```bash # Build with warnings as errors (CI validation) dotnet build -warnaserror ``` -------------------------------- ### Example At-Least-Once Delivery Actor Implementation Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/persistence/at-least-once-delivery.md An example implementation of an actor using at-least-once delivery. It demonstrates how to send messages, handle confirmations, and manage unconfirmed messages during recovery. ```csharp public class ExampleAtLeastOnceDeliveryReceiveActor : AtLeastOnceDeliveryReceiveActor { private readonly IActorRef _destination; public ExampleAtLeastOnceDeliveryReceiveActor(IActorRef destination) { _destination = destination; } protected override void OnReceive(object message) { switch (message) { case ExampleAtLeastOnceDeliveryActorMessages.Send send: // Use 'deliveryId' to correlate 'Deliver' and 'ConfirmDelivery' Deliver(_destination, msg => { // 'deliveryId' is automatically passed to the message mapper return new AtLeastOnceDeliveryActorMessages.MessageDelivered(msg.DeliveryId); }); break; case ExampleAtLeastOnceDeliveryActorMessages.MessageDelivered delivered: // Message has been confirmed by the destination actor ConfirmDelivery(delivered.DeliveryId); break; } } // Optional: Override to configure redelivery interval // public override RedeliverInterval RedeliverInterval => TimeSpan.FromSeconds(30); // Optional: Override to configure redelivery burst limit // public override RedeliveryBurstLimit RedeliveryBurstLimit => new RedeliveryBurstLimit(10); // Optional: Override to configure warning after a number of unconfirmed attempts // public override WarnAfterNumberOfUnconfirmedAttempts WarnAfterNumberOfUnconfirmedAttempts => new WarnAfterNumberOfUnconfirmedAttempts(10); } ``` -------------------------------- ### Create NuGet Packages (FAKE to .NET CLI) Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/community/contributing/build-process.md Equivalent .NET CLI command for the FAKE build script 'build.cmd nuget'. ```bash dotnet pack -c Release ``` -------------------------------- ### Start Cluster Sharding Proxy Source: https://github.com/akkadotnet/akka.net/blob/dev/docs/articles/clustering/cluster-sharding.md Starts a ShardRegionProxy to send messages to entities on a specific node without that node participating in sharding itself. Useful for clients or nodes that only consume sharded entities. ```csharp var proxy = ClusterSharding.Get(system).StartProxy( typeName: "my-actor", role: null, messageExtractor: new MessageExtractor()); ```