Skip to content
Open

Done #11

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added Images/Commands executed success.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Images/First command success.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
62 changes: 49 additions & 13 deletions WorkshopBackend/OrderService/Controllers/OrderController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
using Amazon.EventBridge.Model;
using System.Text.Json;
using InventoryService.Models;
using Npgsql;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

[ApiController]
[Route("[controller]")]
Expand All @@ -15,47 +17,81 @@ public class OrderController : ControllerBase
private readonly IAmazonSQS _sqs;
private readonly IAmazonSimpleNotificationService _sns;
private readonly IAmazonEventBridge _eventBridge;
private readonly string _queueUrl = ""; // Format of https://.*
private readonly string _topicArn = ""; // Format of arn:aws.*
private readonly string _queueUrl = "https://sqs.eu-north-1.amazonaws.com/637423341661/MalteStengardOrderQueue"; // Format of https://.*
private readonly string _topicArn = "arn:aws:sns:eu-north-1:637423341661:MalteStengardOrderCreatedTopic"; // Format of arn:aws.*
private readonly string _connectionString = "your database info";

public OrderController()
{
// Instantiate clients with default configuration
_sqs = new AmazonSQSClient();
_sns = new AmazonSimpleNotificationServiceClient();
_eventBridge = new AmazonEventBridgeClient();

}

[HttpGet]
public async Task<IActionResult> GetOrdersAndProcess()
{
/*
* AmazonSQSClient
*
*/
var request = new ReceiveMessageRequest
{
QueueUrl = _queueUrl,
MaxNumberOfMessages = 10,
WaitTimeSeconds = 20
};

var response = await _sqs.ReceiveMessageAsync(request);

foreach (var message in response.Messages)
using (var connection = new NpgsqlConnection(_connectionString))
{
var order = JsonSerializer.Deserialize<Order>(message.Body);
// Process order (e.g., update inventory)
await connection.OpenAsync();

// Delete message after processing
await _sqs.DeleteMessageAsync(_queueUrl, message.ReceiptHandle);
foreach (var message in response.Messages)
{
try
{
var order = JsonSerializer.Deserialize<Order>(message.Body);

// Update order in the database
var query = $@"UPDATE orders SET processed = @Processed, total = @Total WHERE orderid = @OrderId";
await using (var command = new NpgsqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Processed", true);
command.Parameters.AddWithValue("@Total", order.Quantity * order.Amount);
command.Parameters.AddWithValue("@OrderId", order.OrderId);
await command.ExecuteNonQueryAsync();
}

// Delete message from SQS after processing
await _sqs.DeleteMessageAsync(_queueUrl, message.ReceiptHandle);
}
catch (Exception ex)
{
// Log the exception (consider using a logging framework)
Console.WriteLine($"Error processing order {message.Body}: {ex.Message}");
}
}
}
return Ok(new { Status = $"{response.Messages.Count()}Order have been processed" });
return Ok(new { Status = $"{response.Messages.Count()} Order(s) have been processed" });
}


[HttpPost]
public async Task<IActionResult> CreateOrder([FromBody] Order order)
{
using (var connection = new NpgsqlConnection(_connectionString))
{
await connection.OpenAsync();
var query = "INSERT INTO Orders (product, quantity, amount, processed, total) VALUES (@Product, @Quantity, @Amount, @Processed, @Total)";
using (var command = new NpgsqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Product", order.Product);
command.Parameters.AddWithValue("@Quantity", order.Quantity);
command.Parameters.AddWithValue("@Amount", order.Amount);
command.Parameters.AddWithValue("@Processed", order.Processed);
command.Parameters.AddWithValue("@Total", order.Total);
await command.ExecuteNonQueryAsync();
}
}
/*
* AmazonSimpleNotificationServiceClient
*
Expand Down
1 change: 1 addition & 0 deletions WorkshopBackend/OrderService/OrderService.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<PackageReference Include="AWSSDK.SimpleNotificationService" Version="3.7.400.34" />
<PackageReference Include="AWSSDK.SQS" Version="3.7.400.34" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.7" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.8" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

Expand Down
2 changes: 1 addition & 1 deletion WorkshopBackend/OrderService/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"AWS": {
"Profile": "default",
"Region": "us-west-2"
"Region": "eu-north-1"
},
"Logging": {
"LogLevel": {
Expand Down
3 changes: 3 additions & 0 deletions WorkshopBackend/policy.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":\"SQS:SendMessage\",\"Resource\":\"arn:aws:sqs:eu-north-1:637423341661:MalteStengardOrderQueue\",\"Condition\":{\"ArnEquals\":{\"aws:SourceArn\":\"arn:aws:sns:eu-north-1:637423341661:MalteStengardOrderCreatedTopic\"}}}]}"
}