Skip to content

Commit

Permalink
Use new C# language features
Browse files Browse the repository at this point in the history
- Use primary constructors where relevant.
- Use collection literals where relevant.
- Adopt various IDE suggestions.
- Fix typos.
- Remove redundant suppressions.
_ Skip test locally that needs AWS.
- Fix new code analysis warnings/suggestions.
  • Loading branch information
martincostello committed Sep 30, 2023
1 parent 16b835c commit 519cee0
Show file tree
Hide file tree
Showing 231 changed files with 857 additions and 1,947 deletions.
1 change: 0 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ csharp_new_line_before_open_brace=all
csharp_preferred_modifier_order=public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion
csharp_space_after_keywords_in_control_flow_statements=true
csharp_style_namespace_declarations = file_scoped:warning
csharp_style_var_elsewhere=false:suggestion
csharp_style_var_for_built_in_types=false:suggestion
csharp_style_var_when_type_is_apparent=true:suggestion
dotnet_naming_rule.private_constants_rule.severity=warning
Expand Down
19 changes: 4 additions & 15 deletions samples/src/JustSaying.Sample.Middleware/JustSayingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,14 @@ namespace JustSaying.Sample.Middleware;
/// <summary>
/// A background service responsible for starting the JustSaying message bus and publisher.
/// </summary>
public class JustSayingService : IHostedService
public class JustSayingService(IMessagingBus bus, IMessagePublisher publisher, ILogger<JustSayingService> logger) : IHostedService
{
private readonly IMessagingBus _bus;
private readonly IMessagePublisher _publisher;
private readonly ILogger<JustSayingService> _logger;

public JustSayingService(IMessagingBus bus, IMessagePublisher publisher, ILogger<JustSayingService> logger)
{
_bus = bus;
_publisher = publisher;
_logger = logger;
}

public async Task StartAsync(CancellationToken cancellationToken)
{
await _bus.StartAsync(cancellationToken);
await _publisher.StartAsync(cancellationToken);
await bus.StartAsync(cancellationToken);
await publisher.StartAsync(cancellationToken);

_logger.LogInformation("Message bus and publisher have started successfully");
logger.LogInformation("Message bus and publisher have started successfully");
}

public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,31 +1,24 @@
using JustSaying.Messaging.Middleware;
using JustSaying.Messaging.Middleware;
using Serilog;

namespace JustSaying.Sample.Middleware.Middlewares;

/// <summary>
/// A middleware that will output a log message before and after a message has passed through it.
/// </summary>
public class EchoJustSayingMiddleware : MiddlewareBase<HandleMessageContext, bool>
public class EchoJustSayingMiddleware(string name) : MiddlewareBase<HandleMessageContext, bool>
{
private readonly string _name;

public EchoJustSayingMiddleware(string name)
{
_name = name;
}

protected override async Task<bool> RunInnerAsync(HandleMessageContext context, Func<CancellationToken, Task<bool>> func, CancellationToken stoppingToken)
{
Log.Information("[{MiddlewareName}] Starting {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), _name, context.Message.GetType().Name);
Log.Information("[{MiddlewareName}] Starting {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), name, context.Message.GetType().Name);

try
{
return await func(stoppingToken);
}
finally
{
Log.Information("[{MiddlewareName}] Ending {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), _name, context.Message.GetType().Name);
Log.Information("[{MiddlewareName}] Ending {Name} for {MessageType}", nameof(EchoJustSayingMiddleware), name, context.Message.GetType().Name);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,13 @@ namespace JustSaying.Sample.Restaurant.KitchenConsole;
/// A background service responsible for starting the bus which listens for
/// messages on the configured queues
/// </summary>
public class Subscriber : BackgroundService
public class Subscriber(IMessagingBus bus, ILogger<Subscriber> logger, IMessagePublisher publisher) : BackgroundService
{
private readonly IMessagingBus _bus;
private readonly ILogger<Subscriber> _logger;
private readonly IMessagePublisher _publisher;

public Subscriber(IMessagingBus bus, ILogger<Subscriber> logger, IMessagePublisher publisher)
{
_bus = bus;
_logger = logger;
_publisher = publisher;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Kitchen subscriber running");
logger.LogInformation("Kitchen subscriber running");

await _bus.StartAsync(stoppingToken);
await _publisher.StartAsync(stoppingToken);
await bus.StartAsync(stoppingToken);
await publisher.StartAsync(stoppingToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,8 @@

namespace JustSaying.Sample.Restaurant.KitchenConsole.Handlers;

public class OrderOnItsWayEventHandler : IHandlerAsync<OrderOnItsWayEvent>
public class OrderOnItsWayEventHandler(IMessagePublisher publisher, ILogger<OrderOnItsWayEventHandler> logger) : IHandlerAsync<OrderOnItsWayEvent>
{
private readonly IMessagePublisher _publisher;
private readonly ILogger<OrderOnItsWayEventHandler> _logger;

public OrderOnItsWayEventHandler(IMessagePublisher publisher, ILogger<OrderOnItsWayEventHandler> logger)
{
_publisher = publisher;
_logger = logger;
}

public async Task<bool> Handle(OrderOnItsWayEvent message)
{
await Task.Delay(RandomNumberGenerator.GetInt32(50, 100));
Expand All @@ -26,10 +17,10 @@ public async Task<bool> Handle(OrderOnItsWayEvent message)
OrderId = message.OrderId
};

_logger.LogInformation("Order {OrderId} is on its way!", message.OrderId);
logger.LogInformation("Order {OrderId} is on its way!", message.OrderId);

await _publisher.PublishAsync(orderDeliveredEvent);
await publisher.PublishAsync(orderDeliveredEvent);

return true;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,12 @@

namespace JustSaying.Sample.Restaurant.KitchenConsole.Handlers;

public class OrderPlacedEventHandler : IHandlerAsync<OrderPlacedEvent>
/// <summary>
/// Handles messages of type OrderPlacedEvent
/// Takes a dependency on IMessagePublisher so that further messages can be published
/// </summary>
public class OrderPlacedEventHandler(IMessagePublisher publisher, ILogger<OrderPlacedEventHandler> logger) : IHandlerAsync<OrderPlacedEvent>
{
private readonly IMessagePublisher _publisher;
private readonly ILogger<OrderPlacedEventHandler> _logger;

/// <summary>
/// Handles messages of type OrderPlacedEvent
/// Takes a dependency on IMessagePublisher so that further messages can be published
/// </summary>
public OrderPlacedEventHandler(IMessagePublisher publisher, ILogger<OrderPlacedEventHandler> log)
{
_publisher = publisher;
_logger = log;
}

public async Task<bool> Handle(OrderPlacedEvent message)
{
// Returning true would indicate:
Expand All @@ -33,12 +24,12 @@ public async Task<bool> Handle(OrderPlacedEvent message)

try
{
_logger.LogInformation("Order {orderId} for {description} received", message.OrderId, message.Description);
logger.LogInformation("Order {orderId} for {description} received", message.OrderId, message.Description);

// This is where you would actually handle the order placement
// Intentionally left empty for the sake of this being a sample application

_logger.LogInformation("Order {OrderId} ready", message.OrderId);
logger.LogInformation("Order {OrderId} ready", message.OrderId);

await Task.Delay(RandomNumberGenerator.GetInt32(50, 100));

Expand All @@ -47,13 +38,13 @@ public async Task<bool> Handle(OrderPlacedEvent message)
OrderId = message.OrderId
};

await _publisher.PublishAsync(orderReadyEvent).ConfigureAwait(false);
await publisher.PublishAsync(orderReadyEvent).ConfigureAwait(false);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to handle message for {orderId}", message.OrderId);
logger.LogError(ex, "Failed to handle message for {orderId}", message.OrderId);
return false;
}
}
}
}
19 changes: 4 additions & 15 deletions samples/src/JustSaying.Sample.Restaurant.OrderingApi/BusService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,13 @@ namespace JustSaying.Sample.Restaurant.OrderingApi;
/// A background service responsible for starting the bus which listens for
/// messages on the configured queues
/// </summary>
public class BusService : BackgroundService
public class BusService(IMessagingBus bus, ILogger<BusService> logger, IMessagePublisher publisher) : BackgroundService
{
private readonly IMessagingBus _bus;
private readonly ILogger<BusService> _logger;
private readonly IMessagePublisher _publisher;

public BusService(IMessagingBus bus, ILogger<BusService> logger, IMessagePublisher publisher)
{
_bus = bus;
_logger = logger;
_publisher = publisher;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Ordering API subscriber running");
logger.LogInformation("Ordering API subscriber running");

await _publisher.StartAsync(stoppingToken);
await _bus.StartAsync(stoppingToken);
await publisher.StartAsync(stoppingToken);
await bus.StartAsync(stoppingToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,13 @@

namespace JustSaying.Sample.Restaurant.OrderingApi.Handlers;

public class OrderDeliveredEventHandler : IHandlerAsync<OrderDeliveredEvent>
public class OrderDeliveredEventHandler(ILogger<OrderDeliveredEventHandler> logger) : IHandlerAsync<OrderDeliveredEvent>
{
private readonly ILogger<OrderDeliveredEventHandler> _logger;

public OrderDeliveredEventHandler(ILogger<OrderDeliveredEventHandler> logger)
{
_logger = logger;
}

public async Task<bool> Handle(OrderDeliveredEvent message)
{
await Task.Delay(RandomNumberGenerator.GetInt32(50, 100));

_logger.LogInformation("Order {OrderId} has been delivered", message.OrderId);
logger.LogInformation("Order {OrderId} has been delivered", message.OrderId);
return true;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,11 @@

namespace JustSaying.Sample.Restaurant.OrderingApi.Handlers;

public class OrderReadyEventHandler : IHandlerAsync<OrderReadyEvent>
public class OrderReadyEventHandler(ILogger<OrderReadyEventHandler> logger, IMessagePublisher publisher) : IHandlerAsync<OrderReadyEvent>
{
private readonly ILogger<OrderReadyEventHandler> _logger;
private readonly IMessagePublisher _publisher;

public OrderReadyEventHandler(ILogger<OrderReadyEventHandler> logger, IMessagePublisher publisher)
{
_logger = logger;
_publisher = publisher;
}

public async Task<bool> Handle(OrderReadyEvent message)
{
_logger.LogInformation("Order {orderId} ready", message.OrderId);
logger.LogInformation("Order {orderId} ready", message.OrderId);

// This is where you would actually handle the order placement
// Intentionally left empty for the sake of this being a sample application
Expand All @@ -30,7 +21,7 @@ public async Task<bool> Handle(OrderReadyEvent message)
OrderId = message.OrderId
};

await _publisher.PublishAsync(orderOnItsWayEvent);
await publisher.PublishAsync(orderOnItsWayEvent);

// Returning true would indicate:
// The message was handled successfully
Expand All @@ -41,4 +32,4 @@ public async Task<bool> Handle(OrderReadyEvent message)
// The message should be moved to the error queue if all retries fail
return true;
}
}
}
13 changes: 6 additions & 7 deletions src/JustSaying/AwsTools/ErrorQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,12 @@
namespace JustSaying.AwsTools;

[Obsolete("SqsQueueBase and related classes are not intended for general usage and may be removed in a future major release")]
public class ErrorQueue : SqsQueueByNameBase
public class ErrorQueue(
RegionEndpoint region,
string sourceQueueName,
IAmazonSQS client,
ILoggerFactory loggerFactory) : SqsQueueByNameBase(region, sourceQueueName + "_error", client, loggerFactory)
{
public ErrorQueue(RegionEndpoint region, string sourceQueueName, IAmazonSQS client, ILoggerFactory loggerFactory)
: base(region, sourceQueueName + "_error", client, loggerFactory)
{
}

protected override Dictionary<string, string> GetCreateQueueAttributes(SqsBasicConfiguration queueConfig)
{
return new Dictionary<string, string>
Expand Down Expand Up @@ -55,4 +54,4 @@ public override async Task UpdateQueueAttributeAsync(SqsBasicConfiguration queue

protected override bool QueueNeedsUpdating(SqsBasicConfiguration queueConfig)
=> MessageRetentionPeriod != queueConfig.ErrorQueueRetentionPeriod;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,7 @@ await middleware.RunAsync(handleContext, null, cancellationToken)

return (false, null, null);
}
#pragma warning disable CA1031
catch (Exception ex)
#pragma warning restore CA1031
{
_logger.LogError(
ex,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ namespace JustSaying.AwsTools.MessageHandling.Dispatch;
/// </summary>
public sealed class MiddlewareMap : IInterrogable
{
private readonly Dictionary<(string queueName, Type type), HandleMessageMiddleware> _middlewares
= new Dictionary<(string, Type), HandleMessageMiddleware>();
private readonly Dictionary<(string queueName, Type type), HandleMessageMiddleware> _middlewares = new();

/// <summary>
/// Checks if a middleware has been added for a given queue and message type.
Expand Down Expand Up @@ -91,4 +90,4 @@ public InterrogationResult Interrogate()
Middlewares = middlewares
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,10 @@

namespace JustSaying.AwsTools.MessageHandling;

internal class ForeignTopicArnProvider : ITopicArnProvider
internal class ForeignTopicArnProvider(RegionEndpoint regionEndpoint, string accountId, string topicName) : ITopicArnProvider

Check warning on line 5 in src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs

View check run for this annotation

Codecov / codecov/patch

src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs#L5

Added line #L5 was not covered by tests
{

private readonly string _arn;

public ForeignTopicArnProvider(RegionEndpoint regionEndpoint, string accountId, string topicName)
{
_arn = $"arn:aws:sns:{regionEndpoint.SystemName}:{accountId}:{topicName}";
}
private readonly string _arn = $"arn:aws:sns:{regionEndpoint.SystemName}:{accountId}:{topicName}";

Check warning on line 8 in src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs

View check run for this annotation

Codecov / codecov/patch

src/JustSaying/AwsTools/MessageHandling/ForeignTopicArnProvider.cs#L8

Added line #L8 was not covered by tests

public Task<bool> ArnExistsAsync()
{
Expand All @@ -22,4 +17,4 @@ public Task<string> GetArnAsync()
{
return Task.FromResult(_arn);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ private async Task<string> GetArnInternalAsync(string topicName)
_exists = true;
return topic.TopicArn;
}
#pragma warning disable CA1031
catch
#pragma warning restore CA1031
catch (Exception)

Check warning on line 27 in src/JustSaying/AwsTools/MessageHandling/LocalTopicArnProvider.cs

View check run for this annotation

Codecov / codecov/patch

src/JustSaying/AwsTools/MessageHandling/LocalTopicArnProvider.cs#L27

Added line #L27 was not covered by tests
{
// ignored
}
Expand All @@ -43,4 +41,4 @@ public async Task<bool> ArnExistsAsync()
_ = await _lazyGetArnAsync.Value.ConfigureAwait(false);
return _exists;
}
}
}
Loading

0 comments on commit 519cee0

Please sign in to comment.