### Manually Build DaprClient (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Provides an example of manually creating and configuring a `DaprClient` instance using the `DaprClientBuilder`. It highlights best practices such as creating a single, long-lived instance for performance and thread-safety. ```csharp var daprClient = new DaprClientBuilder() .UseJsonSerializerSettings( ... ) // Configure JSON serializer .Build(); ``` -------------------------------- ### Registering Dependency Injection Services Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Provides an example of how to register custom types, like 'BankService', with the dependency injection container in 'Startup.cs'. This makes the registered types available for injection into actors and other services. ```csharp // In Startup.cs public void ConfigureServices(IServiceCollection services) { ... // Register additional types with dependency injection. services.AddSingleton(); } ``` -------------------------------- ### Query State using DaprClient (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Provides an example of querying state using the Dapr .NET SDK. It constructs a JSON query string with filter and sort criteria, then uses DaprClient to execute the query against a specified state store. The results are iterated, and account data is printed. ```.cs var query = "{" + "\"filter\": {" + "\"EQ\": { \"value.Id\": \"1\" }" + "}," + "\"sort\": [" + "{\"key\": \"value.Balance\", ``` -------------------------------- ### Get Configuration Keys with Dapr .NET SDK Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Shows how to retrieve specific configuration keys or all configuration items from a Dapr configuration store. It utilizes the DaprClient to fetch configuration by store name and a list of keys. An empty list retrieves all items. ```csharp var client = new DaprClientBuilder().Build(); // Retrieve a specific set of keys. var specificItems = await client.GetConfiguration("configstore", new List() { "key1", "key2" }); Console.WriteLine($"Here are my values:\n{specificItems[0].Key} -> {specificItems[0].Value}\n{specificItems[1].Key} -> {specificItems[1].Value}"); // Retrieve all configuration items by providing an empty list. var specificItems = await client.GetConfiguration("configstore", new List()); Console.WriteLine($"I got {configItems.Count} entires!"); foreach (var item in configItems) { Console.WriteLine($"{item.Key} -> {item.Value}") } ``` -------------------------------- ### Interact with Output Bindings using DaprClient (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Shows how to interact with Dapr output bindings using the .NET SDK. This example demonstrates invoking a "send-email" binding, likely for sending emails via a service like SendGrid. It includes constructing a payload with metadata and data relevant to the binding operation. ```.cs using var client = new DaprClientBuilder().Build(); // Example payload for the Twilio SendGrid binding var email = new { metadata = new { emailTo = "customer@example.com", subject = "An email from Dapr SendGrid binding", }, data = "

Testing Dapr Bindings

This is a test.
Bye!"; }; await client.InvokeBindingAsync("send-email", "create", email); ``` -------------------------------- ### Dependency Injection Setup Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/dotnet-daprclient-usage Registering DaprClient with ASP.NET Core's dependency injection container. This example shows the basic registration and an example with custom configuration. ```APIDOC ## Dependency Injection Setup ### Description Register the `DaprClient` with ASP.NET Core dependency injection. The `AddDaprClient()` method can take an optional configuration delegate for `DaprClientBuilder` and a `ServiceLifetime` argument. ### Method `services.AddDaprClient()` ### Endpoint N/A (Dependency Injection) ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```csharp // Basic registration services.AddDaprClient(); // With custom configuration services.AddDaprClient(daprBuilder => { daprBuilder.UseJsonSerializerOptions(new JsonSerializerOptions { WriteIndented = true, MaxDepth = 8 }); daprBuilder.UseTimeout(TimeSpan.FromSeconds(30)); }); // Advanced configuration with IServiceProvider services.AddSingleton(); services.AddDaprClient((serviceProvider, daprBuilder) => { var sampleService = serviceProvider.GetRequiredService(); var timeoutValue = sampleService.TimeoutOptions; daprBuilder.UseTimeout(timeoutValue); }); ``` ### Response #### Success Response (200) N/A (Configuration, not a request/response) #### Response Example None ``` -------------------------------- ### Configure DaprClient with Options Delegate (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Shows how to configure the `DaprClient` during dependency injection registration using an options delegate. This allows customization of `DaprClientBuilder` settings like JSON serialization options and timeouts. ```csharp services.AddDaprClient(daprBuilder => { daprBuilder.UseJsonSerializerOptions(new JsonSerializerOptions { WriteIndented = true, MaxDepth = 8 }); daprBuilder.UseTimeout(TimeSpan.FromSeconds(30)); }); ``` -------------------------------- ### Basic Actor with ActorHost Constructor Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Illustrates the fundamental structure of an actor class in Dapr using the .NET SDK. It shows how to accept and pass the ActorHost to the base class constructor, which is a mandatory requirement for all actors. ```csharp internal class MyActor : Actor, IMyActor, IRemindable { public MyActor(ActorHost host) // Accept ActorHost in the constructor : base(host) // Pass ActorHost to the base class constructor { } } ``` -------------------------------- ### Save, Get, and Delete State using DaprClient (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Demonstrates the basic state management operations using the Dapr .NET SDK. It shows how to save a state object (Widget) with a specific key, retrieve it, and then delete it. The code uses DaprClient to interact with a configured state store. ```.cs var client = new DaprClientBuilder().Build(); var state = new Widget() { Size = "small", Color = "yellow", }; await client.SaveStateAsync(storeName, stateKeyName, state, cancellationToken: cancellationToken); Console.WriteLine("Saved State!"); state = await client.GetStateAsync(storeName, stateKeyName, cancellationToken: cancellationToken); Console.WriteLine($"Got State: {state.Size} {state.Color}"); await client.DeleteStateAsync(storeName, stateKeyName, cancellationToken: cancellationToken); Console.WriteLine("Deleted State!"); ``` -------------------------------- ### Invoke Service via gRPC using DaprClient (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Shows how to invoke a service over gRPC using the Dapr .NET SDK. It involves creating an invocation invoker for a specific Dapr app ID and endpoint, then using it to create a gRPC client. An example of making a gRPC method call with CallOptions, including a deadline, is provided. ```.cs using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(20)); var invoker = DaprClient.CreateInvocationInvoker(appId: myAppId, daprEndpoint: serviceEndpoint); var client = new MyService.MyServiceClient(invoker); var options = new CallOptions(cancellationToken: cts.Token, deadline: DateTime.UtcNow.AddSeconds(1)); await client.MyMethodAsync(new Empty(), options); Assert.Equal(StatusCode.DeadlineExceeded, ex.StatusCode); ``` -------------------------------- ### Navigate to Dapr Jobs Example Directory Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-jobs/_print Navigates to the Dapr Jobs example directory within the cloned Dapr .NET SDK repository. This is necessary to access the sample code for Dapr Jobs. ```bash cd examples/Jobs ``` -------------------------------- ### Install .NET Aspire Project Templates via CLI Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-integrations/dotnet-development-dapr-aspire This command installs the necessary templates for creating new .NET Aspire applications. Ensure you have the .NET SDK installed. ```bash dotnet new install Aspire.ProjectTemplates ``` -------------------------------- ### Navigate to Dapr PubSub Example Directory Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-messaging/dotnet-messaging-pubsub-howto Navigates into the Dapr streaming PubSub example directory within the cloned .NET SDK repository. This sets the context for subsequent commands. ```bash cd examples/Client/PublishSubscribe ``` -------------------------------- ### Navigate to Dapr Workflow Example Directory Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-workflow/dotnet-workflow-howto Changes the current directory to the Dapr Workflow example within the cloned .NET SDK repository. This prepares the environment for running the example. ```bash cd examples/Workflow ``` -------------------------------- ### Navigate to JobsSample Directory Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-jobs/_print Navigates to the JobsSample directory, which contains the specific Dapr application example for demonstrating Dapr Jobs. ```bash cd JobsSample ``` -------------------------------- ### Structured Logging in Actors Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Illustrates the recommended way to perform logging within Dapr actors using structured logging with named placeholders. This approach enhances performance and integration with logging systems compared to traditional string formatting. ```csharp public Task GetDataAsync() { this.Logger.LogInformation("Getting state at {CurrentTime}", DateTime.UtcNow); return this.StateManager.GetStateAsync("my_data"); } ``` -------------------------------- ### Register DaprClient with Dependency Injection (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Demonstrates registering the `DaprClient` with ASP.NET Core's dependency injection container using `services.AddDaprClient()`. This allows for easy injection of the Dapr client throughout the application. ```csharp services.AddDaprClient(); ``` -------------------------------- ### Configure DaprClient with ServiceProvider and Options Delegate (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Illustrates advanced configuration of `DaprClient` during dependency injection registration. This overload provides access to both the `DaprClientBuilder` and `IServiceProvider`, enabling configurations that depend on other registered services. ```csharp services.AddSingleton(); services.AddDaprClient((serviceProvider, daprBuilder) => { var sampleService = serviceProvider.GetRequiredService(); var timeoutValue = sampleService.TimeoutOptions; daprBuilder.UseTimeout(timeoutValue); }); ``` -------------------------------- ### Actor with Dependency Injection (BankService) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Shows how to use dependency injection to provide additional services, such as 'BankService', to an actor's constructor. This allows for easier management of dependencies and promotes a cleaner actor design. ```csharp internal class MyActor : Actor, IMyActor, IRemindable { public MyActor(ActorHost host, BankService bank) // Accept BankService in the constructor : base(host) { ... } } ``` -------------------------------- ### Install Dapr.AI NuGet Package Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-ai/dotnet-ai-conversation-howto Installs the Dapr AI .NET SDK client package using the .NET CLI. This is the first step to using Dapr's conversational AI features in your .NET project. ```bash dotnet add package Dapr.AI ``` -------------------------------- ### Navigate to Streaming Subscription Example Directory Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-messaging/dotnet-messaging-pubsub-howto Navigates into the specific 'StreamingSubscriptionExample' directory. This is where the .NET application for the demonstration resides. ```bash cd StreamingSubscriptionExample ``` -------------------------------- ### Publish Event using DaprClient (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Demonstrates how to publish an event to a Dapr pub/sub component using the .NET SDK. The code shows how to build the DaprClient and then use the PublishEventAsync method, specifying the pub/sub component name, topic name, and the event data payload. ```.cs var client = new DaprClientBuilder().Build(); var eventData = new { Id = "17", Amount = 10m, }; await client.PublishEventAsync(pubsubName, "deposit", eventData, cancellationToken); Console.WriteLine("Published deposit event!"); ``` -------------------------------- ### Clone Dapr .NET SDK Repository Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-workflow/dotnet-workflow-howto Clones the Dapr .NET SDK repository from GitHub. This is the initial step to access the Dapr Workflow examples. ```bash git clone https://github.com/dapr/dotnet-sdk.git ``` -------------------------------- ### C# Record with Serialization Attributes and Primary Constructor Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Demonstrates a C# record decorated with DataContract and DataMember attributes, enabling proper serialization and deserialization, especially when using primary constructors and init-only setters. ```csharp [DataContract] public record Doodad( [property: DataMember] Guid Id, [property: DataMember] string Name, [property: DataMember] int Count) ``` -------------------------------- ### Configure Dapr AI Conversation Client with Dependency Injection Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-ai/dotnet-ai-conversation-howto Configures the `DaprConversationClient` during dependency injection setup. This example shows how to inject custom services to provide configuration values like timeouts to the client builder. ```csharp services.AddSingleton(); services.AddDaprAiConversation((serviceProvider, clientBuilder) => { //Inject a service to source a value from var optionsProvider = serviceProvider.GetRequiredService(); var standardTimeout = optionsProvider.GetStandardTimeout(); //Configure the value on the client builder clientBuilder.UseTimeout(standardTimeout); }); ``` -------------------------------- ### Configure Dapr Sidecar in Program.cs (Basic) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-integrations/dotnet-development-dapr-aspire This C# code snippet demonstrates the basic setup within the AppHost's Program.cs file to register and run Dapr-enabled projects. It assumes project references have already been added. ```csharp var builder = DistributedApplication.CreateBuilder(args); var backEndApp = builder .AddProject("be") .WithDaprSidecar(); var frontEndApp = builder .AddProject("fe") .WithDaprSidecar(); builder.Build().Run(); ``` -------------------------------- ### Configure JSON Serialization Options for Actors (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Customize the `JsonSerializerOptions` used by the Dapr actor runtime for state store serialization and client request handling. This configuration is done within the `AddActors` call in `Startup.cs`'s `ConfigureServices` method. ```csharp // In Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddActors(options => { ... // Customize JSON options options.JsonSerializerOptions = ...; }); } ``` -------------------------------- ### Invoke Service via HTTP using DaprClient (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Demonstrates how to invoke a service using the Dapr .NET SDK's DaprClient. It shows how to build the client, set an optional timeout, and make a POST request with input data, specifying the target app ID, method name, and data payload. The response is deserialized into an Account object. ```.cs using var client = new DaprClientBuilder(). UseTimeout(TimeSpan.FromSeconds(2)). // Optionally, set a timeout Build(); // Invokes a POST method named "deposit" that takes input of type "Transaction" var data = new { id = "17", amount = 99m }; var account = await client.InvokeMethodAsync("routing", "deposit", data, cancellationToken); Console.WriteLine("Returned: id:{0} | Balance:{1}", account.Id, account.Balance); ``` -------------------------------- ### Actor Method Exception Details Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Demonstrates the format of exception details surfaced during actor method invocations. This includes the exception type, method name, line number, and a unique UUID for matching exceptions between caller and callee. ```text Dapr.Actors.ActorMethodInvocationException: Remote Actor Method Exception, DETAILS: Exception: NotImplementedException, Method Name: ExceptionExample, Line Number: 14, Exception uuid: d291a006-84d5-42c4-b39e-d6300e9ac38b ``` -------------------------------- ### Subscribe to Configuration Keys with Dapr .NET SDK Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Illustrates how to subscribe to configuration changes using the Dapr .NET SDK. It returns an IAsyncEnumerable which can be iterated to receive updates. The subscription continues until the stream is closed or a cancellation token is triggered. ```csharp var client = new DaprClientBuilder().Build(); // The Subscribe Configuration API returns a wrapper around an IAsyncEnumerable>. // Iterate through it by accessing its Source in a foreach loop. The loop will end when the stream is severed // or if the cancellation token is cancelled. var subscribeConfigurationResponse = await daprClient.SubscribeConfiguration(store, keys, metadata, cts.Token); await foreach (var items in subscribeConfigurationResponse.Source.WithCancellation(cts.Token)) { foreach (var item in items) { Console.WriteLine($"{item.Key} -> {item.Value}") } } ``` -------------------------------- ### Register DaprEncryptionClient with Default Settings Source: https://docs.dapr.io/developing-applications/sdks/dotnet/_print Registers the DaprEncryptionClient with default settings in the dependency injection container. This is the simplest way to start using the client when default configurations are sufficient. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddDaprEncryptionClent(); //Registers the `DaprEncryptionClient` to be injected as needed var app = builder.Build(); // Alternatively, in Startup.cs or Program.cs: // services.AddDaprEncryptionClient(); ``` -------------------------------- ### Handle Dapr Exceptions in .NET SDK Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Demonstrates basic error handling for Dapr operations using a try-catch block in C#. It shows how to catch `DaprException` or its subclasses, which are thrown by `DaprClient` methods upon encountering failures like configuration issues or network problems. ```csharp try { var widget = new Widget() { Color = "Green" }; await client.SaveStateAsync("mystatestore", "mykey", widget); } catch (DaprException ex) { // handle the exception, log, retry, etc. // Examine ex.InnerException for more details } ``` -------------------------------- ### Start Dapr Workflow Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-workflow/dotnet-workflow-howto This endpoint allows you to start a Dapr Workflow instance. You provide the workflow name and an instance ID, along with the workflow's input data in the request body. ```APIDOC ## POST /v1.0/workflows/{workflow_component_name}/{workflow_name}/start ### Description Starts a new instance of a Dapr workflow. ### Method POST ### Endpoint `/v1.0/workflows/{workflow_component_name}/{workflow_name}/start` ### Query Parameters - **instanceID** (string) - Required - A unique identifier for the workflow instance. ### Request Body - **(object)** - Required - The input payload for the workflow. - **Name** (string) - Example: "Paperclips" - **TotalCost** (number) - Example: 99.95 - **Quantity** (number) - Example: 1 ### Request Example ```json { "Name": "Paperclips", "TotalCost": 99.95, "Quantity": 1 } ``` ### Response #### Success Response (200) - **instanceID** (string) - The ID of the started workflow instance. #### Response Example ```json { "instanceID": "12345678" } ``` ``` -------------------------------- ### Retrieve Secrets with Dapr .NET SDK Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Demonstrates how to retrieve single and multi-value secrets from a Dapr secret store. It uses the DaprClient to access secrets by store name and secret name. The returned secrets are in a Dictionary format. ```csharp var client = new DaprClientBuilder().Build(); // Retrieve a key-value-pair-based secret - returns a Dictionary var secrets = await client.GetSecretAsync("mysecretstore", "key-value-pair-secret"); Console.WriteLine($"Got secret keys: {string.Join(", ", secrets.Keys)}"); // Retrieve a single-valued secret - returns a Dictionary // containing a single value with the secret name as the key var data = await client.GetSecretAsync("mysecretstore", "single-value-secret"); var value = data["single-value-secret"]; Console.WriteLine("Got a secret value, I'm not going to be print it, it's a secret!"); ``` -------------------------------- ### Invoke Actor Methods with Strongly-Typed Client Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Demonstrates how to invoke methods on a Dapr actor using a strongly-typed client generated by the Dapr SDK. It shows the creation of an ActorProxy using the actor's interface, ID, and type, followed by calling methods like SetDataAsync and GetDataAsync. This requires the Dapr.Actors and MyActor.Interfaces namespaces. ```csharp using System; using System.Threading.Tasks; using Dapr.Actors; using Dapr.Actors.Client; using MyActor.Interfaces; namespace MyActorClient { class Program { static async Task MainAsync(string[] args) { Console.WriteLine("Startup up..."); // Registered Actor Type in Actor Service var actorType = "MyActor"; // An ActorId uniquely identifies an actor instance // If the actor matching this id does not exist, it will be created var actorId = new ActorId("1"); // Create the local proxy by using the same interface that the service implements. // // You need to provide the type and id so the actor can be located. var proxy = ActorProxy.Create(actorId, actorType); // Now you can use the actor interface to call the actor's methods. Console.WriteLine($"Calling SetDataAsync on {actorType}:{actorId}..."); var response = await proxy.SetDataAsync(new MyData() { PropertyA = "ValueA", PropertyB = "ValueB", }); Console.WriteLine($"Got response: {response}"); Console.WriteLine($"Calling GetDataAsync on {actorType}:{actorId}..."); var savedData = await proxy.GetDataAsync(); Console.WriteLine($"Got response: {savedData}"); } } } ``` -------------------------------- ### Start a Dapr Workflow Source: https://docs.dapr.io/developing-applications/sdks/dotnet/_print Initiates a new workflow instance by sending a POST request to the Dapr sidecar. The request body contains the input data for the workflow. ```APIDOC ## POST /v1.0/workflows/{workflowComponent}/{workflowName}/start ### Description Starts a new instance of a Dapr workflow. ### Method POST ### Endpoint `/v1.0/workflows/{workflowComponent}/{workflowName}/start` ### Parameters #### Query Parameters - **instanceID** (string) - Optional - A unique identifier for the workflow instance. #### Request Body - **(any)** - Required - The input data for the workflow, typically a JSON object. ### Request Example ```json { "Name": "Paperclips", "TotalCost": 99.95, "Quantity": 1 } ``` ### Response #### Success Response (200) - **instanceID** (string) - The unique identifier of the started workflow instance. #### Response Example ```json { "instanceID": "12345678" } ``` ``` -------------------------------- ### Install Dapr AI .NET SDK Package Source: https://docs.dapr.io/developing-applications/sdks/dotnet/_print This command shows how to add the Dapr.AI NuGet package to your .NET project using the .NET CLI. This package provides the necessary components for integrating Dapr AI conversations into your .NET application. ```bash dotnet add package Dapr.AI ``` -------------------------------- ### Check Sidecar Components Health with Dapr .NET SDK Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Illustrates checking if the Dapr sidecar has initialized all its components using the .NET SDK. The `CheckOutboundHealthAsync` method is useful for scenarios where Dapr components need to be ready before application code execution, such as loading secrets during startup. ```csharp var client = new DaprClientBuilder().Build(); var isDaprComponentsReady = await client.CheckOutboundHealthAsync(); if (isDaprComponentsReady) { // Execute Dapr component dependent code. } ``` -------------------------------- ### Instantiate Dapr Jobs Client Manually (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-jobs/dotnet-jobs-howto This example demonstrates how to create an instance of the DaprJobsClient without relying on dependency injection. It uses the DaprJobsClientBuilder to build the client, providing flexibility in managing the client's lifecycle and dependencies. ```csharp public class MySampleClass { public void DoSomething() { var daprJobsClientBuilder = new DaprJobsClientBuilder(); var daprJobsClient = daprJobsClientBuilder.Build(); //Do something with the `daprJobsClient` } } ``` -------------------------------- ### Run .NET Workflow Console Application Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-workflow/dotnet-workflow-howto Executes the .NET console application that sets up and manages Dapr Workflows. This command starts the application locally. ```bash dotnet run ``` -------------------------------- ### Install Dapr.Cryptography Package Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-cryptography/dotnet-cryptography-howto Installs the Dapr.Cryptography NuGet package required for using Dapr's encryption features in .NET applications. Ensure you have the .NET SDK and Dapr CLI installed. ```bash dotnet add package Dapr.Cryptography ``` -------------------------------- ### Start Dapr Sidecar with Workflow Application Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-workflow/dotnet-workflow-howto Starts the Dapr sidecar alongside the .NET Workflow application. This command registers the application with Dapr and makes it available for workflow operations. ```bash dapr run --app-id wfapp --dapr-grpc-port 4001 --dapr-http-port 3500 ``` -------------------------------- ### Install Dapr Cryptography Package Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-cryptography/_print This command shows how to add the Dapr.Cryptography package to your .NET project using the NuGet package manager. This is a prerequisite for using the Dapr Cryptography client. ```bash dotnet add package Dapr.Cryptography ``` -------------------------------- ### Run Dapr Application Locally Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-messaging/dotnet-messaging-pubsub-howto Starts both the Dapr sidecar and the .NET program simultaneously. It configures application ID, Dapr gRPC port, and Dapr HTTP port. ```bash dapr run --app-id pubsubapp --dapr-grpc-port 4001 --dapr-http-port 3500 -- dotnet run ``` -------------------------------- ### Shutdown Dapr Sidecar (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print This snippet shows how to gracefully shut down the Dapr sidecar using the `DaprClient.ShutdownSidecarAsync` method. This is useful for cleanup operations during application shutdown. ```csharp var client = new DaprClientBuilder().Build(); await client.ShutdownSidecarAsync(); ``` -------------------------------- ### Advanced Dapr Sidecar Configuration in .NET Aspire Source: https://docs.dapr.io/developing-applications/sdks/dotnet/_print This example shows how to configure specific options for the Dapr sidecar, such as AppId, ports, and metrics. Note that `AppPort` is required for certain Dapr features as of Aspire v9.0. ```csharp DaprSidecarOptions sidecarOptions = new() { AppId = "how-dapr-identifies-your-app", AppPort = 8080, //Note that this argument is required if you intend to configure pubsub, actors or workflows as of Aspire v9.0 DaprGrpcPort = 50001, DaprHttpPort = 3500, MetricsPort = 9090 }; builder .AddProject("be") .WithReference(myApp) .WithDaprSidecar(sidecarOptions); ``` -------------------------------- ### Serialized XML Output of Simple .NET Class (XML) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Shows the XML representation of the simple Doodad class when serialized. The element names correspond to the member names of the C# class. ```xml a06ced64-4f42-48ad-84dd-46ae6a7e333d DoodadName 5 ``` -------------------------------- ### Invoke Output Bindings using Dapr .NET SDK Source: https://docs.dapr.io/developing-applications/sdks/dotnet/_print Demonstrates invoking an output binding to send data to external systems. The example shows using the Twilio SendGrid binding to send an email with metadata and HTML content through the Dapr binding interface. ```csharp using var client = new DaprClientBuilder().Build(); // Example payload for the Twilio SendGrid binding var email = new { metadata = new { emailTo = "customer@example.com", subject = "An email from Dapr SendGrid binding", }, data = "

Testing Dapr Bindings

This is a test.
Bye!", }; await client.InvokeBindingAsync("send-email", "create", email); ``` -------------------------------- ### Initialize C# Record Instance Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Initializes an instance of the 'Engagement' record with a name 'Ski Trip' and the 'Season' enum value 'Winter'. This demonstrates how to create objects that utilize the defined enum. ```csharp var myEngagement = new Engagement("Ski Trip", Season.Winter); ``` -------------------------------- ### Define C# Enum Type Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Defines a C# enumeration type named 'Season' with four possible values: Spring, Summer, Fall, and Winter. This is a standard .NET enum definition. ```csharp public enum Season { Spring, Summer, Fall, Winter } ``` -------------------------------- ### String JSON Serialization of Enum with Converter Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Displays the JSON output after applying `JsonStringEnumConverter` to the 'Season' enum. The enum value 'Winter' is now represented as a string "Winter" in the serialized JSON. ```json {"name": "Ski Trip", "season": "Winter"} ``` -------------------------------- ### Start Dapr Workflow Instance (Linux/MacOS) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-workflow/dotnet-workflow-howto Initiates a Dapr Workflow instance by sending an HTTP POST request to the Dapr API. This command specifies the workflow name and provides input data for the workflow. ```bash curl -i -X POST http://localhost:3500/v1.0/workflows/dapr/OrderProcessingWorkflow/start?instanceID=12345678 \ -H "Content-Type: application/json" \ -d '{"Name": "Paperclips", "TotalCost": 99.95, "Quantity": 1}' ``` -------------------------------- ### Apply JsonStringEnumConverter to C# Enum Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Applies the `[JsonConverter(typeof(JsonStringEnumConverter))]` attribute to the 'Season' enum definition. This instructs the serializer to use string representations for enum values instead of numeric ones. ```csharp [JsonConverter(typeof(JsonStringEnumConverter))] public enum Season { Spring, Summer, Fall, Winter } ``` -------------------------------- ### Create Actor Client Project and Add Dependencies Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/dotnet-actors-howto Sets up a console application for acting as an actor client. It creates a new console project, navigates into its directory, adds the `Dapr.Actors` NuGet package, and references the actor interfaces project. ```bash # Create Actor's Client dotnet new console -o MyActorClient cd MyActorClient # Add Dapr.Actors nuget package. Please use the latest package version from nuget.org dotnet add package Dapr.Actors # Add Actor Interface reference dotnet add reference ../MyActor.Interfaces/MyActor.Interfaces.csproj cd .. ``` -------------------------------- ### Start Dapr Workflow Instance (Windows) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-workflow/dotnet-workflow-howto Initiates a Dapr Workflow instance by sending an HTTP POST request to the Dapr API. This command specifies the workflow name and provides input data for the workflow. ```bash curl -i -X POST http://localhost:3500/v1.0/workflows/dapr/OrderProcessingWorkflow/start?instanceID=12345678 ` -H "Content-Type: application/json" ` -d '{"Name": "Paperclips", "TotalCost": 99.95, "Quantity": 1}' ``` -------------------------------- ### Create ASP.NET Core Projects via CLI Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-integrations/_print Creates new empty ASP.NET Core web projects for the frontend and backend of your application. These projects will be integrated into the Aspire orchestration. ```bash dotnet new web --name FrontEndApp dotnet new web --name BackEndApp ``` -------------------------------- ### Dapr Weakly-typed Actor Client JSON Serialization Output Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Illustrates the default JSON output for the 'Doodad' class when serialized by the Dapr weakly-typed actor client. Property names are converted to camel case by System.Text.Json. ```json {"id": "a06ced64-4f42-48ad-84dd-46ae6a7e333d", "name": "DoodadName", "count": 5} ``` -------------------------------- ### Basic .NET Aspire AppHost Program Configuration Source: https://docs.dapr.io/developing-applications/sdks/dotnet/_print This is the default structure of the `Program.cs` file in the AppHost project before Dapr integration. It sets up the application builder and runs the application. ```csharp var builder = DistributedApplication.CreateBuilder(args); builder.Build().Run(); ``` -------------------------------- ### Wait for Dapr Sidecar Health (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print This code snippet demonstrates how to use `DaprClient.WaitForSidecarAsync` to ensure the Dapr sidecar is healthy before proceeding with component operations. It includes a `CancellationToken` for managing timeouts, which is crucial for robust applications. ```csharp // Wait for the Dapr sidecar to report healthy before attempting use Dapr components. using (var tokenSource = new CancellationTokenSource(sidecarWaitTimeout)) { await client.WaitForSidecarAsync(tokenSource.Token); } // Perform Dapr component operations here i.e. fetching secrets. ``` -------------------------------- ### Define C# Record with Enum Reference Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Defines a C# record type named 'Engagement' that includes a string property 'Name' and a property of the 'Season' enum type. This illustrates how to incorporate enums within other data structures. ```csharp public record Engagement(string Name, Season TimeOfYear); ``` -------------------------------- ### Create ASP.NET Core Projects via CLI Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-integrations/dotnet-development-dapr-aspire Generates two new ASP.NET Core projects, 'FrontEndApp' and 'BackEndApp', within the current directory. These will serve as the core applications for demonstrating Dapr functionality. ```bash dotnet new web --name FrontEndApp ``` -------------------------------- ### Dapr Weakly-typed Actor Client JSON Output with Overridden Names Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Presents the JSON output for the 'Doodad' class after applying `[JsonPropertyName]` attributes. This demonstrates how custom names like 'identifier' replace the default camel-cased names. ```json {"identifier": "a06ced64-4f42-48ad-84dd-46ae6a7e333d", "name": "DoodadName", "count": 5} ``` -------------------------------- ### Configure Dapr Pub/Sub Subscription (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/_print This snippet demonstrates how to configure and subscribe to a Dapr Pub/Sub topic using the Dapr .NET SDK. It shows the creation of a `DaprPublishSubscribeClient`, setting subscription options including message handling policies and timeouts, and initiating the subscription with a message handler. ```csharp var messagingClient = app.Services.GetRequiredService(); var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(60)); //Override the default of 30 seconds var options = new DaprSubscriptionOptions(new MessageHandlingPolicy(TimeSpan.FromSeconds(10), TopicResponseAction.Retry)); var subscription = await messagingClient.SubscribeAsync("pubsub", "mytopic", options, HandleMessageAsync, cancellationTokenSource.Token); // The HandleMessageAsync method would be defined elsewhere, e.g.: // async Task HandleMessageAsync(CloudEvent message, CancellationToken cancellationToken) // { // // Process the message // await Task.CompletedTask; // } ``` -------------------------------- ### Check Sidecar Health with Dapr .NET SDK Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Demonstrates polling for the Dapr sidecar's health status using the .NET SDK. The `CheckHealthAsync` method returns true if both the sidecar and the application are fully initialized and ready. ```csharp var client = new DaprClientBuilder().Build(); var isDaprReady = await client.CheckHealthAsync(); if (isDaprReady) { // Execute Dapr dependent code. } ``` -------------------------------- ### Configure DaprConversationClient with OptionsProvider (.NET DI) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/_print This example demonstrates configuring the DaprConversationClient by injecting a custom service, `DefaultOptionsProvider`, to dynamically retrieve configuration values. The `AddDaprAiConversation` method's options delegate uses the injected service to get a standard timeout value, which is then applied to the client builder. ```csharp services.AddSingleton(); services.AddDaprAiConversation((serviceProvider, clientBuilder) => { //Inject a service to source a value from var optionsProvider = serviceProvider.GetRequiredService(); var standardTimeout = optionsProvider.GetStandardTimeout(); //Configure the value on the client builder clientBuilder.UseTimeout(standardTimeout); }); ``` -------------------------------- ### Configure AppHost for Dapr Integration via CLI Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-integrations/dotnet-development-dapr-aspire Navigates to the AppHost directory and adds the 'CommunityToolkit.Aspire.Hosting.Dapr' NuGet package. It also adds project references to 'FrontEndApp' and 'BackEndApp' for integration. ```bash cd aspiredemo.AppHost dotnet add package CommunityToolkit.Aspire.Hosting.Dapr dotnet add reference ../FrontEndApp/ dotnet add reference ../BackEndApp/ ``` -------------------------------- ### Actor with Dependency Injection (IServiceProvider) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Demonstrates injecting IServiceProvider into an actor's constructor. This allows the actor to resolve services from its associated dependency injection scope dynamically, which can be useful for managing resources or accessing services not directly injected. ```csharp internal class MyActor : Actor, IMyActor, IRemindable { public MyActor(ActorHost host, IServiceProvider services) // Accept IServiceProvider in the constructor : base(host) { ... } } ``` -------------------------------- ### Default JSON Serialization of Enum Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Shows the default JSON output when an 'Engagement' record containing a 'Season' enum is serialized. The enum value 'Winter' is represented numerically (3) because the serializer uses zero-based numeric values for enums by default. ```json {"name": "Ski Trip", "season": 3} ``` -------------------------------- ### Create Actor Service Project (C#) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/dotnet-actors-howto This set of commands creates a new ASP.NET web service project to host the Dapr actor, adds the `Dapr.Actors.AspNetCore` NuGet package, and includes a project reference to the `MyActor.Interfaces` project. This sets up the service to implement and expose the actor functionality. ```bash # Create ASP.Net Web service to host Dapr actor dotnet new web -o MyActorService cd MyActorService # Add Dapr.Actors.AspNetCore nuget package. Please use the latest package version from nuget.org dotnet add package Dapr.Actors.AspNetCore # Add Actor Interface reference dotnet add reference ../MyActor.Interfaces/MyActor.Interfaces.csproj cd .. ``` -------------------------------- ### Create New .NET Aspire Application via CLI Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-integrations/dotnet-development-dapr-aspire Creates a new, empty .NET Aspire application. The `-n` argument specifies the solution name; otherwise, it defaults to the directory name. Assumes solution name 'aspiredemo' for subsequent steps. ```bash dotnet new aspire -n aspiredemo ``` -------------------------------- ### Dapr Weakly-typed Actor Client Override Property Names on Record with property: (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Illustrates how to explicitly specify the `property:` modifier for `[JsonPropertyName]` on a C# record's primary constructor parameter when necessary. This ensures the attribute targets the property correctly. ```csharp public record Thingy(string Name, [property: JsonPropertyName("count")] int Count); ``` -------------------------------- ### Dapr Weakly-typed Actor Client Override Property Names on Record (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print Demonstrates overriding JSON property names for a C# 12+ record 'Thingy' using `[JsonPropertyName]`. It shows the syntax for applying the attribute directly to the primary constructor parameter. ```csharp public record Thingy(string Name, [JsonPropertyName("count")] int Count); ``` -------------------------------- ### Get Configuration with Dapr .NET SDK Source: https://docs.dapr.io/developing-applications/sdks/dotnet/_print Shows how to retrieve configuration settings using the Dapr .NET SDK. You can fetch specific configuration keys by providing a list of keys, or retrieve all configuration items by passing an empty list to the GetConfiguration method. The results are returned as an enumerable collection of ConfigurationItem objects, each containing a Key and Value. ```csharp var client = new DaprClientBuilder().Build(); // Retrieve a specific set of keys. var specificItems = await client.GetConfiguration("configstore", new List() { "key1", "key2" }); Console.WriteLine($"Here are my values:\n{specificItems[0].Key} -> {specificItems[0].Value}\n{specificItems[1].Key} -> {specificItems[1].Value}"); // Retrieve all configuration items by providing an empty list. var configItems = await client.GetConfiguration("configstore", new List()); Console.WriteLine($"I got {configItems.Count} entires!"); foreach (var item in configItems) { Console.WriteLine($"{item.Key} -> {item.Value}") } ``` -------------------------------- ### Unlock Distributed Lock with Dapr .NET SDK Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Shows how to explicitly unlock a previously acquired distributed lock using the Dapr .NET SDK. This involves providing the lock store name, resource name, and owner ID to the Unlock method. ```csharp using System; using Dapr.Client; namespace LockService { class Program { static async Task Main(string[] args) { var daprLockName = "lockstore"; var client = new DaprClientBuilder().Build(); var response = await client.Unlock(DAPR_LOCK_NAME, "my_file_name", "random_id_abc123")); Console.WriteLine(response.status); } } } ``` -------------------------------- ### Configure DaprClient gRPC Channel Options for Cancellation (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print This code shows how to configure the gRPC channel options for the DaprClient, specifically enabling the 'ThrowOperationCanceledOnCancellation' setting. This ensures that cancellation requests are handled correctly by the gRPC channel, which is essential for reliable cancellation of Dapr operations. ```csharp var daprClient = new DaprClientBuilder() .UseGrpcChannelOptions(new GrpcChannelOptions { ... ThrowOperationCanceledOnCancellation = true }) .Build(); ``` -------------------------------- ### Registering Services for DI (.NET Startup.cs) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/dotnet-actors-usage Illustrates how to register custom types, such as BankService, with the dependency injection container in the Startup.cs file for use in actor constructors. ```csharp // In Startup.cs public void ConfigureServices(IServiceCollection services) { ... // Register additional types with dependency injection. services.AddSingleton(); } ``` -------------------------------- ### Manual Instantiation Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/dotnet-daprclient-usage Building a DaprClient instance manually using the `DaprClientBuilder`. This is an alternative to dependency injection. ```APIDOC ## Manual Instantiation ### Description Manually create a `DaprClient` instance using the static `DaprClientBuilder`. It is recommended to create a single, long-lived instance of `DaprClient` for performance and thread-safety. ### Method `new DaprClientBuilder()` ### Endpoint N/A (Manual Instantiation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var daprClient = new DaprClientBuilder() .UseJsonSerializerSettings( ... ) // Configure JSON serializer .Build(); ``` ### Response #### Success Response (200) N/A (Instantiation, not a request/response) #### Response Example None ``` -------------------------------- ### Instance Initialization of Record with Custom Enum Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print This C# code shows how to initialize a new instance of the `Engagement` record. It assigns a string value to the `Name` property (which will be serialized as "event") and sets the `TimeOfYear` property to `Season.Fall`. This demonstrates the practical application of the custom enum serialization. ```csharp var myEngagement = new Engagement("Conference", Season.Fall); ``` -------------------------------- ### Serialize Derived Widget State Correctly with DaprClient .NET Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Shows the correct way to serialize derived types like 'SuperWidget' when stored via a base type variable. By explicitly using `` as the type argument in `SaveStateAsync`, the serializer is forced to include all properties of the actual object. ```csharp Widget widget = new SuperWidget() { Color = "Green", HasSelfCleaningFeature = true }; await client.SaveStateAsync("mystatestore", "mykey", widget); ``` -------------------------------- ### Acquire Distributed Lock with Dapr .NET SDK Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Demonstrates acquiring a distributed lock using the Dapr .NET SDK. The lock is acquired using a lock store name, resource name, owner ID, and lock expiry in seconds. The acquired lock is automatically released when the `IacquiredLock` object is disposed. ```csharp using System; using Dapr.Client; namespace LockService { class Program { [Obsolete("Distributed Lock API is in Alpha, this can be removed once it is stable.")] static async Task Main(string[] args) { var daprLockName = "lockstore"; var fileName = "my_file_name"; var client = new DaprClientBuilder().Build(); // Locking with this approach will also unlock it automatically, as this is a disposable object await using (var fileLock = await client.Lock(DAPR_LOCK_NAME, fileName, "random_id_abc123", 60)) { if (fileLock.Success) { Console.WriteLine("Success"); } else { Console.WriteLine($"Failed to lock {fileName}."); } } } } } ``` -------------------------------- ### Actor Constructor with ActorHost (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/dotnet-actors-usage Demonstrates how to properly initialize an actor by passing the ActorHost to the base class constructor. ActorHost is a required parameter provided by the Dapr runtime. ```csharp internal class MyActor : Actor, IMyActor, IRemindable { public MyActor(ActorHost host) // Accept ActorHost in the constructor : base(host) // Pass ActorHost to the base class constructor { } } ``` -------------------------------- ### Manually Instantiate DaprEncryptionClient (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-cryptography/_print Demonstrates how to manually create and configure a DaprEncryptionClient using the DaprEncryptionClientBuilder. This approach allows for fine-grained control over JSON serialization settings before building the client instance. It is recommended to create a single, shared instance for performance. ```csharp var daprEncryptionClient = new DaprEncryptionClientBuilder() .UseJsonSerializerSettings( ... ) //Configure JSON serializer .Build(); ``` -------------------------------- ### Record with Custom Property Name and Enum Type Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-actors/_print This C# code defines a `record` named `Engagement`. It uses `[JsonPropertyName("event")]` to rename the `Name` property during serialization to "event". The `TimeOfYear` property uses the custom-serialized `Season` enum, demonstrating the integration of the custom converter with data structures. ```csharp public record Engagement([property: JsonPropertyName("event")] string Name, Season TimeOfYear); ``` -------------------------------- ### Invoke Service via HTTP using HttpClient (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-client/_print Illustrates invoking a service using System.Net.Http.HttpClient with Dapr's integration. It shows how to create an HTTP client for a specific Dapr app ID, set an optional timeout, and send a POST request with JSON content. The response is read and deserialized into an Account object. ```.cs var client = DaprClient.CreateInvokeHttpClient(appId: "routing"); // To set a timeout on the HTTP client: client.Timeout = TimeSpan.FromSeconds(2); var deposit = new Transaction { Id = "17", Amount = 99m }; var response = await client.PostAsJsonAsync("/deposit", deposit, cancellationToken); var account = await response.Content.ReadFromJsonAsync(cancellationToken: cancellationToken); Console.WriteLine("Returned: id:{0} | Balance:{1}", account.Id, account.Balance); ``` -------------------------------- ### Register Dapr Jobs Client with Dependency Injection (.NET) Source: https://docs.dapr.io/developing-applications/sdks/dotnet/dotnet-jobs/dotnet-jobs-howto Simplifies the registration of the Dapr Jobs client in `Program.cs` using an extension method. This is the most basic way to add the client to your service collection. ```csharp var builder = WebApplication.CreateBuilder(args); //Add anywhere between these two lines builder.Services.AddDaprJobsClient(); var app = builder.Build(); ```