Skip to content

Commit 9432e9b

Browse files
Add DynamoDB 4 Sample (Transactions) (#7568)
* Remove InputLoopService * Clone DynamoDB_3 * Upgrade to .NET 10 * Revert to alpha.1 * Upgrade NSB versions
1 parent b38e15c commit 9432e9b

23 files changed

+390
-42
lines changed

samples/aws/dynamodb-transactions/DynamoDB_3/Client/InputLoopService.cs

Lines changed: 0 additions & 36 deletions
This file was deleted.
Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Threading;
23
using System.Threading.Tasks;
34
using Microsoft.Extensions.DependencyInjection;
45
using Microsoft.Extensions.Hosting;
@@ -7,16 +8,52 @@
78
Console.Title = "Client";
89

910
var builder = Host.CreateApplicationBuilder(args);
10-
builder.Services.AddHostedService<InputLoopService>();
1111

1212
var endpointConfiguration = new EndpointConfiguration("Samples.DynamoDB.Transactions.Client");
1313
endpointConfiguration.UseSerialization<SystemJsonSerializer>();
1414
endpointConfiguration.UseTransport<LearningTransport>();
1515

16-
1716
Console.WriteLine("Press any key, the application is starting");
1817
Console.ReadKey();
1918
Console.WriteLine("Starting...");
2019

2120
builder.UseNServiceBus(endpointConfiguration);
22-
await builder.Build().RunAsync();
21+
22+
var host = builder.Build();
23+
24+
// Get the required services
25+
var messageSession = host.Services.GetRequiredService<IMessageSession>();
26+
// Register a cancellation token to gracefully handle application shutdown
27+
var ct = host.Services.GetRequiredService<IHostApplicationLifetime>().ApplicationStopping;
28+
29+
Console.WriteLine("Press 'S' to send a StartOrder message to the server endpoint.");
30+
Console.WriteLine("Press Ctrl+C to shut down.");
31+
32+
// Wait for user input to publish messages
33+
while (!ct.IsCancellationRequested)
34+
{
35+
if (!Console.KeyAvailable)
36+
{
37+
// If no key is pressed, wait for a short time before checking again
38+
await Task.Delay(100, CancellationToken.None);
39+
continue;
40+
}
41+
42+
var key = Console.ReadKey();
43+
Console.WriteLine();
44+
45+
if (key.Key == ConsoleKey.S)
46+
{
47+
var orderId = Guid.NewGuid();
48+
var startOrder = new StartOrder
49+
{
50+
OrderId = orderId
51+
};
52+
53+
await messageSession.Send("Samples.DynamoDB.Transactions.Server", startOrder);
54+
Console.WriteLine($"StartOrder Message sent to Server with OrderId {orderId}");
55+
}
56+
}
57+
58+
// Wait for the host to stop gracefully
59+
await host.StopAsync();

samples/aws/dynamodb-transactions/DynamoDB_3/Server/Program.cs

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
using Microsoft.Extensions.Hosting;
55
using NServiceBus;
66

7-
87
Console.Title = "Server";
98

109
var builder = Host.CreateApplicationBuilder(args);
@@ -39,8 +38,6 @@
3938
});
4039
endpointConfiguration.EnableInstallers();
4140

42-
43-
4441
Console.WriteLine("Press any key, the application is starting");
4542
Console.ReadKey();
4643
Console.WriteLine("Starting...");
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<TargetFramework>net10.0</TargetFramework>
4+
<OutputType>Exe</OutputType>
5+
<LangVersion>preview</LangVersion>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
</PropertyGroup>
8+
<ItemGroup>
9+
<ProjectReference Include="..\SharedMessages\SharedMessages.csproj" />
10+
</ItemGroup>
11+
<ItemGroup>
12+
<PackageReference Include="NServiceBus" Version="10.0.0-alpha.3" />
13+
<PackageReference Include="NServiceBus.Extensions.Hosting" Version="4.0.0-alpha.2" />
14+
</ItemGroup>
15+
</Project>
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
using Microsoft.Extensions.Logging;
2+
3+
public class OrderCompletedHandler(ILogger<OrderCompletedHandler> logger) :
4+
IHandleMessages<OrderCompleted>
5+
{
6+
public Task Handle(OrderCompleted message, IMessageHandlerContext context)
7+
{
8+
logger.LogInformation("Received OrderCompleted for OrderId {OrderId}", message.OrderId);
9+
return Task.CompletedTask;
10+
}
11+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using Microsoft.Extensions.DependencyInjection;
2+
using Microsoft.Extensions.Hosting;
3+
4+
Console.Title = "Client";
5+
6+
var builder = Host.CreateApplicationBuilder(args);
7+
8+
var endpointConfiguration = new EndpointConfiguration("Samples.DynamoDB.Transactions.Client");
9+
endpointConfiguration.UseSerialization<SystemJsonSerializer>();
10+
endpointConfiguration.UseTransport<LearningTransport>();
11+
12+
builder.UseNServiceBus(endpointConfiguration);
13+
14+
var host = builder.Build();
15+
16+
// Get the required services
17+
var messageSession = host.Services.GetRequiredService<IMessageSession>();
18+
// Register a cancellation token to gracefully handle application shutdown
19+
var ct = host.Services.GetRequiredService<IHostApplicationLifetime>().ApplicationStopping;
20+
21+
Console.WriteLine("Press 'S' to send a StartOrder message to the server endpoint.");
22+
Console.WriteLine("Press Ctrl+C to shut down.");
23+
24+
// Wait for user input to publish messages
25+
while (!ct.IsCancellationRequested)
26+
{
27+
if (!Console.KeyAvailable)
28+
{
29+
// If no key is pressed, wait for a short time before checking again
30+
await Task.Delay(100, CancellationToken.None);
31+
continue;
32+
}
33+
34+
var key = Console.ReadKey();
35+
Console.WriteLine();
36+
37+
if (key.Key == ConsoleKey.S)
38+
{
39+
var orderId = Guid.NewGuid();
40+
var startOrder = new StartOrder
41+
{
42+
OrderId = orderId
43+
};
44+
45+
await messageSession.Send("Samples.DynamoDB.Transactions.Server", startOrder);
46+
Console.WriteLine($"StartOrder Message sent to Server with OrderId {orderId}");
47+
}
48+
}
49+
50+
// Wait for the host to stop gracefully
51+
await host.StopAsync();
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Client\Client.csproj
2+
Server\Server.csproj
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
Microsoft Visual Studio Solution File, Format Version 12.00
2+
# Visual Studio Version 16
3+
VisualStudioVersion = 16.0.29728.190
4+
MinimumVisualStudioVersion = 15.0.26730.12
5+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Server", "Server\Server.csproj", "{48F718EE-6C45-41BA-80EC-81BF34D4A623}"
6+
EndProject
7+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharedMessages", "SharedMessages\SharedMessages.csproj", "{DD438DB2-9C03-4BC0-BA52-BB7A35098458}"
8+
EndProject
9+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client", "Client\Client.csproj", "{2FE71442-7F81-428E-B945-D564850D6564}"
10+
EndProject
11+
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4043293B-171D-4E7D-8E47-A9957327AD20}"
12+
ProjectSection(SolutionItems) = preProject
13+
docker-compose.yml = docker-compose.yml
14+
EndProjectSection
15+
EndProject
16+
Global
17+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
18+
Debug|Any CPU = Debug|Any CPU
19+
EndGlobalSection
20+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
21+
{48F718EE-6C45-41BA-80EC-81BF34D4A623}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
22+
{48F718EE-6C45-41BA-80EC-81BF34D4A623}.Debug|Any CPU.Build.0 = Debug|Any CPU
23+
{DD438DB2-9C03-4BC0-BA52-BB7A35098458}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
24+
{DD438DB2-9C03-4BC0-BA52-BB7A35098458}.Debug|Any CPU.Build.0 = Debug|Any CPU
25+
{2FE71442-7F81-428E-B945-D564850D6564}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26+
{2FE71442-7F81-428E-B945-D564850D6564}.Debug|Any CPU.Build.0 = Debug|Any CPU
27+
EndGlobalSection
28+
GlobalSection(SolutionProperties) = preSolution
29+
HideSolutionNode = FALSE
30+
EndGlobalSection
31+
GlobalSection(ExtensibilityGlobals) = postSolution
32+
SolutionGuid = {BB6580A8-3A40-4373-B226-A86402536658}
33+
EndGlobalSection
34+
EndGlobal
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
public class CompleteOrder
2+
{
3+
public Guid OrderId { get; set; }
4+
public string OrderDescription { get; set; }
5+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
using System;
2+
using System.Threading.Tasks;
3+
using Microsoft.Extensions.Logging;
4+
using NServiceBus;
5+
6+
#region thesaga
7+
8+
public class OrderSaga(ILogger<OrderSaga> logger):
9+
Saga<OrderSagaData>,
10+
IAmStartedByMessages<StartOrder>,
11+
IHandleMessages<OrderShipped>,
12+
IHandleTimeouts<CompleteOrder>
13+
{
14+
protected override void ConfigureHowToFindSaga(SagaPropertyMapper<OrderSagaData> mapper)
15+
{
16+
mapper.MapSaga(saga => saga.OrderId)
17+
.ToMessage<StartOrder>(msg => msg.OrderId)
18+
.ToMessage<OrderShipped>(msg => msg.OrderId);
19+
}
20+
21+
public async Task Handle(StartOrder message, IMessageHandlerContext context)
22+
{
23+
var orderDescription = $"The saga for order {message.OrderId}";
24+
Data.OrderDescription = orderDescription;
25+
26+
logger.LogInformation("Received StartOrder message {OrderId}. Starting Saga", Data.OrderId);
27+
28+
var shipOrder = new ShipOrder
29+
{
30+
OrderId = message.OrderId
31+
};
32+
33+
logger.LogInformation("Order will complete in 5 seconds");
34+
var timeoutData = new CompleteOrder
35+
{
36+
OrderDescription = orderDescription,
37+
OrderId = Data.OrderId,
38+
};
39+
40+
await Task.WhenAll(
41+
context.SendLocal(shipOrder),
42+
RequestTimeout(context, TimeSpan.FromSeconds(5), timeoutData)
43+
);
44+
}
45+
46+
public Task Handle(OrderShipped message, IMessageHandlerContext context)
47+
{
48+
logger.LogInformation("Order with OrderId {OrderId} shipped on {ShippingDate}", Data.OrderId, message.ShippingDate);
49+
return Task.CompletedTask;
50+
}
51+
52+
public async Task Timeout(CompleteOrder state, IMessageHandlerContext context)
53+
{
54+
logger.LogInformation("Saga with OrderId {OrderId} completed", Data.OrderId);
55+
MarkAsComplete();
56+
var orderCompleted = new OrderCompleted
57+
{
58+
OrderId = Data.OrderId
59+
};
60+
await context.Publish(orderCompleted);
61+
}
62+
}
63+
64+
#endregion

0 commit comments

Comments
 (0)