From ea520f9e77b8b57b6824ca68362a6bb9e158f4b1 Mon Sep 17 00:00:00 2001 From: Andrea Vouk Date: Sun, 13 Oct 2024 00:20:41 +0200 Subject: [PATCH] Convert null check to modern ThrowIfNull checks --- .../Server_Retained_Messages_Samples.cs | 5 +- .../EndpointRouterExtensions.cs | 5 +- .../MqttSubProtocolSelector.cs | 10 +-- .../MqttWebSocketServerAdapter.cs | 5 +- Source/MQTTnet.AspnetCore/ReaderExtensions.cs | 5 +- .../ServiceCollectionExtensions.cs | 31 ++------ .../ReaderExtensionsBenchmark.cs | 2 +- .../TopicFilterComparerBenchmark.cs | 11 +-- ...ultMqttRpcClientTopicGenerationStrategy.cs | 7 +- .../MqttFactoryExtensions.cs | 11 +-- .../MQTTnet.Extensions.Rpc/MqttRpcClient.cs | 5 +- .../MqttTopicTemplate.cs | 5 +- .../Formatter/MqttConnAckPacketFactory.cs | 5 +- .../Formatter/MqttPubAckPacketFactory.cs | 11 +-- .../Formatter/MqttPubCompPacketFactory.cs | 5 +- .../Formatter/MqttPubRecPacketFactory.cs | 5 +- .../Formatter/MqttPubRelPacketFactory.cs | 5 +- .../Formatter/MqttPublishPacketFactory.cs | 15 +--- .../Formatter/MqttSubAckPacketFactory.cs | 11 +-- .../Formatter/MqttUnsubAckPacketFactory.cs | 11 +-- .../Internal/MqttClientSessionsManager.cs | 32 ++------ .../Internal/MqttClientStatistics.cs | 10 +-- .../MqttClientSubscriptionsManager.cs | 14 +--- .../Internal/MqttConnectedClient.cs | 5 +- .../Internal/MqttRetainedMessagesManager.cs | 8 +- .../Internal/MqttServerKeepAliveMonitor.cs | 5 +- .../Internal/MqttSessionsStorage.cs | 15 +--- Source/MQTTnet.Server/MqttServer.cs | 64 +++------------- Source/MQTTnet.Server/MqttServerExtensions.cs | 55 +++----------- Source/MQTTnet.Server/MqttServerFactory.cs | 21 +----- .../Options/MqttServerOptionsBuilder.cs | 15 +--- .../MQTTnet.Server/Status/MqttClientStatus.cs | 5 +- .../Status/MqttClientStatusExtensions.cs | 5 +- .../Status/MqttSessionStatus.cs | 10 +-- .../Stopping/MqttServerStopOptionsBuilder.cs | 11 +-- .../MQTTnet.TestApp/MqttNetConsoleLogger.cs | 2 +- .../Helpers/MqttClientExtensions.cs | 5 +- .../Helpers/ReflectionExtensions.cs | 7 +- .../TestApplicationMessageReceivedHandler.cs | 5 +- .../MQTTnet.Tests/Mockups/TestEnvironment.cs | 15 +--- Source/MQTTnet/Adapter/MqttChannelAdapter.cs | 5 +- Source/MQTTnet/Adapter/MqttPacketInspector.cs | 5 +- .../MqttClientConnectResultFactory.cs | 16 +--- .../Logger/MqttNetSourceLoggerExtensions.cs | 9 +-- .../MqttClientDisconnectOptionsValidator.cs | 5 +- ...ttExtendedAuthenticationExchangeContext.cs | 5 +- .../MqttApplicationMessageFactory.cs | 5 +- Source/MQTTnet/Formatter/MqttBufferWriter.cs | 12 +-- .../Formatter/MqttConnectPacketFactory.cs | 5 +- .../Formatter/MqttPubAckPacketFactory.cs | 5 +- .../Formatter/MqttPubCompPacketFactory.cs | 5 +- .../Formatter/MqttPubRecPacketFactory.cs | 5 +- .../Formatter/MqttPubRelPacketFactory.cs | 5 +- .../Formatter/MqttPublishPacketFactory.cs | 5 +- .../Formatter/MqttSubscribePacketFactory.cs | 5 +- .../Formatter/MqttUnsubscribePacketFactory.cs | 5 +- .../Formatter/V3/MqttV3PacketFormatter.cs | 10 +-- .../Formatter/V5/MqttV5PacketEncoder.cs | 5 +- .../Formatter/V5/MqttV5PropertiesWriter.cs | 7 +- .../Implementations/CrossPlatformSocket.cs | 10 +-- .../MqttClientAdapterFactory.cs | 2 +- Source/MQTTnet/Internal/AsyncEvent.cs | 31 ++------ Source/MQTTnet/Internal/AsyncLock.cs | 5 +- Source/MQTTnet/Internal/BlockingQueue.cs | 4 +- Source/MQTTnet/Internal/MqttPacketBus.cs | 5 +- Source/MQTTnet/Internal/TaskExtensions.cs | 5 +- .../LowLevelClient/LowLevelMqttClient.cs | 10 +-- .../MqttApplicationMessageExtensions.cs | 5 +- .../MqttApplicationMessageValidator.cs | 19 ++--- Source/MQTTnet/MqttClient.cs | 25 ++----- Source/MQTTnet/MqttClientExtensions.cs | 75 ++++--------------- Source/MQTTnet/MqttClientFactory.cs | 42 ++--------- .../Options/MqttClientOptionsBuilder.cs | 25 ++----- .../Options/MqttClientOptionsValidator.cs | 5 +- .../Options/MqttClientTlsOptionsBuilder.cs | 20 +---- .../MqttClientWebSocketOptionsBuilder.cs | 5 +- .../PacketDispatcher/MqttPacketDispatcher.cs | 24 ++---- .../MQTTnet/Packets/MqttPacketExtensions.cs | 5 +- Source/MQTTnet/Protocol/MqttTopicValidator.cs | 5 +- .../MqttClientSubscribeOptionsBuilder.cs | 15 +--- .../MqttClientSubscribeOptionsValidator.cs | 5 +- .../MqttClientSubscribeResultFactory.cs | 11 +-- .../MqttClientUnsubscribeOptionsBuilder.cs | 15 +--- .../MqttClientUnsubscribeOptionsValidator.cs | 5 +- .../MqttClientUnsubscribeResultFactory.cs | 11 +-- 85 files changed, 209 insertions(+), 783 deletions(-) diff --git a/Samples/Server/Server_Retained_Messages_Samples.cs b/Samples/Server/Server_Retained_Messages_Samples.cs index 1c7341b72..4564acae9 100644 --- a/Samples/Server/Server_Retained_Messages_Samples.cs +++ b/Samples/Server/Server_Retained_Messages_Samples.cs @@ -102,10 +102,7 @@ sealed class MqttRetainedMessageModel public static MqttRetainedMessageModel Create(MqttApplicationMessage message) { - if (message == null) - { - throw new ArgumentNullException(nameof(message)); - } + ArgumentNullException.ThrowIfNull(message); return new MqttRetainedMessageModel { diff --git a/Source/MQTTnet.AspnetCore/EndpointRouterExtensions.cs b/Source/MQTTnet.AspnetCore/EndpointRouterExtensions.cs index 6640e07e6..8e96a6c28 100644 --- a/Source/MQTTnet.AspnetCore/EndpointRouterExtensions.cs +++ b/Source/MQTTnet.AspnetCore/EndpointRouterExtensions.cs @@ -12,10 +12,7 @@ public static class EndpointRouterExtensions { public static void MapMqtt(this IEndpointRouteBuilder endpoints, string pattern) { - if (endpoints == null) - { - throw new ArgumentNullException(nameof(endpoints)); - } + ArgumentNullException.ThrowIfNull(endpoints); endpoints.MapConnectionHandler(pattern, options => { diff --git a/Source/MQTTnet.AspnetCore/MqttSubProtocolSelector.cs b/Source/MQTTnet.AspnetCore/MqttSubProtocolSelector.cs index 5030f2d9f..c6acdfa8e 100644 --- a/Source/MQTTnet.AspnetCore/MqttSubProtocolSelector.cs +++ b/Source/MQTTnet.AspnetCore/MqttSubProtocolSelector.cs @@ -13,10 +13,7 @@ public static class MqttSubProtocolSelector { public static string SelectSubProtocol(HttpRequest request) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); string subProtocol = null; if (request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues)) @@ -29,10 +26,7 @@ public static string SelectSubProtocol(HttpRequest request) public static string SelectSubProtocol(IList requestedSubProtocolValues) { - if (requestedSubProtocolValues == null) - { - throw new ArgumentNullException(nameof(requestedSubProtocolValues)); - } + ArgumentNullException.ThrowIfNull(requestedSubProtocolValues); // Order the protocols to also match "mqtt", "mqttv-3.1", "mqttv-3.11" etc. return requestedSubProtocolValues.OrderByDescending(p => p.Length).FirstOrDefault(p => p.ToLower().StartsWith("mqtt")); diff --git a/Source/MQTTnet.AspnetCore/MqttWebSocketServerAdapter.cs b/Source/MQTTnet.AspnetCore/MqttWebSocketServerAdapter.cs index 9b364231d..272ead6bf 100644 --- a/Source/MQTTnet.AspnetCore/MqttWebSocketServerAdapter.cs +++ b/Source/MQTTnet.AspnetCore/MqttWebSocketServerAdapter.cs @@ -26,10 +26,7 @@ public void Dispose() public async Task RunWebSocketConnectionAsync(WebSocket webSocket, HttpContext httpContext) { - if (webSocket == null) - { - throw new ArgumentNullException(nameof(webSocket)); - } + ArgumentNullException.ThrowIfNull(webSocket); var endpoint = $"{httpContext.Connection.RemoteIpAddress}:{httpContext.Connection.RemotePort}"; diff --git a/Source/MQTTnet.AspnetCore/ReaderExtensions.cs b/Source/MQTTnet.AspnetCore/ReaderExtensions.cs index d120062ba..9b4f24ca5 100644 --- a/Source/MQTTnet.AspnetCore/ReaderExtensions.cs +++ b/Source/MQTTnet.AspnetCore/ReaderExtensions.cs @@ -22,10 +22,7 @@ public static bool TryDecode( out SequencePosition observed, out int bytesRead) { - if (formatter == null) - { - throw new ArgumentNullException(nameof(formatter)); - } + ArgumentNullException.ThrowIfNull(formatter); packet = null; consumed = input.Start; diff --git a/Source/MQTTnet.AspnetCore/ServiceCollectionExtensions.cs b/Source/MQTTnet.AspnetCore/ServiceCollectionExtensions.cs index d662187f3..915f6791c 100644 --- a/Source/MQTTnet.AspnetCore/ServiceCollectionExtensions.cs +++ b/Source/MQTTnet.AspnetCore/ServiceCollectionExtensions.cs @@ -16,15 +16,8 @@ public static class ServiceCollectionExtensions { public static IServiceCollection AddHostedMqttServer(this IServiceCollection services, MqttServerOptions options) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(options); services.AddSingleton(options); services.AddHostedMqttServer(); @@ -34,10 +27,7 @@ public static IServiceCollection AddHostedMqttServer(this IServiceCollection ser public static IServiceCollection AddHostedMqttServer(this IServiceCollection services, Action configure) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); var serverOptionsBuilder = new MqttServerOptionsBuilder(); @@ -61,10 +51,7 @@ public static void AddHostedMqttServer(this IServiceCollection services) public static IServiceCollection AddHostedMqttServerWithServices(this IServiceCollection services, Action configure) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddSingleton( s => @@ -89,20 +76,14 @@ public static IServiceCollection AddMqttConnectionHandler(this IServiceCollectio public static void AddMqttLogger(this IServiceCollection services, IMqttNetLogger logger) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullException.ThrowIfNull(services); services.AddSingleton(logger); } public static IServiceCollection AddMqttServer(this IServiceCollection serviceCollection, Action configure = null) { - if (serviceCollection is null) - { - throw new ArgumentNullException(nameof(serviceCollection)); - } + ArgumentNullException.ThrowIfNull(serviceCollection); serviceCollection.AddMqttConnectionHandler(); serviceCollection.AddHostedMqttServer(configure); diff --git a/Source/MQTTnet.Benchmarks/ReaderExtensionsBenchmark.cs b/Source/MQTTnet.Benchmarks/ReaderExtensionsBenchmark.cs index cd51297aa..5f2242461 100644 --- a/Source/MQTTnet.Benchmarks/ReaderExtensionsBenchmark.cs +++ b/Source/MQTTnet.Benchmarks/ReaderExtensionsBenchmark.cs @@ -145,7 +145,7 @@ public static bool TryDecode(MqttPacketFormatterAdapter formatter, out SequencePosition observed, out int bytesRead) { - if (formatter == null) throw new ArgumentNullException(nameof(formatter)); + ArgumentNullException.ThrowIfNull(formatter); packet = null; consumed = input.Start; diff --git a/Source/MQTTnet.Benchmarks/TopicFilterComparerBenchmark.cs b/Source/MQTTnet.Benchmarks/TopicFilterComparerBenchmark.cs index a75d3521a..f78cb81c3 100644 --- a/Source/MQTTnet.Benchmarks/TopicFilterComparerBenchmark.cs +++ b/Source/MQTTnet.Benchmarks/TopicFilterComparerBenchmark.cs @@ -73,15 +73,8 @@ public void Setup() static bool LegacyMethodByStringSplit(string topic, string filter) { - if (topic == null) - { - throw new ArgumentNullException(nameof(topic)); - } - - if (filter == null) - { - throw new ArgumentNullException(nameof(filter)); - } + ArgumentNullException.ThrowIfNull(topic); + ArgumentNullException.ThrowIfNull(filter); if (string.Equals(topic, filter, StringComparison.Ordinal)) { diff --git a/Source/MQTTnet.Extensions.Rpc/DefaultMqttRpcClientTopicGenerationStrategy.cs b/Source/MQTTnet.Extensions.Rpc/DefaultMqttRpcClientTopicGenerationStrategy.cs index e1af74735..b21affed2 100644 --- a/Source/MQTTnet.Extensions.Rpc/DefaultMqttRpcClientTopicGenerationStrategy.cs +++ b/Source/MQTTnet.Extensions.Rpc/DefaultMqttRpcClientTopicGenerationStrategy.cs @@ -10,16 +10,13 @@ public sealed class DefaultMqttRpcClientTopicGenerationStrategy : IMqttRpcClient { public MqttRpcTopicPair CreateRpcTopics(TopicGenerationContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); if (context.MethodName.Contains("/") || context.MethodName.Contains("+") || context.MethodName.Contains("#")) { throw new ArgumentException("The method name cannot contain /, + or #."); } - + var requestTopic = $"MQTTnet.RPC/{Guid.NewGuid():N}/{context.MethodName}"; var responseTopic = requestTopic + "/response"; diff --git a/Source/MQTTnet.Extensions.Rpc/MqttFactoryExtensions.cs b/Source/MQTTnet.Extensions.Rpc/MqttFactoryExtensions.cs index 09d690cc3..3de669545 100644 --- a/Source/MQTTnet.Extensions.Rpc/MqttFactoryExtensions.cs +++ b/Source/MQTTnet.Extensions.Rpc/MqttFactoryExtensions.cs @@ -20,15 +20,8 @@ public static IMqttRpcClient CreateMqttRpcClient(this MqttClientFactory clientFa public static IMqttRpcClient CreateMqttRpcClient(this MqttClientFactory _, IMqttClient mqttClient, MqttRpcClientOptions rpcClientOptions) { - if (mqttClient == null) - { - throw new ArgumentNullException(nameof(mqttClient)); - } - - if (rpcClientOptions == null) - { - throw new ArgumentNullException(nameof(rpcClientOptions)); - } + ArgumentNullException.ThrowIfNull(mqttClient); + ArgumentNullException.ThrowIfNull(rpcClientOptions); return new MqttRpcClient(mqttClient, rpcClientOptions); } diff --git a/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs b/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs index 3a301690e..c64b93c2d 100644 --- a/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs +++ b/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs @@ -65,10 +65,7 @@ public async Task ExecuteAsync(TimeSpan timeout, string methodName, byte public async Task ExecuteAsync(string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary parameters = null, CancellationToken cancellationToken = default) { - if (methodName == null) - { - throw new ArgumentNullException(nameof(methodName)); - } + ArgumentNullException.ThrowIfNull(methodName); var context = new TopicGenerationContext(_mqttClient, _options, methodName, parameters, qualityOfServiceLevel); var topicNames = _options.TopicGenerationStrategy.CreateRpcTopics(context); diff --git a/Source/MQTTnet.Extensions.TopicTemplate/MqttTopicTemplate.cs b/Source/MQTTnet.Extensions.TopicTemplate/MqttTopicTemplate.cs index 25b3f3eaa..66b7369eb 100644 --- a/Source/MQTTnet.Extensions.TopicTemplate/MqttTopicTemplate.cs +++ b/Source/MQTTnet.Extensions.TopicTemplate/MqttTopicTemplate.cs @@ -41,10 +41,7 @@ public sealed class MqttTopicTemplate : IEquatable /// public MqttTopicTemplate(string topicTemplate) { - if (topicTemplate == null) - { - throw new ArgumentNullException(nameof(topicTemplate)); - } + ArgumentNullException.ThrowIfNull(topicTemplate); MqttTopicValidator.ThrowIfInvalidSubscribe(topicTemplate); diff --git a/Source/MQTTnet.Server/Internal/Formatter/MqttConnAckPacketFactory.cs b/Source/MQTTnet.Server/Internal/Formatter/MqttConnAckPacketFactory.cs index 39e8a2ae1..79f3a0203 100644 --- a/Source/MQTTnet.Server/Internal/Formatter/MqttConnAckPacketFactory.cs +++ b/Source/MQTTnet.Server/Internal/Formatter/MqttConnAckPacketFactory.cs @@ -12,10 +12,7 @@ public static class MqttConnAckPacketFactory { public static MqttConnAckPacket Create(ValidatingConnectionEventArgs validatingConnectionEventArgs) { - if (validatingConnectionEventArgs == null) - { - throw new ArgumentNullException(nameof(validatingConnectionEventArgs)); - } + ArgumentNullException.ThrowIfNull(validatingConnectionEventArgs); var connAckPacket = new MqttConnAckPacket { diff --git a/Source/MQTTnet.Server/Internal/Formatter/MqttPubAckPacketFactory.cs b/Source/MQTTnet.Server/Internal/Formatter/MqttPubAckPacketFactory.cs index 8e59eb7a9..9c0d24903 100644 --- a/Source/MQTTnet.Server/Internal/Formatter/MqttPubAckPacketFactory.cs +++ b/Source/MQTTnet.Server/Internal/Formatter/MqttPubAckPacketFactory.cs @@ -11,15 +11,8 @@ public static class MqttPubAckPacketFactory { public static MqttPubAckPacket Create(MqttPublishPacket publishPacket, DispatchApplicationMessageResult dispatchApplicationMessageResult) { - if (publishPacket == null) - { - throw new ArgumentNullException(nameof(publishPacket)); - } - - if (dispatchApplicationMessageResult == null) - { - throw new ArgumentNullException(nameof(dispatchApplicationMessageResult)); - } + ArgumentNullException.ThrowIfNull(publishPacket); + ArgumentNullException.ThrowIfNull(dispatchApplicationMessageResult); var pubAckPacket = new MqttPubAckPacket { diff --git a/Source/MQTTnet.Server/Internal/Formatter/MqttPubCompPacketFactory.cs b/Source/MQTTnet.Server/Internal/Formatter/MqttPubCompPacketFactory.cs index bb135b179..75d58ece9 100644 --- a/Source/MQTTnet.Server/Internal/Formatter/MqttPubCompPacketFactory.cs +++ b/Source/MQTTnet.Server/Internal/Formatter/MqttPubCompPacketFactory.cs @@ -11,10 +11,7 @@ public static class MqttPubCompPacketFactory { public static MqttPubCompPacket Create(MqttPubRelPacket pubRelPacket, MqttApplicationMessageReceivedReasonCode reasonCode) { - if (pubRelPacket == null) - { - throw new ArgumentNullException(nameof(pubRelPacket)); - } + ArgumentNullException.ThrowIfNull(pubRelPacket); return new MqttPubCompPacket { diff --git a/Source/MQTTnet.Server/Internal/Formatter/MqttPubRecPacketFactory.cs b/Source/MQTTnet.Server/Internal/Formatter/MqttPubRecPacketFactory.cs index ad800a055..8b52c64fb 100644 --- a/Source/MQTTnet.Server/Internal/Formatter/MqttPubRecPacketFactory.cs +++ b/Source/MQTTnet.Server/Internal/Formatter/MqttPubRecPacketFactory.cs @@ -11,10 +11,7 @@ public static class MqttPubRecPacketFactory { public static MqttPacket Create(MqttPublishPacket publishPacket, DispatchApplicationMessageResult dispatchApplicationMessageResult) { - if (publishPacket == null) - { - throw new ArgumentNullException(nameof(publishPacket)); - } + ArgumentNullException.ThrowIfNull(publishPacket); var pubRecPacket = new MqttPubRecPacket { diff --git a/Source/MQTTnet.Server/Internal/Formatter/MqttPubRelPacketFactory.cs b/Source/MQTTnet.Server/Internal/Formatter/MqttPubRelPacketFactory.cs index f52015dcc..4c750ab30 100644 --- a/Source/MQTTnet.Server/Internal/Formatter/MqttPubRelPacketFactory.cs +++ b/Source/MQTTnet.Server/Internal/Formatter/MqttPubRelPacketFactory.cs @@ -11,10 +11,7 @@ public static class MqttPubRelPacketFactory { public static MqttPubRelPacket Create(MqttPubRecPacket pubRecPacket, MqttApplicationMessageReceivedReasonCode reasonCode) { - if (pubRecPacket == null) - { - throw new ArgumentNullException(nameof(pubRecPacket)); - } + ArgumentNullException.ThrowIfNull(pubRecPacket); return new MqttPubRelPacket { diff --git a/Source/MQTTnet.Server/Internal/Formatter/MqttPublishPacketFactory.cs b/Source/MQTTnet.Server/Internal/Formatter/MqttPublishPacketFactory.cs index caf220a75..03c236639 100644 --- a/Source/MQTTnet.Server/Internal/Formatter/MqttPublishPacketFactory.cs +++ b/Source/MQTTnet.Server/Internal/Formatter/MqttPublishPacketFactory.cs @@ -11,10 +11,7 @@ public static class MqttPublishPacketFactory { public static MqttPublishPacket Create(MqttConnectPacket connectPacket) { - if (connectPacket == null) - { - throw new ArgumentNullException(nameof(connectPacket)); - } + ArgumentNullException.ThrowIfNull(connectPacket); if (!connectPacket.WillFlag) { @@ -46,10 +43,7 @@ public static MqttPublishPacket Create(MqttConnectPacket connectPacket) public static MqttPublishPacket Create(MqttApplicationMessage applicationMessage) { - if (applicationMessage == null) - { - throw new ArgumentNullException(nameof(applicationMessage)); - } + ArgumentNullException.ThrowIfNull(applicationMessage); // Copy all values to their matching counterparts. // The not supported values in MQTT 3.1.1 are not serialized (excluded) later. @@ -75,10 +69,7 @@ public static MqttPublishPacket Create(MqttApplicationMessage applicationMessage public static MqttPublishPacket Create(MqttRetainedMessageMatch retainedMessage) { - if (retainedMessage == null) - { - throw new ArgumentNullException(nameof(retainedMessage)); - } + ArgumentNullException.ThrowIfNull(retainedMessage); var publishPacket = Create(retainedMessage.ApplicationMessage); publishPacket.QualityOfServiceLevel = retainedMessage.SubscriptionQualityOfServiceLevel; diff --git a/Source/MQTTnet.Server/Internal/Formatter/MqttSubAckPacketFactory.cs b/Source/MQTTnet.Server/Internal/Formatter/MqttSubAckPacketFactory.cs index 38f4eeeaa..dd40f33cb 100644 --- a/Source/MQTTnet.Server/Internal/Formatter/MqttSubAckPacketFactory.cs +++ b/Source/MQTTnet.Server/Internal/Formatter/MqttSubAckPacketFactory.cs @@ -10,15 +10,8 @@ public static class MqttSubAckPacketFactory { public static MqttSubAckPacket Create(MqttSubscribePacket subscribePacket, SubscribeResult subscribeResult) { - if (subscribePacket == null) - { - throw new ArgumentNullException(nameof(subscribePacket)); - } - - if (subscribeResult == null) - { - throw new ArgumentNullException(nameof(subscribeResult)); - } + ArgumentNullException.ThrowIfNull(subscribePacket); + ArgumentNullException.ThrowIfNull(subscribeResult); var subAckPacket = new MqttSubAckPacket { diff --git a/Source/MQTTnet.Server/Internal/Formatter/MqttUnsubAckPacketFactory.cs b/Source/MQTTnet.Server/Internal/Formatter/MqttUnsubAckPacketFactory.cs index ad630882b..cd9e36760 100644 --- a/Source/MQTTnet.Server/Internal/Formatter/MqttUnsubAckPacketFactory.cs +++ b/Source/MQTTnet.Server/Internal/Formatter/MqttUnsubAckPacketFactory.cs @@ -10,15 +10,8 @@ public static class MqttUnsubAckPacketFactory { public static MqttUnsubAckPacket Create(MqttUnsubscribePacket unsubscribePacket, UnsubscribeResult unsubscribeResult) { - if (unsubscribePacket == null) - { - throw new ArgumentNullException(nameof(unsubscribePacket)); - } - - if (unsubscribeResult == null) - { - throw new ArgumentNullException(nameof(unsubscribeResult)); - } + ArgumentNullException.ThrowIfNull(unsubscribePacket); + ArgumentNullException.ThrowIfNull(unsubscribeResult); var unsubAckPacket = new MqttUnsubAckPacket { diff --git a/Source/MQTTnet.Server/Internal/MqttClientSessionsManager.cs b/Source/MQTTnet.Server/Internal/MqttClientSessionsManager.cs index b1a427cbc..6c0cf68ec 100644 --- a/Source/MQTTnet.Server/Internal/MqttClientSessionsManager.cs +++ b/Source/MQTTnet.Server/Internal/MqttClientSessionsManager.cs @@ -38,10 +38,7 @@ public sealed class MqttClientSessionsManager : ISubscriptionChangedNotification public MqttClientSessionsManager(MqttServerOptions options, MqttRetainedMessagesManager retainedMessagesManager, MqttServerEventContainer eventContainer, IMqttNetLogger logger) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); _logger = logger.WithSource(nameof(MqttClientSessionsManager)); _rootLogger = logger; @@ -53,10 +50,7 @@ public MqttClientSessionsManager(MqttServerOptions options, MqttRetainedMessages public async Task CloseAllConnections(MqttServerClientDisconnectOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); List connections; lock (_clients) @@ -481,15 +475,8 @@ public void Start() public async Task SubscribeAsync(string clientId, ICollection topicFilters) { - if (clientId == null) - { - throw new ArgumentNullException(nameof(clientId)); - } - - if (topicFilters == null) - { - throw new ArgumentNullException(nameof(topicFilters)); - } + ArgumentNullException.ThrowIfNull(clientId); + ArgumentNullException.ThrowIfNull(topicFilters); var fakeSubscribePacket = new MqttSubscribePacket(); fakeSubscribePacket.TopicFilters.AddRange(topicFilters); @@ -510,15 +497,8 @@ public async Task SubscribeAsync(string clientId, ICollection t public Task UnsubscribeAsync(string clientId, ICollection topicFilters) { - if (clientId == null) - { - throw new ArgumentNullException(nameof(clientId)); - } - - if (topicFilters == null) - { - throw new ArgumentNullException(nameof(topicFilters)); - } + ArgumentNullException.ThrowIfNull(clientId); + ArgumentNullException.ThrowIfNull(topicFilters); var fakeUnsubscribePacket = new MqttUnsubscribePacket(); fakeUnsubscribePacket.TopicFilters.AddRange(topicFilters); diff --git a/Source/MQTTnet.Server/Internal/MqttClientStatistics.cs b/Source/MQTTnet.Server/Internal/MqttClientStatistics.cs index baa2a3bd7..481f2945e 100644 --- a/Source/MQTTnet.Server/Internal/MqttClientStatistics.cs +++ b/Source/MQTTnet.Server/Internal/MqttClientStatistics.cs @@ -50,10 +50,7 @@ public MqttClientStatistics() public void HandleReceivedPacket(MqttPacket packet) { - if (packet == null) - { - throw new ArgumentNullException(nameof(packet)); - } + ArgumentNullException.ThrowIfNull(packet); // This class is tracking all values from Clients perspective! LastPacketSentTimestamp = DateTime.UtcNow; @@ -74,10 +71,7 @@ public void HandleReceivedPacket(MqttPacket packet) public void HandleSentPacket(MqttPacket packet) { - if (packet == null) - { - throw new ArgumentNullException(nameof(packet)); - } + ArgumentNullException.ThrowIfNull(packet); // This class is tracking all values from Clients perspective! LastPacketReceivedTimestamp = DateTime.UtcNow; diff --git a/Source/MQTTnet.Server/Internal/MqttClientSubscriptionsManager.cs b/Source/MQTTnet.Server/Internal/MqttClientSubscriptionsManager.cs index 96c0eafe0..4413755ad 100644 --- a/Source/MQTTnet.Server/Internal/MqttClientSubscriptionsManager.cs +++ b/Source/MQTTnet.Server/Internal/MqttClientSubscriptionsManager.cs @@ -161,10 +161,7 @@ public void Dispose() public async Task Subscribe(MqttSubscribePacket subscribePacket, CancellationToken cancellationToken) { - if (subscribePacket == null) - { - throw new ArgumentNullException(nameof(subscribePacket)); - } + ArgumentNullException.ThrowIfNull(subscribePacket); var retainedApplicationMessages = await _retainedMessagesManager.GetMessages().ConfigureAwait(false); var result = new SubscribeResult(subscribePacket.TopicFilters.Count); @@ -222,10 +219,7 @@ public async Task Subscribe(MqttSubscribePacket subscribePacket public async Task Unsubscribe(MqttUnsubscribePacket unsubscribePacket, CancellationToken cancellationToken) { - if (unsubscribePacket == null) - { - throw new ArgumentNullException(nameof(unsubscribePacket)); - } + ArgumentNullException.ThrowIfNull(unsubscribePacket); var result = new UnsubscribeResult(); @@ -440,7 +434,7 @@ static void FilterRetainedApplicationMessages( var retainedMessageMatch = new MqttRetainedMessageMatch(retainedMessage, createSubscriptionResult.Subscription.GrantedQualityOfServiceLevel); if (retainedMessageMatch.SubscriptionQualityOfServiceLevel > retainedMessageMatch.ApplicationMessage.QualityOfServiceLevel) { - // UPGRADING the QoS is not allowed! + // UPGRADING the QoS is not allowed! // From MQTT spec: Subscribing to a Topic Filter at QoS 2 is equivalent to saying // "I would like to receive Messages matching this filter at the QoS with which they were published". // This means a publisher is responsible for determining the maximum QoS a Message can be delivered at, @@ -455,7 +449,7 @@ static void FilterRetainedApplicationMessages( subscribeResult.RetainedMessages.Add(retainedMessageMatch); - // Clear the retained message from the list because the client should receive every message only + // Clear the retained message from the list because the client should receive every message only // one time even if multiple subscriptions affect them. retainedMessages[index] = null; } diff --git a/Source/MQTTnet.Server/Internal/MqttConnectedClient.cs b/Source/MQTTnet.Server/Internal/MqttConnectedClient.cs index b4d7938a9..2217def09 100644 --- a/Source/MQTTnet.Server/Internal/MqttConnectedClient.cs +++ b/Source/MQTTnet.Server/Internal/MqttConnectedClient.cs @@ -48,10 +48,7 @@ public MqttConnectedClient( Endpoint = channelAdapter.Endpoint; Session = session ?? throw new ArgumentNullException(nameof(session)); - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); _logger = logger.WithSource(nameof(MqttConnectedClient)); } diff --git a/Source/MQTTnet.Server/Internal/MqttRetainedMessagesManager.cs b/Source/MQTTnet.Server/Internal/MqttRetainedMessagesManager.cs index 8995b35fc..854696c73 100644 --- a/Source/MQTTnet.Server/Internal/MqttRetainedMessagesManager.cs +++ b/Source/MQTTnet.Server/Internal/MqttRetainedMessagesManager.cs @@ -19,8 +19,7 @@ public MqttRetainedMessagesManager(MqttServerEventContainer eventContainer, IMqt { _eventContainer = eventContainer ?? throw new ArgumentNullException(nameof(eventContainer)); - if (logger == null) - throw new ArgumentNullException(nameof(logger)); + ArgumentNullException.ThrowIfNull(logger); _logger = logger.WithSource(nameof(MqttRetainedMessagesManager)); } @@ -53,10 +52,7 @@ public async Task Start() public async Task UpdateMessage(string clientId, MqttApplicationMessage applicationMessage) { - if (applicationMessage == null) - { - throw new ArgumentNullException(nameof(applicationMessage)); - } + ArgumentNullException.ThrowIfNull(applicationMessage); try { diff --git a/Source/MQTTnet.Server/Internal/MqttServerKeepAliveMonitor.cs b/Source/MQTTnet.Server/Internal/MqttServerKeepAliveMonitor.cs index 622c31770..69802e4eb 100644 --- a/Source/MQTTnet.Server/Internal/MqttServerKeepAliveMonitor.cs +++ b/Source/MQTTnet.Server/Internal/MqttServerKeepAliveMonitor.cs @@ -27,10 +27,7 @@ public MqttServerKeepAliveMonitor(MqttServerOptions options, MqttClientSessionsM _options = options ?? throw new ArgumentNullException(nameof(options)); _sessionsManager = sessionsManager ?? throw new ArgumentNullException(nameof(sessionsManager)); - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); _logger = logger.WithSource(nameof(MqttServerKeepAliveMonitor)); } diff --git a/Source/MQTTnet.Server/Internal/MqttSessionsStorage.cs b/Source/MQTTnet.Server/Internal/MqttSessionsStorage.cs index c28103362..2aab0b41c 100644 --- a/Source/MQTTnet.Server/Internal/MqttSessionsStorage.cs +++ b/Source/MQTTnet.Server/Internal/MqttSessionsStorage.cs @@ -34,10 +34,7 @@ public IReadOnlyCollection ReadAllSessions() public bool TryGetSession(string id, out MqttSession session) { - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } + ArgumentNullException.ThrowIfNull(id); if (!_sessions.TryGetValue(id, out session)) { @@ -63,10 +60,7 @@ public bool TryGetSession(string id, out MqttSession session) public bool TryRemoveSession(string id, out MqttSession session) { - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } + ArgumentNullException.ThrowIfNull(id); if (_sessions.TryGetValue(id, out session)) { @@ -79,10 +73,7 @@ public bool TryRemoveSession(string id, out MqttSession session) public void UpdateSession(string id, MqttSession session) { - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } + ArgumentNullException.ThrowIfNull(id); _sessions[id] = session; } diff --git a/Source/MQTTnet.Server/MqttServer.cs b/Source/MQTTnet.Server/MqttServer.cs index f6da769ed..dc30ac93f 100644 --- a/Source/MQTTnet.Server/MqttServer.cs +++ b/Source/MQTTnet.Server/MqttServer.cs @@ -31,10 +31,7 @@ public MqttServer(MqttServerOptions options, IEnumerable ada { _options = options ?? throw new ArgumentNullException(nameof(options)); - if (adapters == null) - { - throw new ArgumentNullException(nameof(adapters)); - } + ArgumentNullException.ThrowIfNull(adapters); _adapters = adapters.ToList(); @@ -202,15 +199,8 @@ public Task DeleteRetainedMessagesAsync() public Task DisconnectClientAsync(string id, MqttServerClientDisconnectOptions options) { - if (id == null) - { - throw new ArgumentNullException(nameof(id)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(id); + ArgumentNullException.ThrowIfNull(options); ThrowIfNotStarted(); @@ -226,10 +216,7 @@ public Task> GetClientsAsync() public Task GetRetainedMessageAsync(string topic) { - if (topic == null) - { - throw new ArgumentNullException(nameof(topic)); - } + ArgumentNullException.ThrowIfNull(topic); ThrowIfNotStarted(); @@ -252,15 +239,8 @@ public Task> GetSessionsAsync() public Task InjectApplicationMessage(InjectedMqttApplicationMessage injectedApplicationMessage, CancellationToken cancellationToken = default) { - if (injectedApplicationMessage == null) - { - throw new ArgumentNullException(nameof(injectedApplicationMessage)); - } - - if (injectedApplicationMessage.ApplicationMessage == null) - { - throw new ArgumentNullException(nameof(injectedApplicationMessage.ApplicationMessage)); - } + ArgumentNullException.ThrowIfNull(injectedApplicationMessage); + ArgumentNullException.ThrowIfNull(injectedApplicationMessage.ApplicationMessage); MqttTopicValidator.ThrowIfInvalid(injectedApplicationMessage.ApplicationMessage.Topic); @@ -306,10 +286,7 @@ public async Task StartAsync() public async Task StopAsync(MqttServerStopOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); try { @@ -343,15 +320,8 @@ public async Task StopAsync(MqttServerStopOptions options) public Task SubscribeAsync(string clientId, ICollection topicFilters) { - if (clientId == null) - { - throw new ArgumentNullException(nameof(clientId)); - } - - if (topicFilters == null) - { - throw new ArgumentNullException(nameof(topicFilters)); - } + ArgumentNullException.ThrowIfNull(clientId); + ArgumentNullException.ThrowIfNull(topicFilters); foreach (var topicFilter in topicFilters) { @@ -366,15 +336,8 @@ public Task SubscribeAsync(string clientId, ICollection topicFi public Task UnsubscribeAsync(string clientId, ICollection topicFilters) { - if (clientId == null) - { - throw new ArgumentNullException(nameof(clientId)); - } - - if (topicFilters == null) - { - throw new ArgumentNullException(nameof(topicFilters)); - } + ArgumentNullException.ThrowIfNull(clientId); + ArgumentNullException.ThrowIfNull(topicFilters); ThrowIfDisposed(); ThrowIfNotStarted(); @@ -384,10 +347,7 @@ public Task UnsubscribeAsync(string clientId, ICollection topicFilters) public Task UpdateRetainedMessageAsync(MqttApplicationMessage retainedMessage) { - if (retainedMessage == null) - { - throw new ArgumentNullException(nameof(retainedMessage)); - } + ArgumentNullException.ThrowIfNull(retainedMessage); ThrowIfDisposed(); ThrowIfNotStarted(); diff --git a/Source/MQTTnet.Server/MqttServerExtensions.cs b/Source/MQTTnet.Server/MqttServerExtensions.cs index 59aecebbf..c25c89453 100644 --- a/Source/MQTTnet.Server/MqttServerExtensions.cs +++ b/Source/MQTTnet.Server/MqttServerExtensions.cs @@ -13,10 +13,7 @@ public static class MqttServerExtensions { public static Task DisconnectClientAsync(this MqttServer server, string id, MqttDisconnectReasonCode reasonCode = MqttDisconnectReasonCode.NormalDisconnection) { - if (server == null) - { - throw new ArgumentNullException(nameof(server)); - } + ArgumentNullException.ThrowIfNull(server); return server.DisconnectClientAsync(id, new MqttServerClientDisconnectOptions { ReasonCode = reasonCode }); } @@ -28,15 +25,8 @@ public static Task InjectApplicationMessage( MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false) { - if (server == null) - { - throw new ArgumentNullException(nameof(server)); - } - - if (topic == null) - { - throw new ArgumentNullException(nameof(topic)); - } + ArgumentNullException.ThrowIfNull(server); + ArgumentNullException.ThrowIfNull(topic); var payloadBuffer = EmptyBuffer.Array; if (payload is string stringPayload) @@ -57,50 +47,25 @@ public static Task InjectApplicationMessage( public static Task StopAsync(this MqttServer server) { - if (server == null) - { - throw new ArgumentNullException(nameof(server)); - } + ArgumentNullException.ThrowIfNull(server); return server.StopAsync(new MqttServerStopOptions()); } public static Task SubscribeAsync(this MqttServer server, string clientId, params MqttTopicFilter[] topicFilters) { - if (server == null) - { - throw new ArgumentNullException(nameof(server)); - } - - if (clientId == null) - { - throw new ArgumentNullException(nameof(clientId)); - } - - if (topicFilters == null) - { - throw new ArgumentNullException(nameof(topicFilters)); - } + ArgumentNullException.ThrowIfNull(server); + ArgumentNullException.ThrowIfNull(clientId); + ArgumentNullException.ThrowIfNull(topicFilters); return server.SubscribeAsync(clientId, topicFilters); } public static Task SubscribeAsync(this MqttServer server, string clientId, string topic) { - if (server == null) - { - throw new ArgumentNullException(nameof(server)); - } - - if (clientId == null) - { - throw new ArgumentNullException(nameof(clientId)); - } - - if (topic == null) - { - throw new ArgumentNullException(nameof(topic)); - } + ArgumentNullException.ThrowIfNull(server); + ArgumentNullException.ThrowIfNull(clientId); + ArgumentNullException.ThrowIfNull(topic); var topicFilters = new MqttTopicFilterBuilder().WithTopic(topic).Build(); return server.SubscribeAsync(clientId, topicFilters); diff --git a/Source/MQTTnet.Server/MqttServerFactory.cs b/Source/MQTTnet.Server/MqttServerFactory.cs index 848130a1c..0bb030f8b 100644 --- a/Source/MQTTnet.Server/MqttServerFactory.cs +++ b/Source/MQTTnet.Server/MqttServerFactory.cs @@ -39,10 +39,7 @@ public MqttServer CreateMqttServer(MqttServerOptions options) public MqttServer CreateMqttServer(MqttServerOptions options, IMqttNetLogger logger) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); var serverAdapters = DefaultServerAdapters.Select(a => a.Invoke(this)); return CreateMqttServer(options, serverAdapters, logger); @@ -50,25 +47,15 @@ public MqttServer CreateMqttServer(MqttServerOptions options, IMqttNetLogger log public MqttServer CreateMqttServer(MqttServerOptions options, IEnumerable serverAdapters, IMqttNetLogger logger) { - if (serverAdapters == null) - { - throw new ArgumentNullException(nameof(serverAdapters)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(serverAdapters); + ArgumentNullException.ThrowIfNull(logger); return new MqttServer(options, serverAdapters, logger); } public MqttServer CreateMqttServer(MqttServerOptions options, IEnumerable serverAdapters) { - if (serverAdapters == null) - { - throw new ArgumentNullException(nameof(serverAdapters)); - } + ArgumentNullException.ThrowIfNull(serverAdapters); return new MqttServer(options, serverAdapters, DefaultLogger); } diff --git a/Source/MQTTnet.Server/Options/MqttServerOptionsBuilder.cs b/Source/MQTTnet.Server/Options/MqttServerOptionsBuilder.cs index 52c3fb117..2e86e21eb 100644 --- a/Source/MQTTnet.Server/Options/MqttServerOptionsBuilder.cs +++ b/Source/MQTTnet.Server/Options/MqttServerOptionsBuilder.cs @@ -180,10 +180,7 @@ public MqttServerOptionsBuilder WithTlsEndpointReuseAddress() public MqttServerOptionsBuilder WithEncryptionCertificate(byte[] value, IMqttServerCertificateCredentials credentials = null) { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullException.ThrowIfNull(value); _options.TlsEndpointOptions.CertificateProvider = new BlobCertificateProvider(value) { @@ -195,10 +192,7 @@ public MqttServerOptionsBuilder WithEncryptionCertificate(byte[] value, IMqttSer public MqttServerOptionsBuilder WithEncryptionCertificate(X509Certificate2 certificate) { - if (certificate == null) - { - throw new ArgumentNullException(nameof(certificate)); - } + ArgumentNullException.ThrowIfNull(certificate); _options.TlsEndpointOptions.CertificateProvider = new X509CertificateProvider(certificate); return this; @@ -206,10 +200,7 @@ public MqttServerOptionsBuilder WithEncryptionCertificate(X509Certificate2 certi public MqttServerOptionsBuilder WithEncryptionCertificate(ICertificateProvider certificateProvider) { - if (certificateProvider == null) - { - throw new ArgumentNullException(nameof(certificateProvider)); - } + ArgumentNullException.ThrowIfNull(certificateProvider); _options.TlsEndpointOptions.CertificateProvider = certificateProvider; diff --git a/Source/MQTTnet.Server/Status/MqttClientStatus.cs b/Source/MQTTnet.Server/Status/MqttClientStatus.cs index 68ba27f57..447dde223 100644 --- a/Source/MQTTnet.Server/Status/MqttClientStatus.cs +++ b/Source/MQTTnet.Server/Status/MqttClientStatus.cs @@ -50,10 +50,7 @@ public MqttClientStatus(MqttConnectedClient client) public Task DisconnectAsync(MqttServerClientDisconnectOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); return _client.StopAsync(options); } diff --git a/Source/MQTTnet.Server/Status/MqttClientStatusExtensions.cs b/Source/MQTTnet.Server/Status/MqttClientStatusExtensions.cs index 81e64122b..ae635ebaf 100644 --- a/Source/MQTTnet.Server/Status/MqttClientStatusExtensions.cs +++ b/Source/MQTTnet.Server/Status/MqttClientStatusExtensions.cs @@ -18,10 +18,7 @@ public static class MqttClientStatusExtensions public static Task DisconnectAsync(this MqttClientStatus clientStatus) { - if (clientStatus == null) - { - throw new ArgumentNullException(nameof(clientStatus)); - } + ArgumentNullException.ThrowIfNull(clientStatus); return clientStatus.DisconnectAsync(DefaultDisconnectOptions); } diff --git a/Source/MQTTnet.Server/Status/MqttSessionStatus.cs b/Source/MQTTnet.Server/Status/MqttSessionStatus.cs index f0ed176d1..ecb8460fb 100644 --- a/Source/MQTTnet.Server/Status/MqttSessionStatus.cs +++ b/Source/MQTTnet.Server/Status/MqttSessionStatus.cs @@ -42,10 +42,7 @@ public Task DeleteAsync() public Task DeliverApplicationMessageAsync(MqttApplicationMessage applicationMessage) { - if (applicationMessage == null) - { - throw new ArgumentNullException(nameof(applicationMessage)); - } + ArgumentNullException.ThrowIfNull(applicationMessage); var packetBusItem = new MqttPacketBusItem(MqttPublishPacketFactory.Create(applicationMessage)); _session.EnqueueDataPacket(packetBusItem); @@ -55,10 +52,7 @@ public Task DeliverApplicationMessageAsync(MqttApplicationMessage applicationMes public Task EnqueueApplicationMessageAsync(MqttApplicationMessage applicationMessage) { - if (applicationMessage == null) - { - throw new ArgumentNullException(nameof(applicationMessage)); - } + ArgumentNullException.ThrowIfNull(applicationMessage); _session.EnqueueDataPacket(new MqttPacketBusItem(MqttPublishPacketFactory.Create(applicationMessage))); diff --git a/Source/MQTTnet.Server/Stopping/MqttServerStopOptionsBuilder.cs b/Source/MQTTnet.Server/Stopping/MqttServerStopOptionsBuilder.cs index 227f0d967..b851f25d7 100644 --- a/Source/MQTTnet.Server/Stopping/MqttServerStopOptionsBuilder.cs +++ b/Source/MQTTnet.Server/Stopping/MqttServerStopOptionsBuilder.cs @@ -15,21 +15,18 @@ public MqttServerStopOptionsBuilder WithDefaultClientDisconnectOptions(MqttServe _options.DefaultClientDisconnectOptions = value; return this; } - + public MqttServerStopOptionsBuilder WithDefaultClientDisconnectOptions(Action builder) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } + ArgumentNullException.ThrowIfNull(builder); var optionsBuilder = new MqttServerClientDisconnectOptionsBuilder(); builder.Invoke(optionsBuilder); - + _options.DefaultClientDisconnectOptions = optionsBuilder.Build(); return this; } - + public MqttServerStopOptions Build() { return _options; diff --git a/Source/MQTTnet.TestApp/MqttNetConsoleLogger.cs b/Source/MQTTnet.TestApp/MqttNetConsoleLogger.cs index f73dc06b9..40ea09b61 100644 --- a/Source/MQTTnet.TestApp/MqttNetConsoleLogger.cs +++ b/Source/MQTTnet.TestApp/MqttNetConsoleLogger.cs @@ -14,7 +14,7 @@ public static class MqttNetConsoleLogger public static void ForwardToConsole(MqttNetEventLogger logger) { - if (logger == null) throw new ArgumentNullException(nameof(logger)); + ArgumentNullException.ThrowIfNull(logger); logger.LogMessagePublished -= PrintToConsole; logger.LogMessagePublished += PrintToConsole; diff --git a/Source/MQTTnet.Tests/Helpers/MqttClientExtensions.cs b/Source/MQTTnet.Tests/Helpers/MqttClientExtensions.cs index 59a092e9c..836507293 100644 --- a/Source/MQTTnet.Tests/Helpers/MqttClientExtensions.cs +++ b/Source/MQTTnet.Tests/Helpers/MqttClientExtensions.cs @@ -11,10 +11,7 @@ public static class MqttClientExtensions { public static TestApplicationMessageReceivedHandler TrackReceivedMessages(this IMqttClient client) { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); return new TestApplicationMessageReceivedHandler(client); } diff --git a/Source/MQTTnet.Tests/Helpers/ReflectionExtensions.cs b/Source/MQTTnet.Tests/Helpers/ReflectionExtensions.cs index 2639153fa..6e857aeb5 100644 --- a/Source/MQTTnet.Tests/Helpers/ReflectionExtensions.cs +++ b/Source/MQTTnet.Tests/Helpers/ReflectionExtensions.cs @@ -11,17 +11,14 @@ public static class ReflectionExtensions { public static object GetFieldValue(this object source, string fieldName) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); var field = source.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic); if (field == null) { throw new ArgumentException($"Field {fieldName} not found."); } - + return field.GetValue(source); } } diff --git a/Source/MQTTnet.Tests/Mockups/TestApplicationMessageReceivedHandler.cs b/Source/MQTTnet.Tests/Mockups/TestApplicationMessageReceivedHandler.cs index a0b3ec316..66b44bd16 100644 --- a/Source/MQTTnet.Tests/Mockups/TestApplicationMessageReceivedHandler.cs +++ b/Source/MQTTnet.Tests/Mockups/TestApplicationMessageReceivedHandler.cs @@ -18,10 +18,7 @@ public sealed class TestApplicationMessageReceivedHandler public TestApplicationMessageReceivedHandler(IMqttClient mqttClient) { - if (mqttClient == null) - { - throw new ArgumentNullException(nameof(mqttClient)); - } + ArgumentNullException.ThrowIfNull(mqttClient); mqttClient.ApplicationMessageReceivedAsync += OnApplicationMessageReceivedAsync; } diff --git a/Source/MQTTnet.Tests/Mockups/TestEnvironment.cs b/Source/MQTTnet.Tests/Mockups/TestEnvironment.cs index 93c346591..4f1391f15 100644 --- a/Source/MQTTnet.Tests/Mockups/TestEnvironment.cs +++ b/Source/MQTTnet.Tests/Mockups/TestEnvironment.cs @@ -102,10 +102,7 @@ public Task ConnectClient() public async Task ConnectClient(Action configureOptions, TimeSpan timeout = default) { - if (configureOptions == null) - { - throw new ArgumentNullException(nameof(configureOptions)); - } + ArgumentNullException.ThrowIfNull(configureOptions); // Start with initial default values. var optionsBuilder = ClientFactory.CreateClientOptionsBuilder().WithProtocolVersion(_protocolVersion).WithTcpServer("127.0.0.1", ServerPort); @@ -134,10 +131,7 @@ public async Task ConnectClient(Action co public async Task ConnectClient(MqttClientOptionsBuilder options, TimeSpan timeout = default) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); options = options.WithTcpServer("127.0.0.1", ServerPort); @@ -160,10 +154,7 @@ public async Task ConnectClient(MqttClientOptionsBuilder options, T public async Task ConnectClient(MqttClientOptions options, TimeSpan timeout = default) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); var client = CreateClient(); diff --git a/Source/MQTTnet/Adapter/MqttChannelAdapter.cs b/Source/MQTTnet/Adapter/MqttChannelAdapter.cs index a071c13d5..390fe9420 100644 --- a/Source/MQTTnet/Adapter/MqttChannelAdapter.cs +++ b/Source/MQTTnet/Adapter/MqttChannelAdapter.cs @@ -38,10 +38,7 @@ public MqttChannelAdapter(IMqttChannel channel, MqttPacketFormatterAdapter packe PacketFormatterAdapter = packetFormatterAdapter ?? throw new ArgumentNullException(nameof(packetFormatterAdapter)); - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); _logger = logger.WithSource(nameof(MqttChannelAdapter)); } diff --git a/Source/MQTTnet/Adapter/MqttPacketInspector.cs b/Source/MQTTnet/Adapter/MqttPacketInspector.cs index b18e6adf5..f4ea7753b 100644 --- a/Source/MQTTnet/Adapter/MqttPacketInspector.cs +++ b/Source/MQTTnet/Adapter/MqttPacketInspector.cs @@ -23,10 +23,7 @@ public MqttPacketInspector(AsyncEvent asyncEvent, IM { _asyncEvent = asyncEvent ?? throw new ArgumentNullException(nameof(asyncEvent)); - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); _logger = logger.WithSource(nameof(MqttPacketInspector)); } diff --git a/Source/MQTTnet/Connecting/MqttClientConnectResultFactory.cs b/Source/MQTTnet/Connecting/MqttClientConnectResultFactory.cs index 42a7ba2d0..b9e442730 100644 --- a/Source/MQTTnet/Connecting/MqttClientConnectResultFactory.cs +++ b/Source/MQTTnet/Connecting/MqttClientConnectResultFactory.cs @@ -14,10 +14,7 @@ public sealed class MqttClientConnectResultFactory { public MqttClientConnectResult Create(MqttConnAckPacket connAckPacket, MqttProtocolVersion protocolVersion) { - if (connAckPacket == null) - { - throw new ArgumentNullException(nameof(connAckPacket)); - } + ArgumentNullException.ThrowIfNull(connAckPacket); if (protocolVersion == MqttProtocolVersion.V500) { @@ -68,10 +65,8 @@ static MqttClientConnectResultCode ConvertReturnCodeToResultCode(MqttConnectRetu static MqttClientConnectResult CreateForMqtt311(MqttConnAckPacket connAckPacket) { - if (connAckPacket == null) - { - throw new ArgumentNullException(nameof(connAckPacket)); - } + ArgumentNullException.ThrowIfNull(connAckPacket); + return new MqttClientConnectResult { @@ -84,10 +79,7 @@ static MqttClientConnectResult CreateForMqtt311(MqttConnAckPacket connAckPacket) static MqttClientConnectResult CreateForMqtt500(MqttConnAckPacket connAckPacket) { - if (connAckPacket == null) - { - throw new ArgumentNullException(nameof(connAckPacket)); - } + ArgumentNullException.ThrowIfNull(connAckPacket); return new MqttClientConnectResult { diff --git a/Source/MQTTnet/Diagnostics/Logger/MqttNetSourceLoggerExtensions.cs b/Source/MQTTnet/Diagnostics/Logger/MqttNetSourceLoggerExtensions.cs index 8fb52beb1..1c3fb1763 100644 --- a/Source/MQTTnet/Diagnostics/Logger/MqttNetSourceLoggerExtensions.cs +++ b/Source/MQTTnet/Diagnostics/Logger/MqttNetSourceLoggerExtensions.cs @@ -9,7 +9,7 @@ namespace MQTTnet.Diagnostics.Logger /* * The logger uses generic parameters in order to avoid boxing of parameter values like integers etc. */ - + public static class MqttNetSourceLoggerExtensions { public static void Error(this MqttNetSourceLogger logger, Exception exception, string message, TParameter1 parameter1) @@ -91,7 +91,7 @@ public static void Publish(this MqttNetSourceLogger logger, MqttNet logger.Publish(logLevel, message, new object[] { parameter1 }, exception); } - + public static void Publish(this MqttNetSourceLogger logger, MqttNetLogLevel logLevel, Exception exception, string message, TParameter1 parameter1, TParameter2 parameter2) { if (!logger.IsEnabled) @@ -209,10 +209,7 @@ public static void Warning(this MqttNetSourceLogger logger, string message) public static MqttNetSourceLogger WithSource(this IMqttNetLogger logger, string source) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); return new MqttNetSourceLogger(logger, source); } diff --git a/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptionsValidator.cs b/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptionsValidator.cs index fdee00689..b8da24ea2 100644 --- a/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptionsValidator.cs +++ b/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptionsValidator.cs @@ -12,10 +12,7 @@ public static class MqttClientDisconnectOptionsValidator { public static void ThrowIfNotSupported(MqttClientDisconnectOptions options, MqttProtocolVersion protocolVersion) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (protocolVersion == MqttProtocolVersion.V500) { diff --git a/Source/MQTTnet/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs b/Source/MQTTnet/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs index 801192f42..1f93a8075 100644 --- a/Source/MQTTnet/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs +++ b/Source/MQTTnet/ExtendedAuthenticationExchange/MqttExtendedAuthenticationExchangeContext.cs @@ -13,10 +13,7 @@ public class MqttExtendedAuthenticationExchangeContext { public MqttExtendedAuthenticationExchangeContext(MqttAuthPacket authPacket, MqttClient client) { - if (authPacket == null) - { - throw new ArgumentNullException(nameof(authPacket)); - } + ArgumentNullException.ThrowIfNull(authPacket); ReasonCode = authPacket.ReasonCode; ReasonString = authPacket.ReasonString; diff --git a/Source/MQTTnet/Formatter/MqttApplicationMessageFactory.cs b/Source/MQTTnet/Formatter/MqttApplicationMessageFactory.cs index 1fd23bf70..60cbcbb12 100644 --- a/Source/MQTTnet/Formatter/MqttApplicationMessageFactory.cs +++ b/Source/MQTTnet/Formatter/MqttApplicationMessageFactory.cs @@ -11,10 +11,7 @@ public static class MqttApplicationMessageFactory { public static MqttApplicationMessage Create(MqttPublishPacket publishPacket) { - if (publishPacket == null) - { - throw new ArgumentNullException(nameof(publishPacket)); - } + ArgumentNullException.ThrowIfNull(publishPacket); return new MqttApplicationMessage { diff --git a/Source/MQTTnet/Formatter/MqttBufferWriter.cs b/Source/MQTTnet/Formatter/MqttBufferWriter.cs index 14ad707b5..c89ccad76 100644 --- a/Source/MQTTnet/Formatter/MqttBufferWriter.cs +++ b/Source/MQTTnet/Formatter/MqttBufferWriter.cs @@ -105,10 +105,7 @@ public void Seek(int position) public void Write(MqttBufferWriter propertyWriter) { - if (propertyWriter == null) - { - throw new ArgumentNullException(nameof(propertyWriter)); - } + ArgumentNullException.ThrowIfNull(propertyWriter); WriteBinary(propertyWriter._buffer, 0, propertyWriter.Length); } @@ -140,10 +137,7 @@ public void WriteBinary(byte[] value) public void WriteBinary(byte[] buffer, int offset, int count) { - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } + ArgumentNullException.ThrowIfNull(buffer); if (count == 0) { @@ -292,7 +286,7 @@ void IncreasePosition(int length) if (_position > Length) { - // Also extend the position because we reached the end of the + // Also extend the position because we reached the end of the // pre allocated buffer. Length = _position; } diff --git a/Source/MQTTnet/Formatter/MqttConnectPacketFactory.cs b/Source/MQTTnet/Formatter/MqttConnectPacketFactory.cs index 605087961..89dda0598 100644 --- a/Source/MQTTnet/Formatter/MqttConnectPacketFactory.cs +++ b/Source/MQTTnet/Formatter/MqttConnectPacketFactory.cs @@ -11,10 +11,7 @@ public static class MqttConnectPacketFactory { public static MqttConnectPacket Create(MqttClientOptions clientOptions) { - if (clientOptions == null) - { - throw new ArgumentNullException(nameof(clientOptions)); - } + ArgumentNullException.ThrowIfNull(clientOptions); var connectPacket = new MqttConnectPacket { diff --git a/Source/MQTTnet/Formatter/MqttPubAckPacketFactory.cs b/Source/MQTTnet/Formatter/MqttPubAckPacketFactory.cs index f4a2d6a1f..b15ca7de6 100644 --- a/Source/MQTTnet/Formatter/MqttPubAckPacketFactory.cs +++ b/Source/MQTTnet/Formatter/MqttPubAckPacketFactory.cs @@ -12,10 +12,7 @@ public static class MqttPubAckPacketFactory { public static MqttPubAckPacket Create(MqttApplicationMessageReceivedEventArgs applicationMessageReceivedEventArgs) { - if (applicationMessageReceivedEventArgs == null) - { - throw new ArgumentNullException(nameof(applicationMessageReceivedEventArgs)); - } + ArgumentNullException.ThrowIfNull(applicationMessageReceivedEventArgs); var pubAckPacket = new MqttPubAckPacket { diff --git a/Source/MQTTnet/Formatter/MqttPubCompPacketFactory.cs b/Source/MQTTnet/Formatter/MqttPubCompPacketFactory.cs index f3e1603f6..ca67f3239 100644 --- a/Source/MQTTnet/Formatter/MqttPubCompPacketFactory.cs +++ b/Source/MQTTnet/Formatter/MqttPubCompPacketFactory.cs @@ -12,10 +12,7 @@ public static class MqttPubCompPacketFactory { public static MqttPubCompPacket Create(MqttPubRelPacket pubRelPacket, MqttApplicationMessageReceivedReasonCode reasonCode) { - if (pubRelPacket == null) - { - throw new ArgumentNullException(nameof(pubRelPacket)); - } + ArgumentNullException.ThrowIfNull(pubRelPacket); return new MqttPubCompPacket { diff --git a/Source/MQTTnet/Formatter/MqttPubRecPacketFactory.cs b/Source/MQTTnet/Formatter/MqttPubRecPacketFactory.cs index dcde9edd1..d6e8b9a2d 100644 --- a/Source/MQTTnet/Formatter/MqttPubRecPacketFactory.cs +++ b/Source/MQTTnet/Formatter/MqttPubRecPacketFactory.cs @@ -12,10 +12,7 @@ public static class MqttPubRecPacketFactory { public static MqttPubRecPacket Create(MqttApplicationMessageReceivedEventArgs applicationMessageReceivedEventArgs) { - if (applicationMessageReceivedEventArgs == null) - { - throw new ArgumentNullException(nameof(applicationMessageReceivedEventArgs)); - } + ArgumentNullException.ThrowIfNull(applicationMessageReceivedEventArgs); var pubRecPacket = Create(applicationMessageReceivedEventArgs.PublishPacket, applicationMessageReceivedEventArgs.ReasonCode); pubRecPacket.UserProperties = applicationMessageReceivedEventArgs.ResponseUserProperties; diff --git a/Source/MQTTnet/Formatter/MqttPubRelPacketFactory.cs b/Source/MQTTnet/Formatter/MqttPubRelPacketFactory.cs index 0e33f0386..cde1ef71b 100644 --- a/Source/MQTTnet/Formatter/MqttPubRelPacketFactory.cs +++ b/Source/MQTTnet/Formatter/MqttPubRelPacketFactory.cs @@ -12,10 +12,7 @@ public static class MqttPubRelPacketFactory { public static MqttPubRelPacket Create(MqttPubRecPacket pubRecPacket, MqttApplicationMessageReceivedReasonCode reasonCode) { - if (pubRecPacket == null) - { - throw new ArgumentNullException(nameof(pubRecPacket)); - } + ArgumentNullException.ThrowIfNull(pubRecPacket); return new MqttPubRelPacket { diff --git a/Source/MQTTnet/Formatter/MqttPublishPacketFactory.cs b/Source/MQTTnet/Formatter/MqttPublishPacketFactory.cs index 761e60a54..daf0237b7 100644 --- a/Source/MQTTnet/Formatter/MqttPublishPacketFactory.cs +++ b/Source/MQTTnet/Formatter/MqttPublishPacketFactory.cs @@ -12,10 +12,7 @@ public static class MqttPublishPacketFactory { public static MqttPublishPacket Create(MqttApplicationMessage applicationMessage) { - if (applicationMessage == null) - { - throw new ArgumentNullException(nameof(applicationMessage)); - } + ArgumentNullException.ThrowIfNull(applicationMessage); // Copy all values to their matching counterparts. // The not supported values in MQTT 3.1.1 are not serialized (excluded) later. diff --git a/Source/MQTTnet/Formatter/MqttSubscribePacketFactory.cs b/Source/MQTTnet/Formatter/MqttSubscribePacketFactory.cs index 3ac7ad917..a58a26eb2 100644 --- a/Source/MQTTnet/Formatter/MqttSubscribePacketFactory.cs +++ b/Source/MQTTnet/Formatter/MqttSubscribePacketFactory.cs @@ -11,10 +11,7 @@ public static class MqttSubscribePacketFactory { public static MqttSubscribePacket Create(MqttClientSubscribeOptions clientSubscribeOptions) { - if (clientSubscribeOptions == null) - { - throw new ArgumentNullException(nameof(clientSubscribeOptions)); - } + ArgumentNullException.ThrowIfNull(clientSubscribeOptions); var packet = new MqttSubscribePacket { diff --git a/Source/MQTTnet/Formatter/MqttUnsubscribePacketFactory.cs b/Source/MQTTnet/Formatter/MqttUnsubscribePacketFactory.cs index 4cc6d2631..573db1bc0 100644 --- a/Source/MQTTnet/Formatter/MqttUnsubscribePacketFactory.cs +++ b/Source/MQTTnet/Formatter/MqttUnsubscribePacketFactory.cs @@ -11,10 +11,7 @@ public static class MqttUnsubscribePacketFactory { public static MqttUnsubscribePacket Create(MqttClientUnsubscribeOptions clientUnsubscribeOptions) { - if (clientUnsubscribeOptions == null) - { - throw new ArgumentNullException(nameof(clientUnsubscribeOptions)); - } + ArgumentNullException.ThrowIfNull(clientUnsubscribeOptions); var packet = new MqttUnsubscribePacket { diff --git a/Source/MQTTnet/Formatter/V3/MqttV3PacketFormatter.cs b/Source/MQTTnet/Formatter/V3/MqttV3PacketFormatter.cs index 5a072f92d..5e5a2f150 100644 --- a/Source/MQTTnet/Formatter/V3/MqttV3PacketFormatter.cs +++ b/Source/MQTTnet/Formatter/V3/MqttV3PacketFormatter.cs @@ -91,10 +91,7 @@ public MqttPacket Decode(ReceivedMqttPacket receivedMqttPacket) public MqttPacketBuffer Encode(MqttPacket packet) { - if (packet == null) - { - throw new ArgumentNullException(nameof(packet)); - } + ArgumentNullException.ThrowIfNull(packet); // Leave enough head space for max header size (fixed + 4 variable remaining length = 5 bytes) _bufferWriter.Reset(5); @@ -797,10 +794,7 @@ static void ThrowIfBodyIsEmpty(ArraySegment body) void ValidateConnectPacket(MqttConnectPacket packet) { - if (packet == null) - { - throw new ArgumentNullException(nameof(packet)); - } + ArgumentNullException.ThrowIfNull(packet); if (string.IsNullOrEmpty(packet.ClientId) && !packet.CleanSession) { diff --git a/Source/MQTTnet/Formatter/V5/MqttV5PacketEncoder.cs b/Source/MQTTnet/Formatter/V5/MqttV5PacketEncoder.cs index 95699925e..9d5a6d09b 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV5PacketEncoder.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV5PacketEncoder.cs @@ -25,10 +25,7 @@ public MqttV5PacketEncoder(MqttBufferWriter bufferWriter) public MqttPacketBuffer Encode(MqttPacket packet) { - if (packet == null) - { - throw new ArgumentNullException(nameof(packet)); - } + ArgumentNullException.ThrowIfNull(packet); // Leave enough head space for max header size (fixed + 4 variable remaining length = 5 bytes) const int ReservedHeaderSize = 5; diff --git a/Source/MQTTnet/Formatter/V5/MqttV5PropertiesWriter.cs b/Source/MQTTnet/Formatter/V5/MqttV5PropertiesWriter.cs index 29c065667..25546d332 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV5PropertiesWriter.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV5PropertiesWriter.cs @@ -221,7 +221,7 @@ public void WriteSubscriptionIdentifiersAvailable(bool value) { if (value) { - // Absence of the flag means it is supported! + // Absence of the flag means it is supported! return; } @@ -230,10 +230,7 @@ public void WriteSubscriptionIdentifiersAvailable(bool value) public void WriteTo(MqttBufferWriter target) { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } + ArgumentNullException.ThrowIfNull(target); target.WriteVariableByteInteger((uint)_bufferWriter.Length); target.Write(_bufferWriter); diff --git a/Source/MQTTnet/Implementations/CrossPlatformSocket.cs b/Source/MQTTnet/Implementations/CrossPlatformSocket.cs index f1caab8f7..dd923eb5b 100644 --- a/Source/MQTTnet/Implementations/CrossPlatformSocket.cs +++ b/Source/MQTTnet/Implementations/CrossPlatformSocket.cs @@ -124,20 +124,14 @@ public async Task AcceptAsync(CancellationToken cancellatio public void Bind(EndPoint localEndPoint) { - if (localEndPoint is null) - { - throw new ArgumentNullException(nameof(localEndPoint)); - } + ArgumentNullException.ThrowIfNull(localEndPoint); _socket.Bind(localEndPoint); } public async Task ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken) { - if (endPoint is null) - { - throw new ArgumentNullException(nameof(endPoint)); - } + ArgumentNullException.ThrowIfNull(endPoint); cancellationToken.ThrowIfCancellationRequested(); diff --git a/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs b/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs index 1c9cfe285..0a4031f31 100644 --- a/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs +++ b/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs @@ -14,7 +14,7 @@ public sealed class MqttClientAdapterFactory : IMqttClientAdapterFactory { public IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector packetInspector, IMqttNetLogger logger) { - if (options == null) throw new ArgumentNullException(nameof(options)); + ArgumentNullException.ThrowIfNull(options); IMqttChannel channel; switch (options.ChannelOptions) diff --git a/Source/MQTTnet/Internal/AsyncEvent.cs b/Source/MQTTnet/Internal/AsyncEvent.cs index b2059c546..cd38105b3 100644 --- a/Source/MQTTnet/Internal/AsyncEvent.cs +++ b/Source/MQTTnet/Internal/AsyncEvent.cs @@ -26,10 +26,7 @@ public AsyncEvent() public void AddHandler(Func handler) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullException.ThrowIfNull(handler); lock (_handlers) { @@ -42,10 +39,7 @@ public void AddHandler(Func handler) public void AddHandler(Action handler) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullException.ThrowIfNull(handler); lock (_handlers) { @@ -75,10 +69,7 @@ public async Task InvokeAsync(TEventArgs eventArgs) public void RemoveHandler(Func handler) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullException.ThrowIfNull(handler); lock (_handlers) { @@ -91,10 +82,7 @@ public void RemoveHandler(Func handler) public void RemoveHandler(Action handler) { - if (handler == null) - { - throw new ArgumentNullException(nameof(handler)); - } + ArgumentNullException.ThrowIfNull(handler); lock (_handlers) { @@ -107,15 +95,8 @@ public void RemoveHandler(Action handler) public async Task TryInvokeAsync(TEventArgs eventArgs, MqttNetSourceLogger logger) { - if (eventArgs == null) - { - throw new ArgumentNullException(nameof(eventArgs)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(eventArgs); + ArgumentNullException.ThrowIfNull(logger); try { diff --git a/Source/MQTTnet/Internal/AsyncLock.cs b/Source/MQTTnet/Internal/AsyncLock.cs index 580d570d6..0d129b102 100644 --- a/Source/MQTTnet/Internal/AsyncLock.cs +++ b/Source/MQTTnet/Internal/AsyncLock.cs @@ -116,10 +116,7 @@ public AsyncLockWaiter(CancellationToken cancellationToken) public bool Approve(IDisposable scope) { - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } + ArgumentNullException.ThrowIfNull(scope); if (_promise.Task.IsCompleted) { diff --git a/Source/MQTTnet/Internal/BlockingQueue.cs b/Source/MQTTnet/Internal/BlockingQueue.cs index b31ed09e2..e4122dfec 100644 --- a/Source/MQTTnet/Internal/BlockingQueue.cs +++ b/Source/MQTTnet/Internal/BlockingQueue.cs @@ -28,7 +28,7 @@ public int Count public void Enqueue(TItem item) { - if (item == null) throw new ArgumentNullException(nameof(item)); + ArgumentNullException.ThrowIfNull(item); lock (_syncRoot) { @@ -88,7 +88,7 @@ public TItem PeekAndWait(CancellationToken cancellationToken = default) public void RemoveFirst(Predicate match) { - if (match == null) throw new ArgumentNullException(nameof(match)); + ArgumentNullException.ThrowIfNull(match); lock (_syncRoot) { diff --git a/Source/MQTTnet/Internal/MqttPacketBus.cs b/Source/MQTTnet/Internal/MqttPacketBus.cs index b8c5b363c..8aec37565 100644 --- a/Source/MQTTnet/Internal/MqttPacketBus.cs +++ b/Source/MQTTnet/Internal/MqttPacketBus.cs @@ -124,10 +124,7 @@ public MqttPacketBusItem DropFirstItem(MqttPacketBusPartition partition) public void EnqueueItem(MqttPacketBusItem item, MqttPacketBusPartition partition) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); lock (_syncRoot) { diff --git a/Source/MQTTnet/Internal/TaskExtensions.cs b/Source/MQTTnet/Internal/TaskExtensions.cs index 58de525f7..5ab14f75e 100644 --- a/Source/MQTTnet/Internal/TaskExtensions.cs +++ b/Source/MQTTnet/Internal/TaskExtensions.cs @@ -24,10 +24,7 @@ public static void RunInBackground(this Task task, MqttNetSourceLogger logger = public static async Task WaitAsync(this Task task, Task sender, MqttNetSourceLogger logger) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); if (task == null) { diff --git a/Source/MQTTnet/LowLevelClient/LowLevelMqttClient.cs b/Source/MQTTnet/LowLevelClient/LowLevelMqttClient.cs index 6777eb2fc..186e8bfd1 100644 --- a/Source/MQTTnet/LowLevelClient/LowLevelMqttClient.cs +++ b/Source/MQTTnet/LowLevelClient/LowLevelMqttClient.cs @@ -41,10 +41,7 @@ public event Func InspectPacketAsync public async Task ConnectAsync(MqttClientOptions options, CancellationToken cancellationToken) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (_adapter != null) { @@ -127,10 +124,7 @@ public async Task ReceiveAsync(CancellationToken cancellationToken) public async Task SendAsync(MqttPacket packet, CancellationToken cancellationToken) { - if (packet is null) - { - throw new ArgumentNullException(nameof(packet)); - } + ArgumentNullException.ThrowIfNull(packet); var adapter = _adapter; if (adapter == null) diff --git a/Source/MQTTnet/MqttApplicationMessageExtensions.cs b/Source/MQTTnet/MqttApplicationMessageExtensions.cs index f111611e0..eef59cb54 100644 --- a/Source/MQTTnet/MqttApplicationMessageExtensions.cs +++ b/Source/MQTTnet/MqttApplicationMessageExtensions.cs @@ -11,10 +11,7 @@ public static class MqttApplicationMessageExtensions { public static string ConvertPayloadToString(this MqttApplicationMessage applicationMessage) { - if (applicationMessage == null) - { - throw new ArgumentNullException(nameof(applicationMessage)); - } + ArgumentNullException.ThrowIfNull(applicationMessage); if (applicationMessage.Payload.Length == 0) { diff --git a/Source/MQTTnet/MqttApplicationMessageValidator.cs b/Source/MQTTnet/MqttApplicationMessageValidator.cs index 17edbeaf1..d7eb3b611 100644 --- a/Source/MQTTnet/MqttApplicationMessageValidator.cs +++ b/Source/MQTTnet/MqttApplicationMessageValidator.cs @@ -13,10 +13,7 @@ public static class MqttApplicationMessageValidator { public static void ThrowIfNotSupported(MqttApplicationMessage applicationMessage, MqttProtocolVersion protocolVersion) { - if (applicationMessage == null) - { - throw new ArgumentNullException(nameof(applicationMessage)); - } + ArgumentNullException.ThrowIfNull(applicationMessage); if (protocolVersion == MqttProtocolVersion.V500) { @@ -28,38 +25,38 @@ public static void ThrowIfNotSupported(MqttApplicationMessage applicationMessage { Throw(nameof(applicationMessage.ContentType)); } - + if (applicationMessage.UserProperties?.Any() == true) { Throw(nameof(applicationMessage.UserProperties)); } - + if (applicationMessage.CorrelationData?.Any() == true) { Throw(nameof(applicationMessage.CorrelationData)); } - + if (applicationMessage.ResponseTopic?.Any() == true) { Throw(nameof(applicationMessage.ResponseTopic)); } - + if (applicationMessage.SubscriptionIdentifiers?.Any() == true) { Throw(nameof(applicationMessage.SubscriptionIdentifiers)); } - + if (applicationMessage.TopicAlias > 0) { Throw(nameof(applicationMessage.TopicAlias)); } - + if (applicationMessage.PayloadFormatIndicator != MqttPayloadFormatIndicator.Unspecified) { Throw(nameof(applicationMessage.PayloadFormatIndicator)); } } - + static void Throw(string featureName) { throw new NotSupportedException($"Feature {featureName} requires MQTT version 5.0.0."); diff --git a/Source/MQTTnet/MqttClient.cs b/Source/MQTTnet/MqttClient.cs index b010a5861..9d19ce574 100644 --- a/Source/MQTTnet/MqttClient.cs +++ b/Source/MQTTnet/MqttClient.cs @@ -183,10 +183,7 @@ public async Task ConnectAsync(MqttClientOptions option public async Task DisconnectAsync(MqttClientDisconnectOptions options, CancellationToken cancellationToken = default) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); ThrowIfDisposed(); @@ -293,10 +290,7 @@ public Task PublishAsync(MqttApplicationMessage applica public Task SendExtendedAuthenticationExchangeDataAsync(MqttExtendedAuthenticationExchangeData data, CancellationToken cancellationToken = default) { - if (data == null) - { - throw new ArgumentNullException(nameof(data)); - } + ArgumentNullException.ThrowIfNull(data); ThrowIfDisposed(); ThrowIfNotConnected(); @@ -316,10 +310,7 @@ public Task SendExtendedAuthenticationExchangeDataAsync(MqttExtendedAuthenticati public async Task SubscribeAsync(MqttClientSubscribeOptions options, CancellationToken cancellationToken = default) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); foreach (var topicFilter in options.TopicFilters) { @@ -355,10 +346,7 @@ public async Task SubscribeAsync(MqttClientSubscribeO public async Task UnsubscribeAsync(MqttClientUnsubscribeOptions options, CancellationToken cancellationToken = default) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); foreach (var topicFilter in options.TopicFilters) { @@ -919,10 +907,7 @@ void ThrowIfNotConnected() static void ThrowIfOptionsInvalid(MqttClientOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.ChannelOptions == null) { diff --git a/Source/MQTTnet/MqttClientExtensions.cs b/Source/MQTTnet/MqttClientExtensions.cs index ddb39a3e4..f6d09dd08 100644 --- a/Source/MQTTnet/MqttClientExtensions.cs +++ b/Source/MQTTnet/MqttClientExtensions.cs @@ -23,10 +23,7 @@ public static Task DisconnectAsync( List userProperties = null, CancellationToken cancellationToken = default) { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); var disconnectOptions = new MqttClientDisconnectOptions { @@ -47,15 +44,8 @@ public static Task PublishBinaryAsync( bool retain = false, CancellationToken cancellationToken = default) { - if (mqttClient == null) - { - throw new ArgumentNullException(nameof(mqttClient)); - } - - if (topic == null) - { - throw new ArgumentNullException(nameof(topic)); - } + ArgumentNullException.ThrowIfNull(mqttClient); + ArgumentNullException.ThrowIfNull(topic); var applicationMessage = new MqttApplicationMessageBuilder().WithTopic(topic) .WithPayload(payload) @@ -74,15 +64,8 @@ public static Task PublishSequenceAsync( bool retain = false, CancellationToken cancellationToken = default) { - if (mqttClient == null) - { - throw new ArgumentNullException(nameof(mqttClient)); - } - - if (topic == null) - { - throw new ArgumentNullException(nameof(topic)); - } + ArgumentNullException.ThrowIfNull(mqttClient); + ArgumentNullException.ThrowIfNull(topic); var applicationMessage = new MqttApplicationMessageBuilder().WithTopic(topic) .WithPayload(payload) @@ -118,25 +101,15 @@ public static Task ReconnectAsync(this IMqttClient client, CancellationToken can public static Task SendExtendedAuthenticationExchangeDataAsync(this IMqttClient client, MqttExtendedAuthenticationExchangeData data) { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); return client.SendExtendedAuthenticationExchangeDataAsync(data, CancellationToken.None); } public static Task SubscribeAsync(this IMqttClient mqttClient, MqttTopicFilter topicFilter, CancellationToken cancellationToken = default) { - if (mqttClient == null) - { - throw new ArgumentNullException(nameof(mqttClient)); - } - - if (topicFilter == null) - { - throw new ArgumentNullException(nameof(topicFilter)); - } + ArgumentNullException.ThrowIfNull(mqttClient); + ArgumentNullException.ThrowIfNull(topicFilter); var subscribeOptions = new MqttClientSubscribeOptionsBuilder().WithTopicFilter(topicFilter).Build(); @@ -149,15 +122,8 @@ public static Task SubscribeAsync( MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, CancellationToken cancellationToken = default) { - if (mqttClient == null) - { - throw new ArgumentNullException(nameof(mqttClient)); - } - - if (topic == null) - { - throw new ArgumentNullException(nameof(topic)); - } + ArgumentNullException.ThrowIfNull(mqttClient); + ArgumentNullException.ThrowIfNull(topic); var subscribeOptions = new MqttClientSubscribeOptionsBuilder().WithTopicFilter(topic, qualityOfServiceLevel).Build(); @@ -169,10 +135,7 @@ public static async Task TryDisconnectAsync( MqttClientDisconnectOptionsReason reason = MqttClientDisconnectOptionsReason.NormalDisconnection, string reasonString = null) { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); try { @@ -189,10 +152,7 @@ public static async Task TryDisconnectAsync( public static async Task TryPingAsync(this IMqttClient client, CancellationToken cancellationToken = default) { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } + ArgumentNullException.ThrowIfNull(client); try { @@ -209,15 +169,8 @@ public static async Task TryPingAsync(this IMqttClient client, Cancellatio public static Task UnsubscribeAsync(this IMqttClient mqttClient, string topic, CancellationToken cancellationToken = default) { - if (mqttClient == null) - { - throw new ArgumentNullException(nameof(mqttClient)); - } - - if (topic == null) - { - throw new ArgumentNullException(nameof(topic)); - } + ArgumentNullException.ThrowIfNull(mqttClient); + ArgumentNullException.ThrowIfNull(topic); var unsubscribeOptions = new MqttClientUnsubscribeOptionsBuilder().WithTopicFilter(topic).Build(); diff --git a/Source/MQTTnet/MqttClientFactory.cs b/Source/MQTTnet/MqttClientFactory.cs index c7d1566e2..2e5504df0 100644 --- a/Source/MQTTnet/MqttClientFactory.cs +++ b/Source/MQTTnet/MqttClientFactory.cs @@ -52,35 +52,22 @@ public ILowLevelMqttClient CreateLowLevelMqttClient() public ILowLevelMqttClient CreateLowLevelMqttClient(IMqttNetLogger logger) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); return new LowLevelMqttClient(_clientAdapterFactory, logger); } public ILowLevelMqttClient CreateLowLevelMqttClient(IMqttClientAdapterFactory clientAdapterFactory) { - if (clientAdapterFactory == null) - { - throw new ArgumentNullException(nameof(clientAdapterFactory)); - } + ArgumentNullException.ThrowIfNull(clientAdapterFactory); return new LowLevelMqttClient(_clientAdapterFactory, DefaultLogger); } public ILowLevelMqttClient CreateLowLevelMqttClient(IMqttNetLogger logger, IMqttClientAdapterFactory clientAdapterFactory) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (clientAdapterFactory == null) - { - throw new ArgumentNullException(nameof(clientAdapterFactory)); - } + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(clientAdapterFactory); return new LowLevelMqttClient(_clientAdapterFactory, logger); } @@ -92,35 +79,22 @@ public IMqttClient CreateMqttClient() public IMqttClient CreateMqttClient(IMqttNetLogger logger) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullException.ThrowIfNull(logger); return new MqttClient(_clientAdapterFactory, logger); } public IMqttClient CreateMqttClient(IMqttClientAdapterFactory clientAdapterFactory) { - if (clientAdapterFactory == null) - { - throw new ArgumentNullException(nameof(clientAdapterFactory)); - } + ArgumentNullException.ThrowIfNull(clientAdapterFactory); return new MqttClient(clientAdapterFactory, DefaultLogger); } public IMqttClient CreateMqttClient(IMqttNetLogger logger, IMqttClientAdapterFactory clientAdapterFactory) { - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (clientAdapterFactory == null) - { - throw new ArgumentNullException(nameof(clientAdapterFactory)); - } + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(clientAdapterFactory); return new MqttClient(clientAdapterFactory, logger); } diff --git a/Source/MQTTnet/Options/MqttClientOptionsBuilder.cs b/Source/MQTTnet/Options/MqttClientOptionsBuilder.cs index 9252bac2e..0afb64de0 100644 --- a/Source/MQTTnet/Options/MqttClientOptionsBuilder.cs +++ b/Source/MQTTnet/Options/MqttClientOptionsBuilder.cs @@ -131,10 +131,7 @@ public MqttClientOptionsBuilder WithClientId(string value) public MqttClientOptionsBuilder WithConnectionUri(Uri uri) { - if (uri == null) - { - throw new ArgumentNullException(nameof(uri)); - } + ArgumentNullException.ThrowIfNull(uri); var port = uri.IsDefaultPort ? null : (int?)uri.Port; switch (uri.Scheme.ToLower()) @@ -286,10 +283,7 @@ public MqttClientOptionsBuilder WithSessionExpiryInterval(uint sessionExpiryInte public MqttClientOptionsBuilder WithTcpServer(string host, int? port = null, AddressFamily addressFamily = AddressFamily.Unspecified) { - if (host == null) - { - throw new ArgumentNullException(nameof(host)); - } + ArgumentNullException.ThrowIfNull(host); _tcpOptions = new MqttClientTcpOptions(); @@ -303,10 +297,7 @@ public MqttClientOptionsBuilder WithTcpServer(string host, int? port = null, Add public MqttClientOptionsBuilder WithTcpServer(Action optionsBuilder) { - if (optionsBuilder == null) - { - throw new ArgumentNullException(nameof(optionsBuilder)); - } + ArgumentNullException.ThrowIfNull(optionsBuilder); _tcpOptions = new MqttClientTcpOptions(); optionsBuilder.Invoke(_tcpOptions); @@ -332,10 +323,7 @@ public MqttClientOptionsBuilder WithTlsOptions(MqttClientTlsOptions tlsOptions) public MqttClientOptionsBuilder WithTlsOptions(Action configure) { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(configure); var builder = new MqttClientTlsOptionsBuilder(); configure.Invoke(builder); @@ -377,10 +365,7 @@ public MqttClientOptionsBuilder WithUserProperty(string name, string value) public MqttClientOptionsBuilder WithWebSocketServer(Action configure) { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(configure); var webSocketOptionsBuilder = new MqttClientWebSocketOptionsBuilder(); configure.Invoke(webSocketOptionsBuilder); diff --git a/Source/MQTTnet/Options/MqttClientOptionsValidator.cs b/Source/MQTTnet/Options/MqttClientOptionsValidator.cs index f91f2263b..6e9c09f9b 100644 --- a/Source/MQTTnet/Options/MqttClientOptionsValidator.cs +++ b/Source/MQTTnet/Options/MqttClientOptionsValidator.cs @@ -13,10 +13,7 @@ public static class MqttClientOptionsValidator { public static void ThrowIfNotSupported(MqttClientOptions options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.ProtocolVersion == MqttProtocolVersion.V500) { diff --git a/Source/MQTTnet/Options/MqttClientTlsOptionsBuilder.cs b/Source/MQTTnet/Options/MqttClientTlsOptionsBuilder.cs index 7ad45c9e7..6a097afe1 100644 --- a/Source/MQTTnet/Options/MqttClientTlsOptionsBuilder.cs +++ b/Source/MQTTnet/Options/MqttClientTlsOptionsBuilder.cs @@ -38,10 +38,7 @@ public MqttClientTlsOptionsBuilder WithAllowUntrustedCertificates(bool allowUntr public MqttClientTlsOptionsBuilder WithCertificateValidationHandler(Func certificateValidationHandler) { - if (certificateValidationHandler == null) - { - throw new ArgumentNullException(nameof(certificateValidationHandler)); - } + ArgumentNullException.ThrowIfNull(certificateValidationHandler); _tlsOptions.CertificateValidationHandler = certificateValidationHandler; return this; @@ -49,10 +46,7 @@ public MqttClientTlsOptionsBuilder WithCertificateValidationHandler(Func certificateSelectionHandler) { - if (certificateSelectionHandler == null) - { - throw new ArgumentNullException(nameof(certificateSelectionHandler)); - } + ArgumentNullException.ThrowIfNull(certificateSelectionHandler); _tlsOptions.CertificateSelectionHandler = certificateSelectionHandler; return this; @@ -60,10 +54,7 @@ public MqttClientTlsOptionsBuilder WithCertificateSelectionHandler(Func certificates) { - if (certificates == null) - { - throw new ArgumentNullException(nameof(certificates)); - } + ArgumentNullException.ThrowIfNull(certificates); _tlsOptions.ClientCertificatesProvider = new DefaultMqttCertificatesProvider(certificates); return this; @@ -71,10 +62,7 @@ public MqttClientTlsOptionsBuilder WithClientCertificates(IEnumerable configure) { - if (configure == null) - { - throw new ArgumentNullException(nameof(configure)); - } + ArgumentNullException.ThrowIfNull(configure); var proxyOptionsBuilder = new MqttClientWebSocketProxyOptionsBuilder(); configure.Invoke(proxyOptionsBuilder); diff --git a/Source/MQTTnet/PacketDispatcher/MqttPacketDispatcher.cs b/Source/MQTTnet/PacketDispatcher/MqttPacketDispatcher.cs index 85413a2c0..fd71406de 100644 --- a/Source/MQTTnet/PacketDispatcher/MqttPacketDispatcher.cs +++ b/Source/MQTTnet/PacketDispatcher/MqttPacketDispatcher.cs @@ -46,15 +46,12 @@ public void Dispose() public void Dispose(Exception exception) { - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); lock (_waiters) { FailAll(exception); - + // Make sure that no task can start waiting after this instance is already disposed. // This will prevent unexpected freezes. _isDisposed = true; @@ -63,10 +60,7 @@ public void Dispose(Exception exception) public void FailAll(Exception exception) { - if (exception == null) - { - throw new ArgumentNullException(nameof(exception)); - } + ArgumentNullException.ThrowIfNull(exception); lock (_waiters) { @@ -81,10 +75,7 @@ public void FailAll(Exception exception) public void RemoveAwaitable(IMqttPacketAwaitable awaitable) { - if (awaitable == null) - { - throw new ArgumentNullException(nameof(awaitable)); - } + ArgumentNullException.ThrowIfNull(awaitable); lock (_waiters) { @@ -94,10 +85,7 @@ public void RemoveAwaitable(IMqttPacketAwaitable awaitable) public bool TryDispatch(MqttPacket packet) { - if (packet == null) - { - throw new ArgumentNullException(nameof(packet)); - } + ArgumentNullException.ThrowIfNull(packet); ushort identifier = 0; if (packet is MqttPacketWithIdentifier packetWithIdentifier) @@ -111,7 +99,7 @@ public bool TryDispatch(MqttPacket packet) lock (_waiters) { ThrowIfDisposed(); - + for (var i = _waiters.Count - 1; i >= 0; i--) { var entry = _waiters[i]; diff --git a/Source/MQTTnet/Packets/MqttPacketExtensions.cs b/Source/MQTTnet/Packets/MqttPacketExtensions.cs index a85b441f8..90be0ef7d 100644 --- a/Source/MQTTnet/Packets/MqttPacketExtensions.cs +++ b/Source/MQTTnet/Packets/MqttPacketExtensions.cs @@ -10,10 +10,7 @@ public static class MqttPacketExtensions { public static string GetRfcName(this MqttPacket packet) { - if (packet == null) - { - throw new ArgumentNullException(nameof(packet)); - } + ArgumentNullException.ThrowIfNull(packet); switch (packet) { diff --git a/Source/MQTTnet/Protocol/MqttTopicValidator.cs b/Source/MQTTnet/Protocol/MqttTopicValidator.cs index b373397c7..efdeeafaf 100644 --- a/Source/MQTTnet/Protocol/MqttTopicValidator.cs +++ b/Source/MQTTnet/Protocol/MqttTopicValidator.cs @@ -11,10 +11,7 @@ public static class MqttTopicValidator { public static void ThrowIfInvalid(MqttApplicationMessage applicationMessage) { - if (applicationMessage == null) - { - throw new ArgumentNullException(nameof(applicationMessage)); - } + ArgumentNullException.ThrowIfNull(applicationMessage); if (applicationMessage.TopicAlias == 0) { diff --git a/Source/MQTTnet/Subscribing/MqttClientSubscribeOptionsBuilder.cs b/Source/MQTTnet/Subscribing/MqttClientSubscribeOptionsBuilder.cs index 431d64abd..486b86cc8 100644 --- a/Source/MQTTnet/Subscribing/MqttClientSubscribeOptionsBuilder.cs +++ b/Source/MQTTnet/Subscribing/MqttClientSubscribeOptionsBuilder.cs @@ -50,10 +50,7 @@ public MqttClientSubscribeOptionsBuilder WithTopicFilter( public MqttClientSubscribeOptionsBuilder WithTopicFilter(Action topicFilterBuilder) { - if (topicFilterBuilder == null) - { - throw new ArgumentNullException(nameof(topicFilterBuilder)); - } + ArgumentNullException.ThrowIfNull(topicFilterBuilder); var internalTopicFilterBuilder = new MqttTopicFilterBuilder(); topicFilterBuilder(internalTopicFilterBuilder); @@ -63,20 +60,14 @@ public MqttClientSubscribeOptionsBuilder WithTopicFilter(Action public MqttClientUnsubscribeOptionsBuilder WithUserProperty(MqttUserProperty userProperty) { - if (userProperty is null) - { - throw new ArgumentNullException(nameof(userProperty)); - } + ArgumentNullException.ThrowIfNull(userProperty); if (_unsubscribeOptions.UserProperties is null) { diff --git a/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeOptionsValidator.cs b/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeOptionsValidator.cs index ad8f75221..78fbb8eda 100644 --- a/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeOptionsValidator.cs +++ b/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeOptionsValidator.cs @@ -12,10 +12,7 @@ public static class MqttClientUnsubscribeOptionsValidator { public static void ThrowIfNotSupported(MqttClientUnsubscribeOptions options, MqttProtocolVersion protocolVersion) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (protocolVersion == MqttProtocolVersion.V500) { diff --git a/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResultFactory.cs b/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResultFactory.cs index a3ddedb6f..202460e3e 100644 --- a/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResultFactory.cs +++ b/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResultFactory.cs @@ -15,15 +15,8 @@ public sealed class MqttClientUnsubscribeResultFactory public MqttClientUnsubscribeResult Create(MqttUnsubscribePacket unsubscribePacket, MqttUnsubAckPacket unsubAckPacket) { - if (unsubscribePacket == null) - { - throw new ArgumentNullException(nameof(unsubscribePacket)); - } - - if (unsubAckPacket == null) - { - throw new ArgumentNullException(nameof(unsubAckPacket)); - } + ArgumentNullException.ThrowIfNull(unsubscribePacket); + ArgumentNullException.ThrowIfNull(unsubAckPacket); // MQTTv3.1.1 has no reason code at all! if (unsubAckPacket.ReasonCodes != null && unsubAckPacket.ReasonCodes.Count != unsubscribePacket.TopicFilters.Count)