### Start a Local Orleans Silo Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/configuration-guide/local-development-configuration This example demonstrates how to build and start a local Orleans silo with specific configurations for development, including cluster and endpoint options. ```csharp public static async Task StartLocalSilo() { try { var host = await BuildAndStartSiloAsync(); Console.WriteLine("Press Enter to terminate..."); Console.ReadLine(); await host.StopAsync(); } catch (Exception ex) { Console.WriteLine(ex); } } static async Task BuildAndStartSiloAsync() { var host = new HostBuilder() .UseOrleans(builder => { builder.UseLocalhostClustering() .Configure(options => { options.ClusterId = "dev"; options.ServiceId = "MyAwesomeService"; }) .Configure( options => options.AdvertisedIPAddress = IPAddress.Loopback) .ConfigureLogging(logging => logging.AddConsole()); }) .Build(); await host.StartAsync(); return host; } ``` -------------------------------- ### Install Orleans Server Meta-Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Install the Orleans server meta-package for easily building and starting a silo. It includes several essential Orleans packages. ```powershell Install-Package Microsoft.Orleans.Server ``` -------------------------------- ### Generic Stream Subscription Setup Source: https://learn.microsoft.com/en-us/dotnet/orleans/streaming/streams-programming-apis A generic C# example showing the core logic for obtaining a stream and subscribing an observer. This pattern is fundamental for integrating with Orleans Streams, allowing grains to process events from various sources. ```csharp IStreamProvider streamProvider = base.GetStreamProvider("SimpleStreamProvider"); IAsyncStream stream = streamProvider.GetStream(this.GetPrimaryKey(), "MyStreamNamespace"); StreamSubscriptionHandle subscription = await stream.SubscribeAsync(IAsyncObserver); ``` -------------------------------- ### Install Orleans Google Utilities Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the Google Protocol Buffers serializer. ```powershell Install-Package Microsoft.Orleans.OrleansGoogleUtils ``` -------------------------------- ### Install Orleans protobuf-net Serializer Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the protobuf-net version of the Protocol Buffers serializer. ```powershell Install-Package Microsoft.Orleans.ProtobufNet ``` -------------------------------- ### Install Orleans Testing Host Library Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the library for hosting silos and clients in a testing project. ```powershell Install-Package Microsoft.Orleans.TestingHost ``` -------------------------------- ### Install Aspire CLI (macOS/Linux) Source: https://learn.microsoft.com/en-us/dotnet/orleans/deployment/deploy-to-azure-container-apps Installs the .NET Aspire CLI on macOS and Linux using Bash. ```bash curl -sSL https://aspire.dev/install.sh | bash ``` -------------------------------- ### Install Aspire CLI (Windows) Source: https://learn.microsoft.com/en-us/dotnet/orleans/deployment/deploy-to-azure-container-apps Installs the .NET Aspire CLI on Windows using PowerShell. ```powershell irm https://aspire.dev/install.ps1 | iex ``` -------------------------------- ### Run the Silo Application Source: https://learn.microsoft.com/en-us/dotnet/orleans/tutorials-and-samples/tutorial-1 Execute this command from the Silo's project directory to start the Silo. Ensure the Silo is running before starting the client. ```bash dotnet run ``` -------------------------------- ### Install Orleans Telemetry Consumer - NewRelic Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the telemetry consumer for NewRelic. ```powershell Install-Package Microsoft.Orleans.OrleansTelemetryConsumers.NewRelic ``` -------------------------------- ### Install Orleans Bond Serializer Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs support for the Bond serializer. ```powershell Install-Package Microsoft.Orleans.Serialization.Bond ``` -------------------------------- ### Install Cosmos DB Persistence Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/grains/grain-persistence Install the Microsoft.Orleans.Persistence.Cosmos NuGet package using the .NET CLI. ```.NET CLI dotnet add package Microsoft.Orleans.Persistence.Cosmos ``` -------------------------------- ### Build Orleans Client with ClientBuilder Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/client This example shows how to programmatically build an Orleans client using ClientBuilder. It configures cluster options, Azure Storage clustering, and application parts, which is useful for more complex client setups. ```csharp var client = new ClientBuilder() .Configure(options => { options.ClusterId = "my-first-cluster"; options.ServiceId = "MyOrleansService"; }) .UseAzureStorageClustering( options => options.ConfigureTableServiceClient(connectionString)) .ConfigureApplicationParts( parts => parts.AddApplicationPart(typeof(IValueGrain).Assembly)) .Build(); ``` -------------------------------- ### Install Orleans Providers Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs in-memory persistence and stream providers for testing. Not recommended for production unless data loss is acceptable. ```powershell Install-Package Microsoft.Orleans.OrleansProviders ``` -------------------------------- ### Install ADO.NET Persistence Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/grains/grain-persistence/relational-storage Install the base package for ADO.NET grain persistence using PowerShell. ```powershell Install-Package Microsoft.Orleans.Persistence.AdoNet ``` -------------------------------- ### Install Orleans Event Sourcing Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs base types for creating event-sourced grain classes. ```powershell Install-Package Microsoft.Orleans.EventSourcing ``` -------------------------------- ### Install Orleans Google Cloud Platform Utilities Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the NuGet package that includes the stream provider for GCP PubSub service. ```powershell Install-Package Microsoft.Orleans.OrleansGCPUtils ``` -------------------------------- ### Install ADO.NET Grain Directory NuGet Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/grain-directory Install the necessary NuGet package for the ADO.NET grain directory using the .NET CLI. ```bash dotnet add package Microsoft.Orleans.GrainDirectory.AdoNet ``` -------------------------------- ### Implementing IGrainMigrationParticipant Directly Source: https://learn.microsoft.com/en-us/dotnet/orleans/grains/grain-lifecycle Example of a grain implementing IGrainMigrationParticipant to manually save and restore its custom state during migration. ```csharp public class MyMigratableGrain : Grain, IMyGrain, IGrainMigrationParticipant { private int _cachedValue; private string _sessionData; public void OnDehydrate(IDehydrationContext dehydrationContext) { // Save state before migration dehydrationContext.TryAddValue("cached", _cachedValue); dehydrationContext.TryAddValue("session", _sessionData); } public void OnRehydrate(IRehydrationContext rehydrationContext) { // Restore state after migration rehydrationContext.TryGetValue("cached", out _cachedValue); rehydrationContext.TryGetValue("session", out _sessionData); } } ``` -------------------------------- ### Install Orleans Telemetry Consumer - Performance Counters Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the Windows Performance Counters implementation of the Orleans Telemetry API. ```powershell Install-Package Microsoft.Orleans.OrleansTelemetryConsumers.Counters ``` -------------------------------- ### Add Kubernetes Hosting Integration Source: https://learn.microsoft.com/en-us/dotnet/orleans/deployment/kubernetes Install the Aspire.Hosting.Kubernetes NuGet package in your AppHost project to enable Kubernetes deployment. ```bash dotnet add package Aspire.Hosting.Kubernetes ``` -------------------------------- ### Install Microsoft.Orleans.Client NuGet Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/configuration-guide/local-development-configuration Use this PowerShell command to install the necessary NuGet package for Orleans client development. This package includes essential components for building and running Orleans clients. ```powershell Install-Package Microsoft.Orleans.Client ``` -------------------------------- ### Add Cassandra Clustering NuGet Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/implementation/cluster-management Install the Microsoft.Orleans.Clustering.Cassandra NuGet package using the .NET CLI. ```bash dotnet add package Microsoft.Orleans.Clustering.Cassandra ``` -------------------------------- ### Example AWS Credentials File with Named Profile Source: https://learn.microsoft.com/en-us/dotnet/orleans/grains/grain-persistence/dynamodb-storage This is an example of an AWS credentials file format that includes a named profile. It shows the structure for storing access key, secret key, and security token. ```bash [YOUR_PROFILE_NAME] aws_access_key_id = *** aws_secret_access_key = *** aws_security_token = *** aws_session_expiration = *** aws_session_token = *** ``` -------------------------------- ### Registering a Startup Task with Silo Builder Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/silo-lifecycle Demonstrates how to register a startup task with the silo builder, specifying the initialization logic and the lifecycle stage at which it should run. ```csharp siloBuilder.AddStartupTask( async (serviceProvider, cancellationToken) => { var logger = serviceProvider.GetRequiredService>(); logger.LogInformation("Silo is starting up..."); // Perform initialization logic, such as warming caches or validating configuration var config = serviceProvider.GetRequiredService(); await ValidateExternalDependenciesAsync(config, cancellationToken); }, ServiceLifecycleStage.Active); ``` -------------------------------- ### Initialize Orleans URL Shortener Sample Source: https://learn.microsoft.com/en-us/dotnet/orleans/quickstarts/deploy-scale-orleans-on-azure Get the sample Orleans URL shortener application using the AZD template. This command initializes the project with the specified template. ```bash azd init --template orleans-url-shortener ``` -------------------------------- ### Get Orleans Stream Provider and Stream (StreamProvider) Source: https://learn.microsoft.com/en-us/dotnet/orleans/streaming/streams-quick-start Obtain a stream provider configured with 'StreamProvider' and get a reference to a specific stream identified by a GUID and namespace. ```csharp var guid = new Guid("some guid identifying the chat room"); var streamProvider = GetStreamProvider("StreamProvider"); var streamId = StreamId.Create("RANDOMDATA", guid); var stream = streamProvider.GetStream(streamId); ``` -------------------------------- ### Deploy Azure Resources and Sample Application Source: https://learn.microsoft.com/en-us/dotnet/orleans/quickstarts/deploy-scale-orleans-on-azure Deploy the Azure Cosmos DB for NoSQL account and a sample web application using AZD. This command provisions the necessary Azure resources. ```bash azd up ``` -------------------------------- ### Get Orleans Stream Provider and Stream (SMSProvider) Source: https://learn.microsoft.com/en-us/dotnet/orleans/streaming/streams-quick-start Obtain a stream provider configured with 'SMSProvider' and get a reference to a specific stream identified by a GUID and a stream name. ```csharp var guid = new Guid("some guid identifying the chat room"); var streamProvider = GetStreamProvider("SMSProvider"); var stream = streamProvider.GetStream(guid, "RANDOMDATA"); ``` -------------------------------- ### Get Stream Provider and Stream Handle Source: https://learn.microsoft.com/en-us/dotnet/orleans/streaming/streams-programming-apis Obtain a stream provider and a handle to an asynchronous stream within a grain. This is the starting point for interacting with Orleans streams. ```C# public async Task SetupStream() { IStreamProvider streamProvider = this.GetStreamProvider("SimpleStreamProvider"); StreamId streamId = StreamId.Create("MyStreamNamespace", this.GetPrimaryKey()); IAsyncStream stream = streamProvider.GetStream(streamId); } ``` -------------------------------- ### Add and Map Orleans Dashboard Source: https://learn.microsoft.com/en-us/dotnet/orleans/dashboard Basic setup to add Orleans Dashboard services and map its endpoints to the application. This is the minimum required to get the dashboard running. ```csharp using Orleans.Dashboard; var builder = WebApplication.CreateBuilder(args); // Configure Orleans with the dashboard builder.UseOrleans(siloBuilder => { siloBuilder.UseLocalhostClustering(); siloBuilder.AddMemoryGrainStorageAsDefault(); // Add the dashboard services siloBuilder.AddDashboard(); }); var app = builder.Build(); // Map dashboard endpoints at the root path app.MapOrleansDashboard(); app.Run(); ``` -------------------------------- ### Register a Startup Task Delegate Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/configuration-guide/startup-tasks Register a delegate as a startup task using the AddStartupTask extension method on ISiloBuilder. This is useful for simple, inline initialization logic. ```csharp siloBuilder.AddStartupTask( async (IServiceProvider services, CancellationToken cancellation) => { var grainFactory = services.GetRequiredService(); var grain = grainFactory.GetGrain("startup-task-grain"); await grain.Initialize(); }); ``` -------------------------------- ### Install Orleans Code Generator Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the runtime code generator for Orleans. ```powershell Install-Package Microsoft.Orleans.OrleansCodeGenerator ``` -------------------------------- ### Navigate to Web Project Directory Source: https://learn.microsoft.com/en-us/dotnet/orleans/quickstarts/deploy-scale-orleans-on-azure Change the current working directory to the web project's source folder before installing NuGet packages. ```bash cd ./src/web ``` -------------------------------- ### Configure Separate Silo and Client Projects in AppHost Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/aspire-integration Set up an AppHost for separate Orleans silo and client projects. The client is configured using `.AsClient()` for a client-only reference, and waits for the silo. ```csharp public static void SeparateSiloAndClient(string[] args) { var builder = DistributedApplication.CreateBuilder(args); var redis = builder.AddRedis("orleans-redis"); var orleans = builder.AddOrleans("cluster") .WithClustering(redis) .WithGrainStorage("Default", redis); // Backend Orleans silo cluster var silo = builder.AddProject("backend") .WithReference(orleans) .WaitFor(redis) .WithReplicas(5); // Frontend web project as Orleans client builder.AddProject("frontend") .WithReference(orleans.AsClient()) // Client-only reference .WaitFor(silo); builder.Build().Run(); } ``` -------------------------------- ### Configure Multiple Stream Providers (Connection String) Source: https://learn.microsoft.com/en-us/dotnet/orleans/streaming/streams-programming-apis Sets up memory streams, Azure Queue streams with a connection string, and Azure Table storage for Pub-Sub. Replace "" with your actual connection strings. ```csharp hostBuilder.UseOrleans(siloBuilder =>\n{\n siloBuilder.AddMemoryStreams("StreamProvider")\n .AddAzureQueueStreams("AzureQueueProvider",\n optionsBuilder => optionsBuilder.ConfigureAzureQueue(\n options => options.Configure(\n opt => opt.QueueServiceClient = new QueueServiceClient(connectionString))))\n .AddAzureTableGrainStorage("PubSubStore",\n options => options.TableServiceClient = new TableServiceClient(connectionString));\n}); ``` -------------------------------- ### StartupTask Implementation for Silo Lifecycle Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/silo-lifecycle A concrete implementation of ILifecycleParticipant that subscribes a given startup task to a specific stage of the silo lifecycle. ```csharp class StartupTask : ILifecycleParticipant { private readonly IServiceProvider _serviceProvider; private readonly Func _startupTask; private readonly int _stage; public StartupTask( IServiceProvider serviceProvider, Func startupTask, int stage) { _serviceProvider = serviceProvider; _startupTask = startupTask; _stage = stage; } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe( _stage, cancellation => _startupTask(_serviceProvider, cancellation)); } } ``` -------------------------------- ### Register IHostedService Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/configuration-guide/startup-tasks Register an IHostedService implementation with the dependency injection container to have it automatically started when the host starts. ```csharp builder.Services.AddHostedService(); ``` -------------------------------- ### Deploy with Parameters File Source: https://learn.microsoft.com/en-us/dotnet/orleans/deployment/deploy-to-azure-container-apps Deploys your application to Azure Container Apps using parameters defined in a JSON file. ```bash aspire deploy --deployment-params-file deployment-params.json ``` -------------------------------- ### Implementing IGrainBase with Lifecycle Methods Source: https://learn.microsoft.com/en-us/dotnet/orleans/migration-guide This example shows a grain class implementing IGrainBase and overriding OnActivateAsync and OnDeactivateAsync to participate in the grain's lifecycle. It includes logging for activation and deactivation events. ```csharp public sealed class PingGrain : IGrainBase, IPingGrain { private readonly ILogger _logger; public PingGrain(IGrainContext context, ILogger logger) { _logger = logger; GrainContext = context; } public IGrainContext GrainContext { get; } public Task OnActivateAsync(CancellationToken cancellationToken) { _logger.LogInformation("OnActivateAsync()"); return Task.CompletedTask; } public Task OnDeactivateAsync(DeactivationReason reason, CancellationToken token) { _logger.LogInformation("OnDeactivateAsync({Reason})", reason); return Task.CompletedTask; } public ValueTask Ping() => ValueTask.CompletedTask; } ``` -------------------------------- ### Install Orleans Reminders DynamoDB Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the NuGet package for using AWS DynamoDB to persist reminders. ```powershell Install-Package Microsoft.Orleans.Reminders.DynamoDB ``` -------------------------------- ### Install Orleans Runtime Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the core Orleans runtime package. This is a fundamental package for any Orleans project. ```powershell Install-Package Microsoft.Orleans.OrleansRuntime ``` -------------------------------- ### Extended Orleans Client Example with Grain Interaction and Observers Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/client Demonstrates a client application connecting to Orleans, finding a player account, subscribing to game session updates using an observer, and handling potential exceptions during the process. Requires Azure Storage for clustering. ```C# try { using IHost host = Host.CreateDefaultBuilder(args) .UseOrleansClient((context, client) => { client.Configure(options => { options.ClusterId = "my-first-cluster"; options.ServiceId = "MyOrleansService"; }) .UseAzureStorageClustering( options => options.TableServiceClient = new TableServiceClient( context.Configuration["ORLEANS_AZURE_STORAGE_CONNECTION_STRING"])); }) .UseConsoleLifetime() .Build(); await host.StartAsync(); IGrainFactory client = host.Services.GetRequiredService(); // Hardcoded player ID Guid playerId = new("{2349992C-860A-4EDA-9590-000000000006}"); IPlayerGrain player = client.GetGrain(playerId); IGameGrain? game = null; while (game is null) { Console.WriteLine( $"Getting current game for player {playerId}..."); try { game = await player.GetCurrentGame(); if (game is null) // Wait until the player joins a game { await Task.Delay(TimeSpan.FromMilliseconds(5_000)); } } catch (Exception ex) { Console.WriteLine($"Exception: {ex.GetBaseException()}"); } } Console.WriteLine( $"Subscribing to updates for game {game.GetPrimaryKey()}..."); // Subscribe for updates var watcher = new GameObserver(); await game.ObserveGameUpdates( client.CreateObjectReference(watcher)); Console.WriteLine( "Subscribed successfully. Press to stop."); } catch (Exception e) { Console.WriteLine( $"Unexpected Error: {e.GetBaseException()}"); } ``` -------------------------------- ### Implement Custom Partition Key Provider Source: https://learn.microsoft.com/en-us/dotnet/orleans/grains/grain-persistence Implement the IPartitionKeyProvider interface to define custom logic for determining the partition key for grains. ```C# public class MyPartitionKeyProvider : IPartitionKeyProvider { public ValueTask GetPartitionKey(string grainType, GrainId grainId) { // Custom logic to determine partition key return new ValueTask(grainId.Key.ToString()!); } } ``` -------------------------------- ### Install Orleans Telemetry Consumer - Azure Application Insights Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the telemetry consumer for Azure Application Insights. ```powershell Install-Package Microsoft.Orleans.OrleansTelemetryConsumers.AI ``` -------------------------------- ### Initializing Storage and JSON Settings Source: https://learn.microsoft.com/en-us/dotnet/orleans/tutorials-and-samples/custom-grain-storage The Init function configures JSON serializer settings and creates the state storage directory if it doesn't exist. ```csharp private Task Init(CancellationToken ct) { // Settings could be made configurable from Options. _jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings( OrleansJsonSerializer.GetDefaultSerializerSettings( _typeResolver, _grainFactory), false, false, null); var directory = new DirectoryInfo(_options.RootDirectory); if (!directory.Exists) directory.Create(); return Task.CompletedTask; } ``` -------------------------------- ### Install Orleans Streaming Azure Storage Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the NuGet package that includes the stream provider for Azure Queues. ```powershell Install-Package Microsoft.Orleans.Streaming.AzureStorage ``` -------------------------------- ### Install Orleans ServiceBus Utilities Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the NuGet package that includes the stream provider for Azure Event Hubs. ```powershell Install-Package Microsoft.Orleans.OrleansServiceBus ``` -------------------------------- ### Connect Orleans Client to a Local Silo Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/configuration-guide/local-development-configuration This C# example demonstrates how to build and connect an Orleans client to a local silo. It configures the client with a specific cluster and service ID, enables console logging, and establishes a connection. ```csharp public static async Task StartLocalClient() { var client = new ClientBuilder() .UseLocalhostClustering() .Configure(options => { options.ClusterId = "dev"; options.ServiceId = "MyAwesomeService"; }) .ConfigureLogging(logging => logging.AddConsole()) .Build(); await client.Connect(); } ``` -------------------------------- ### Install Orleans Persistence DynamoDB Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the NuGet package for using AWS DynamoDB to persist grain state. ```powershell Install-Package Microsoft.Orleans.Persistence.DynamoDB ``` -------------------------------- ### Using Task.Factory.StartNew with a Custom Scheduler in Orleans Source: https://learn.microsoft.com/en-us/dotnet/orleans/grains/external-tasks-and-grains Demonstrates escaping the Orleans task scheduler using `Task.Factory.StartNew` with a custom scheduler and returning to the Orleans context. ```csharp public async Task MyGrainMethod() { // Grab the grain's task scheduler var orleansTS = TaskScheduler.Current; await Task.Delay(10_000); // Current task scheduler did not change, the code after await is still running // in the same task scheduler. Assert.AreEqual(orleansTS, TaskScheduler.Current); Task t1 = Task.Run(() => { // This code runs on the thread pool scheduler, not on Orleans task scheduler Assert.AreNotEqual(orleansTS, TaskScheduler.Current); Assert.AreEqual(TaskScheduler.Default, TaskScheduler.Current); }); await t1; // We are back to the Orleans task scheduler. // Since await was executed in Orleans task scheduler context, we are now back // to that context. Assert.AreEqual(orleansTS, TaskScheduler.Current); // Example of using Task.Factory.StartNew with a custom scheduler to escape from // the Orleans scheduler Task t2 = Task.Factory.StartNew(() => { // This code runs on the MyCustomSchedulerThatIWroteMyself scheduler, not on // the Orleans task scheduler Assert.AreNotEqual(orleansTS, TaskScheduler.Current); Assert.AreEqual(MyCustomSchedulerThatIWroteMyself, TaskScheduler.Current); }, CancellationToken.None, TaskCreationOptions.None, scheduler: MyCustomSchedulerThatIWroteMyself); await t2; // We are back to Orleans task scheduler. Assert.AreEqual(orleansTS, TaskScheduler.Current); } ``` -------------------------------- ### Install Orleans Reminders ADO.NET Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the NuGet package for using ADO.NET to persist reminders in supported databases. ```powershell Install-Package Microsoft.Orleans.Reminders.AdoNet ``` -------------------------------- ### Install Orleans Reminders Azure Storage Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the NuGet package for using Azure Tables to persist reminders. ```powershell Install-Package Microsoft.Orleans.Reminders.AzureStorage ``` -------------------------------- ### Initiate a Grain Call Sequence Source: https://learn.microsoft.com/en-us/dotnet/orleans/grains/request-scheduling Demonstrates how a client can obtain grain references and initiate a call sequence using the grain factory. This example shows a simple one-way call from grain A to grain B. ```csharp var a = grainFactory.GetGrain("A"); var b = grainFactory.GetGrain("B"); await a.CallOther(b); ``` -------------------------------- ### Install Orleans Transactions Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Use this command to install the Orleans Transactions package, which includes support for cross-grain transactions (beta). ```powershell Install-Package Microsoft.Orleans.Transactions ``` -------------------------------- ### Configure and Run Client Source: https://learn.microsoft.com/en-us/dotnet/orleans/tutorials-and-samples/tutorial-1 Sets up the client to connect to the Orleans cluster and invoke grain operations. It mirrors the silo's clustering configuration and retrieves a grain reference to send a message. ```csharp using Microsoft.Extensions.Logging; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using GrainInterfaces; IHostBuilder builder = Host.CreateDefaultBuilder(args) .UseOrleansClient(client => { client.UseLocalhostClustering(); }) .ConfigureLogging(logging => logging.AddConsole()) .UseConsoleLifetime(); using IHost host = builder.Build(); await host.StartAsync(); IClusterClient client = host.Services.GetRequiredService(); IHello friend = client.GetGrain(0); string response = await friend.SayHello("Hi friend!"); Console.WriteLine($""" {response} Press any key to exit... """); Console.ReadKey(); await host.StopAsync(); ``` -------------------------------- ### Install Orleans Streaming AWS SQS Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the NuGet package that includes the stream provider for AWS SQS service. ```powershell Install-Package Microsoft.Orleans.Streaming.SQS ``` -------------------------------- ### Silo Startup Confirmation Source: https://learn.microsoft.com/en-us/dotnet/orleans/tutorials-and-samples/tutorial-1 This message indicates that the Silo has successfully started and is ready to accept client connections. Press Ctrl+C to shut down. ```text Application started. Press Ctrl+C to shut down. ``` -------------------------------- ### Install Orleans Persistence ADO.NET Package Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Installs the NuGet package for using ADO.NET to persist grain state in supported databases. ```powershell Install-Package Microsoft.Orleans.Persistence.AdoNet ``` -------------------------------- ### Configure Initialization-Time Code Generation with Logging Source: https://learn.microsoft.com/en-us/dotnet/orleans/grains/code-generation This snippet demonstrates how to configure initialization-time code generation with logging enabled. It includes setting up an ILoggerFactory and passing it to the WithCodeGeneration method. ```csharp public static void ConfigureWithCodeGenerationLogging(ISiloHostBuilder builder) { ILoggerFactory codeGenLoggerFactory = new LoggerFactory(); codeGenLoggerFactory.AddProvider(new ConsoleLoggerProvider()); builder.ConfigureApplicationParts( parts => parts .AddApplicationPart(typeof(IRuntimeCodeGenGrain).Assembly) .WithCodeGeneration(codeGenLoggerFactory)); } ``` -------------------------------- ### Implement a Hello World Grain Source: https://learn.microsoft.com/en-us/dotnet/orleans/tutorials-and-samples/overview-helloworld This C# code defines the 'HelloGrain' class, which implements the 'IHello' interface. It includes a constructor for dependency injection of an ILogger and a method to handle the 'SayHello' request, logging the received greeting and returning a formatted response. ```csharp public class HelloGrain : Orleans.Grain, IHello { private readonly ILogger _logger; public HelloGrain(ILogger logger) => _logger = logger; Task IHello.SayHello(string greeting) { _logger.LogInformation("SayHello message received: greeting = '{Greeting}'", greeting); return Task.FromResult($"You said: '{greeting}', I say: Hello!"); } } ``` -------------------------------- ### Install Orleans Core Abstractions Source: https://learn.microsoft.com/en-us/dotnet/orleans/resources/nuget-packages Install the core abstractions package for Orleans. This package is required for projects defining grain interfaces and classes. ```powershell Install-Package Microsoft.Orleans.Core.Abstractions ``` -------------------------------- ### Build and Connect Orleans Client with Azure Storage Clustering Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/configuration-guide/client-configuration Demonstrates building an Orleans client using ClientBuilder, configuring it with Azure Storage clustering, and connecting to the cluster. It also shows how to configure application parts. ```C# public static async Task ConfigureClient(string connectionString) { var client = new ClientBuilder() .Configure(options => { options.ClusterId = "my-first-cluster"; options.ServiceId = "MyOrleansService"; }) .UseAzureStorageClustering( options => options.ConfigureTableServiceClient(connectionString)) .ConfigureApplicationParts( parts => parts.AddApplicationPart( typeof(IValueGrain).Assembly)) .Build(); await client.Connect(); } ``` -------------------------------- ### Configure Basic Orleans Cluster with Redis Clustering in AppHost Source: https://learn.microsoft.com/en-us/dotnet/orleans/host/aspire-integration Set up a basic Orleans cluster in your AppHost, using Redis for clustering. This example configures a 3-replica silo. ```csharp public static void BasicOrleansCluster(string[] args) { var builder = DistributedApplication.CreateBuilder(args); // Add Redis for Orleans clustering var redis = builder.AddRedis("orleans-redis"); // Define the Orleans resource with Redis clustering var orleans = builder.AddOrleans("cluster") .WithClustering(redis); // Add the Orleans silo project builder.AddProject("silo") .WithReference(orleans) .WaitFor(redis) .WithReplicas(3); builder.Build().Run(); } ``` -------------------------------- ### Sign in to Azure Source: https://learn.microsoft.com/en-us/dotnet/orleans/deployment/deploy-to-azure-container-apps Authenticates the Azure CLI with your Azure account. ```bash az login ```