diff --git a/all.sln b/all.sln
index 9a163b1d9..eabc532e9 100644
--- a/all.sln
+++ b/all.sln
@@ -54,7 +54,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ControllerSample", "example
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Actor", "Actor", "{02374BD0-BF0B-40F8-A04A-C4C4D61D4992}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IDemoActor", "examples\Actor\IDemoActor\IDemoActor.csproj", "{7957E852-1291-4FAA-9034-FB66CE817FF1}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DemoActor.Interfaces", "examples\Actor\DemoActor.Interfaces\DemoActor.Interfaces.csproj", "{7957E852-1291-4FAA-9034-FB66CE817FF1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DemoActor", "examples\Actor\DemoActor\DemoActor.csproj", "{626D74DD-4F37-4F74-87A3-5A6888684F5E}"
EndProject
@@ -155,6 +155,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JobsSample", "examples\Jobs
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dapr.Workflow.Test", "test\Dapr.Workflow.Test\Dapr.Workflow.Test.csproj", "{E90114C6-86FC-43B8-AE5C-D9273CF21FE4}"
EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Messaging", "Messaging", "{8DB002D2-19E9-4342-A86B-025A367DF3D1}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -471,12 +473,13 @@ Global
{00359961-0C50-4BB1-A794-8B06DE991639} = {BF3ED6BF-ADF3-4D25-8E89-02FB8D945CA9}
{4E04EB35-7FD2-4FDB-B09A-F75CE24053B9} = {DD020B34-460F-455F-8D17-CF4A949F100B}
{0EAE36A1-B578-4F13-A113-7A477ECA1BDA} = {27C5D71D-0721-4221-9286-B94AB07B58CF}
- {290D1278-F613-4DF3-9DF5-F37E38CDC363} = {0EF6EA64-D7C3-420D-9890-EAE8D54A57E6}
{C8BB6A85-A7EA-40C0-893D-F36F317829B3} = {27C5D71D-0721-4221-9286-B94AB07B58CF}
{BF9828E9-5597-4D42-AA6E-6E6C12214204} = {DD020B34-460F-455F-8D17-CF4A949F100B}
{D9697361-232F-465D-A136-4561E0E88488} = {D687DDC4-66C5-4667-9E3A-FD8B78ECAA78}
{9CAF360E-5AD3-4C4F-89A0-327EEB70D673} = {D9697361-232F-465D-A136-4561E0E88488}
{E90114C6-86FC-43B8-AE5C-D9273CF21FE4} = {DD020B34-460F-455F-8D17-CF4A949F100B}
+ {8DB002D2-19E9-4342-A86B-025A367DF3D1} = {D687DDC4-66C5-4667-9E3A-FD8B78ECAA78}
+ {290D1278-F613-4DF3-9DF5-F37E38CDC363} = {8DB002D2-19E9-4342-A86B-025A367DF3D1}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {65220BF2-EAE1-4CB2-AA58-EBE80768CB40}
diff --git a/examples/Actor/ActorClient/ActorClient.csproj b/examples/Actor/ActorClient/ActorClient.csproj
index 43aa659b1..9631e5175 100644
--- a/examples/Actor/ActorClient/ActorClient.csproj
+++ b/examples/Actor/ActorClient/ActorClient.csproj
@@ -6,7 +6,7 @@
-
+
diff --git a/examples/Actor/ActorClient/Program.cs b/examples/Actor/ActorClient/Program.cs
index 950869b2b..b578d488a 100644
--- a/examples/Actor/ActorClient/Program.cs
+++ b/examples/Actor/ActorClient/Program.cs
@@ -11,146 +11,123 @@
// limitations under the License.
// ------------------------------------------------------------------------
-using Dapr.Actors.Communication;
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using Dapr.Actors;
+using Dapr.Actors.Client;
using IDemoActor;
-namespace ActorClient
+var data = new MyData("ValueA", "ValueB");
+
+// Create an actor Id.
+var actorId = new ActorId("abc");
+
+// Make strongly typed Actor calls with Remoting.
+// DemoActor is the type registered with Dapr runtime in the service.
+var proxy = ActorProxy.Create(actorId, "DemoActor");
+
+Console.WriteLine("Making call using actor proxy to save data.");
+await proxy.SaveData(data, TimeSpan.FromMinutes(10));
+Console.WriteLine("Making call using actor proxy to get data.");
+var receivedData = await proxy.GetData();
+Console.WriteLine($"Received data is {receivedData}.");
+
+// Making some more calls to test methods.
+try
+{
+ Console.WriteLine("Making calls to an actor method which has no argument and no return type.");
+ await proxy.TestNoArgumentNoReturnType();
+}
+catch (Exception ex)
+{
+ Console.WriteLine($"ERROR: Got exception while making call to method with No Argument & No Return Type. Exception: {ex}");
+}
+
+try
+{
+ await proxy.TestThrowException();
+}
+catch (ActorMethodInvocationException ex)
{
- using System;
- using System.Threading;
- using System.Threading.Tasks;
- using Dapr.Actors;
- using Dapr.Actors.Client;
-
- ///
- /// Actor Client class.
- ///
- public class Program
+ if (ex.InnerException is ActorInvokeException invokeEx && invokeEx.ActualExceptionType is "System.NotImplementedException")
{
- ///
- /// Entry point.
- ///
- /// Arguments.
- /// A representing the asynchronous operation.
- public static async Task Main(string[] args)
- {
- var data = new MyData()
- {
- PropertyA = "ValueA",
- PropertyB = "ValueB",
- };
-
- // Create an actor Id.
- var actorId = new ActorId("abc");
-
- // Make strongly typed Actor calls with Remoting.
- // DemoActor is the type registered with Dapr runtime in the service.
- var proxy = ActorProxy.Create(actorId, "DemoActor");
-
- Console.WriteLine("Making call using actor proxy to save data.");
- await proxy.SaveData(data, TimeSpan.FromMinutes(10));
- Console.WriteLine("Making call using actor proxy to get data.");
- var receivedData = await proxy.GetData();
- Console.WriteLine($"Received data is {receivedData}.");
-
- // Making some more calls to test methods.
- try
- {
- Console.WriteLine("Making calls to an actor method which has no argument and no return type.");
- await proxy.TestNoArgumentNoReturnType();
- }
- catch (Exception ex)
- {
- Console.WriteLine($"ERROR: Got exception while making call to method with No Argument & No Return Type. Exception: {ex}");
- }
-
- try
- {
- await proxy.TestThrowException();
- }
- catch (ActorMethodInvocationException ex)
- {
- if (ex.InnerException is ActorInvokeException invokeEx && invokeEx.ActualExceptionType is "System.NotImplementedException")
- {
- Console.WriteLine($"Got Correct Exception from actor method invocation.");
- }
- else
- {
- Console.WriteLine($"Got Incorrect Exception from actor method invocation. Exception {ex.InnerException}");
- }
- }
-
- // Making calls without Remoting, this shows method invocation using InvokeMethodAsync methods, the method name and its payload is provided as arguments to InvokeMethodAsync methods.
- Console.WriteLine("Making calls without Remoting.");
- var nonRemotingProxy = ActorProxy.Create(actorId, "DemoActor");
- await nonRemotingProxy.InvokeMethodAsync("TestNoArgumentNoReturnType");
- await nonRemotingProxy.InvokeMethodAsync("SaveData", data);
- await nonRemotingProxy.InvokeMethodAsync("GetData");
-
- Console.WriteLine("Registering the timer and reminder");
- await proxy.RegisterTimer();
- await proxy.RegisterReminder();
- Console.WriteLine("Waiting so the timer and reminder can be triggered");
- await Task.Delay(6000);
-
- Console.WriteLine("Making call using actor proxy to get data after timer and reminder triggered");
- receivedData = await proxy.GetData();
- Console.WriteLine($"Received data is {receivedData}.");
-
- Console.WriteLine("Getting details of the registered reminder");
- var reminder = await proxy.GetReminder();
- Console.WriteLine($"Received reminder is {reminder}.");
-
- Console.WriteLine("Deregistering timer. Timers would any way stop if the actor is deactivated as part of Dapr garbage collection.");
- await proxy.UnregisterTimer();
- Console.WriteLine("Deregistering reminder. Reminders are durable and would not stop until an explicit deregistration or the actor is deleted.");
- await proxy.UnregisterReminder();
+ Console.WriteLine($"Got Correct Exception from actor method invocation.");
+ }
+ else
+ {
+ Console.WriteLine($"Got Incorrect Exception from actor method invocation. Exception {ex.InnerException}");
+ }
+}
+
+// Making calls without Remoting, this shows method invocation using InvokeMethodAsync methods, the method name and its payload is provided as arguments to InvokeMethodAsync methods.
+Console.WriteLine("Making calls without Remoting.");
+var nonRemotingProxy = ActorProxy.Create(actorId, "DemoActor");
+await nonRemotingProxy.InvokeMethodAsync("TestNoArgumentNoReturnType");
+await nonRemotingProxy.InvokeMethodAsync("SaveData", data);
+await nonRemotingProxy.InvokeMethodAsync("GetData");
+
+Console.WriteLine("Registering the timer and reminder");
+await proxy.RegisterTimer();
+await proxy.RegisterReminder();
+Console.WriteLine("Waiting so the timer and reminder can be triggered");
+await Task.Delay(6000);
+
+Console.WriteLine("Making call using actor proxy to get data after timer and reminder triggered");
+receivedData = await proxy.GetData();
+Console.WriteLine($"Received data is {receivedData}.");
+
+Console.WriteLine("Getting details of the registered reminder");
+var reminder = await proxy.GetReminder();
+Console.WriteLine($"Received reminder is {reminder}.");
+
+Console.WriteLine("Deregistering timer. Timers would any way stop if the actor is deactivated as part of Dapr garbage collection.");
+await proxy.UnregisterTimer();
+Console.WriteLine("Deregistering reminder. Reminders are durable and would not stop until an explicit deregistration or the actor is deleted.");
+await proxy.UnregisterReminder();
- Console.WriteLine("Registering reminder with repetitions - The reminder will repeat 3 times.");
- await proxy.RegisterReminderWithRepetitions(3);
- Console.WriteLine("Waiting so the reminder can be triggered");
- await Task.Delay(5000);
- Console.WriteLine("Getting details of the registered reminder");
- reminder = await proxy.GetReminder();
- Console.WriteLine($"Received reminder is {reminder?.ToString() ?? "None"} (expecting None).");
- Console.WriteLine("Registering reminder with ttl and repetitions, i.e. reminder stops when either condition is met - The reminder will repeat 2 times.");
- await proxy.RegisterReminderWithTtlAndRepetitions(TimeSpan.FromSeconds(5), 2);
- Console.WriteLine("Getting details of the registered reminder");
- reminder = await proxy.GetReminder();
- Console.WriteLine($"Received reminder is {reminder}.");
- Console.WriteLine("Deregistering reminder. Reminders are durable and would not stop until an explicit deregistration or the actor is deleted.");
- await proxy.UnregisterReminder();
-
- Console.WriteLine("Registering reminder and Timer with TTL - The reminder will self delete after 10 seconds.");
- await proxy.RegisterReminderWithTtl(TimeSpan.FromSeconds(10));
- await proxy.RegisterTimerWithTtl(TimeSpan.FromSeconds(10));
- Console.WriteLine("Getting details of the registered reminder");
- reminder = await proxy.GetReminder();
- Console.WriteLine($"Received reminder is {reminder}.");
-
- // Track the reminder.
- var timer = new Timer(async state => Console.WriteLine($"Received data: {await proxy.GetData()}"), null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
- await Task.Delay(TimeSpan.FromSeconds(21));
- await timer.DisposeAsync();
-
- Console.WriteLine("Creating a Bank Actor");
- var bank = ActorProxy.Create(ActorId.CreateRandom(), "DemoActor");
- while (true)
- {
- var balance = await bank.GetAccountBalance();
- Console.WriteLine($"Balance for account '{balance.AccountId}' is '{balance.Balance:c}'.");
-
- Console.WriteLine($"Withdrawing '{10m:c}'...");
- try
- {
- await bank.Withdraw(new WithdrawRequest() { Amount = 10m, });
- }
- catch (ActorMethodInvocationException ex)
- {
- Console.WriteLine("Overdraft: " + ex.Message);
- break;
- }
- }
- }
+Console.WriteLine("Registering reminder with repetitions - The reminder will repeat 3 times.");
+await proxy.RegisterReminderWithRepetitions(3);
+Console.WriteLine("Waiting so the reminder can be triggered");
+await Task.Delay(5000);
+Console.WriteLine("Getting details of the registered reminder");
+reminder = await proxy.GetReminder();
+Console.WriteLine($"Received reminder is {reminder?.ToString() ?? "None"} (expecting None).");
+Console.WriteLine("Registering reminder with ttl and repetitions, i.e. reminder stops when either condition is met - The reminder will repeat 2 times.");
+await proxy.RegisterReminderWithTtlAndRepetitions(TimeSpan.FromSeconds(5), 2);
+Console.WriteLine("Getting details of the registered reminder");
+reminder = await proxy.GetReminder();
+Console.WriteLine($"Received reminder is {reminder}.");
+Console.WriteLine("Deregistering reminder. Reminders are durable and would not stop until an explicit deregistration or the actor is deleted.");
+await proxy.UnregisterReminder();
+
+Console.WriteLine("Registering reminder and Timer with TTL - The reminder will self delete after 10 seconds.");
+await proxy.RegisterReminderWithTtl(TimeSpan.FromSeconds(10));
+await proxy.RegisterTimerWithTtl(TimeSpan.FromSeconds(10));
+Console.WriteLine("Getting details of the registered reminder");
+reminder = await proxy.GetReminder();
+Console.WriteLine($"Received reminder is {reminder}.");
+
+// Track the reminder.
+var timer = new Timer(async state => Console.WriteLine($"Received data: {await proxy.GetData()}"), null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
+await Task.Delay(TimeSpan.FromSeconds(21));
+await timer.DisposeAsync();
+
+Console.WriteLine("Creating a Bank Actor");
+var bank = ActorProxy.Create(ActorId.CreateRandom(), "DemoActor");
+while (true)
+{
+ var balance = await bank.GetAccountBalance();
+ Console.WriteLine($"Balance for account '{balance.AccountId}' is '{balance.Balance:c}'.");
+
+ Console.WriteLine($"Withdrawing '{10m:c}'...");
+ try
+ {
+ await bank.Withdraw(new WithdrawRequest(10m));
+ }
+ catch (ActorMethodInvocationException ex)
+ {
+ Console.WriteLine($"Overdraft: {ex.Message}");
+ break;
}
}
diff --git a/examples/Actor/IDemoActor/IDemoActor.csproj b/examples/Actor/DemoActor.Interfaces/DemoActor.Interfaces.csproj
similarity index 57%
rename from examples/Actor/IDemoActor/IDemoActor.csproj
rename to examples/Actor/DemoActor.Interfaces/DemoActor.Interfaces.csproj
index 8b8a84b21..f4955942b 100644
--- a/examples/Actor/IDemoActor/IDemoActor.csproj
+++ b/examples/Actor/DemoActor.Interfaces/DemoActor.Interfaces.csproj
@@ -1,5 +1,10 @@
+
+ IDemoActor
+ enable
+
+
diff --git a/examples/Actor/IDemoActor/IBankActor.cs b/examples/Actor/DemoActor.Interfaces/IBankActor.cs
similarity index 55%
rename from examples/Actor/IDemoActor/IBankActor.cs
rename to examples/Actor/DemoActor.Interfaces/IBankActor.cs
index c495f027b..92d847421 100644
--- a/examples/Actor/IDemoActor/IBankActor.cs
+++ b/examples/Actor/DemoActor.Interfaces/IBankActor.cs
@@ -15,32 +15,18 @@
using System.Threading.Tasks;
using Dapr.Actors;
-namespace IDemoActor
-{
- public interface IBankActor : IActor
- {
- Task GetAccountBalance();
+namespace IDemoActor;
- Task Withdraw(WithdrawRequest withdraw);
- }
+public interface IBankActor : IActor
+{
+ Task GetAccountBalance();
- public class AccountBalance
- {
- public string AccountId { get; set; }
+ Task Withdraw(WithdrawRequest withdraw);
+}
- public decimal Balance { get; set; }
- }
+public sealed record AccountBalance(string AccountId, decimal Balance);
- public class WithdrawRequest
- {
- public decimal Amount { get; set; }
- }
+public sealed record WithdrawRequest(decimal Amount);
- public class OverdraftException : Exception
- {
- public OverdraftException(decimal balance, decimal amount)
- : base($"Your current balance is {balance:c} - that's not enough to withdraw {amount:c}.")
- {
- }
- }
-}
+public class OverdraftException(decimal balance, decimal amount)
+ : Exception($"Your current balance is {balance:c} - that's not enough to withdraw {amount:c}.");
diff --git a/examples/Actor/DemoActor.Interfaces/IDemoActor.cs b/examples/Actor/DemoActor.Interfaces/IDemoActor.cs
new file mode 100644
index 000000000..c5fefdb9f
--- /dev/null
+++ b/examples/Actor/DemoActor.Interfaces/IDemoActor.cs
@@ -0,0 +1,129 @@
+// ------------------------------------------------------------------------
+// Copyright 2021 The Dapr Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+// ------------------------------------------------------------------------
+
+using System;
+using System.Threading.Tasks;
+using Dapr.Actors;
+
+namespace IDemoActor;
+
+///
+/// Interface for Actor method.
+///
+public interface IDemoActor : IActor
+{
+ ///
+ /// Method to save data.
+ ///
+ /// DAta to save.
+ /// TTL of state key.
+ /// A task that represents the asynchronous save operation.
+ Task SaveData(MyData data, TimeSpan ttl);
+
+ ///
+ /// Method to get data.
+ ///
+ /// A task that represents the asynchronous save operation.
+ Task GetData();
+
+ ///
+ /// A test method which throws exception.
+ ///
+ /// A task that represents the asynchronous save operation.
+ Task TestThrowException();
+
+ ///
+ /// A test method which validates calls for methods with no arguments and no return types.
+ ///
+ /// A task that represents the asynchronous save operation.
+ Task TestNoArgumentNoReturnType();
+
+ ///
+ /// Registers a reminder.
+ ///
+ /// A task that represents the asynchronous save operation.
+ Task RegisterReminder();
+
+ ///
+ /// Registers a reminder.
+ ///
+ /// TimeSpan that dictates when the reminder expires.
+ /// A task that represents the asynchronous save operation.
+ Task RegisterReminderWithTtl(TimeSpan ttl);
+
+ ///
+ /// Unregisters the registered reminder.
+ ///
+ /// Task representing the operation.
+ Task UnregisterReminder();
+
+ ///
+ /// Registers a timer.
+ ///
+ /// A task that represents the asynchronous save operation.
+ Task RegisterTimer();
+
+ ///
+ /// Registers a timer.
+ ///
+ /// Optional TimeSpan that dictates when the timer expires.
+ /// A task that represents the asynchronous save operation.
+ Task RegisterTimerWithTtl(TimeSpan ttl);
+
+ ///
+ /// Registers a reminder with repetitions.
+ ///
+ /// The number of repetitions for which the reminder should be invoked.
+ /// A task that represents the asynchronous save operation.
+ Task RegisterReminderWithRepetitions(int repetitions);
+
+ ///
+ /// Registers a reminder with ttl and repetitions.
+ ///
+ /// TimeSpan that dictates when the timer expires.
+ /// The number of repetitions for which the reminder should be invoked.
+ /// A task that represents the asynchronous save operation.
+ Task RegisterReminderWithTtlAndRepetitions(TimeSpan ttl, int repetitions);
+
+ ///
+ /// Gets the registered reminder.
+ ///
+ /// A task that returns the reminder after completion.
+ Task GetReminder();
+
+ ///
+ /// Unregisters the registered timer.
+ ///
+ /// A task that represents the asynchronous save operation.
+ Task UnregisterTimer();
+}
+
+///
+/// Data Used by the Sample Actor.
+///
+public sealed record MyData(string? PropertyA, string? PropertyB)
+{
+ ///
+ public override string ToString() => $"PropertyA: {PropertyA ?? "null"}, PropertyB: {PropertyB ?? "null"}";
+}
+
+public class ActorReminderData
+{
+ public string? Name { get; set; }
+
+ public TimeSpan DueTime { get; set; }
+
+ public TimeSpan Period { get; set; }
+
+ public override string ToString() => $"Name: {this.Name}, DueTime: {this.DueTime}, Period: {this.Period}";
+}
diff --git a/examples/Actor/DemoActor/BankService.cs b/examples/Actor/DemoActor/BankService.cs
index a24eadedb..22d2ac44f 100644
--- a/examples/Actor/DemoActor/BankService.cs
+++ b/examples/Actor/DemoActor/BankService.cs
@@ -13,24 +13,23 @@
using IDemoActor;
-namespace DemoActor
+namespace DemoActor;
+
+public sealed class BankService
{
- public class BankService
+ // Allow overdraft of up to 50 (of whatever currency).
+ private const decimal OverdraftThreshold = -50m;
+
+ public decimal Withdraw(decimal balance, decimal amount)
{
- // Allow overdraft of up to 50 (of whatever currency).
- private readonly decimal OverdraftThreshold = -50m;
+ // Imagine putting some complex auditing logic here in addition to the basics.
- public decimal Withdraw(decimal balance, decimal amount)
+ var updated = balance - amount;
+ if (updated < OverdraftThreshold)
{
- // Imagine putting some complex auditing logic here in addition to the basics.
-
- var updated = balance - amount;
- if (updated < OverdraftThreshold)
- {
- throw new OverdraftException(balance, amount);
- }
-
- return updated;
+ throw new OverdraftException(balance, amount);
}
+
+ return updated;
}
}
diff --git a/examples/Actor/DemoActor/DemoActor.cs b/examples/Actor/DemoActor/DemoActor.cs
index b5ef53e93..3e5de369d 100644
--- a/examples/Actor/DemoActor/DemoActor.cs
+++ b/examples/Actor/DemoActor/DemoActor.cs
@@ -17,195 +17,182 @@
using Dapr.Actors.Runtime;
using IDemoActor;
-namespace DemoActor
+namespace DemoActor;
+
+// The following example showcases a few features of Actors
+//
+// Every actor should inherit from the Actor type, and must implement one or more actor interfaces.
+// In this case the actor interfaces are DemoActor.Interfaces and IBankActor.
+//
+// For Actors to use Reminders, it must derive from IRemindable.
+// If you don't intend to use Reminder feature, you can skip implementing IRemindable and reminder
+// specific methods which are shown in the code below.
+public class DemoActor(ActorHost host, BankService bank) : Actor(host), IDemoActor.IDemoActor, IBankActor, IRemindable
{
- // The following example showcases a few features of Actors
- //
- // Every actor should inherit from the Actor type, and must implement one or more actor interfaces.
- // In this case the actor interfaces are IDemoActor and IBankActor.
- //
- // For Actors to use Reminders, it must derive from IRemindable.
- // If you don't intend to use Reminder feature, you can skip implementing IRemindable and reminder
- // specific methods which are shown in the code below.
- public class DemoActor : Actor, IDemoActor.IDemoActor, IBankActor, IRemindable
- {
- private const string StateName = "my_data";
-
- private readonly BankService bank;
-
- public DemoActor(ActorHost host, BankService bank)
- : base(host)
- {
- // BankService is provided by dependency injection.
- // See Program.cs
- this.bank = bank;
- }
+ private const string StateName = "my_data";
- public async Task SaveData(MyData data, TimeSpan ttl)
- {
- Console.WriteLine($"This is Actor id {this.Id} with data {data}.");
+ public async Task SaveData(MyData data, TimeSpan ttl)
+ {
+ Console.WriteLine($"This is Actor id {this.Id} with data {data}.");
- // Set State using StateManager, state is saved after the method execution.
- await this.StateManager.SetStateAsync(StateName, data, ttl);
- }
+ // Set State using StateManager, state is saved after the method execution.
+ await this.StateManager.SetStateAsync(StateName, data, ttl);
+ }
- public Task GetData()
- {
- // Get state using StateManager.
- return this.StateManager.GetStateAsync(StateName);
- }
+ public Task GetData()
+ {
+ // Get state using StateManager.
+ return this.StateManager.GetStateAsync(StateName);
+ }
- public Task TestThrowException()
- {
- throw new NotImplementedException();
- }
+ public Task TestThrowException()
+ {
+ throw new NotImplementedException();
+ }
- public Task TestNoArgumentNoReturnType()
- {
- return Task.CompletedTask;
- }
+ public Task TestNoArgumentNoReturnType()
+ {
+ return Task.CompletedTask;
+ }
- public async Task RegisterReminder()
- {
- await this.RegisterReminderAsync("TestReminder", null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
- }
+ public async Task RegisterReminder()
+ {
+ await this.RegisterReminderAsync("TestReminder", null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5));
+ }
- public async Task RegisterReminderWithTtl(TimeSpan ttl)
- {
- await this.RegisterReminderAsync("TestReminder", null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5), ttl);
- }
+ public async Task RegisterReminderWithTtl(TimeSpan ttl)
+ {
+ await this.RegisterReminderAsync("TestReminder", null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5), ttl);
+ }
- public async Task RegisterReminderWithRepetitions(int repetitions)
- {
- await this.RegisterReminderAsync("TestReminder", null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), repetitions);
- }
+ public async Task RegisterReminderWithRepetitions(int repetitions)
+ {
+ await this.RegisterReminderAsync("TestReminder", null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), repetitions);
+ }
- public async Task RegisterReminderWithTtlAndRepetitions(TimeSpan ttl, int repetitions)
- {
- await this.RegisterReminderAsync("TestReminder", null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), repetitions, ttl);
- }
+ public async Task RegisterReminderWithTtlAndRepetitions(TimeSpan ttl, int repetitions)
+ {
+ await this.RegisterReminderAsync("TestReminder", null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), repetitions, ttl);
+ }
- public async Task GetReminder()
- {
- var reminder = await this.GetReminderAsync("TestReminder");
-
- return reminder is not null
- ? new ActorReminderData
- {
- Name = reminder.Name,
- Period = reminder.Period,
- DueTime = reminder.DueTime
- }
- : null;
- }
+ public async Task GetReminder()
+ {
+ var reminder = await this.GetReminderAsync("TestReminder");
+
+ return reminder is not null
+ ? new ActorReminderData
+ {
+ Name = reminder.Name,
+ Period = reminder.Period,
+ DueTime = reminder.DueTime
+ }
+ : null;
+ }
- public Task UnregisterReminder()
- {
- return this.UnregisterReminderAsync("TestReminder");
- }
+ public Task UnregisterReminder()
+ {
+ return this.UnregisterReminderAsync("TestReminder");
+ }
- public async Task ReceiveReminderAsync(string reminderName, byte[] state, TimeSpan dueTime, TimeSpan period)
+ public async Task ReceiveReminderAsync(string reminderName, byte[] state, TimeSpan dueTime, TimeSpan period)
+ {
+ // This method is invoked when an actor reminder is fired.
+ var actorState = await this.StateManager.GetStateAsync(StateName);
+ var updatedActorState = actorState with
{
- // This method is invoked when an actor reminder is fired.
- var actorState = await this.StateManager.GetStateAsync(StateName);
- actorState.PropertyB = $"Reminder triggered at '{DateTime.Now:yyyy-MM-ddTHH:mm:ss}'";
- await this.StateManager.SetStateAsync(StateName, actorState, ttl: TimeSpan.FromMinutes(5));
- }
+ PropertyB = $"Reminder triggered at '{DateTime.Now:yyyy-MM-ddTHH:mm:ss}'"
+ };
+ await this.StateManager.SetStateAsync(StateName, updatedActorState, ttl: TimeSpan.FromMinutes(5));
+ }
- class TimerParams
- {
- public int IntParam { get; set; }
- public string StringParam { get; set; }
- }
+ class TimerParams
+ {
+ public int IntParam { get; set; }
+ public string? StringParam { get; set; }
+ }
- ///
- public Task RegisterTimer()
+ ///
+ public Task RegisterTimer()
+ {
+ var timerParams = new TimerParams
{
- var timerParams = new TimerParams
- {
- IntParam = 100,
- StringParam = "timer test",
- };
+ IntParam = 100,
+ StringParam = "timer test",
+ };
- var serializedTimerParams = JsonSerializer.SerializeToUtf8Bytes(timerParams);
- return this.RegisterTimerAsync("TestTimer", nameof(this.TimerCallback), serializedTimerParams, TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3));
- }
+ var serializedTimerParams = JsonSerializer.SerializeToUtf8Bytes(timerParams);
+ return this.RegisterTimerAsync("TestTimer", nameof(this.TimerCallback), serializedTimerParams, TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3));
+ }
- public Task RegisterTimerWithTtl(TimeSpan ttl)
+ public Task RegisterTimerWithTtl(TimeSpan ttl)
+ {
+ var timerParams = new TimerParams
{
- var timerParams = new TimerParams
- {
- IntParam = 100,
- StringParam = "timer test",
- };
+ IntParam = 100,
+ StringParam = "timer test",
+ };
- var serializedTimerParams = JsonSerializer.SerializeToUtf8Bytes(timerParams);
- return this.RegisterTimerAsync("TestTimer", nameof(this.TimerCallback), serializedTimerParams, TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3), ttl);
- }
+ var serializedTimerParams = JsonSerializer.SerializeToUtf8Bytes(timerParams);
+ return this.RegisterTimerAsync("TestTimer", nameof(this.TimerCallback), serializedTimerParams, TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3), ttl);
+ }
- public Task UnregisterTimer()
- {
- return this.UnregisterTimerAsync("TestTimer");
- }
+ public Task UnregisterTimer()
+ {
+ return this.UnregisterTimerAsync("TestTimer");
+ }
- // This method is called whenever an actor is activated.
- // An actor is activated the first time any of its methods are invoked.
- protected override Task OnActivateAsync()
- {
- // Provides opportunity to perform some optional setup.
- return Task.CompletedTask;
- }
+ // This method is called whenever an actor is activated.
+ // An actor is activated the first time any of its methods are invoked.
+ protected override Task OnActivateAsync()
+ {
+ // Provides opportunity to perform some optional setup.
+ return Task.CompletedTask;
+ }
- // This method is called whenever an actor is deactivated after a period of inactivity.
- protected override Task OnDeactivateAsync()
- {
- // Provides Opportunity to perform optional cleanup.
- return Task.CompletedTask;
- }
+ // This method is called whenever an actor is deactivated after a period of inactivity.
+ protected override Task OnDeactivateAsync()
+ {
+ // Provides Opportunity to perform optional cleanup.
+ return Task.CompletedTask;
+ }
- ///
- /// This method is called when the timer is triggered based on its registration.
- /// It updates the PropertyA value.
- ///
- /// Timer input data.
- /// A task that represents the asynchronous operation.
- public async Task TimerCallback(byte[] data)
+ ///
+ /// This method is called when the timer is triggered based on its registration.
+ /// It updates the PropertyA value.
+ ///
+ /// Timer input data.
+ /// A task that represents the asynchronous operation.
+ public async Task TimerCallback(byte[] data)
+ {
+ var state = await this.StateManager.GetStateAsync(StateName);
+ var updatedState = state with { PropertyA = $"Timer triggered at '{DateTime.Now:yyyyy-MM-ddTHH:mm:s}'" };
+ await this.StateManager.SetStateAsync(StateName, updatedState, ttl: TimeSpan.FromMinutes(5));
+ var timerParams = JsonSerializer.Deserialize(data);
+ if (timerParams != null)
{
- var state = await this.StateManager.GetStateAsync(StateName);
- state.PropertyA = $"Timer triggered at '{DateTime.Now:yyyyy-MM-ddTHH:mm:s}'";
- await this.StateManager.SetStateAsync(StateName, state, ttl: TimeSpan.FromMinutes(5));
- var timerParams = JsonSerializer.Deserialize(data);
- Console.WriteLine("Timer parameter1: " + timerParams.IntParam);
- Console.WriteLine("Timer parameter2: " + timerParams.StringParam);
+ Console.WriteLine($"Timer parameter1: {timerParams.IntParam}");
+ Console.WriteLine($"Timer parameter2: {timerParams.StringParam ?? ""}");
}
+ }
- public async Task GetAccountBalance()
- {
- var starting = new AccountBalance()
- {
- AccountId = this.Id.GetId(),
- Balance = 100m, // Start new accounts with 100, we're pretty generous.
- };
+ public async Task GetAccountBalance()
+ {
+ var starting = new AccountBalance(this.Id.GetId(), 100m); // Start new accounts with 100 million; we're pretty generous
- var balance = await this.StateManager.GetOrAddStateAsync("balance", starting);
- return balance;
- }
+ var balance = await this.StateManager.GetOrAddStateAsync("balance", starting);
+ return balance;
+ }
- public async Task Withdraw(WithdrawRequest withdraw)
- {
- var starting = new AccountBalance()
- {
- AccountId = this.Id.GetId(),
- Balance = 100m, // Start new accounts with 100, we're pretty generous.
- };
+ public async Task Withdraw(WithdrawRequest withdraw)
+ {
+ var starting = new AccountBalance(this.Id.GetId(), 100m); // Start new accounts with 100 million; we're pretty generous.
- var balance = await this.StateManager.GetOrAddStateAsync("balance", starting);
+ var balance = await this.StateManager.GetOrAddStateAsync("balance", starting);
- // Throws Overdraft exception if the account doesn't have enough money.
- var updated = this.bank.Withdraw(balance.Balance, withdraw.Amount);
+ // Throws Overdraft exception if the account doesn't have enough money.
+ var updated = bank.Withdraw(balance.Balance, withdraw.Amount);
- balance.Balance = updated;
- await this.StateManager.SetStateAsync("balance", balance);
- }
+ balance = balance with { Balance = updated };
+ await this.StateManager.SetStateAsync("balance", balance);
}
}
diff --git a/examples/Actor/DemoActor/DemoActor.csproj b/examples/Actor/DemoActor/DemoActor.csproj
index 4ed29d66e..f6bf9e8ee 100644
--- a/examples/Actor/DemoActor/DemoActor.csproj
+++ b/examples/Actor/DemoActor/DemoActor.csproj
@@ -4,6 +4,7 @@
true
true
demo-actor
+ enable
@@ -14,7 +15,7 @@
-
+
diff --git a/examples/Actor/DemoActor/Program.cs b/examples/Actor/DemoActor/Program.cs
index 1d538b471..575bc7183 100644
--- a/examples/Actor/DemoActor/Program.cs
+++ b/examples/Actor/DemoActor/Program.cs
@@ -11,23 +11,23 @@
// limitations under the License.
// ------------------------------------------------------------------------
-using Microsoft.AspNetCore.Hosting;
+using DemoActor;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
-namespace DemoActor
+var builder = WebApplication.CreateBuilder(args);
+builder.Services.AddSingleton();
+builder.Services.AddActors(options =>
{
- public class Program
- {
- public static void Main(string[] args)
- {
- CreateHostBuilder(args).Build().Run();
- }
+ options.Actors.RegisterActor();
+});
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup();
- });
- }
+var app = builder.Build();
+if (app.Environment.IsDevelopment())
+{
+ app.UseDeveloperExceptionPage();
}
+
+app.UseRouting();
+app.MapActorsHandlers();
diff --git a/examples/Actor/DemoActor/Startup.cs b/examples/Actor/DemoActor/Startup.cs
deleted file mode 100644
index f1165e3c7..000000000
--- a/examples/Actor/DemoActor/Startup.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-// ------------------------------------------------------------------------
-// Copyright 2021 The Dapr Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-// ------------------------------------------------------------------------
-
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Hosting;
-
-namespace DemoActor
-{
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- this.Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddSingleton();
- services.AddActors(options =>
- {
- options.Actors.RegisterActor();
- });
- }
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- else
- {
- app.UseHsts();
- }
-
- app.UseRouting();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapActorsHandlers();
- });
- }
- }
-}
diff --git a/examples/Actor/IDemoActor/IDemoActor.cs b/examples/Actor/IDemoActor/IDemoActor.cs
deleted file mode 100644
index 6f2d32801..000000000
--- a/examples/Actor/IDemoActor/IDemoActor.cs
+++ /dev/null
@@ -1,149 +0,0 @@
-// ------------------------------------------------------------------------
-// Copyright 2021 The Dapr Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-// http://www.apache.org/licenses/LICENSE-2.0
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-// ------------------------------------------------------------------------
-
-using System;
-using System.Threading.Tasks;
-using Dapr.Actors;
-
-namespace IDemoActor
-{
- ///
- /// Interface for Actor method.
- ///
- public interface IDemoActor : IActor
- {
- ///
- /// Method to save data.
- ///
- /// DAta to save.
- /// TTL of state key.
- /// A task that represents the asynchronous save operation.
- Task SaveData(MyData data, TimeSpan ttl);
-
- ///
- /// Method to get data.
- ///
- /// A task that represents the asynchronous save operation.
- Task GetData();
-
- ///
- /// A test method which throws exception.
- ///
- /// A task that represents the asynchronous save operation.
- Task TestThrowException();
-
- ///
- /// A test method which validates calls for methods with no arguments and no return types.
- ///
- /// A task that represents the asynchronous save operation.
- Task TestNoArgumentNoReturnType();
-
- ///
- /// Registers a reminder.
- ///
- /// A task that represents the asynchronous save operation.
- Task RegisterReminder();
-
- ///
- /// Registers a reminder.
- ///
- /// TimeSpan that dictates when the reminder expires.
- /// A task that represents the asynchronous save operation.
- Task RegisterReminderWithTtl(TimeSpan ttl);
-
- ///
- /// Unregisters the registered reminder.
- ///
- /// Task representing the operation.
- Task UnregisterReminder();
-
- ///
- /// Registers a timer.
- ///
- /// A task that represents the asynchronous save operation.
- Task RegisterTimer();
-
- ///
- /// Registers a timer.
- ///
- /// Optional TimeSpan that dictates when the timer expires.
- /// A task that represents the asynchronous save operation.
- Task RegisterTimerWithTtl(TimeSpan ttl);
-
- ///
- /// Registers a reminder with repetitions.
- ///
- /// The number of repetitions for which the reminder should be invoked.
- /// A task that represents the asynchronous save operation.
- Task RegisterReminderWithRepetitions(int repetitions);
-
- ///
- /// Registers a reminder with ttl and repetitions.
- ///
- /// TimeSpan that dictates when the timer expires.
- /// The number of repetitions for which the reminder should be invoked.
- /// A task that represents the asynchronous save operation.
- Task RegisterReminderWithTtlAndRepetitions(TimeSpan ttl, int repetitions);
-
- ///
- /// Gets the registered reminder.
- ///
- /// The name of the reminder.
- /// A task that returns the reminder after completion.
- Task GetReminder();
-
- ///
- /// Unregisters the registered timer.
- ///
- /// A task that represents the asynchronous save operation.
- Task UnregisterTimer();
- }
-
- ///
- /// Data Used by the Sample Actor.
- ///
- public class MyData
- {
- ///
- /// Gets or sets the value for PropertyA.
- ///
- public string PropertyA { get; set; }
-
- ///
- /// Gets or sets the value for PropertyB.
- ///
- public string PropertyB { get; set; }
-
- ///
- public override string ToString()
- {
- var propAValue = this.PropertyA ?? "null";
- var propBValue = this.PropertyB ?? "null";
- return $"PropertyA: {propAValue}, PropertyB: {propBValue}";
- }
- }
-
- public class ActorReminderData
- {
- public string Name { get; set; }
-
- public TimeSpan DueTime { get; set; }
-
- public TimeSpan Period { get; set; }
-
- public override string ToString()
- {
- return $"Name: {this.Name}, DueTime: {this.DueTime}, Period: {this.Period}";
- }
- }
-}
diff --git a/examples/AspNetCore/ControllerSample/Account.cs b/examples/AspNetCore/ControllerSample/Account.cs
index ed2bddd21..bcd0d3501 100644
--- a/examples/AspNetCore/ControllerSample/Account.cs
+++ b/examples/AspNetCore/ControllerSample/Account.cs
@@ -11,21 +11,20 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace ControllerSample
+namespace ControllerSample;
+
+///
+/// Class representing an Account for samples.
+///
+public class Account
{
///
- /// Class representing an Account for samples.
+ /// Gets or sets account id.
///
- public class Account
- {
- ///
- /// Gets or sets account id.
- ///
- public string Id { get; set; }
+ public string Id { get; set; }
- ///
- /// Gets or sets account balance.
- ///
- public decimal Balance { get; set; }
- }
+ ///
+ /// Gets or sets account balance.
+ ///
+ public decimal Balance { get; set; }
}
\ No newline at end of file
diff --git a/examples/AspNetCore/ControllerSample/Controllers/SampleController.cs b/examples/AspNetCore/ControllerSample/Controllers/SampleController.cs
index 5b339288c..195c5ea50 100644
--- a/examples/AspNetCore/ControllerSample/Controllers/SampleController.cs
+++ b/examples/AspNetCore/ControllerSample/Controllers/SampleController.cs
@@ -13,286 +13,285 @@
using System.Linq;
-namespace ControllerSample.Controllers
+namespace ControllerSample.Controllers;
+
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Dapr;
+using Dapr.AspNetCore;
+using Dapr.Client;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+///
+/// Sample showing Dapr integration with controller.
+///
+[ApiController]
+public class SampleController : ControllerBase
{
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using Dapr;
- using Dapr.AspNetCore;
- using Dapr.Client;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Logging;
+ ///
+ /// SampleController Constructor with logger injection
+ ///
+ ///
+ public SampleController(ILogger logger)
+ {
+ this.logger = logger;
+ }
///
- /// Sample showing Dapr integration with controller.
+ /// State store name.
///
- [ApiController]
- public class SampleController : ControllerBase
+ public const string StoreName = "statestore";
+
+ private readonly ILogger logger;
+
+ ///
+ /// Gets the account information as specified by the id.
+ ///
+ /// Account information for the id from Dapr state store.
+ /// Account information.
+ [HttpGet("{account}")]
+ public ActionResult Get([FromState(StoreName)] StateEntry account)
{
- ///
- /// SampleController Constructor with logger injection
- ///
- ///
- public SampleController(ILogger logger)
+ if (account.Value is null)
{
- this.logger = logger;
+ return this.NotFound();
}
- ///
- /// State store name.
- ///
- public const string StoreName = "statestore";
+ return account.Value;
+ }
- private readonly ILogger logger;
+ ///
+ /// Method for depositing to account as specified in transaction.
+ ///
+ /// Transaction info.
+ /// State client to interact with Dapr runtime.
+ /// A representing the result of the asynchronous operation.
+ /// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
+ [Topic("pubsub", "deposit", "amountDeadLetterTopic", false)]
+ [HttpPost("deposit")]
+ public async Task> Deposit(Transaction transaction, [FromServices] DaprClient daprClient)
+ {
+ // Example reading cloudevent properties from the headers
+ var headerEntries = Request.Headers.Aggregate("", (current, header) => current + ($"------- Header: {header.Key} : {header.Value}" + Environment.NewLine));
- ///
- /// Gets the account information as specified by the id.
- ///
- /// Account information for the id from Dapr state store.
- /// Account information.
- [HttpGet("{account}")]
- public ActionResult Get([FromState(StoreName)] StateEntry account)
- {
- if (account.Value is null)
- {
- return this.NotFound();
- }
+ logger.LogInformation(headerEntries);
- return account.Value;
- }
+ logger.LogInformation("Enter deposit");
+ var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
+ state.Value ??= new Account() { Id = transaction.Id, };
+ logger.LogInformation("Id is {0}, the amount to be deposited is {1}", transaction.Id, transaction.Amount);
- ///
- /// Method for depositing to account as specified in transaction.
- ///
- /// Transaction info.
- /// State client to interact with Dapr runtime.
- /// A representing the result of the asynchronous operation.
- /// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
- [Topic("pubsub", "deposit", "amountDeadLetterTopic", false)]
- [HttpPost("deposit")]
- public async Task> Deposit(Transaction transaction, [FromServices] DaprClient daprClient)
+ if (transaction.Amount < 0m)
{
- // Example reading cloudevent properties from the headers
- var headerEntries = Request.Headers.Aggregate("", (current, header) => current + ($"------- Header: {header.Key} : {header.Value}" + Environment.NewLine));
-
- logger.LogInformation(headerEntries);
+ return BadRequest(new { statusCode = 400, message = "bad request" });
+ }
- logger.LogInformation("Enter deposit");
- var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
- state.Value ??= new Account() { Id = transaction.Id, };
- logger.LogInformation("Id is {0}, the amount to be deposited is {1}", transaction.Id, transaction.Amount);
+ state.Value.Balance += transaction.Amount;
+ logger.LogInformation("Balance for Id {0} is {1}", state.Value.Id, state.Value.Balance);
+ await state.SaveAsync();
+ return state.Value;
+ }
- if (transaction.Amount < 0m)
- {
- return BadRequest(new { statusCode = 400, message = "bad request" });
- }
+ ///
+ /// Method for depositing multiple times to the account as specified in transaction.
+ ///
+ /// List of entries of type BulkMessageModel received from dapr.
+ /// State client to interact with Dapr runtime.
+ /// A representing the result of the asynchronous operation.
+ /// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
+ [Topic("pubsub", "multideposit", "amountDeadLetterTopic", false)]
+ [BulkSubscribe("multideposit", 500, 2000)]
+ [HttpPost("multideposit")]
+ public async Task> MultiDeposit([FromBody]
+ BulkSubscribeMessage>
+ bulkMessage, [FromServices] DaprClient daprClient)
+ {
+ logger.LogInformation("Enter bulk deposit");
- state.Value.Balance += transaction.Amount;
- logger.LogInformation("Balance for Id {0} is {1}", state.Value.Id, state.Value.Balance);
- await state.SaveAsync();
- return state.Value;
- }
+ List entries = new List();
- ///
- /// Method for depositing multiple times to the account as specified in transaction.
- ///
- /// List of entries of type BulkMessageModel received from dapr.
- /// State client to interact with Dapr runtime.
- /// A representing the result of the asynchronous operation.
- /// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
- [Topic("pubsub", "multideposit", "amountDeadLetterTopic", false)]
- [BulkSubscribe("multideposit", 500, 2000)]
- [HttpPost("multideposit")]
- public async Task> MultiDeposit([FromBody]
- BulkSubscribeMessage>
- bulkMessage, [FromServices] DaprClient daprClient)
+ foreach (var entry in bulkMessage.Entries)
{
- logger.LogInformation("Enter bulk deposit");
+ try
+ {
+ var transaction = entry.Event.Data;
- List entries = new List();
+ var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
+ state.Value ??= new Account() { Id = transaction.Id, };
+ logger.LogInformation("Id is {0}, the amount to be deposited is {1}",
+ transaction.Id, transaction.Amount);
- foreach (var entry in bulkMessage.Entries)
- {
- try
+ if (transaction.Amount < 0m)
{
- var transaction = entry.Event.Data;
-
- var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
- state.Value ??= new Account() { Id = transaction.Id, };
- logger.LogInformation("Id is {0}, the amount to be deposited is {1}",
- transaction.Id, transaction.Amount);
-
- if (transaction.Amount < 0m)
- {
- return BadRequest(new { statusCode = 400, message = "bad request" });
- }
-
- state.Value.Balance += transaction.Amount;
- logger.LogInformation("Balance is {0}", state.Value.Balance);
- await state.SaveAsync();
- entries.Add(
- new BulkSubscribeAppResponseEntry(entry.EntryId, BulkSubscribeAppResponseStatus.SUCCESS));
+ return BadRequest(new { statusCode = 400, message = "bad request" });
}
- catch (Exception e)
- {
- logger.LogError(e.Message);
- entries.Add(new BulkSubscribeAppResponseEntry(entry.EntryId, BulkSubscribeAppResponseStatus.RETRY));
- }
- }
-
- return new BulkSubscribeAppResponse(entries);
- }
- ///
- /// Method for viewing the error message when the deposit/withdrawal amounts
- /// are negative.
- ///
- /// Transaction info.
- [Topic("pubsub", "amountDeadLetterTopic")]
- [HttpPost("deadLetterTopicRoute")]
- public ActionResult ViewErrorMessage(Transaction transaction)
- {
- logger.LogInformation("The amount cannot be negative: {0}", transaction.Amount);
- return Ok();
- }
-
- ///
- /// Method for withdrawing from account as specified in transaction.
- ///
- /// Transaction info.
- /// State client to interact with Dapr runtime.
- /// A representing the result of the asynchronous operation.
- /// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
- [Topic("pubsub", "withdraw", "amountDeadLetterTopic", false)]
- [HttpPost("withdraw")]
- public async Task> Withdraw(Transaction transaction, [FromServices] DaprClient daprClient)
- {
- logger.LogInformation("Enter withdraw method...");
- var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
- logger.LogInformation("Id is {0}, the amount to be withdrawn is {1}", transaction.Id, transaction.Amount);
-
- if (state.Value == null)
- {
- return this.NotFound();
+ state.Value.Balance += transaction.Amount;
+ logger.LogInformation("Balance is {0}", state.Value.Balance);
+ await state.SaveAsync();
+ entries.Add(
+ new BulkSubscribeAppResponseEntry(entry.EntryId, BulkSubscribeAppResponseStatus.SUCCESS));
}
-
- if (transaction.Amount < 0m)
+ catch (Exception e)
{
- return BadRequest(new { statusCode = 400, message = "bad request" });
+ logger.LogError(e.Message);
+ entries.Add(new BulkSubscribeAppResponseEntry(entry.EntryId, BulkSubscribeAppResponseStatus.RETRY));
}
-
- state.Value.Balance -= transaction.Amount;
- logger.LogInformation("Balance is {0}", state.Value.Balance);
- await state.SaveAsync();
- return state.Value;
}
- ///
- /// Method for withdrawing from account as specified in transaction.
- ///
- /// Transaction info.
- /// State client to interact with Dapr runtime.
- /// A representing the result of the asynchronous operation.
- /// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
- [Topic("pubsub", "withdraw", "event.type ==\"withdraw.v2\"", 1)]
- [HttpPost("withdraw.v2")]
- public async Task> WithdrawV2(TransactionV2 transaction,
- [FromServices] DaprClient daprClient)
- {
- logger.LogInformation("Enter withdraw.v2");
- if (transaction.Channel == "mobile" && transaction.Amount > 10000)
- {
- return this.Unauthorized("mobile transactions for large amounts are not permitted.");
- }
+ return new BulkSubscribeAppResponse(entries);
+ }
- var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
+ ///
+ /// Method for viewing the error message when the deposit/withdrawal amounts
+ /// are negative.
+ ///
+ /// Transaction info.
+ [Topic("pubsub", "amountDeadLetterTopic")]
+ [HttpPost("deadLetterTopicRoute")]
+ public ActionResult ViewErrorMessage(Transaction transaction)
+ {
+ logger.LogInformation("The amount cannot be negative: {0}", transaction.Amount);
+ return Ok();
+ }
- if (state.Value == null)
- {
- return this.NotFound();
- }
+ ///
+ /// Method for withdrawing from account as specified in transaction.
+ ///
+ /// Transaction info.
+ /// State client to interact with Dapr runtime.
+ /// A representing the result of the asynchronous operation.
+ /// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
+ [Topic("pubsub", "withdraw", "amountDeadLetterTopic", false)]
+ [HttpPost("withdraw")]
+ public async Task> Withdraw(Transaction transaction, [FromServices] DaprClient daprClient)
+ {
+ logger.LogInformation("Enter withdraw method...");
+ var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
+ logger.LogInformation("Id is {0}, the amount to be withdrawn is {1}", transaction.Id, transaction.Amount);
- state.Value.Balance -= transaction.Amount;
- await state.SaveAsync();
- return state.Value;
+ if (state.Value == null)
+ {
+ return this.NotFound();
}
- ///
- /// Method for depositing to account as specified in transaction via a raw message.
- ///
- /// Transaction info.
- /// State client to interact with Dapr runtime.
- /// A representing the result of the asynchronous operation.
- /// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
- [Topic("pubsub", "rawDeposit", true)]
- [HttpPost("rawDeposit")]
- public async Task> RawDeposit([FromBody] JsonDocument rawTransaction,
- [FromServices] DaprClient daprClient)
+ if (transaction.Amount < 0m)
{
- var transactionString = rawTransaction.RootElement.GetProperty("data_base64").GetString();
- logger.LogInformation(
- $"Enter deposit: {transactionString} - {Encoding.UTF8.GetString(Convert.FromBase64String(transactionString))}");
- var transactionJson = JsonSerializer.Deserialize(Convert.FromBase64String(transactionString));
- var transaction =
- JsonSerializer.Deserialize(transactionJson.RootElement.GetProperty("data").GetRawText());
- var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
- state.Value ??= new Account() { Id = transaction.Id, };
- logger.LogInformation("Id is {0}, the amount to be deposited is {1}", transaction.Id, transaction.Amount);
-
- if (transaction.Amount < 0m)
- {
- return BadRequest(new { statusCode = 400, message = "bad request" });
- }
-
- state.Value.Balance += transaction.Amount;
- logger.LogInformation("Balance is {0}", state.Value.Balance);
- await state.SaveAsync();
- return state.Value;
+ return BadRequest(new { statusCode = 400, message = "bad request" });
}
- ///
- /// Method for returning a BadRequest result which will cause Dapr sidecar to throw an RpcException
- ///
- [HttpPost("throwException")]
- public async Task> ThrowException(Transaction transaction,
- [FromServices] DaprClient daprClient)
+ state.Value.Balance -= transaction.Amount;
+ logger.LogInformation("Balance is {0}", state.Value.Balance);
+ await state.SaveAsync();
+ return state.Value;
+ }
+
+ ///
+ /// Method for withdrawing from account as specified in transaction.
+ ///
+ /// Transaction info.
+ /// State client to interact with Dapr runtime.
+ /// A representing the result of the asynchronous operation.
+ /// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
+ [Topic("pubsub", "withdraw", "event.type ==\"withdraw.v2\"", 1)]
+ [HttpPost("withdraw.v2")]
+ public async Task> WithdrawV2(TransactionV2 transaction,
+ [FromServices] DaprClient daprClient)
+ {
+ logger.LogInformation("Enter withdraw.v2");
+ if (transaction.Channel == "mobile" && transaction.Amount > 10000)
{
- logger.LogInformation("Enter ThrowException");
- var task = Task.Delay(10);
- await task;
- return BadRequest(new { statusCode = 400, message = "bad request" });
+ return this.Unauthorized("mobile transactions for large amounts are not permitted.");
}
- ///
- ///
- /// Method which uses for binding this endpoint to a subscription.
- ///
- ///
- /// This endpoint will be bound to a subscription where the topic name is the value of the environment variable 'CUSTOM_TOPIC'
- /// and the pubsub name is the value of the environment variable 'CUSTOM_PUBSUB'.
- ///
- ///
- [CustomTopic("%CUSTOM_PUBSUB%", "%CUSTOM_TOPIC%")]
- [HttpPost("exampleCustomTopic")]
- public ActionResult ExampleCustomTopic(Transaction transaction)
+ var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
+
+ if (state.Value == null)
{
- return Ok();
+ return this.NotFound();
}
- ///
- /// Method which uses for binding this endpoint to a subscription and adds routingkey metadata.
- ///
- ///
- ///
- [Topic("pubsub", "topicmetadata")]
- [TopicMetadata("routingKey", "keyA")]
- [HttpPost("examplecustomtopicmetadata")]
- public ActionResult ExampleCustomTopicMetadata(Transaction transaction)
+ state.Value.Balance -= transaction.Amount;
+ await state.SaveAsync();
+ return state.Value;
+ }
+
+ ///
+ /// Method for depositing to account as specified in transaction via a raw message.
+ ///
+ /// Transaction info.
+ /// State client to interact with Dapr runtime.
+ /// A representing the result of the asynchronous operation.
+ /// "pubsub", the first parameter into the Topic attribute, is name of the default pub/sub configured by the Dapr CLI.
+ [Topic("pubsub", "rawDeposit", true)]
+ [HttpPost("rawDeposit")]
+ public async Task> RawDeposit([FromBody] JsonDocument rawTransaction,
+ [FromServices] DaprClient daprClient)
+ {
+ var transactionString = rawTransaction.RootElement.GetProperty("data_base64").GetString();
+ logger.LogInformation(
+ $"Enter deposit: {transactionString} - {Encoding.UTF8.GetString(Convert.FromBase64String(transactionString))}");
+ var transactionJson = JsonSerializer.Deserialize(Convert.FromBase64String(transactionString));
+ var transaction =
+ JsonSerializer.Deserialize(transactionJson.RootElement.GetProperty("data").GetRawText());
+ var state = await daprClient.GetStateEntryAsync(StoreName, transaction.Id);
+ state.Value ??= new Account() { Id = transaction.Id, };
+ logger.LogInformation("Id is {0}, the amount to be deposited is {1}", transaction.Id, transaction.Amount);
+
+ if (transaction.Amount < 0m)
{
- return Ok();
+ return BadRequest(new { statusCode = 400, message = "bad request" });
}
+
+ state.Value.Balance += transaction.Amount;
+ logger.LogInformation("Balance is {0}", state.Value.Balance);
+ await state.SaveAsync();
+ return state.Value;
+ }
+
+ ///
+ /// Method for returning a BadRequest result which will cause Dapr sidecar to throw an RpcException
+ ///
+ [HttpPost("throwException")]
+ public async Task> ThrowException(Transaction transaction,
+ [FromServices] DaprClient daprClient)
+ {
+ logger.LogInformation("Enter ThrowException");
+ var task = Task.Delay(10);
+ await task;
+ return BadRequest(new { statusCode = 400, message = "bad request" });
+ }
+
+ ///
+ ///
+ /// Method which uses for binding this endpoint to a subscription.
+ ///
+ ///
+ /// This endpoint will be bound to a subscription where the topic name is the value of the environment variable 'CUSTOM_TOPIC'
+ /// and the pubsub name is the value of the environment variable 'CUSTOM_PUBSUB'.
+ ///
+ ///
+ [CustomTopic("%CUSTOM_PUBSUB%", "%CUSTOM_TOPIC%")]
+ [HttpPost("exampleCustomTopic")]
+ public ActionResult ExampleCustomTopic(Transaction transaction)
+ {
+ return Ok();
+ }
+
+ ///
+ /// Method which uses for binding this endpoint to a subscription and adds routingkey metadata.
+ ///
+ ///
+ ///
+ [Topic("pubsub", "topicmetadata")]
+ [TopicMetadata("routingKey", "keyA")]
+ [HttpPost("examplecustomtopicmetadata")]
+ public ActionResult ExampleCustomTopicMetadata(Transaction transaction)
+ {
+ return Ok();
}
-}
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/ControllerSample/CustomTopicAttribute.cs b/examples/AspNetCore/ControllerSample/CustomTopicAttribute.cs
index 5c9996aea..eb96ba894 100644
--- a/examples/AspNetCore/ControllerSample/CustomTopicAttribute.cs
+++ b/examples/AspNetCore/ControllerSample/CustomTopicAttribute.cs
@@ -13,33 +13,32 @@
using Dapr.AspNetCore;
-namespace ControllerSample
+namespace ControllerSample;
+
+using System;
+using Dapr;
+
+///
+/// Sample custom implementation that returns topic metadata from environment variables.
+///
+[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
+public class CustomTopicAttribute : Attribute, ITopicMetadata
{
- using System;
- using Dapr;
-
- ///
- /// Sample custom implementation that returns topic metadata from environment variables.
- ///
- [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
- public class CustomTopicAttribute : Attribute, ITopicMetadata
+ public CustomTopicAttribute(string pubsubName, string name)
{
- public CustomTopicAttribute(string pubsubName, string name)
- {
- this.PubsubName = Environment.ExpandEnvironmentVariables(pubsubName);
- this.Name = Environment.ExpandEnvironmentVariables(name);
- }
+ this.PubsubName = Environment.ExpandEnvironmentVariables(pubsubName);
+ this.Name = Environment.ExpandEnvironmentVariables(name);
+ }
- ///
- public string PubsubName { get; }
+ ///
+ public string PubsubName { get; }
- ///
- public string Name { get; }
+ ///
+ public string Name { get; }
- ///
- public new string Match { get; }
+ ///
+ public new string Match { get; }
- ///
- public int Priority { get; }
- }
-}
+ ///
+ public int Priority { get; }
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/ControllerSample/Program.cs b/examples/AspNetCore/ControllerSample/Program.cs
index 251d11fc1..68eb85cc5 100644
--- a/examples/AspNetCore/ControllerSample/Program.cs
+++ b/examples/AspNetCore/ControllerSample/Program.cs
@@ -11,35 +11,34 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace ControllerSample
-{
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Hosting;
+namespace ControllerSample;
+
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Hosting;
+///
+/// Controller Sample.
+///
+public class Program
+{
///
- /// Controller Sample.
+ /// Main for Controller Sample.
///
- public class Program
+ /// Arguments.
+ public static void Main(string[] args)
{
- ///
- /// Main for Controller Sample.
- ///
- /// Arguments.
- public static void Main(string[] args)
- {
- CreateHostBuilder(args).Build().Run();
- }
-
- ///
- /// Creates WebHost Builder.
- ///
- /// Arguments.
- /// Returns IHostbuilder.
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup();
- });
+ CreateHostBuilder(args).Build().Run();
}
-}
+
+ ///
+ /// Creates WebHost Builder.
+ ///
+ /// Arguments.
+ /// Returns IHostbuilder.
+ public static IHostBuilder CreateHostBuilder(string[] args) =>
+ Host.CreateDefaultBuilder(args)
+ .ConfigureWebHostDefaults(webBuilder =>
+ {
+ webBuilder.UseStartup();
+ });
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/ControllerSample/Startup.cs b/examples/AspNetCore/ControllerSample/Startup.cs
index ddc6d1c5f..17afa06b5 100644
--- a/examples/AspNetCore/ControllerSample/Startup.cs
+++ b/examples/AspNetCore/ControllerSample/Startup.cs
@@ -16,68 +16,67 @@
using Dapr.AspNetCore;
-namespace ControllerSample
-{
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
+namespace ControllerSample;
+
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+///
+/// Startup class.
+///
+public class Startup
+{
///
- /// Startup class.
+ /// Initializes a new instance of the class.
///
- public class Startup
+ /// Configuration.
+ public Startup(IConfiguration configuration)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// Configuration.
- public Startup(IConfiguration configuration)
- {
- this.Configuration = configuration;
- }
+ this.Configuration = configuration;
+ }
- ///
- /// Gets the configuration.
- ///
- public IConfiguration Configuration { get; }
+ ///
+ /// Gets the configuration.
+ ///
+ public IConfiguration Configuration { get; }
- ///
- /// Configures Services.
- ///
- /// Service Collection.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllers().AddDapr();
- }
+ ///
+ /// Configures Services.
+ ///
+ /// Service Collection.
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddControllers().AddDapr();
+ }
- ///
- /// Configures Application Builder and WebHost environment.
- ///
- /// Application builder.
- /// Webhost environment.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ ///
+ /// Configures Application Builder and WebHost environment.
+ ///
+ /// Application builder.
+ /// Webhost environment.
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ {
+ if (env.IsDevelopment())
{
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
+ app.UseDeveloperExceptionPage();
+ }
- app.UseRouting();
+ app.UseRouting();
- app.UseCloudEvents(new CloudEventsMiddlewareOptions
- {
- ForwardCloudEventPropertiesAsHeaders = true
- });
+ app.UseCloudEvents(new CloudEventsMiddlewareOptions
+ {
+ ForwardCloudEventPropertiesAsHeaders = true
+ });
- app.UseAuthorization();
+ app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapSubscribeHandler();
- endpoints.MapControllers();
- });
- }
+ app.UseEndpoints(endpoints =>
+ {
+ endpoints.MapSubscribeHandler();
+ endpoints.MapControllers();
+ });
}
-}
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/ControllerSample/Transaction.cs b/examples/AspNetCore/ControllerSample/Transaction.cs
index 2d6f5a5aa..5b7a1c868 100644
--- a/examples/AspNetCore/ControllerSample/Transaction.cs
+++ b/examples/AspNetCore/ControllerSample/Transaction.cs
@@ -11,24 +11,23 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace ControllerSample
-{
- using System.ComponentModel.DataAnnotations;
+namespace ControllerSample;
+
+using System.ComponentModel.DataAnnotations;
+///
+/// Represents a transaction used by sample code.
+///
+public class Transaction
+{
///
- /// Represents a transaction used by sample code.
+ /// Gets or sets account id for the transaction.
///
- public class Transaction
- {
- ///
- /// Gets or sets account id for the transaction.
- ///
- [Required]
- public string Id { get; set; }
+ [Required]
+ public string Id { get; set; }
- ///
- /// Gets or sets amount for the transaction.
- ///
+ /// Gets or sets amount for the transaction.
+ ///
+/// Represents a transaction used by sample code.
+///
+public class TransactionV2
+{
///
- /// Represents a transaction used by sample code.
+ /// Gets or sets account id for the transaction.
///
- public class TransactionV2
- {
- ///
- /// Gets or sets account id for the transaction.
- ///
- [Required]
- public string Id { get; set; }
+ [Required]
+ public string Id { get; set; }
- ///
- /// Gets or sets amount for the transaction.
- ///
- [Range(0, double.MaxValue)]
- public decimal Amount { get; set; }
+ ///
+ /// Gets or sets amount for the transaction.
+ ///
+ [Range(0, double.MaxValue)]
+ public decimal Amount { get; set; }
- ///
- /// Gets or sets channel from which this transaction was received.
- ///
- [Required]
- public string Channel { get; set; }
- }
+ ///
+ /// Gets or sets channel from which this transaction was received.
+ ///
+ [Required]
+ public string Channel { get; set; }
}
\ No newline at end of file
diff --git a/examples/AspNetCore/GrpcServiceSample/Models/Account.cs b/examples/AspNetCore/GrpcServiceSample/Models/Account.cs
index 0b6f810d1..91746beff 100644
--- a/examples/AspNetCore/GrpcServiceSample/Models/Account.cs
+++ b/examples/AspNetCore/GrpcServiceSample/Models/Account.cs
@@ -11,21 +11,20 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace GrpcServiceSample.Models
+namespace GrpcServiceSample.Models;
+
+///
+/// Class representing an Account for samples.
+///
+public class Account
{
///
- /// Class representing an Account for samples.
+ /// Gets or sets account id.
///
- public class Account
- {
- ///
- /// Gets or sets account id.
- ///
- public string Id { get; set; }
+ public string Id { get; set; }
- ///
- /// Gets or sets account balance.
- ///
- public decimal Balance { get; set; }
- }
-}
+ ///
+ /// Gets or sets account balance.
+ ///
+ public decimal Balance { get; set; }
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/GrpcServiceSample/Models/GetAccountInput.cs b/examples/AspNetCore/GrpcServiceSample/Models/GetAccountInput.cs
index bcb835bd6..7d7f59fc4 100644
--- a/examples/AspNetCore/GrpcServiceSample/Models/GetAccountInput.cs
+++ b/examples/AspNetCore/GrpcServiceSample/Models/GetAccountInput.cs
@@ -11,16 +11,15 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace GrpcServiceSample.Models
+namespace GrpcServiceSample.Models;
+
+///
+/// BankService GetAccount input model
+///
+public class GetAccountInput
{
///
- /// BankService GetAccount input model
+ /// Id of account
///
- public class GetAccountInput
- {
- ///
- /// Id of account
- ///
- public string Id { get; set; }
- }
-}
+ public string Id { get; set; }
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/GrpcServiceSample/Models/Transaction.cs b/examples/AspNetCore/GrpcServiceSample/Models/Transaction.cs
index 7a1ef7cbd..a13e5c5eb 100644
--- a/examples/AspNetCore/GrpcServiceSample/Models/Transaction.cs
+++ b/examples/AspNetCore/GrpcServiceSample/Models/Transaction.cs
@@ -13,23 +13,22 @@
using System.ComponentModel.DataAnnotations;
-namespace GrpcServiceSample.Models
+namespace GrpcServiceSample.Models;
+
+///
+/// Represents a transaction used by sample code.
+///
+public class Transaction
{
///
- /// Represents a transaction used by sample code.
+ /// Gets or sets account id for the transaction.
///
- public class Transaction
- {
- ///
- /// Gets or sets account id for the transaction.
- ///
- [Required]
- public string Id { get; set; }
+ [Required]
+ public string Id { get; set; }
- ///
- /// Gets or sets amount for the transaction.
- ///
- [Range(0, double.MaxValue)]
- public decimal Amount { get; set; }
- }
-}
+ ///
+ /// Gets or sets amount for the transaction.
+ ///
+ [Range(0, double.MaxValue)]
+ public decimal Amount { get; set; }
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/GrpcServiceSample/Program.cs b/examples/AspNetCore/GrpcServiceSample/Program.cs
index dbec5ba2c..d7af01704 100644
--- a/examples/AspNetCore/GrpcServiceSample/Program.cs
+++ b/examples/AspNetCore/GrpcServiceSample/Program.cs
@@ -15,39 +15,38 @@
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Hosting;
-namespace GrpcServiceSample
+namespace GrpcServiceSample;
+
+///
+/// GrpcService Sample
+///
+public class Program
{
///
- /// GrpcService Sample
+ /// Entry point
///
- public class Program
+ ///
+ public static void Main(string[] args)
{
- ///
- /// Entry point
- ///
- ///
- public static void Main(string[] args)
- {
- CreateHostBuilder(args).Build().Run();
- }
+ CreateHostBuilder(args).Build().Run();
+ }
- ///
- /// Creates WebHost Builder.
- ///
- ///
- ///
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
+ ///
+ /// Creates WebHost Builder.
+ ///
+ ///
+ ///
+ public static IHostBuilder CreateHostBuilder(string[] args) =>
+ Host.CreateDefaultBuilder(args)
+ .ConfigureWebHostDefaults(webBuilder =>
+ {
+ webBuilder.ConfigureKestrel(options =>
{
- webBuilder.ConfigureKestrel(options =>
- {
- // Setup a HTTP/2 endpoint without TLS.
- options.ListenLocalhost(5050, o => o.Protocols =
- HttpProtocols.Http2);
- });
-
- webBuilder.UseStartup();
+ // Setup a HTTP/2 endpoint without TLS.
+ options.ListenLocalhost(5050, o => o.Protocols =
+ HttpProtocols.Http2);
});
- }
-}
+
+ webBuilder.UseStartup();
+ });
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/GrpcServiceSample/Services/BankingService.cs b/examples/AspNetCore/GrpcServiceSample/Services/BankingService.cs
index 9518fd610..05b037841 100644
--- a/examples/AspNetCore/GrpcServiceSample/Services/BankingService.cs
+++ b/examples/AspNetCore/GrpcServiceSample/Services/BankingService.cs
@@ -22,158 +22,157 @@
using GrpcServiceSample.Generated;
using Microsoft.Extensions.Logging;
-namespace GrpcServiceSample.Services
+namespace GrpcServiceSample.Services;
+
+///
+/// BankAccount gRPC service
+///
+public class BankingService : AppCallback.AppCallbackBase
{
///
- /// BankAccount gRPC service
+ /// State store name.
///
- public class BankingService : AppCallback.AppCallbackBase
- {
- ///
- /// State store name.
- ///
- public const string StoreName = "statestore";
+ public const string StoreName = "statestore";
- private readonly ILogger _logger;
- private readonly DaprClient _daprClient;
+ private readonly ILogger _logger;
+ private readonly DaprClient _daprClient;
- ///
- /// Constructor
- ///
- ///
- ///
- public BankingService(DaprClient daprClient, ILogger logger)
- {
- _daprClient = daprClient;
- _logger = logger;
- }
+ ///
+ /// Constructor
+ ///
+ ///
+ ///
+ public BankingService(DaprClient daprClient, ILogger logger)
+ {
+ _daprClient = daprClient;
+ _logger = logger;
+ }
- readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+ readonly JsonSerializerOptions jsonOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
- ///
- /// implement OnIvoke to support getaccount, deposit and withdraw
- ///
- ///
- ///
- ///
- public override async Task OnInvoke(InvokeRequest request, ServerCallContext context)
+ ///
+ /// implement OnIvoke to support getaccount, deposit and withdraw
+ ///
+ ///
+ ///
+ ///
+ public override async Task OnInvoke(InvokeRequest request, ServerCallContext context)
+ {
+ var response = new InvokeResponse();
+ switch (request.Method)
{
- var response = new InvokeResponse();
- switch (request.Method)
- {
- case "getaccount":
- var input = request.Data.Unpack();
- var output = await GetAccount(input, context);
- response.Data = Any.Pack(output);
- break;
- case "deposit":
- case "withdraw":
- var transaction = request.Data.Unpack();
- var account = request.Method == "deposit" ?
- await Deposit(transaction, context) :
- await Withdraw(transaction, context);
- response.Data = Any.Pack(account);
- break;
- default:
- break;
- }
- return response;
+ case "getaccount":
+ var input = request.Data.Unpack();
+ var output = await GetAccount(input, context);
+ response.Data = Any.Pack(output);
+ break;
+ case "deposit":
+ case "withdraw":
+ var transaction = request.Data.Unpack();
+ var account = request.Method == "deposit" ?
+ await Deposit(transaction, context) :
+ await Withdraw(transaction, context);
+ response.Data = Any.Pack(account);
+ break;
+ default:
+ break;
}
+ return response;
+ }
- ///
- /// implement ListTopicSubscriptions to register deposit and withdraw subscriber
- ///
- ///
- ///
- ///
- public override Task ListTopicSubscriptions(Empty request, ServerCallContext context)
+ ///
+ /// implement ListTopicSubscriptions to register deposit and withdraw subscriber
+ ///
+ ///
+ ///
+ ///
+ public override Task ListTopicSubscriptions(Empty request, ServerCallContext context)
+ {
+ var result = new ListTopicSubscriptionsResponse();
+ result.Subscriptions.Add(new TopicSubscription
{
- var result = new ListTopicSubscriptionsResponse();
- result.Subscriptions.Add(new TopicSubscription
- {
- PubsubName = "pubsub",
- Topic = "deposit"
- });
- result.Subscriptions.Add(new TopicSubscription
- {
- PubsubName = "pubsub",
- Topic = "withdraw"
- });
- return Task.FromResult(result);
- }
+ PubsubName = "pubsub",
+ Topic = "deposit"
+ });
+ result.Subscriptions.Add(new TopicSubscription
+ {
+ PubsubName = "pubsub",
+ Topic = "withdraw"
+ });
+ return Task.FromResult(result);
+ }
- ///
- /// implement OnTopicEvent to handle deposit and withdraw event
- ///
- ///
- ///
- ///
- public override async Task OnTopicEvent(TopicEventRequest request, ServerCallContext context)
+ ///
+ /// implement OnTopicEvent to handle deposit and withdraw event
+ ///
+ ///
+ ///
+ ///
+ public override async Task OnTopicEvent(TopicEventRequest request, ServerCallContext context)
+ {
+ if (request.PubsubName == "pubsub")
{
- if (request.PubsubName == "pubsub")
+ var input = JsonSerializer.Deserialize(request.Data.ToStringUtf8(), this.jsonOptions);
+ var transaction = new GrpcServiceSample.Generated.Transaction() { Id = input.Id, Amount = (int)input.Amount, };
+ if (request.Topic == "deposit")
{
- var input = JsonSerializer.Deserialize(request.Data.ToStringUtf8(), this.jsonOptions);
- var transaction = new GrpcServiceSample.Generated.Transaction() { Id = input.Id, Amount = (int)input.Amount, };
- if (request.Topic == "deposit")
- {
- await Deposit(transaction, context);
- }
- else
- {
- await Withdraw(transaction, context);
- }
+ await Deposit(transaction, context);
+ }
+ else
+ {
+ await Withdraw(transaction, context);
}
-
- return new TopicEventResponse();
}
- ///
- /// GetAccount
- ///
- ///
- ///
- ///
- public async Task GetAccount(GetAccountRequest input, ServerCallContext context)
- {
- var state = await _daprClient.GetStateEntryAsync(StoreName, input.Id);
- return new GrpcServiceSample.Generated.Account() { Id = state.Value.Id, Balance = (int)state.Value.Balance, };
- }
+ return new TopicEventResponse();
+ }
- ///
- /// Deposit
- ///
- ///
- ///
- ///
- public async Task Deposit(GrpcServiceSample.Generated.Transaction transaction, ServerCallContext context)
- {
- _logger.LogDebug("Enter deposit");
- var state = await _daprClient.GetStateEntryAsync(StoreName, transaction.Id);
- state.Value ??= new Models.Account() { Id = transaction.Id, };
- state.Value.Balance += transaction.Amount;
- await state.SaveAsync();
- return new GrpcServiceSample.Generated.Account() { Id = state.Value.Id, Balance = (int)state.Value.Balance, };
- }
+ ///
+ /// GetAccount
+ ///
+ ///
+ ///
+ ///
+ public async Task GetAccount(GetAccountRequest input, ServerCallContext context)
+ {
+ var state = await _daprClient.GetStateEntryAsync(StoreName, input.Id);
+ return new GrpcServiceSample.Generated.Account() { Id = state.Value.Id, Balance = (int)state.Value.Balance, };
+ }
- ///
- /// Withdraw
- ///
- ///
- ///
- ///
- public async Task Withdraw(GrpcServiceSample.Generated.Transaction transaction, ServerCallContext context)
- {
- _logger.LogDebug("Enter withdraw");
- var state = await _daprClient.GetStateEntryAsync(StoreName, transaction.Id);
+ ///
+ /// Deposit
+ ///
+ ///
+ ///
+ ///
+ public async Task Deposit(GrpcServiceSample.Generated.Transaction transaction, ServerCallContext context)
+ {
+ _logger.LogDebug("Enter deposit");
+ var state = await _daprClient.GetStateEntryAsync(StoreName, transaction.Id);
+ state.Value ??= new Models.Account() { Id = transaction.Id, };
+ state.Value.Balance += transaction.Amount;
+ await state.SaveAsync();
+ return new GrpcServiceSample.Generated.Account() { Id = state.Value.Id, Balance = (int)state.Value.Balance, };
+ }
- if (state.Value == null)
- {
- throw new Exception($"NotFound: {transaction.Id}");
- }
+ ///
+ /// Withdraw
+ ///
+ ///
+ ///
+ ///
+ public async Task Withdraw(GrpcServiceSample.Generated.Transaction transaction, ServerCallContext context)
+ {
+ _logger.LogDebug("Enter withdraw");
+ var state = await _daprClient.GetStateEntryAsync(StoreName, transaction.Id);
- state.Value.Balance -= transaction.Amount;
- await state.SaveAsync();
- return new GrpcServiceSample.Generated.Account() { Id = state.Value.Id, Balance = (int)state.Value.Balance, };
+ if (state.Value == null)
+ {
+ throw new Exception($"NotFound: {transaction.Id}");
}
+
+ state.Value.Balance -= transaction.Amount;
+ await state.SaveAsync();
+ return new GrpcServiceSample.Generated.Account() { Id = state.Value.Id, Balance = (int)state.Value.Balance, };
}
-}
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/GrpcServiceSample/Startup.cs b/examples/AspNetCore/GrpcServiceSample/Startup.cs
index 4aa5ac7d3..f2c606496 100644
--- a/examples/AspNetCore/GrpcServiceSample/Startup.cs
+++ b/examples/AspNetCore/GrpcServiceSample/Startup.cs
@@ -19,47 +19,46 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
-namespace GrpcServiceSample
+namespace GrpcServiceSample;
+
+///
+/// Startup class.
+///
+public class Startup
{
///
- /// Startup class.
+ /// Configure Services
///
- public class Startup
+ ///
+ public void ConfigureServices(IServiceCollection services)
{
- ///
- /// Configure Services
- ///
- ///
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddGrpc();
+ services.AddGrpc();
- services.AddDaprClient();
- }
+ services.AddDaprClient();
+ }
- ///
- /// Configure app
- ///
- ///
- ///
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ ///
+ /// Configure app
+ ///
+ ///
+ ///
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ {
+ if (env.IsDevelopment())
{
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
+ app.UseDeveloperExceptionPage();
+ }
- app.UseRouting();
+ app.UseRouting();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapGrpcService();
+ app.UseEndpoints(endpoints =>
+ {
+ endpoints.MapGrpcService();
- endpoints.MapGet("/", async context =>
- {
- await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
- });
+ endpoints.MapGet("/", async context =>
+ {
+ await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
});
- }
+ });
}
-}
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/RoutingSample/Account.cs b/examples/AspNetCore/RoutingSample/Account.cs
index ede662b10..5aac78ce6 100644
--- a/examples/AspNetCore/RoutingSample/Account.cs
+++ b/examples/AspNetCore/RoutingSample/Account.cs
@@ -11,21 +11,20 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace RoutingSample
+namespace RoutingSample;
+
+///
+/// Class representing an Account for samples.
+///
+public class Account
{
///
- /// Class representing an Account for samples.
+ /// Gets or sets account id.
///
- public class Account
- {
- ///
- /// Gets or sets account id.
- ///
- public string Id { get; set; }
+ public string Id { get; set; }
- ///
- /// Gets or sets account balance.
- ///
- public decimal Balance { get; set; }
- }
+ ///
+ /// Gets or sets account balance.
+ ///
+ public decimal Balance { get; set; }
}
\ No newline at end of file
diff --git a/examples/AspNetCore/RoutingSample/Program.cs b/examples/AspNetCore/RoutingSample/Program.cs
index 505f58d10..6aa86d120 100644
--- a/examples/AspNetCore/RoutingSample/Program.cs
+++ b/examples/AspNetCore/RoutingSample/Program.cs
@@ -11,35 +11,34 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace RoutingSample
-{
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Hosting;
+namespace RoutingSample;
+
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Hosting;
+///
+/// Controller Sample.
+///
+public static class Program
+{
///
- /// Controller Sample.
+ /// Main for Controller Sample.
///
- public static class Program
+ /// Arguments.
+ public static void Main(string[] args)
{
- ///
- /// Main for Controller Sample.
- ///
- /// Arguments.
- public static void Main(string[] args)
- {
- CreateHostBuilder(args).Build().Run();
- }
-
- ///
- /// Creates WebHost Builder.
- ///
- /// Arguments.
- /// Returns IHostbuilder.
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup();
- });
+ CreateHostBuilder(args).Build().Run();
}
-}
+
+ ///
+ /// Creates WebHost Builder.
+ ///
+ /// Arguments.
+ /// Returns IHostbuilder.
+ public static IHostBuilder CreateHostBuilder(string[] args) =>
+ Host.CreateDefaultBuilder(args)
+ .ConfigureWebHostDefaults(webBuilder =>
+ {
+ webBuilder.UseStartup();
+ });
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/RoutingSample/Startup.cs b/examples/AspNetCore/RoutingSample/Startup.cs
index 3d71e9e1f..3e7d7b0c5 100644
--- a/examples/AspNetCore/RoutingSample/Startup.cs
+++ b/examples/AspNetCore/RoutingSample/Startup.cs
@@ -11,254 +11,253 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace RoutingSample
+namespace RoutingSample;
+
+using System;
+using System.Collections.Generic;
+using System.Text.Json;
+using System.Threading.Tasks;
+using Dapr;
+using Dapr.AspNetCore;
+using Dapr.Client;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+
+///
+/// Startup class.
+///
+public class Startup
{
- using System;
- using System.Collections.Generic;
- using System.Text.Json;
- using System.Threading.Tasks;
- using Dapr;
- using Dapr.AspNetCore;
- using Dapr.Client;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
+ ///
+ /// State store name.
+ ///
+ public const string StoreName = "statestore";
+
+ ///
+ /// Pubsub component name. "pubsub" is name of the default pub/sub configured by the Dapr CLI.
+ ///
+ public const string PubsubName = "pubsub";
///
- /// Startup class.
+ /// Initializes a new instance of the class.
///
- public class Startup
+ /// Configuration.
+ public Startup(IConfiguration configuration)
{
- ///
- /// State store name.
- ///
- public const string StoreName = "statestore";
-
- ///
- /// Pubsub component name. "pubsub" is name of the default pub/sub configured by the Dapr CLI.
- ///
- public const string PubsubName = "pubsub";
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Configuration.
- public Startup(IConfiguration configuration)
- {
- this.Configuration = configuration;
- }
+ this.Configuration = configuration;
+ }
+
+ ///
+ /// Gets the configuration.
+ ///
+ public IConfiguration Configuration { get; }
- ///
- /// Gets the configuration.
- ///
- public IConfiguration Configuration { get; }
+ ///
+ /// Configures Services.
+ ///
+ /// Service Collection.
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddDaprClient();
- ///
- /// Configures Services.
- ///
- /// Service Collection.
- public void ConfigureServices(IServiceCollection services)
+ services.AddSingleton(new JsonSerializerOptions()
{
- services.AddDaprClient();
-
- services.AddSingleton(new JsonSerializerOptions()
- {
- PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
- PropertyNameCaseInsensitive = true,
- });
- }
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+ PropertyNameCaseInsensitive = true,
+ });
+ }
- ///
- /// Configures Application Builder and WebHost environment.
- ///
- /// Application builder.
- /// Webhost environment.
- /// Options for JSON serialization.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env, JsonSerializerOptions serializerOptions,
- ILogger logger)
+ ///
+ /// Configures Application Builder and WebHost environment.
+ ///
+ /// Application builder.
+ /// Webhost environment.
+ /// Options for JSON serialization.
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, JsonSerializerOptions serializerOptions,
+ ILogger logger)
+ {
+ if (env.IsDevelopment())
{
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
+ app.UseDeveloperExceptionPage();
+ }
- app.UseRouting();
+ app.UseRouting();
- app.UseCloudEvents();
+ app.UseCloudEvents();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapSubscribeHandler();
+ app.UseEndpoints(endpoints =>
+ {
+ endpoints.MapSubscribeHandler();
- var depositTopicOptions = new TopicOptions();
- depositTopicOptions.PubsubName = PubsubName;
- depositTopicOptions.Name = "deposit";
- depositTopicOptions.DeadLetterTopic = "amountDeadLetterTopic";
+ var depositTopicOptions = new TopicOptions();
+ depositTopicOptions.PubsubName = PubsubName;
+ depositTopicOptions.Name = "deposit";
+ depositTopicOptions.DeadLetterTopic = "amountDeadLetterTopic";
- var withdrawTopicOptions = new TopicOptions();
- withdrawTopicOptions.PubsubName = PubsubName;
- withdrawTopicOptions.Name = "withdraw";
- withdrawTopicOptions.DeadLetterTopic = "amountDeadLetterTopic";
+ var withdrawTopicOptions = new TopicOptions();
+ withdrawTopicOptions.PubsubName = PubsubName;
+ withdrawTopicOptions.Name = "withdraw";
+ withdrawTopicOptions.DeadLetterTopic = "amountDeadLetterTopic";
- var multiDepositTopicOptions = new TopicOptions { PubsubName = PubsubName, Name = "multideposit" };
-
- var bulkSubscribeTopicOptions = new BulkSubscribeTopicOptions
- {
- TopicName = "multideposit", MaxMessagesCount = 250, MaxAwaitDurationMs = 1000
- };
+ var multiDepositTopicOptions = new TopicOptions { PubsubName = PubsubName, Name = "multideposit" };
- endpoints.MapGet("{id}", Balance);
- endpoints.MapPost("deposit", Deposit).WithTopic(depositTopicOptions);
- endpoints.MapPost("multideposit", MultiDeposit).WithTopic(multiDepositTopicOptions).WithBulkSubscribe(bulkSubscribeTopicOptions);
- endpoints.MapPost("deadLetterTopicRoute", ViewErrorMessage).WithTopic(PubsubName, "amountDeadLetterTopic");
- endpoints.MapPost("withdraw", Withdraw).WithTopic(withdrawTopicOptions);
- });
-
- async Task Balance(HttpContext context)
+ var bulkSubscribeTopicOptions = new BulkSubscribeTopicOptions
{
- logger.LogInformation("Enter Balance");
- var client = context.RequestServices.GetRequiredService();
+ TopicName = "multideposit", MaxMessagesCount = 250, MaxAwaitDurationMs = 1000
+ };
- var id = (string)context.Request.RouteValues["id"];
- logger.LogInformation("id is {0}", id);
- var account = await client.GetStateAsync(StoreName, id);
- if (account == null)
- {
- logger.LogInformation("Account not found");
- context.Response.StatusCode = 404;
- return;
- }
+ endpoints.MapGet("{id}", Balance);
+ endpoints.MapPost("deposit", Deposit).WithTopic(depositTopicOptions);
+ endpoints.MapPost("multideposit", MultiDeposit).WithTopic(multiDepositTopicOptions).WithBulkSubscribe(bulkSubscribeTopicOptions);
+ endpoints.MapPost("deadLetterTopicRoute", ViewErrorMessage).WithTopic(PubsubName, "amountDeadLetterTopic");
+ endpoints.MapPost("withdraw", Withdraw).WithTopic(withdrawTopicOptions);
+ });
- logger.LogInformation("Account balance is {0}", account.Balance);
+ async Task Balance(HttpContext context)
+ {
+ logger.LogInformation("Enter Balance");
+ var client = context.RequestServices.GetRequiredService();
- context.Response.ContentType = "application/json";
- await JsonSerializer.SerializeAsync(context.Response.Body, account, serializerOptions);
+ var id = (string)context.Request.RouteValues["id"];
+ logger.LogInformation("id is {0}", id);
+ var account = await client.GetStateAsync(StoreName, id);
+ if (account == null)
+ {
+ logger.LogInformation("Account not found");
+ context.Response.StatusCode = 404;
+ return;
}
- async Task Deposit(HttpContext context)
- {
- logger.LogInformation("Enter Deposit");
+ logger.LogInformation("Account balance is {0}", account.Balance);
- var client = context.RequestServices.GetRequiredService();
- var transaction = await JsonSerializer.DeserializeAsync(context.Request.Body, serializerOptions);
+ context.Response.ContentType = "application/json";
+ await JsonSerializer.SerializeAsync(context.Response.Body, account, serializerOptions);
+ }
- logger.LogInformation("Id is {0}, Amount is {1}", transaction.Id, transaction.Amount);
+ async Task Deposit(HttpContext context)
+ {
+ logger.LogInformation("Enter Deposit");
- var account = await client.GetStateAsync(StoreName, transaction.Id);
- if (account == null)
- {
- account = new Account() { Id = transaction.Id, };
- }
+ var client = context.RequestServices.GetRequiredService();
+ var transaction = await JsonSerializer.DeserializeAsync(context.Request.Body, serializerOptions);
- if (transaction.Amount < 0m)
- {
- logger.LogInformation("Invalid amount");
- context.Response.StatusCode = 400;
- return;
- }
+ logger.LogInformation("Id is {0}, Amount is {1}", transaction.Id, transaction.Amount);
- account.Balance += transaction.Amount;
- await client.SaveStateAsync(StoreName, transaction.Id, account);
- logger.LogInformation("Balance is {0}", account.Balance);
+ var account = await client.GetStateAsync(StoreName, transaction.Id);
+ if (account == null)
+ {
+ account = new Account() { Id = transaction.Id, };
+ }
- context.Response.ContentType = "application/json";
- await JsonSerializer.SerializeAsync(context.Response.Body, account, serializerOptions);
+ if (transaction.Amount < 0m)
+ {
+ logger.LogInformation("Invalid amount");
+ context.Response.StatusCode = 400;
+ return;
}
+
+ account.Balance += transaction.Amount;
+ await client.SaveStateAsync(StoreName, transaction.Id, account);
+ logger.LogInformation("Balance is {0}", account.Balance);
+
+ context.Response.ContentType = "application/json";
+ await JsonSerializer.SerializeAsync(context.Response.Body, account, serializerOptions);
+ }
- async Task MultiDeposit(HttpContext context)
- {
- logger.LogInformation("Enter bulk deposit");
+ async Task MultiDeposit(HttpContext context)
+ {
+ logger.LogInformation("Enter bulk deposit");
- var client = context.RequestServices.GetRequiredService();
+ var client = context.RequestServices.GetRequiredService();
- var bulkMessage = await JsonSerializer.DeserializeAsync>>(
- context.Request.Body, serializerOptions);
+ var bulkMessage = await JsonSerializer.DeserializeAsync>>(
+ context.Request.Body, serializerOptions);
- List entries = new List();
+ List entries = new List();
- if (bulkMessage != null)
+ if (bulkMessage != null)
+ {
+ foreach (var entry in bulkMessage.Entries)
{
- foreach (var entry in bulkMessage.Entries)
+ try
{
- try
- {
- var transaction = entry.Event.Data;
-
- var state = await client.GetStateEntryAsync(StoreName, transaction.Id);
- state.Value ??= new Account() { Id = transaction.Id, };
- logger.LogInformation("Id is {0}, the amount to be deposited is {1}",
- transaction.Id, transaction.Amount);
-
- if (transaction.Amount < 0m)
- {
- logger.LogInformation("Invalid amount");
- context.Response.StatusCode = 400;
- return;
- }
-
- state.Value.Balance += transaction.Amount;
- logger.LogInformation("Balance is {0}", state.Value.Balance);
- await state.SaveAsync();
- entries.Add(new BulkSubscribeAppResponseEntry(entry.EntryId,
- BulkSubscribeAppResponseStatus.SUCCESS));
- }
- catch (Exception e)
+ var transaction = entry.Event.Data;
+
+ var state = await client.GetStateEntryAsync(StoreName, transaction.Id);
+ state.Value ??= new Account() { Id = transaction.Id, };
+ logger.LogInformation("Id is {0}, the amount to be deposited is {1}",
+ transaction.Id, transaction.Amount);
+
+ if (transaction.Amount < 0m)
{
- logger.LogError(e.Message);
- entries.Add(new BulkSubscribeAppResponseEntry(entry.EntryId,
- BulkSubscribeAppResponseStatus.RETRY));
+ logger.LogInformation("Invalid amount");
+ context.Response.StatusCode = 400;
+ return;
}
+
+ state.Value.Balance += transaction.Amount;
+ logger.LogInformation("Balance is {0}", state.Value.Balance);
+ await state.SaveAsync();
+ entries.Add(new BulkSubscribeAppResponseEntry(entry.EntryId,
+ BulkSubscribeAppResponseStatus.SUCCESS));
+ }
+ catch (Exception e)
+ {
+ logger.LogError(e.Message);
+ entries.Add(new BulkSubscribeAppResponseEntry(entry.EntryId,
+ BulkSubscribeAppResponseStatus.RETRY));
}
}
-
- await JsonSerializer.SerializeAsync(context.Response.Body,
- new BulkSubscribeAppResponse(entries), serializerOptions);
}
- async Task ViewErrorMessage(HttpContext context)
- {
- var transaction = await JsonSerializer.DeserializeAsync(context.Request.Body, serializerOptions);
+ await JsonSerializer.SerializeAsync(context.Response.Body,
+ new BulkSubscribeAppResponse(entries), serializerOptions);
+ }
- logger.LogInformation("The amount cannot be negative: {0}", transaction.Amount);
+ async Task ViewErrorMessage(HttpContext context)
+ {
+ var transaction = await JsonSerializer.DeserializeAsync(context.Request.Body, serializerOptions);
- return;
- }
+ logger.LogInformation("The amount cannot be negative: {0}", transaction.Amount);
- async Task Withdraw(HttpContext context)
- {
- logger.LogInformation("Enter Withdraw");
+ return;
+ }
- var client = context.RequestServices.GetRequiredService();
- var transaction = await JsonSerializer.DeserializeAsync(context.Request.Body, serializerOptions);
+ async Task Withdraw(HttpContext context)
+ {
+ logger.LogInformation("Enter Withdraw");
- logger.LogInformation("Id is {0}, Amount is {1}", transaction.Id, transaction.Amount);
+ var client = context.RequestServices.GetRequiredService();
+ var transaction = await JsonSerializer.DeserializeAsync(context.Request.Body, serializerOptions);
- var account = await client.GetStateAsync(StoreName, transaction.Id);
- if (account == null)
- {
- logger.LogInformation("Account not found");
- context.Response.StatusCode = 404;
- return;
- }
+ logger.LogInformation("Id is {0}, Amount is {1}", transaction.Id, transaction.Amount);
- if (transaction.Amount < 0m)
- {
- logger.LogInformation("Invalid amount");
- context.Response.StatusCode = 400;
- return;
- }
-
- account.Balance -= transaction.Amount;
- await client.SaveStateAsync(StoreName, transaction.Id, account);
- logger.LogInformation("Balance is {0}", account.Balance);
+ var account = await client.GetStateAsync(StoreName, transaction.Id);
+ if (account == null)
+ {
+ logger.LogInformation("Account not found");
+ context.Response.StatusCode = 404;
+ return;
+ }
- context.Response.ContentType = "application/json";
- await JsonSerializer.SerializeAsync(context.Response.Body, account, serializerOptions);
+ if (transaction.Amount < 0m)
+ {
+ logger.LogInformation("Invalid amount");
+ context.Response.StatusCode = 400;
+ return;
}
+
+ account.Balance -= transaction.Amount;
+ await client.SaveStateAsync(StoreName, transaction.Id, account);
+ logger.LogInformation("Balance is {0}", account.Balance);
+
+ context.Response.ContentType = "application/json";
+ await JsonSerializer.SerializeAsync(context.Response.Body, account, serializerOptions);
}
}
-}
+}
\ No newline at end of file
diff --git a/examples/AspNetCore/RoutingSample/Transaction.cs b/examples/AspNetCore/RoutingSample/Transaction.cs
index f37340f45..b6042e433 100644
--- a/examples/AspNetCore/RoutingSample/Transaction.cs
+++ b/examples/AspNetCore/RoutingSample/Transaction.cs
@@ -11,21 +11,20 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace RoutingSample
+namespace RoutingSample;
+
+///
+/// Represents a transaction used by sample code.
+///
+public class Transaction
{
///
- /// Represents a transaction used by sample code.
+ /// Gets or sets account id for the transaction.
///
- public class Transaction
- {
- ///
- /// Gets or sets account id for the transaction.
- ///
- public string Id { get; set; }
+ public string Id { get; set; }
- ///
- /// Gets or sets amount for the transaction.
- ///
- public decimal Amount { get; set; }
- }
+ ///
+ /// Gets or sets amount for the transaction.
+ ///
+ public decimal Amount { get; set; }
}
\ No newline at end of file
diff --git a/examples/AspNetCore/SecretStoreConfigurationProviderSample/Program.cs b/examples/AspNetCore/SecretStoreConfigurationProviderSample/Program.cs
index 658d6d163..fd4b31c8d 100644
--- a/examples/AspNetCore/SecretStoreConfigurationProviderSample/Program.cs
+++ b/examples/AspNetCore/SecretStoreConfigurationProviderSample/Program.cs
@@ -11,64 +11,63 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace SecretStoreConfigurationProviderSample
-{
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Hosting;
- using Dapr.Client;
- using Dapr.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using System;
+namespace SecretStoreConfigurationProviderSample;
+
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Hosting;
+using Dapr.Client;
+using Dapr.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+///
+/// Secret Store Configuration Provider Sample.
+///
+public class Program
+{
///
- /// Secret Store Configuration Provider Sample.
+ /// Main for Secret Store Configuration Provider Sample.
///
- public class Program
+ /// Arguments.
+ public static void Main(string[] args)
{
- ///
- /// Main for Secret Store Configuration Provider Sample.
- ///
- /// Arguments.
- public static void Main(string[] args)
- {
- CreateHostBuilder(args).Build().Run();
- }
+ CreateHostBuilder(args).Build().Run();
+ }
- ///
- /// Creates WebHost Builder.
- ///
- /// Arguments.
- /// Returns IHostbuilder.
- public static IHostBuilder CreateHostBuilder(string[] args)
- {
- // Create Dapr Client
- var client = new DaprClientBuilder()
- .Build();
+ ///
+ /// Creates WebHost Builder.
+ ///
+ /// Arguments.
+ /// Returns IHostbuilder.
+ public static IHostBuilder CreateHostBuilder(string[] args)
+ {
+ // Create Dapr Client
+ var client = new DaprClientBuilder()
+ .Build();
- return Host.CreateDefaultBuilder(args)
- .ConfigureServices((services) =>
- {
- // Add the DaprClient to DI.
- services.AddSingleton(client);
- })
- .ConfigureAppConfiguration((configBuilder) =>
- {
- // To retrive specific secrets use secretDescriptors
- // Create descriptors for the secrets you want to rerieve from the Dapr Secret Store.
- // var secretDescriptors = new DaprSecretDescriptor[]
- // {
- // new DaprSecretDescriptor("super-secret")
- // };
- // configBuilder.AddDaprSecretStore("demosecrets", secretDescriptors, client);
+ return Host.CreateDefaultBuilder(args)
+ .ConfigureServices((services) =>
+ {
+ // Add the DaprClient to DI.
+ services.AddSingleton(client);
+ })
+ .ConfigureAppConfiguration((configBuilder) =>
+ {
+ // To retrive specific secrets use secretDescriptors
+ // Create descriptors for the secrets you want to rerieve from the Dapr Secret Store.
+ // var secretDescriptors = new DaprSecretDescriptor[]
+ // {
+ // new DaprSecretDescriptor("super-secret")
+ // };
+ // configBuilder.AddDaprSecretStore("demosecrets", secretDescriptors, client);
- // Add the secret store Configuration Provider to the configuration builder.
- // Including a TimeSpan allows us to dictate how long we should wait for the Sidecar to start.
- configBuilder.AddDaprSecretStore("demosecrets", client, TimeSpan.FromSeconds(10));
- })
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup();
- });
- }
+ // Add the secret store Configuration Provider to the configuration builder.
+ // Including a TimeSpan allows us to dictate how long we should wait for the Sidecar to start.
+ configBuilder.AddDaprSecretStore("demosecrets", client, TimeSpan.FromSeconds(10));
+ })
+ .ConfigureWebHostDefaults(webBuilder =>
+ {
+ webBuilder.UseStartup();
+ });
}
}
\ No newline at end of file
diff --git a/examples/AspNetCore/SecretStoreConfigurationProviderSample/Startup.cs b/examples/AspNetCore/SecretStoreConfigurationProviderSample/Startup.cs
index 6d2268d64..c89dcff82 100644
--- a/examples/AspNetCore/SecretStoreConfigurationProviderSample/Startup.cs
+++ b/examples/AspNetCore/SecretStoreConfigurationProviderSample/Startup.cs
@@ -11,72 +11,71 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace SecretStoreConfigurationProviderSample
-{
- using System.Text.Json;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.DependencyInjection;
+namespace SecretStoreConfigurationProviderSample;
+
+using System.Text.Json;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.DependencyInjection;
+///
+/// Startup class.
+///
+public class Startup
+{
///
- /// Startup class.
+ /// Initializes a new instance of the class.
///
- public class Startup
+ /// Configuration.
+ public Startup(IConfiguration configuration)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// Configuration.
- public Startup(IConfiguration configuration)
- {
- this.Configuration = configuration;
- }
+ this.Configuration = configuration;
+ }
- ///
- /// Gets the configuration.
- ///
- public IConfiguration Configuration { get; }
+ ///
+ /// Gets the configuration.
+ ///
+ public IConfiguration Configuration { get; }
- ///
- /// Configures Services.
- ///
- /// Service Collection.
- public void ConfigureServices(IServiceCollection services)
- {
+ ///
+ /// Configures Services.
+ ///
+ /// Service Collection.
+ public void ConfigureServices(IServiceCollection services)
+ {
- }
+ }
- ///
- /// Configures Application Builder and WebHost environment.
- ///
- /// Application builder.
- /// Webhost environment.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ ///
+ /// Configures Application Builder and WebHost environment.
+ ///
+ /// Application builder.
+ /// Webhost environment.
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ {
+ if (env.IsDevelopment())
{
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
+ app.UseDeveloperExceptionPage();
+ }
- app.UseRouting();
+ app.UseRouting();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapGet("secret", Secret);
- });
+ app.UseEndpoints(endpoints =>
+ {
+ endpoints.MapGet("secret", Secret);
+ });
- async Task Secret(HttpContext context)
- {
- // Get secret from configuration!!!
- var secretValue = Configuration["super-secret"];
+ async Task Secret(HttpContext context)
+ {
+ // Get secret from configuration!!!
+ var secretValue = Configuration["super-secret"];
- context.Response.ContentType = "application/json";
- await JsonSerializer.SerializeAsync(context.Response.Body, secretValue);
- }
+ context.Response.ContentType = "application/json";
+ await JsonSerializer.SerializeAsync(context.Response.Body, secretValue);
}
}
}
\ No newline at end of file
diff --git a/examples/Client/ConfigurationApi/Controllers/ConfigurationController.cs b/examples/Client/ConfigurationApi/Controllers/ConfigurationController.cs
index 9ceb60c0b..faad24079 100644
--- a/examples/Client/ConfigurationApi/Controllers/ConfigurationController.cs
+++ b/examples/Client/ConfigurationApi/Controllers/ConfigurationController.cs
@@ -7,81 +7,80 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
-namespace ConfigurationApi.Controllers
+namespace ConfigurationApi.Controllers;
+
+[ApiController]
+[Route("configuration")]
+public class ConfigurationController : ControllerBase
{
- [ApiController]
- [Route("configuration")]
- public class ConfigurationController : ControllerBase
+ private ILogger logger;
+ private IConfiguration configuration;
+ private DaprClient client;
+
+ public ConfigurationController(ILogger logger, IConfiguration configuration, [FromServices] DaprClient client)
+ {
+ this.logger = logger;
+ this.configuration = configuration;
+ this.client = client;
+ }
+
+ [HttpGet("get/{configStore}/{queryKey}")]
+ public async Task GetConfiguration([FromRoute] string configStore, [FromRoute] string queryKey)
{
- private ILogger logger;
- private IConfiguration configuration;
- private DaprClient client;
+ logger.LogInformation($"Querying Configuration with key: {queryKey}");
+ var configItems = await client.GetConfiguration(configStore, new List() { queryKey });
- public ConfigurationController(ILogger logger, IConfiguration configuration, [FromServices] DaprClient client)
+ if (configItems.Items.Count == 0)
{
- this.logger = logger;
- this.configuration = configuration;
- this.client = client;
+ logger.LogInformation($"No configuration item found for key: {queryKey}");
}
- [HttpGet("get/{configStore}/{queryKey}")]
- public async Task GetConfiguration([FromRoute] string configStore, [FromRoute] string queryKey)
+ foreach (var item in configItems.Items)
{
- logger.LogInformation($"Querying Configuration with key: {queryKey}");
- var configItems = await client.GetConfiguration(configStore, new List() { queryKey });
-
- if (configItems.Items.Count == 0)
- {
- logger.LogInformation($"No configuration item found for key: {queryKey}");
- }
-
- foreach (var item in configItems.Items)
- {
- logger.LogInformation($"Got configuration item:\nKey: {item.Key}\nValue: {item.Value.Value}\nVersion: {item.Value.Version}");
- }
+ logger.LogInformation($"Got configuration item:\nKey: {item.Key}\nValue: {item.Value.Value}\nVersion: {item.Value.Version}");
}
+ }
- [HttpGet("extension")]
- public Task SubscribeAndWatchConfiguration()
- {
- logger.LogInformation($"Getting values from Configuration Extension, watched values ['withdrawVersion', 'source'].");
+ [HttpGet("extension")]
+ public Task SubscribeAndWatchConfiguration()
+ {
+ logger.LogInformation($"Getting values from Configuration Extension, watched values ['withdrawVersion', 'source'].");
- logger.LogInformation($"'withdrawVersion' from extension: {configuration["withdrawVersion"]}");
- logger.LogInformation($"'source' from extension: {configuration["source"]}");
+ logger.LogInformation($"'withdrawVersion' from extension: {configuration["withdrawVersion"]}");
+ logger.LogInformation($"'source' from extension: {configuration["source"]}");
- return Task.CompletedTask;
- }
+ return Task.CompletedTask;
+ }
#nullable enable
- [HttpPost("withdraw")]
- public async Task> CreateAccountHandler(Transaction transaction)
+ [HttpPost("withdraw")]
+ public async Task> CreateAccountHandler(Transaction transaction)
+ {
+ // Check if the V2 method is enabled.
+ if (configuration["withdrawVersion"] == "v2")
{
- // Check if the V2 method is enabled.
- if (configuration["withdrawVersion"] == "v2")
+ var source = !string.IsNullOrEmpty(configuration["source"]) ? configuration["source"] : "local";
+ var transactionV2 = new TransactionV2
+ {
+ Id = transaction.Id,
+ Amount = transaction.Amount,
+ Channel = source
+ };
+ logger.LogInformation($"Calling V2 Withdraw API - Id: {transactionV2.Id} Amount: {transactionV2.Amount} Channel: {transactionV2.Channel}");
+ try
{
- var source = !string.IsNullOrEmpty(configuration["source"]) ? configuration["source"] : "local";
- var transactionV2 = new TransactionV2
- {
- Id = transaction.Id,
- Amount = transaction.Amount,
- Channel = source
- };
- logger.LogInformation($"Calling V2 Withdraw API - Id: {transactionV2.Id} Amount: {transactionV2.Amount} Channel: {transactionV2.Channel}");
- try
- {
- return await this.client.InvokeMethodAsync("controller", "withdraw.v2", transactionV2);
- }
- catch (DaprException ex)
- {
- logger.LogError($"Error executing withdrawal: {ex.Message}");
- return BadRequest();
- }
+ return await this.client.InvokeMethodAsync("controller", "withdraw.v2", transactionV2);
+ }
+ catch (DaprException ex)
+ {
+ logger.LogError($"Error executing withdrawal: {ex.Message}");
+ return BadRequest();
}
-
- // Default to the original method.
- logger.LogInformation($"Calling V1 Withdraw API: {transaction}");
- return await this.client.InvokeMethodAsync("controller", "withdraw", transaction);
}
-#nullable disable
+
+ // Default to the original method.
+ logger.LogInformation($"Calling V1 Withdraw API: {transaction}");
+ return await this.client.InvokeMethodAsync("controller", "withdraw", transaction);
}
-}
+#nullable disable
+}
\ No newline at end of file
diff --git a/examples/Client/ConfigurationApi/Program.cs b/examples/Client/ConfigurationApi/Program.cs
index 22f12cfae..832b06246 100644
--- a/examples/Client/ConfigurationApi/Program.cs
+++ b/examples/Client/ConfigurationApi/Program.cs
@@ -5,37 +5,36 @@
using Dapr.Extensions.Configuration;
using System.Collections.Generic;
-namespace ConfigurationApi
+namespace ConfigurationApi;
+
+public class Program
{
- public class Program
+ public static void Main(string[] args)
{
- public static void Main(string[] args)
- {
- Console.WriteLine("Starting application.");
- CreateHostBuilder(args).Build().Run();
- Console.WriteLine("Closing application.");
- }
+ Console.WriteLine("Starting application.");
+ CreateHostBuilder(args).Build().Run();
+ Console.WriteLine("Closing application.");
+ }
- ///
- /// Creates WebHost Builder.
- ///
- /// Arguments.
- /// Returns IHostbuilder.
- public static IHostBuilder CreateHostBuilder(string[] args)
- {
- var client = new DaprClientBuilder().Build();
- return Host.CreateDefaultBuilder(args)
- .ConfigureAppConfiguration(config =>
- {
- // Get the initial value and continue to watch it for changes.
- config.AddDaprConfigurationStore("redisconfig", new List() { "withdrawVersion" }, client, TimeSpan.FromSeconds(20));
- config.AddStreamingDaprConfigurationStore("redisconfig", new List() { "withdrawVersion", "source" }, client, TimeSpan.FromSeconds(20));
+ ///
+ /// Creates WebHost Builder.
+ ///
+ /// Arguments.
+ /// Returns IHostbuilder.
+ public static IHostBuilder CreateHostBuilder(string[] args)
+ {
+ var client = new DaprClientBuilder().Build();
+ return Host.CreateDefaultBuilder(args)
+ .ConfigureAppConfiguration(config =>
+ {
+ // Get the initial value and continue to watch it for changes.
+ config.AddDaprConfigurationStore("redisconfig", new List() { "withdrawVersion" }, client, TimeSpan.FromSeconds(20));
+ config.AddStreamingDaprConfigurationStore("redisconfig", new List() { "withdrawVersion", "source" }, client, TimeSpan.FromSeconds(20));
- })
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup();
- });
- }
+ })
+ .ConfigureWebHostDefaults(webBuilder =>
+ {
+ webBuilder.UseStartup();
+ });
}
-}
+}
\ No newline at end of file
diff --git a/examples/Client/ConfigurationApi/Startup.cs b/examples/Client/ConfigurationApi/Startup.cs
index b858b810c..6ab1f8cf8 100644
--- a/examples/Client/ConfigurationApi/Startup.cs
+++ b/examples/Client/ConfigurationApi/Startup.cs
@@ -4,51 +4,50 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
-namespace ConfigurationApi
+namespace ConfigurationApi;
+
+public class Startup
{
- public class Startup
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Configuration.
+ public Startup(IConfiguration configuration)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// Configuration.
- public Startup(IConfiguration configuration)
- {
- this.Configuration = configuration;
- }
+ this.Configuration = configuration;
+ }
- ///
- /// Gets the configuration.
- ///
- public IConfiguration Configuration { get; }
+ ///
+ /// Gets the configuration.
+ ///
+ public IConfiguration Configuration { get; }
- ///
- /// Configures Services.
- ///
- /// Service Collection.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllers().AddDapr();
- }
+ ///
+ /// Configures Services.
+ ///
+ /// Service Collection.
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddControllers().AddDapr();
+ }
- ///
- /// Configures Application Builder and WebHost environment.
- ///
- /// Application builder.
- /// Webhost environment.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ ///
+ /// Configures Application Builder and WebHost environment.
+ ///
+ /// Application builder.
+ /// Webhost environment.
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ {
+ if (env.IsDevelopment())
{
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
+ app.UseDeveloperExceptionPage();
+ }
- app.UseRouting();
+ app.UseRouting();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
+ app.UseEndpoints(endpoints =>
+ {
+ endpoints.MapControllers();
+ });
}
-}
+}
\ No newline at end of file
diff --git a/examples/Client/Cryptography/Example.cs b/examples/Client/Cryptography/Example.cs
index 2c2d41626..ac3d525bb 100644
--- a/examples/Client/Cryptography/Example.cs
+++ b/examples/Client/Cryptography/Example.cs
@@ -11,12 +11,11 @@
// limitations under the License.
// ------------------------------------------------------------------------
-namespace Cryptography
+namespace Cryptography;
+
+internal abstract class Example
{
- internal abstract class Example
- {
- public abstract string DisplayName { get; }
+ public abstract string DisplayName { get; }
- public abstract Task RunAsync(CancellationToken cancellationToken);
- }
-}
+ public abstract Task RunAsync(CancellationToken cancellationToken);
+}
\ No newline at end of file
diff --git a/examples/Client/Cryptography/Examples/EncryptDecryptFileStreamExample.cs b/examples/Client/Cryptography/Examples/EncryptDecryptFileStreamExample.cs
index 19df06345..43cf2dc9f 100644
--- a/examples/Client/Cryptography/Examples/EncryptDecryptFileStreamExample.cs
+++ b/examples/Client/Cryptography/Examples/EncryptDecryptFileStreamExample.cs
@@ -15,59 +15,58 @@
using Dapr.Client;
#pragma warning disable CS0618 // Type or member is obsolete
-namespace Cryptography.Examples
+namespace Cryptography.Examples;
+
+internal class EncryptDecryptFileStreamExample(string componentName, string keyName) : Example
{
- internal class EncryptDecryptFileStreamExample(string componentName, string keyName) : Example
+ public override string DisplayName => "Use Cryptography to encrypt and decrypt a file";
+ public override async Task RunAsync(CancellationToken cancellationToken)
{
- public override string DisplayName => "Use Cryptography to encrypt and decrypt a file";
- public override async Task RunAsync(CancellationToken cancellationToken)
- {
- using var client = new DaprClientBuilder().Build();
+ using var client = new DaprClientBuilder().Build();
- // The name of the file we're using as an example
- const string fileName = "file.txt";
+ // The name of the file we're using as an example
+ const string fileName = "file.txt";
- Console.WriteLine("Original file contents:");
- foreach (var line in await File.ReadAllLinesAsync(fileName, cancellationToken))
- {
- Console.WriteLine(line);
- }
+ Console.WriteLine("Original file contents:");
+ foreach (var line in await File.ReadAllLinesAsync(fileName, cancellationToken))
+ {
+ Console.WriteLine(line);
+ }
- //Encrypt from a file stream and buffer the resulting bytes to an in-memory buffer
- await using var encryptFs = new FileStream(fileName, FileMode.Open);
+ //Encrypt from a file stream and buffer the resulting bytes to an in-memory buffer
+ await using var encryptFs = new FileStream(fileName, FileMode.Open);
- var bufferedEncryptedBytes = new ArrayBufferWriter();
- await foreach (var bytes in (await client.EncryptAsync(componentName, encryptFs, keyName,
- new EncryptionOptions(KeyWrapAlgorithm.Rsa), cancellationToken))
- .WithCancellation(cancellationToken))
- {
- bufferedEncryptedBytes.Write(bytes.Span);
- }
+ var bufferedEncryptedBytes = new ArrayBufferWriter();
+ await foreach (var bytes in (await client.EncryptAsync(componentName, encryptFs, keyName,
+ new EncryptionOptions(KeyWrapAlgorithm.Rsa), cancellationToken))
+ .WithCancellation(cancellationToken))
+ {
+ bufferedEncryptedBytes.Write(bytes.Span);
+ }
- Console.WriteLine("Encrypted bytes:");
- Console.WriteLine(Convert.ToBase64String(bufferedEncryptedBytes.WrittenMemory.ToArray()));
+ Console.WriteLine("Encrypted bytes:");
+ Console.WriteLine(Convert.ToBase64String(bufferedEncryptedBytes.WrittenMemory.ToArray()));
- //We'll write to a temporary file via a FileStream
- var tempDecryptedFile = Path.GetTempFileName();
- await using var decryptFs = new FileStream(tempDecryptedFile, FileMode.Create);
+ //We'll write to a temporary file via a FileStream
+ var tempDecryptedFile = Path.GetTempFileName();
+ await using var decryptFs = new FileStream(tempDecryptedFile, FileMode.Create);
- //We'll stream the decrypted bytes from a MemoryStream into the above temporary file
- await using var encryptedMs = new MemoryStream(bufferedEncryptedBytes.WrittenMemory.ToArray());
- await foreach (var result in (await client.DecryptAsync(componentName, encryptedMs, keyName,
- cancellationToken)).WithCancellation(cancellationToken))
- {
- decryptFs.Write(result.Span);
- }
+ //We'll stream the decrypted bytes from a MemoryStream into the above temporary file
+ await using var encryptedMs = new MemoryStream(bufferedEncryptedBytes.WrittenMemory.ToArray());
+ await foreach (var result in (await client.DecryptAsync(componentName, encryptedMs, keyName,
+ cancellationToken)).WithCancellation(cancellationToken))
+ {
+ decryptFs.Write(result.Span);
+ }
- decryptFs.Close();
+ decryptFs.Close();
- //Let's confirm the value as written to the file
- var decryptedValue = await File.ReadAllTextAsync(tempDecryptedFile, cancellationToken);
- Console.WriteLine("Decrypted value: ");
- Console.WriteLine(decryptedValue);
+ //Let's confirm the value as written to the file
+ var decryptedValue = await File.ReadAllTextAsync(tempDecryptedFile, cancellationToken);
+ Console.WriteLine("Decrypted value: ");
+ Console.WriteLine(decryptedValue);
- //And some cleanup to delete our temp file
- File.Delete(tempDecryptedFile);
- }
+ //And some cleanup to delete our temp file
+ File.Delete(tempDecryptedFile);
}
-}
+}
\ No newline at end of file
diff --git a/examples/Client/Cryptography/Examples/EncryptDecryptStringExample.cs b/examples/Client/Cryptography/Examples/EncryptDecryptStringExample.cs
index d29b24a60..1a31e9153 100644
--- a/examples/Client/Cryptography/Examples/EncryptDecryptStringExample.cs
+++ b/examples/Client/Cryptography/Examples/EncryptDecryptStringExample.cs
@@ -15,29 +15,28 @@
using Dapr.Client;
#pragma warning disable CS0618 // Type or member is obsolete
-namespace Cryptography.Examples
+namespace Cryptography.Examples;
+
+internal class EncryptDecryptStringExample(string componentName, string keyName) : Example
{
- internal class EncryptDecryptStringExample(string componentName, string keyName) : Example
- {
- public override string DisplayName => "Using Cryptography to encrypt and decrypt a string";
+ public override string DisplayName => "Using Cryptography to encrypt and decrypt a string";
- public override async Task RunAsync(CancellationToken cancellationToken)
- {
- using var client = new DaprClientBuilder().Build();
+ public override async Task RunAsync(CancellationToken cancellationToken)
+ {
+ using var client = new DaprClientBuilder().Build();
- const string plaintextStr = "This is the value we're going to encrypt today";
- Console.WriteLine($"Original string value: '{plaintextStr}'");
+ const string plaintextStr = "This is the value we're going to encrypt today";
+ Console.WriteLine($"Original string value: '{plaintextStr}'");
- //Encrypt the string
- var plaintextBytes = Encoding.UTF8.GetBytes(plaintextStr);
- var encryptedBytesResult = await client.EncryptAsync(componentName, plaintextBytes, keyName, new EncryptionOptions(KeyWrapAlgorithm.Rsa),
- cancellationToken);
+ //Encrypt the string
+ var plaintextBytes = Encoding.UTF8.GetBytes(plaintextStr);
+ var encryptedBytesResult = await client.EncryptAsync(componentName, plaintextBytes, keyName, new EncryptionOptions(KeyWrapAlgorithm.Rsa),
+ cancellationToken);
- Console.WriteLine($"Encrypted bytes: '{Convert.ToBase64String(encryptedBytesResult.Span)}'");
+ Console.WriteLine($"Encrypted bytes: '{Convert.ToBase64String(encryptedBytesResult.Span)}'");
- //Decrypt the string
- var decryptedBytes = await client.DecryptAsync(componentName, encryptedBytesResult, keyName, cancellationToken);
- Console.WriteLine($"Decrypted string: '{Encoding.UTF8.GetString(decryptedBytes.ToArray())}'");
- }
+ //Decrypt the string
+ var decryptedBytes = await client.DecryptAsync(componentName, encryptedBytesResult, keyName, cancellationToken);
+ Console.WriteLine($"Decrypted string: '{Encoding.UTF8.GetString(decryptedBytes.ToArray())}'");
}
-}
+}
\ No newline at end of file
diff --git a/examples/Client/Cryptography/Program.cs b/examples/Client/Cryptography/Program.cs
index 5c63d7361..9fe3ec979 100644
--- a/examples/Client/Cryptography/Program.cs
+++ b/examples/Client/Cryptography/Program.cs
@@ -13,37 +13,36 @@
using Cryptography.Examples;
-namespace Cryptography
+namespace Cryptography;
+
+class Program
{
- class Program
- {
- private const string ComponentName = "localstorage";
- private const string KeyName = "rsa-private-key.pem"; //This should match the name of your generated key - this sample expects an RSA symmetrical key.
+ private const string ComponentName = "localstorage";
+ private const string KeyName = "rsa-private-key.pem"; //This should match the name of your generated key - this sample expects an RSA symmetrical key.
- private static readonly Example[] Examples = new Example[]
- {
- new EncryptDecryptStringExample(ComponentName, KeyName),
- new EncryptDecryptFileStreamExample(ComponentName, KeyName)
- };
+ private static readonly Example[] Examples = new Example[]
+ {
+ new EncryptDecryptStringExample(ComponentName, KeyName),
+ new EncryptDecryptFileStreamExample(ComponentName, KeyName)
+ };
- static async Task Main(string[] args)
+ static async Task Main(string[] args)
+ {
+ if (args.Length > 0 && int.TryParse(args[0], out var index) && index >= 0 && index < Examples.Length)
{
- if (args.Length > 0 && int.TryParse(args[0], out var index) && index >= 0 && index < Examples.Length)
- {
- var cts = new CancellationTokenSource();
- Console.CancelKeyPress += (object? sender, ConsoleCancelEventArgs e) => cts.Cancel();
+ var cts = new CancellationTokenSource();
+ Console.CancelKeyPress += (object? sender, ConsoleCancelEventArgs e) => cts.Cancel();
- await Examples[index].RunAsync(cts.Token);
- return 0;
- }
+ await Examples[index].RunAsync(cts.Token);
+ return 0;
+ }
- Console.WriteLine("Hello, please choose a sample to run by passing your selection's number into the arguments, e.g. 'dotnet run 0':");
- for (var i = 0; i < Examples.Length; i++)
- {
- Console.WriteLine($"{i}: {Examples[i].DisplayName}");
- }
- Console.WriteLine();
- return 1;
+ Console.WriteLine("Hello, please choose a sample to run by passing your selection's number into the arguments, e.g. 'dotnet run 0':");
+ for (var i = 0; i < Examples.Length; i++)
+ {
+ Console.WriteLine($"{i}: {Examples[i].DisplayName}");
}
+ Console.WriteLine();
+ return 1;
}
-}
+}
\ No newline at end of file
diff --git a/examples/Client/DistributedLock/Controllers/BindingController.cs b/examples/Client/DistributedLock/Controllers/BindingController.cs
index aa4dd1f52..37fbe637b 100644
--- a/examples/Client/DistributedLock/Controllers/BindingController.cs
+++ b/examples/Client/DistributedLock/Controllers/BindingController.cs
@@ -8,100 +8,99 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
-namespace DistributedLock.Controllers
+namespace DistributedLock.Controllers;
+
+[ApiController]
+public class BindingController : ControllerBase
{
- [ApiController]
- public class BindingController : ControllerBase
- {
- private DaprClient client;
- private ILogger logger;
- private string appId;
+ private DaprClient client;
+ private ILogger logger;
+ private string appId;
- public BindingController(DaprClient client, ILogger logger)
- {
- this.client = client;
- this.logger = logger;
- this.appId = Environment.GetEnvironmentVariable("APP_ID");
- }
+ public BindingController(DaprClient client, ILogger logger)
+ {
+ this.client = client;
+ this.logger = logger;
+ this.appId = Environment.GetEnvironmentVariable("APP_ID");
+ }
- [HttpPost("cronbinding")]
- [Obsolete]
- public async Task HandleBindingEvent()
- {
- logger.LogInformation($"Received binding event on {appId}, scanning for work.");
+ [HttpPost("cronbinding")]
+ [Obsolete]
+ public async Task HandleBindingEvent()
+ {
+ logger.LogInformation($"Received binding event on {appId}, scanning for work.");
- var request = new BindingRequest("localstorage", "list");
- var result = client.InvokeBindingAsync(request);
+ var request = new BindingRequest("localstorage", "list");
+ var result = client.InvokeBindingAsync(request);
- var rawData = result.Result.Data.ToArray();
- var files = JsonSerializer.Deserialize(rawData);
+ var rawData = result.Result.Data.ToArray();
+ var files = JsonSerializer.Deserialize(rawData);
- if (files != null)
+ if (files != null)
+ {
+ foreach (var file in files.Select(file => file.Split("/").Last()).OrderBy(file => file))
{
- foreach (var file in files.Select(file => file.Split("/").Last()).OrderBy(file => file))
- {
- await AttemptToProcessFile(file);
- }
+ await AttemptToProcessFile(file);
}
-
- return Ok();
}
+
+ return Ok();
+ }
- [Obsolete]
- private async Task AttemptToProcessFile(string fileName)
+ [Obsolete]
+ private async Task AttemptToProcessFile(string fileName)
+ {
+ // Locks are Disposable and will automatically unlock at the end of a 'using' statement.
+ logger.LogInformation($"Attempting to lock: {fileName}");
+ await using (var fileLock = await client.Lock("redislock", fileName, appId, 60))
{
- // Locks are Disposable and will automatically unlock at the end of a 'using' statement.
- logger.LogInformation($"Attempting to lock: {fileName}");
- await using (var fileLock = await client.Lock("redislock", fileName, appId, 60))
+ if (fileLock.Success)
{
- if (fileLock.Success)
- {
- logger.LogInformation($"Successfully locked file: {fileName}");
+ logger.LogInformation($"Successfully locked file: {fileName}");
- // Get the file after we've locked it, we're safe here because of the lock.
- var fileState = await GetFile(fileName);
+ // Get the file after we've locked it, we're safe here because of the lock.
+ var fileState = await GetFile(fileName);
- if (fileState == null)
- {
- logger.LogWarning($"File {fileName} has already been processed!");
- return;
- }
+ if (fileState == null)
+ {
+ logger.LogWarning($"File {fileName} has already been processed!");
+ return;
+ }
- // "Analyze" the file before committing it to our remote storage.
- fileState.Analysis = fileState.Number > 50 ? "High" : "Low";
+ // "Analyze" the file before committing it to our remote storage.
+ fileState.Analysis = fileState.Number > 50 ? "High" : "Low";
- // Save it to remote storage.
- await client.SaveStateAsync("redisstore", fileName, fileState);
+ // Save it to remote storage.
+ await client.SaveStateAsync("redisstore", fileName, fileState);
- // Remove it from local storage.
- var bindingDeleteRequest = new BindingRequest("localstorage", "delete");
- bindingDeleteRequest.Metadata["fileName"] = fileName;
- await client.InvokeBindingAsync(bindingDeleteRequest);
+ // Remove it from local storage.
+ var bindingDeleteRequest = new BindingRequest("localstorage", "delete");
+ bindingDeleteRequest.Metadata["fileName"] = fileName;
+ await client.InvokeBindingAsync(bindingDeleteRequest);
- logger.LogInformation($"Done processing {fileName}");
- }
- else
- {
- logger.LogWarning($"Failed to lock {fileName}.");
- }
+ logger.LogInformation($"Done processing {fileName}");
+ }
+ else
+ {
+ logger.LogWarning($"Failed to lock {fileName}.");
}
}
+ }
- private async Task GetFile(string fileName)
+ private async Task GetFile(string fileName)
+ {
+ try
{
- try
- {
- var bindingGetRequest = new BindingRequest("localstorage", "get");
- bindingGetRequest.Metadata["fileName"] = fileName;
+ var bindingGetRequest = new BindingRequest("localstorage", "get");
+ bindingGetRequest.Metadata["fileName"] = fileName;
- var bindingResponse = await client.InvokeBindingAsync(bindingGetRequest);
- return JsonSerializer.Deserialize(bindingResponse.Data.ToArray());
- }
- catch (DaprException)
- {
- return null;
- }
+ var bindingResponse = await client.InvokeBindingAsync(bindingGetRequest);
+ return JsonSerializer.Deserialize(bindingResponse.Data.ToArray());
}
+ catch (DaprException)
+ {
+ return null;
+ }
}
-}
+}
\ No newline at end of file
diff --git a/examples/Client/DistributedLock/Model/StateData.cs b/examples/Client/DistributedLock/Model/StateData.cs
index 0ad5d2fd9..f5eeeb29d 100644
--- a/examples/Client/DistributedLock/Model/StateData.cs
+++ b/examples/Client/DistributedLock/Model/StateData.cs
@@ -1,15 +1,13 @@
-namespace DistributedLock.Model
-{
+namespace DistributedLock.Model;
#nullable enable
- public class StateData
- {
- public int Number { get; }
- public string? Analysis { get; set; }
+public class StateData
+{
+ public int Number { get; }
+ public string? Analysis { get; set; }
- public StateData(int number, string? analysis = null)
- {
- Number = number;
- Analysis = analysis;
- }
+ public StateData(int number, string? analysis = null)
+ {
+ Number = number;
+ Analysis = analysis;
}
-}
+}
\ No newline at end of file
diff --git a/examples/Client/DistributedLock/Program.cs b/examples/Client/DistributedLock/Program.cs
index 3080b5b1e..830fb5dc0 100644
--- a/examples/Client/DistributedLock/Program.cs
+++ b/examples/Client/DistributedLock/Program.cs
@@ -2,22 +2,21 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
-namespace DistributedLock
+namespace DistributedLock;
+
+public class Program
{
- public class Program
+ static string DEFAULT_APP_PORT = "22222";
+ public static void Main(string[] args)
{
- static string DEFAULT_APP_PORT = "22222";
- public static void Main(string[] args)
- {
- CreateHostBuilder(args).Build().Run();
- }
-
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup()
- .UseUrls($"http://localhost:{Environment.GetEnvironmentVariable("APP_PORT") ?? DEFAULT_APP_PORT}");
- });
+ CreateHostBuilder(args).Build().Run();
}
-}
+
+ public static IHostBuilder CreateHostBuilder(string[] args) =>
+ Host.CreateDefaultBuilder(args)
+ .ConfigureWebHostDefaults(webBuilder =>
+ {
+ webBuilder.UseStartup()
+ .UseUrls($"http://localhost:{Environment.GetEnvironmentVariable("APP_PORT") ?? DEFAULT_APP_PORT}");
+ });
+}
\ No newline at end of file
diff --git a/examples/Client/DistributedLock/Services/GeneratorService.cs b/examples/Client/DistributedLock/Services/GeneratorService.cs
index aa59d9b75..4d5c0a3ff 100644
--- a/examples/Client/DistributedLock/Services/GeneratorService.cs
+++ b/examples/Client/DistributedLock/Services/GeneratorService.cs
@@ -3,30 +3,29 @@
using Dapr.Client;
using DistributedLock.Model;
-namespace DistributedLock.Services
+namespace DistributedLock.Services;
+
+public class GeneratorService
{
- public class GeneratorService
- {
- Timer generateDataTimer;
+ Timer generateDataTimer;
- public GeneratorService()
+ public GeneratorService()
+ {
+ // Generate some data every second.
+ if (Environment.GetEnvironmentVariable("APP_ID") == "generator")
{
- // Generate some data every second.
- if (Environment.GetEnvironmentVariable("APP_ID") == "generator")
- {
- generateDataTimer = new Timer(GenerateData, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10));
- }
+ generateDataTimer = new Timer(GenerateData, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10));
}
+ }
- public async void GenerateData(Object stateInfo)
+ public async void GenerateData(Object stateInfo)
+ {
+ using (var client = new DaprClientBuilder().Build())
{
- using (var client = new DaprClientBuilder().Build())
- {
- var rand = new Random();
- var state = new StateData(rand.Next(100));
+ var rand = new Random();
+ var state = new StateData(rand.Next(100));
- await client.InvokeBindingAsync("localstorage", "create", state);
- }
+ await client.InvokeBindingAsync("localstorage", "create", state);
}
}
-}
+}
\ No newline at end of file
diff --git a/examples/Client/DistributedLock/Startup.cs b/examples/Client/DistributedLock/Startup.cs
index 9f40e4752..0e2e0df3a 100644
--- a/examples/Client/DistributedLock/Startup.cs
+++ b/examples/Client/DistributedLock/Startup.cs
@@ -1,46 +1,45 @@
using Dapr.AspNetCore;
-using DistributedLock.Services;
+using DistributedLock.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
-namespace DistributedLock
+namespace DistributedLock;
+
+public class Startup
{
- public class Startup
+ public Startup(IConfiguration configuration)
{
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
+ Configuration = configuration;
+ }
- public IConfiguration Configuration { get; }
+ public IConfiguration Configuration { get; }
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllers().AddDapr();
- services.AddLogging();
- services.AddSingleton(new GeneratorService());
- }
+ // This method gets called by the runtime. Use this method to add services to the container.
+ public void ConfigureServices(IServiceCollection services)
+ {
+ services.AddControllers().AddDapr();
+ services.AddLogging();
+ services.AddSingleton(new GeneratorService());
+ }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
+ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+ {
+ if (env.IsDevelopment())
{
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
+ app.UseDeveloperExceptionPage();
+ }
- app.UseRouting();
+ app.UseRouting();
- app.UseAuthorization();
+ app.UseAuthorization();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
+ app.UseEndpoints(endpoints =>
+ {
+ endpoints.MapControllers();
+ });
}
-}
+}
\ No newline at end of file
diff --git a/examples/Client/PublishSubscribe/BulkPublishEventExample/BulkPublishEventExample.cs b/examples/Client/PublishSubscribe/BulkPublishEventExample/BulkPublishEventExample.cs
index 343618457..af1fc639f 100644
--- a/examples/Client/PublishSubscribe/BulkPublishEventExample/BulkPublishEventExample.cs
+++ b/examples/Client/PublishSubscribe/BulkPublishEventExample/BulkPublishEventExample.cs
@@ -17,46 +17,45 @@
using System.Threading.Tasks;
using Dapr.Client;
-namespace Samples.Client
+namespace Samples.Client;
+
+public sealed class BulkPublishEventExample : Example
{
- public class BulkPublishEventExample : Example
- {
- private const string PubsubName = "pubsub";
- private const string TopicName = "deposit";
+ private const string PubsubName = "pubsub";
+ private const string TopicName = "deposit";
- IReadOnlyList