diff --git a/Samples/MQTTnet.Samples.csproj b/Samples/MQTTnet.Samples.csproj index 5fe84d38..223adae1 100644 --- a/Samples/MQTTnet.Samples.csproj +++ b/Samples/MQTTnet.Samples.csproj @@ -15,6 +15,7 @@ true low latest-Recommended + default diff --git a/Source/MQTTnet.AspnetCore/MQTTnet.AspNetCore.csproj b/Source/MQTTnet.AspnetCore/MQTTnet.AspNetCore.csproj index ae4708a2..41302e91 100644 --- a/Source/MQTTnet.AspnetCore/MQTTnet.AspNetCore.csproj +++ b/Source/MQTTnet.AspnetCore/MQTTnet.AspNetCore.csproj @@ -39,6 +39,8 @@ low latest-Recommended true + default + enable diff --git a/Source/MQTTnet.Extensions.Rpc/IMqttRpcClient.cs b/Source/MQTTnet.Extensions.Rpc/IMqttRpcClient.cs index 84846071..123dad38 100644 --- a/Source/MQTTnet.Extensions.Rpc/IMqttRpcClient.cs +++ b/Source/MQTTnet.Extensions.Rpc/IMqttRpcClient.cs @@ -12,7 +12,12 @@ namespace MQTTnet.Extensions.Rpc; public interface IMqttRpcClient : IDisposable { - Task ExecuteAsync(TimeSpan timeout, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary parameters = null); + Task ExecuteAsync(TimeSpan timeout, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary? parameters = null); - Task ExecuteAsync(string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary parameters = null, CancellationToken cancellationToken = default); + Task ExecuteAsync( + string methodName, + byte[] payload, + MqttQualityOfServiceLevel qualityOfServiceLevel, + IDictionary? parameters = null, + CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/Source/MQTTnet.Extensions.Rpc/MQTTnet.Extensions.Rpc.csproj b/Source/MQTTnet.Extensions.Rpc/MQTTnet.Extensions.Rpc.csproj index 41a84f4e..213af24e 100644 --- a/Source/MQTTnet.Extensions.Rpc/MQTTnet.Extensions.Rpc.csproj +++ b/Source/MQTTnet.Extensions.Rpc/MQTTnet.Extensions.Rpc.csproj @@ -37,6 +37,8 @@ low latest-Recommended true + default + enable diff --git a/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs b/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs index fc83bff1..4690e4ff 100644 --- a/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs +++ b/Source/MQTTnet.Extensions.Rpc/MqttRpcClient.cs @@ -20,7 +20,7 @@ public sealed class MqttRpcClient : IMqttRpcClient readonly IMqttClient _mqttClient; readonly MqttRpcClientOptions _options; - readonly ConcurrentDictionary> _waitingCalls = new ConcurrentDictionary>(); + readonly ConcurrentDictionary> _waitingCalls = new(); public MqttRpcClient(IMqttClient mqttClient, MqttRpcClientOptions options) { @@ -42,7 +42,12 @@ public sealed class MqttRpcClient : IMqttRpcClient _waitingCalls.Clear(); } - public async Task ExecuteAsync(TimeSpan timeout, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary parameters = null) + public async Task ExecuteAsync( + TimeSpan timeout, + string methodName, + byte[] payload, + MqttQualityOfServiceLevel qualityOfServiceLevel, + IDictionary? parameters = null) { using var timeoutToken = new CancellationTokenSource(timeout); try @@ -60,7 +65,12 @@ public sealed class MqttRpcClient : IMqttRpcClient } } - public async Task ExecuteAsync(string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary parameters = null, CancellationToken cancellationToken = default) + public async Task ExecuteAsync( + string methodName, + byte[] payload, + MqttQualityOfServiceLevel qualityOfServiceLevel, + IDictionary? parameters = null, + CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(methodName); @@ -82,7 +92,7 @@ public sealed class MqttRpcClient : IMqttRpcClient var requestMessageBuilder = new MqttApplicationMessageBuilder().WithTopic(requestTopic).WithPayload(payload).WithQualityOfServiceLevel(qualityOfServiceLevel); - if (_mqttClient.Options.ProtocolVersion == MqttProtocolVersion.V500) + if (_mqttClient.Options!.ProtocolVersion == MqttProtocolVersion.V500) { requestMessageBuilder.WithResponseTopic(responseTopic); } @@ -103,11 +113,10 @@ public sealed class MqttRpcClient : IMqttRpcClient await _mqttClient.SubscribeAsync(subscribeOptions, cancellationToken).ConfigureAwait(false); await _mqttClient.PublishAsync(requestMessage, cancellationToken).ConfigureAwait(false); - using (cancellationToken.Register( - () => - { - awaitable.TrySetCanceled(); - })) + using (cancellationToken.Register(() => + { + awaitable.TrySetCanceled(); + })) { return await awaitable.Task.ConfigureAwait(false); } diff --git a/Source/MQTTnet.Extensions.Rpc/MqttRpcClientExtensions.cs b/Source/MQTTnet.Extensions.Rpc/MqttRpcClientExtensions.cs index bde8aefc..f8d3ecde 100644 --- a/Source/MQTTnet.Extensions.Rpc/MqttRpcClientExtensions.cs +++ b/Source/MQTTnet.Extensions.Rpc/MqttRpcClientExtensions.cs @@ -12,7 +12,7 @@ namespace MQTTnet.Extensions.Rpc; public static class MqttRpcClientExtensions { - public static Task ExecuteAsync(this IMqttRpcClient client, TimeSpan timeout, string methodName, string payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary parameters = null) + public static Task ExecuteAsync(this IMqttRpcClient client, TimeSpan timeout, string methodName, string payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary? parameters = null) { if (client == null) throw new ArgumentNullException(nameof(client)); diff --git a/Source/MQTTnet.Extensions.Rpc/MqttRpcTopicPair.cs b/Source/MQTTnet.Extensions.Rpc/MqttRpcTopicPair.cs index 2cdf7ffc..f27dfa65 100644 --- a/Source/MQTTnet.Extensions.Rpc/MqttRpcTopicPair.cs +++ b/Source/MQTTnet.Extensions.Rpc/MqttRpcTopicPair.cs @@ -6,7 +6,7 @@ namespace MQTTnet.Extensions.Rpc; public sealed class MqttRpcTopicPair { - public string RequestTopic { get; set; } + public required string RequestTopic { get; init; } - public string ResponseTopic { get; set; } + public required string ResponseTopic { get; init; } } \ No newline at end of file diff --git a/Source/MQTTnet.Extensions.Rpc/TopicGenerationContext.cs b/Source/MQTTnet.Extensions.Rpc/TopicGenerationContext.cs index 9559f638..519b05d8 100644 --- a/Source/MQTTnet.Extensions.Rpc/TopicGenerationContext.cs +++ b/Source/MQTTnet.Extensions.Rpc/TopicGenerationContext.cs @@ -10,8 +10,12 @@ namespace MQTTnet.Extensions.Rpc; public sealed class TopicGenerationContext { - public TopicGenerationContext(IMqttClient mqttClient, MqttRpcClientOptions options, string methodName, - IDictionary parameters, MqttQualityOfServiceLevel qualityOfServiceLevel) + public TopicGenerationContext( + IMqttClient mqttClient, + MqttRpcClientOptions options, + string methodName, + IDictionary? parameters, + MqttQualityOfServiceLevel qualityOfServiceLevel) { MethodName = methodName ?? throw new ArgumentNullException(nameof(methodName)); Parameters = parameters; @@ -22,12 +26,12 @@ public sealed class TopicGenerationContext public string MethodName { get; } - public IDictionary Parameters { get; } - public IMqttClient MqttClient { get; } public MqttRpcClientOptions Options { get; } + public IDictionary? Parameters { get; } + /// /// Gets or sets the quality of service level. /// The Quality of Service (QoS) level is an agreement between the sender of a message and the receiver of a message diff --git a/Source/MQTTnet.Extensions.TopicTemplate/MQTTnet.Extensions.TopicTemplate.csproj b/Source/MQTTnet.Extensions.TopicTemplate/MQTTnet.Extensions.TopicTemplate.csproj index cef08d80..adcddc85 100644 --- a/Source/MQTTnet.Extensions.TopicTemplate/MQTTnet.Extensions.TopicTemplate.csproj +++ b/Source/MQTTnet.Extensions.TopicTemplate/MQTTnet.Extensions.TopicTemplate.csproj @@ -33,6 +33,8 @@ true 1591;NETSDK1138 true + default + enable diff --git a/Source/MQTTnet.Server/EnhancedAuthentication/ExchangeEnhancedAuthenticationOptions.cs b/Source/MQTTnet.Server/EnhancedAuthentication/ExchangeEnhancedAuthenticationOptions.cs index d832a96d..140d579c 100644 --- a/Source/MQTTnet.Server/EnhancedAuthentication/ExchangeEnhancedAuthenticationOptions.cs +++ b/Source/MQTTnet.Server/EnhancedAuthentication/ExchangeEnhancedAuthenticationOptions.cs @@ -8,9 +8,9 @@ namespace MQTTnet.Server.EnhancedAuthentication; public sealed class ExchangeEnhancedAuthenticationOptions { - public byte[] AuthenticationData { get; set; } + public byte[]? AuthenticationData { get; set; } - public string ReasonString { get; set; } + public string? ReasonString { get; set; } - public List UserProperties { get; set; } + public List? UserProperties { get; set; } } \ No newline at end of file diff --git a/Source/MQTTnet.Server/EnhancedAuthentication/ExchangeEnhancedAuthenticationResult.cs b/Source/MQTTnet.Server/EnhancedAuthentication/ExchangeEnhancedAuthenticationResult.cs index 9b9d6ba9..b747ba17 100644 --- a/Source/MQTTnet.Server/EnhancedAuthentication/ExchangeEnhancedAuthenticationResult.cs +++ b/Source/MQTTnet.Server/EnhancedAuthentication/ExchangeEnhancedAuthenticationResult.cs @@ -4,9 +4,9 @@ namespace MQTTnet.Server.EnhancedAuthentication; public sealed class ExchangeEnhancedAuthenticationResult { - public string ReasonString { get; set; } + public string? ReasonString { get; init; } - public List UserProperties { get; set; } + public List? UserProperties { get; init; } - public byte[] AuthenticationData { get; set; } + public byte[]? AuthenticationData { get; init; } } \ No newline at end of file diff --git a/Source/MQTTnet.Server/Events/ClientConnectedEventArgs.cs b/Source/MQTTnet.Server/Events/ClientConnectedEventArgs.cs index 718ecb65..148f682f 100644 --- a/Source/MQTTnet.Server/Events/ClientConnectedEventArgs.cs +++ b/Source/MQTTnet.Server/Events/ClientConnectedEventArgs.cs @@ -22,15 +22,15 @@ public sealed class ClientConnectedEventArgs : EventArgs SessionItems = sessionItems ?? throw new ArgumentNullException(nameof(sessionItems)); } - public byte[] AuthenticationData => _connectPacket.AuthenticationData; + public byte[]? AuthenticationData => _connectPacket.AuthenticationData; - public string AuthenticationMethod => _connectPacket.AuthenticationMethod; + public string? AuthenticationMethod => _connectPacket.AuthenticationMethod; /// /// Gets the client identifier of the connected client. /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. /// - public string ClientId => _connectPacket.ClientId; + public string ClientId => _connectPacket.ClientId!; /// /// Gets the endpoint of the connected client. @@ -38,7 +38,7 @@ public sealed class ClientConnectedEventArgs : EventArgs public EndPoint RemoteEndPoint { get; } [Obsolete("Use RemoteEndPoint instead.")] - public string Endpoint => RemoteEndPoint?.ToString(); + public string? Endpoint => RemoteEndPoint?.ToString(); /// /// Gets the protocol version which is used by the connected client. @@ -53,16 +53,16 @@ public sealed class ClientConnectedEventArgs : EventArgs /// /// Gets the user name of the connected client. /// - public string UserName => _connectPacket.Username; + public string? UserName => _connectPacket.Username; /// /// Gets the password of the connected client. /// - public string Password => Encoding.UTF8.GetString(_connectPacket.Password.AsSpan()); + public string? Password => Encoding.UTF8.GetString(_connectPacket.Password.AsSpan()); /// /// Gets the user properties sent by the client. /// MQTT 5.0.0+ feature. /// - public List UserProperties => _connectPacket?.UserProperties; + public List? UserProperties => _connectPacket?.UserProperties; } \ No newline at end of file diff --git a/Source/MQTTnet.Server/Events/ClientDisconnectedEventArgs.cs b/Source/MQTTnet.Server/Events/ClientDisconnectedEventArgs.cs index 9cb85202..783add3c 100644 --- a/Source/MQTTnet.Server/Events/ClientDisconnectedEventArgs.cs +++ b/Source/MQTTnet.Server/Events/ClientDisconnectedEventArgs.cs @@ -35,24 +35,24 @@ public sealed class ClientDisconnectedEventArgs : EventArgs /// Gets the client identifier. /// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues. /// - public string ClientId => _connectPacket.ClientId; + public string ClientId => _connectPacket.ClientId!; /// /// Gets the user name of the client. /// - public string UserName => _connectPacket.Username; + public string? UserName => _connectPacket.Username; /// /// Gets the password of the client. /// - public string Password => Encoding.UTF8.GetString(_connectPacket.Password.AsSpan()); + public string? Password => Encoding.UTF8.GetString(_connectPacket.Password.AsSpan()); public MqttClientDisconnectType DisconnectType { get; } public EndPoint RemoteEndPoint { get; } [Obsolete("Use RemoteEndPoint instead.")] - public string Endpoint => RemoteEndPoint?.ToString(); + public string? Endpoint => RemoteEndPoint?.ToString(); /// /// Gets the reason code sent by the client. @@ -66,7 +66,7 @@ public sealed class ClientDisconnectedEventArgs : EventArgs /// Only available for clean disconnects. /// MQTT 5.0.0+ feature. /// - public string ReasonString => _disconnectPacket?.ReasonString; + public string? ReasonString => _disconnectPacket?.ReasonString; /// /// Gets the session expiry interval sent by the client. @@ -85,5 +85,5 @@ public sealed class ClientDisconnectedEventArgs : EventArgs /// Only available for clean disconnects. /// MQTT 5.0.0+ feature. /// - public List UserProperties => _disconnectPacket?.UserProperties; + public List? UserProperties => _disconnectPacket?.UserProperties; } \ No newline at end of file diff --git a/Source/MQTTnet.Server/Internal/Adapter/MqttTcpServerAdapter.cs b/Source/MQTTnet.Server/Internal/Adapter/MqttTcpServerAdapter.cs index 9c955a03..49f91aab 100644 --- a/Source/MQTTnet.Server/Internal/Adapter/MqttTcpServerAdapter.cs +++ b/Source/MQTTnet.Server/Internal/Adapter/MqttTcpServerAdapter.cs @@ -12,7 +12,7 @@ namespace MQTTnet.Server.Internal.Adapter; public sealed class MqttTcpServerAdapter : IMqttServerAdapter { - readonly List _listeners = new List(); + readonly List _listeners = new(); CancellationTokenSource _cancellationTokenSource; diff --git a/Source/MQTTnet.Server/Internal/Adapter/MqttTcpServerListener.cs b/Source/MQTTnet.Server/Internal/Adapter/MqttTcpServerListener.cs index e539dc60..0a51dcc1 100644 --- a/Source/MQTTnet.Server/Internal/Adapter/MqttTcpServerListener.cs +++ b/Source/MQTTnet.Server/Internal/Adapter/MqttTcpServerListener.cs @@ -165,8 +165,8 @@ public sealed class MqttTcpServerListener : IDisposable async Task TryHandleClientConnectionAsync(CrossPlatformSocket clientSocket) { - Stream stream = null; - EndPoint remoteEndPoint = null; + Stream? stream = null; + EndPoint? remoteEndPoint = null; try { diff --git a/Source/MQTTnet.Server/Internal/MqttClientSessionsManager.cs b/Source/MQTTnet.Server/Internal/MqttClientSessionsManager.cs index b4985bd2..7d47f4e9 100644 --- a/Source/MQTTnet.Server/Internal/MqttClientSessionsManager.cs +++ b/Source/MQTTnet.Server/Internal/MqttClientSessionsManager.cs @@ -667,7 +667,7 @@ public sealed class MqttClientSessionsManager : ISubscriptionChangedNotification } } - async Task ReceiveConnectPacket(IMqttChannelAdapter channelAdapter, CancellationToken cancellationToken) + async Task ReceiveConnectPacket(IMqttChannelAdapter channelAdapter, CancellationToken cancellationToken) { try { diff --git a/Source/MQTTnet.Server/MQTTnet.Server.csproj b/Source/MQTTnet.Server/MQTTnet.Server.csproj index b9cd0ca2..719cf6f3 100644 --- a/Source/MQTTnet.Server/MQTTnet.Server.csproj +++ b/Source/MQTTnet.Server/MQTTnet.Server.csproj @@ -35,9 +35,10 @@ true low enable - disable + enable latest-Recommended true + default diff --git a/Source/MQTTnet.Server/MqttServerExtensions.cs b/Source/MQTTnet.Server/MqttServerExtensions.cs index 747a9dfb..496d0e77 100644 --- a/Source/MQTTnet.Server/MqttServerExtensions.cs +++ b/Source/MQTTnet.Server/MqttServerExtensions.cs @@ -21,7 +21,7 @@ public static class MqttServerExtensions public static Task InjectApplicationMessage( this MqttServer server, string topic, - string payload = null, + string? payload = null, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false) { diff --git a/Source/MQTTnet.Server/Options/MqttServerOptionsBuilder.cs b/Source/MQTTnet.Server/Options/MqttServerOptionsBuilder.cs index 52035890..24bc6023 100644 --- a/Source/MQTTnet.Server/Options/MqttServerOptionsBuilder.cs +++ b/Source/MQTTnet.Server/Options/MqttServerOptionsBuilder.cs @@ -20,7 +20,7 @@ public class MqttServerOptionsBuilder return _options; } - public MqttServerOptionsBuilder WithClientCertificate(RemoteCertificateValidationCallback validationCallback = null, bool checkCertificateRevocation = false) + public MqttServerOptionsBuilder WithClientCertificate(RemoteCertificateValidationCallback? validationCallback = null, bool checkCertificateRevocation = false) { _options.TlsEndpointOptions.ClientCertificateRequired = true; _options.TlsEndpointOptions.CheckCertificateRevocation = checkCertificateRevocation; @@ -183,7 +183,7 @@ public class MqttServerOptionsBuilder return this; } - public MqttServerOptionsBuilder WithEncryptionCertificate(byte[] value, IMqttServerCertificateCredentials credentials = null) + public MqttServerOptionsBuilder WithEncryptionCertificate(byte[] value, IMqttServerCertificateCredentials? credentials = null) { ArgumentNullException.ThrowIfNull(value); diff --git a/Source/MQTTnet.Server/SubscribeResponse.cs b/Source/MQTTnet.Server/SubscribeResponse.cs index 00ebf402..10098e68 100644 --- a/Source/MQTTnet.Server/SubscribeResponse.cs +++ b/Source/MQTTnet.Server/SubscribeResponse.cs @@ -16,7 +16,7 @@ public sealed class SubscribeResponse /// public MqttSubscribeReasonCode ReasonCode { get; set; } - public string ReasonString { get; set; } + public string? ReasonString { get; set; } - public List UserProperties { get; } = []; + public List? UserProperties { get; set; } = []; } \ No newline at end of file diff --git a/Source/MQTTnet.Server/UnsubscribeResponse.cs b/Source/MQTTnet.Server/UnsubscribeResponse.cs index 741d323d..e7d5d32c 100644 --- a/Source/MQTTnet.Server/UnsubscribeResponse.cs +++ b/Source/MQTTnet.Server/UnsubscribeResponse.cs @@ -15,7 +15,7 @@ public sealed class UnsubscribeResponse /// public MqttUnsubscribeReasonCode ReasonCode { get; set; } - public string ReasonString { get; set; } + public string? ReasonString { get; set; } - public List UserProperties { get; } = []; + public List? UserProperties { get; } = []; } \ No newline at end of file diff --git a/Source/MQTTnet.TestApp/MQTTnet.TestApp.csproj b/Source/MQTTnet.TestApp/MQTTnet.TestApp.csproj index 68fc336b..2367b4a6 100644 --- a/Source/MQTTnet.TestApp/MQTTnet.TestApp.csproj +++ b/Source/MQTTnet.TestApp/MQTTnet.TestApp.csproj @@ -14,6 +14,8 @@ true low latest-Recommended + default + enable diff --git a/Source/MQTTnet.Tests/MQTTnet.Tests.csproj b/Source/MQTTnet.Tests/MQTTnet.Tests.csproj index e49348bc..e0ab60c5 100644 --- a/Source/MQTTnet.Tests/MQTTnet.Tests.csproj +++ b/Source/MQTTnet.Tests/MQTTnet.Tests.csproj @@ -14,6 +14,8 @@ true low latest-Recommended + default + enable diff --git a/Source/MQTTnet/Adapter/IMqttChannelAdapter.cs b/Source/MQTTnet/Adapter/IMqttChannelAdapter.cs index 9337354a..d7ae785e 100644 --- a/Source/MQTTnet/Adapter/IMqttChannelAdapter.cs +++ b/Source/MQTTnet/Adapter/IMqttChannelAdapter.cs @@ -18,9 +18,9 @@ public interface IMqttChannelAdapter : IDisposable long BytesSent { get; } - X509Certificate2 ClientCertificate { get; } + X509Certificate2? ClientCertificate { get; } - EndPoint RemoteEndPoint { get; } + EndPoint? RemoteEndPoint { get; } bool IsSecureConnection { get; } @@ -30,7 +30,7 @@ public interface IMqttChannelAdapter : IDisposable Task DisconnectAsync(CancellationToken cancellationToken); - Task ReceivePacketAsync(CancellationToken cancellationToken); + Task ReceivePacketAsync(CancellationToken cancellationToken); void ResetStatistics(); diff --git a/Source/MQTTnet/Adapter/IMqttClientAdapterFactory.cs b/Source/MQTTnet/Adapter/IMqttClientAdapterFactory.cs index 3ea49381..49cf05f4 100644 --- a/Source/MQTTnet/Adapter/IMqttClientAdapterFactory.cs +++ b/Source/MQTTnet/Adapter/IMqttClientAdapterFactory.cs @@ -8,5 +8,5 @@ namespace MQTTnet.Adapter; public interface IMqttClientAdapterFactory { - IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector packetInspector, IMqttNetLogger logger); + IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector? packetInspector, IMqttNetLogger logger); } \ No newline at end of file diff --git a/Source/MQTTnet/Adapter/MqttChannelAdapter.cs b/Source/MQTTnet/Adapter/MqttChannelAdapter.cs index 724d47df..f6f920ce 100644 --- a/Source/MQTTnet/Adapter/MqttChannelAdapter.cs +++ b/Source/MQTTnet/Adapter/MqttChannelAdapter.cs @@ -50,15 +50,15 @@ public sealed class MqttChannelAdapter : Disposable, IMqttChannelAdapter public long BytesSent => Volatile.Read(ref _statistics._bytesSent); - public X509Certificate2 ClientCertificate => _channel.ClientCertificate; + public X509Certificate2? ClientCertificate => _channel.ClientCertificate; - public EndPoint RemoteEndPoint => _channel.RemoteEndPoint; + public EndPoint? RemoteEndPoint => _channel.RemoteEndPoint; public bool IsSecureConnection => _channel.IsSecureConnection; public MqttPacketFormatterAdapter PacketFormatterAdapter { get; } - public MqttPacketInspector PacketInspector { get; set; } + public MqttPacketInspector? PacketInspector { get; set; } public async Task ConnectAsync(CancellationToken cancellationToken) { @@ -73,7 +73,7 @@ public sealed class MqttChannelAdapter : Disposable, IMqttChannelAdapter * block forever. Even a cancellation token is not supported properly. */ - var timeout = new TaskCompletionSource(); + var timeout = new TaskCompletionSource(); await using (cancellationToken.Register(() => timeout.TrySetResult(null))) { var connectTask = Task.Run( @@ -133,7 +133,7 @@ public sealed class MqttChannelAdapter : Disposable, IMqttChannelAdapter } } - public async Task ReceivePacketAsync(CancellationToken cancellationToken) + public async Task ReceivePacketAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); diff --git a/Source/MQTTnet/Adapter/MqttPacketInspector.cs b/Source/MQTTnet/Adapter/MqttPacketInspector.cs index 63296840..735c91ba 100644 --- a/Source/MQTTnet/Adapter/MqttPacketInspector.cs +++ b/Source/MQTTnet/Adapter/MqttPacketInspector.cs @@ -17,7 +17,7 @@ public sealed class MqttPacketInspector readonly AsyncEvent _asyncEvent; readonly MqttNetSourceLogger _logger; - MemoryStream _receivedPacketBuffer; + MemoryStream? _receivedPacketBuffer; public MqttPacketInspector(AsyncEvent asyncEvent, IMqttNetLogger logger) { @@ -61,7 +61,7 @@ public sealed class MqttPacketInspector return CompletedTask.Instance; } - var buffer = _receivedPacketBuffer.ToArray(); + var buffer = _receivedPacketBuffer!.ToArray(); _receivedPacketBuffer.SetLength(0); return InspectPacket(buffer, MqttPacketFlowDirection.Inbound); diff --git a/Source/MQTTnet/Certificates/BlobCertificateProvider.cs b/Source/MQTTnet/Certificates/BlobCertificateProvider.cs index 7675125c..b032fe18 100644 --- a/Source/MQTTnet/Certificates/BlobCertificateProvider.cs +++ b/Source/MQTTnet/Certificates/BlobCertificateProvider.cs @@ -11,7 +11,7 @@ public class BlobCertificateProvider(byte[] blob) : ICertificateProvider { public byte[] Blob { get; } = blob ?? throw new ArgumentNullException(nameof(blob)); - public string Password { get; set; } + public string? Password { get; set; } public X509Certificate2 GetCertificate() { diff --git a/Source/MQTTnet/Channel/IMqttChannel.cs b/Source/MQTTnet/Channel/IMqttChannel.cs index 02af43e4..ffbb5348 100644 --- a/Source/MQTTnet/Channel/IMqttChannel.cs +++ b/Source/MQTTnet/Channel/IMqttChannel.cs @@ -13,8 +13,9 @@ namespace MQTTnet.Channel; public interface IMqttChannel : IDisposable { - X509Certificate2 ClientCertificate { get; } - EndPoint RemoteEndPoint { get; } + X509Certificate2? ClientCertificate { get; } + + EndPoint? RemoteEndPoint { get; } bool IsSecureConnection { get; } diff --git a/Source/MQTTnet/Connecting/MqttClientConnectResult.cs b/Source/MQTTnet/Connecting/MqttClientConnectResult.cs index 66cf0300..8e85fa10 100644 --- a/Source/MQTTnet/Connecting/MqttClientConnectResult.cs +++ b/Source/MQTTnet/Connecting/MqttClientConnectResult.cs @@ -14,19 +14,19 @@ public sealed class MqttClientConnectResult /// Gets the client identifier which was chosen by the server. /// MQTTv5 only. /// - public string AssignedClientIdentifier { get; init; } + public string? AssignedClientIdentifier { get; init; } /// /// Gets the authentication data. /// MQTTv5 only. /// - public byte[] AuthenticationData { get; init; } + public byte[]? AuthenticationData { get; init; } /// /// Gets the authentication method. /// MQTTv5 only. /// - public string AuthenticationMethod { get; init; } + public string? AuthenticationMethod { get; init; } /// /// Gets a value indicating whether a session was already available or not. @@ -45,7 +45,7 @@ public sealed class MqttClientConnectResult /// Gets the reason string. /// MQTTv5 only. /// - public string ReasonString { get; init; } + public string? ReasonString { get; init; } public ushort? ReceiveMaximum { get; init; } @@ -53,7 +53,7 @@ public sealed class MqttClientConnectResult /// Gets the response information. /// MQTTv5 only. /// - public string ResponseInformation { get; init; } + public string? ResponseInformation { get; init; } /// /// Gets the result code. @@ -78,7 +78,7 @@ public sealed class MqttClientConnectResult /// Gets an alternate server which should be used instead of the current one. /// MQTTv5 only. /// - public string ServerReference { get; init; } + public string? ServerReference { get; init; } public uint? SessionExpiryInterval { get; init; } @@ -109,7 +109,7 @@ public sealed class MqttClientConnectResult /// The feature is very similar to the HTTP header concept. /// MQTTv5 only. /// - public List UserProperties { get; init; } + public List? UserProperties { get; init; } /// /// Gets a value indicating whether wildcards can be used in subscriptions at the current server. diff --git a/Source/MQTTnet/Diagnostics/Logger/IMqttNetLogger.cs b/Source/MQTTnet/Diagnostics/Logger/IMqttNetLogger.cs index e1c98aa3..45a22850 100644 --- a/Source/MQTTnet/Diagnostics/Logger/IMqttNetLogger.cs +++ b/Source/MQTTnet/Diagnostics/Logger/IMqttNetLogger.cs @@ -10,5 +10,5 @@ public interface IMqttNetLogger { bool IsEnabled { get; } - void Publish(MqttNetLogLevel level, string source, string message, object[] parameters, Exception exception); + void Publish(MqttNetLogLevel level, string source, string message, object?[]? parameters, Exception? exception); } \ No newline at end of file diff --git a/Source/MQTTnet/Diagnostics/Logger/MqttNetEventLogger.cs b/Source/MQTTnet/Diagnostics/Logger/MqttNetEventLogger.cs index 8361ac06..a24c741e 100644 --- a/Source/MQTTnet/Diagnostics/Logger/MqttNetEventLogger.cs +++ b/Source/MQTTnet/Diagnostics/Logger/MqttNetEventLogger.cs @@ -9,17 +9,17 @@ namespace MQTTnet.Diagnostics.Logger; /// /// This logger fires an event when a new message was published. /// -public sealed class MqttNetEventLogger(string logId = null) : IMqttNetLogger +public sealed class MqttNetEventLogger(string? logId = null) : IMqttNetLogger { - public event EventHandler LogMessagePublished; + public event EventHandler? LogMessagePublished; public bool IsEnabled => LogMessagePublished != null; - public string LogId { get; } = logId; + public string? LogId { get; } = logId; - public IFormatProvider FormatProvider { get; set; } + public IFormatProvider? FormatProvider { get; set; } - public void Publish(MqttNetLogLevel level, string source, string message, object[] parameters, Exception exception) + public void Publish(MqttNetLogLevel level, string source, string message, object?[]? parameters, Exception? exception) { var eventHandler = LogMessagePublished; if (eventHandler == null) @@ -30,7 +30,7 @@ public sealed class MqttNetEventLogger(string logId = null) : IMqttNetLogger return; } - if (parameters?.Length > 0 && message?.Length > 0) + if (parameters?.Length > 0 && message.Length > 0) { try { diff --git a/Source/MQTTnet/Diagnostics/Logger/MqttNetLogMessage.cs b/Source/MQTTnet/Diagnostics/Logger/MqttNetLogMessage.cs index b6d928f7..f95b57f9 100644 --- a/Source/MQTTnet/Diagnostics/Logger/MqttNetLogMessage.cs +++ b/Source/MQTTnet/Diagnostics/Logger/MqttNetLogMessage.cs @@ -8,19 +8,19 @@ namespace MQTTnet.Diagnostics.Logger; public sealed class MqttNetLogMessage { - public string LogId { get; set; } + public string? LogId { get; set; } public DateTime Timestamp { get; set; } public int ThreadId { get; set; } - public string Source { get; set; } + public string? Source { get; set; } public MqttNetLogLevel Level { get; set; } - public string Message { get; set; } + public string? Message { get; set; } - public Exception Exception { get; set; } + public Exception? Exception { get; set; } public override string ToString() { diff --git a/Source/MQTTnet/Diagnostics/Logger/MqttNetNullLogger.cs b/Source/MQTTnet/Diagnostics/Logger/MqttNetNullLogger.cs index e1140a4b..d68484f4 100644 --- a/Source/MQTTnet/Diagnostics/Logger/MqttNetNullLogger.cs +++ b/Source/MQTTnet/Diagnostics/Logger/MqttNetNullLogger.cs @@ -15,7 +15,7 @@ public sealed class MqttNetNullLogger : IMqttNetLogger public bool IsEnabled { get; } - public void Publish(MqttNetLogLevel level, string source, string message, object[] parameters, Exception exception) + public void Publish(MqttNetLogLevel level, string source, string message, object?[]? parameters, Exception? exception) { } } \ No newline at end of file diff --git a/Source/MQTTnet/Diagnostics/Logger/MqttNetSourceLogger.cs b/Source/MQTTnet/Diagnostics/Logger/MqttNetSourceLogger.cs index e7ea7dca..fe4f98bc 100644 --- a/Source/MQTTnet/Diagnostics/Logger/MqttNetSourceLogger.cs +++ b/Source/MQTTnet/Diagnostics/Logger/MqttNetSourceLogger.cs @@ -12,7 +12,7 @@ public sealed class MqttNetSourceLogger(IMqttNetLogger logger, string source) public bool IsEnabled => _logger.IsEnabled; - public void Publish(MqttNetLogLevel logLevel, string message, object[] parameters, Exception exception) + public void Publish(MqttNetLogLevel logLevel, string message, object?[]? parameters, Exception? exception) { _logger.Publish(logLevel, source, message, parameters, exception); } diff --git a/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptions.cs b/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptions.cs index fa3e9de7..8fb6411b 100644 --- a/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptions.cs +++ b/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptions.cs @@ -19,7 +19,7 @@ public sealed class MqttClientDisconnectOptions /// Gets or sets the reason string. /// MQTT 5.0.0+ feature. /// - public string ReasonString { get; set; } + public string? ReasonString { get; set; } /// /// Gets or sets the session expiry interval. @@ -31,5 +31,5 @@ public sealed class MqttClientDisconnectOptions /// Gets or sets the user properties. /// MQTT 5.0.0+ feature. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } } \ No newline at end of file diff --git a/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptionsBuilder.cs b/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptionsBuilder.cs index c8a7b88d..3b9fa89a 100644 --- a/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptionsBuilder.cs +++ b/Source/MQTTnet/Disconnecting/MqttClientDisconnectOptionsBuilder.cs @@ -10,9 +10,9 @@ namespace MQTTnet; public sealed class MqttClientDisconnectOptionsBuilder { MqttClientDisconnectOptionsReason _reason = MqttClientDisconnectOptionsReason.NormalDisconnection; - string _reasonString; + string? _reasonString; uint _sessionExpiryInterval; - List _userProperties; + List? _userProperties; public MqttClientDisconnectOptions Build() { diff --git a/Source/MQTTnet/Disconnecting/MqttClientDisconnectedEventArgs.cs b/Source/MQTTnet/Disconnecting/MqttClientDisconnectedEventArgs.cs index 590e8bc6..c744ca2d 100644 --- a/Source/MQTTnet/Disconnecting/MqttClientDisconnectedEventArgs.cs +++ b/Source/MQTTnet/Disconnecting/MqttClientDisconnectedEventArgs.cs @@ -12,11 +12,11 @@ public sealed class MqttClientDisconnectedEventArgs : EventArgs { public MqttClientDisconnectedEventArgs( bool clientWasConnected, - MqttClientConnectResult connectResult, + MqttClientConnectResult? connectResult, MqttClientDisconnectReason reason, - string reasonString, - List userProperties, - Exception exception) + string? reasonString, + List? userProperties, + Exception? exception) { ClientWasConnected = clientWasConnected; ConnectResult = connectResult; @@ -32,9 +32,9 @@ public sealed class MqttClientDisconnectedEventArgs : EventArgs /// Gets the authentication result. /// MQTT 5.0.0+ feature. /// - public MqttClientConnectResult ConnectResult { get; } + public MqttClientConnectResult? ConnectResult { get; } - public Exception Exception { get; } + public Exception? Exception { get; } /// /// Gets or sets the reason. @@ -42,7 +42,7 @@ public sealed class MqttClientDisconnectedEventArgs : EventArgs /// public MqttClientDisconnectReason Reason { get; } - public string ReasonString { get; } + public string? ReasonString { get; } - public List UserProperties { get; } + public List? UserProperties { get; } } \ No newline at end of file diff --git a/Source/MQTTnet/Exceptions/MqttClientUnexpectedDisconnectReceivedException.cs b/Source/MQTTnet/Exceptions/MqttClientUnexpectedDisconnectReceivedException.cs index 9880e751..d09abd3a 100644 --- a/Source/MQTTnet/Exceptions/MqttClientUnexpectedDisconnectReceivedException.cs +++ b/Source/MQTTnet/Exceptions/MqttClientUnexpectedDisconnectReceivedException.cs @@ -9,17 +9,17 @@ using MQTTnet.Protocol; namespace MQTTnet.Exceptions; -public sealed class MqttClientUnexpectedDisconnectReceivedException(MqttDisconnectPacket disconnectPacket, Exception innerException = null) : MqttCommunicationException( +public sealed class MqttClientUnexpectedDisconnectReceivedException(MqttDisconnectPacket disconnectPacket, Exception? innerException = null) : MqttCommunicationException( $"Unexpected DISCONNECT (Reason code={disconnectPacket.ReasonCode}) received.", innerException) { public MqttDisconnectReasonCode? ReasonCode { get; } = disconnectPacket.ReasonCode; - public string ReasonString { get; } = disconnectPacket.ReasonString; + public string? ReasonString { get; } = disconnectPacket.ReasonString; - public string ServerReference { get; } = disconnectPacket.ServerReference; + public string? ServerReference { get; } = disconnectPacket.ServerReference; public uint? SessionExpiryInterval { get; } = disconnectPacket.SessionExpiryInterval; - public List UserProperties { get; } = disconnectPacket.UserProperties; + public List? UserProperties { get; } = disconnectPacket.UserProperties; } \ No newline at end of file diff --git a/Source/MQTTnet/Exceptions/MqttCommunicationException.cs b/Source/MQTTnet/Exceptions/MqttCommunicationException.cs index 7f8a3ffd..f28632ef 100644 --- a/Source/MQTTnet/Exceptions/MqttCommunicationException.cs +++ b/Source/MQTTnet/Exceptions/MqttCommunicationException.cs @@ -8,12 +8,12 @@ namespace MQTTnet.Exceptions; public class MqttCommunicationException : Exception { - public MqttCommunicationException(Exception innerException) + public MqttCommunicationException(Exception? innerException) : base(innerException?.Message ?? "MQTT communication failed.", innerException) { } - public MqttCommunicationException(string message, Exception innerException = null) + public MqttCommunicationException(string message, Exception? innerException = null) : base(message, innerException) { } diff --git a/Source/MQTTnet/Formatter/IMqttPacketFormatter.cs b/Source/MQTTnet/Formatter/IMqttPacketFormatter.cs index 7754d8b2..df1e428e 100644 --- a/Source/MQTTnet/Formatter/IMqttPacketFormatter.cs +++ b/Source/MQTTnet/Formatter/IMqttPacketFormatter.cs @@ -9,7 +9,7 @@ namespace MQTTnet.Formatter; public interface IMqttPacketFormatter { - MqttPacket Decode(ReceivedMqttPacket receivedPacket); + MqttPacket? Decode(ReceivedMqttPacket receivedPacket); MqttPacketBuffer Encode(MqttPacket packet); } \ No newline at end of file diff --git a/Source/MQTTnet/Formatter/MqttBufferReader.cs b/Source/MQTTnet/Formatter/MqttBufferReader.cs index c6ca138e..9d906861 100644 --- a/Source/MQTTnet/Formatter/MqttBufferReader.cs +++ b/Source/MQTTnet/Formatter/MqttBufferReader.cs @@ -131,7 +131,7 @@ public sealed class MqttBufferReader public void SetBuffer(ArraySegment buffer) { - SetBuffer(buffer.Array, buffer.Offset, buffer.Count); + SetBuffer(buffer.Array!, buffer.Offset, buffer.Count); } public void SetBuffer(byte[] buffer, int offset, int length) diff --git a/Source/MQTTnet/Formatter/MqttBufferWriter.cs b/Source/MQTTnet/Formatter/MqttBufferWriter.cs index abaca7da..334ef0e4 100644 --- a/Source/MQTTnet/Formatter/MqttBufferWriter.cs +++ b/Source/MQTTnet/Formatter/MqttBufferWriter.cs @@ -110,7 +110,7 @@ public sealed class MqttBufferWriter WriteBinary(propertyWriter._buffer, 0, propertyWriter.Length); } - public void WriteBinary(byte[] value) + public void WriteBinary(byte[]? value) { if (value == null || value.Length == 0) { @@ -158,7 +158,7 @@ public sealed class MqttBufferWriter IncreasePosition(1); } - public void WriteString(string value) + public void WriteString(string? value) { if (string.IsNullOrEmpty(value)) { diff --git a/Source/MQTTnet/Formatter/MqttPacketBuffer.cs b/Source/MQTTnet/Formatter/MqttPacketBuffer.cs index 91376e35..453149e2 100644 --- a/Source/MQTTnet/Formatter/MqttPacketBuffer.cs +++ b/Source/MQTTnet/Formatter/MqttPacketBuffer.cs @@ -40,7 +40,7 @@ public readonly struct MqttPacketBuffer } var buffer = GC.AllocateUninitializedArray(Length); - MqttMemoryHelper.Copy(Packet.Array, Packet.Offset, buffer, 0, Packet.Count); + MqttMemoryHelper.Copy(Packet.Array!, Packet.Offset, buffer, 0, Packet.Count); MqttMemoryHelper.Copy(Payload, 0, buffer, Packet.Count, (int)Payload.Length); return buffer; diff --git a/Source/MQTTnet/Formatter/MqttPacketFormatterAdapter.cs b/Source/MQTTnet/Formatter/MqttPacketFormatterAdapter.cs index 4f974369..81d8149b 100644 --- a/Source/MQTTnet/Formatter/MqttPacketFormatterAdapter.cs +++ b/Source/MQTTnet/Formatter/MqttPacketFormatterAdapter.cs @@ -17,7 +17,7 @@ public sealed class MqttPacketFormatterAdapter readonly MqttBufferReader _bufferReader = new(); readonly MqttBufferWriter _bufferWriter; - IMqttPacketFormatter _formatter; + IMqttPacketFormatter? _formatter; public MqttPacketFormatterAdapter(MqttBufferWriter mqttBufferWriter) { @@ -37,10 +37,10 @@ public sealed class MqttPacketFormatterAdapter _bufferWriter.Cleanup(); } - public MqttPacket Decode(ReceivedMqttPacket receivedMqttPacket) + public MqttPacket? Decode(ReceivedMqttPacket receivedMqttPacket) { ThrowIfFormatterNotSet(); - return _formatter.Decode(receivedMqttPacket); + return _formatter!.Decode(receivedMqttPacket); } public void DetectProtocolVersion(ReceivedMqttPacket receivedMqttPacket) @@ -52,7 +52,7 @@ public sealed class MqttPacketFormatterAdapter public MqttPacketBuffer Encode(MqttPacket packet) { ThrowIfFormatterNotSet(); - return _formatter.Encode(packet); + return _formatter!.Encode(packet); } public static IMqttPacketFormatter GetMqttPacketFormatter(MqttProtocolVersion protocolVersion, MqttBufferWriter bufferWriter) @@ -80,7 +80,7 @@ public sealed class MqttPacketFormatterAdapter throw new MqttProtocolViolationException("CONNECT packet must have at least 7 bytes."); } - _bufferReader.SetBuffer(receivedMqttPacket.Body.Array, receivedMqttPacket.Body.Offset, receivedMqttPacket.Body.Count); + _bufferReader.SetBuffer(receivedMqttPacket.Body.Array!, receivedMqttPacket.Body.Offset, receivedMqttPacket.Body.Count); var protocolName = _bufferReader.ReadString(); var protocolLevel = _bufferReader.ReadByte(); diff --git a/Source/MQTTnet/Formatter/MqttUnsubscribePacketFactory.cs b/Source/MQTTnet/Formatter/MqttUnsubscribePacketFactory.cs index 573db1bc..b1cca274 100644 --- a/Source/MQTTnet/Formatter/MqttUnsubscribePacketFactory.cs +++ b/Source/MQTTnet/Formatter/MqttUnsubscribePacketFactory.cs @@ -18,10 +18,7 @@ public static class MqttUnsubscribePacketFactory UserProperties = clientUnsubscribeOptions.UserProperties }; - if (clientUnsubscribeOptions.TopicFilters != null) - { - packet.TopicFilters.AddRange(clientUnsubscribeOptions.TopicFilters); - } + packet.TopicFilters!.AddRange(clientUnsubscribeOptions.TopicFilters); return packet; } diff --git a/Source/MQTTnet/Formatter/V3/MqttV3PacketFormatter.cs b/Source/MQTTnet/Formatter/V3/MqttV3PacketFormatter.cs index 4e30ec90..9718fa26 100644 --- a/Source/MQTTnet/Formatter/V3/MqttV3PacketFormatter.cs +++ b/Source/MQTTnet/Formatter/V3/MqttV3PacketFormatter.cs @@ -29,7 +29,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter _mqttProtocolVersion = mqttProtocolVersion; } - public MqttPacket Decode(ReceivedMqttPacket receivedPacket) + public MqttPacket? Decode(ReceivedMqttPacket receivedPacket) { if (receivedPacket.TotalLength == 0) { @@ -126,7 +126,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttConnAckPacket(); @@ -140,7 +140,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttConnAckPacket(); @@ -156,7 +156,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var protocolName = _bufferReader.ReadString(); var protocolVersion = _bufferReader.ReadByte(); @@ -224,7 +224,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); return new MqttPubAckPacket { @@ -236,7 +236,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); return new MqttPubCompPacket { @@ -248,7 +248,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(receivedMqttPacket.Body); - _bufferReader.SetBuffer(receivedMqttPacket.Body.Array, receivedMqttPacket.Body.Offset, receivedMqttPacket.Body.Count); + _bufferReader.SetBuffer(receivedMqttPacket.Body.Array!, receivedMqttPacket.Body.Offset, receivedMqttPacket.Body.Count); var retain = (receivedMqttPacket.FixedHeader & 0x1) > 0; var qualityOfServiceLevel = (MqttQualityOfServiceLevel)((receivedMqttPacket.FixedHeader >> 1) & 0x3); @@ -283,7 +283,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); return new MqttPubRecPacket { @@ -295,7 +295,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); return new MqttPubRelPacket { @@ -307,7 +307,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttSubAckPacket { @@ -327,7 +327,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttSubscribePacket { @@ -352,7 +352,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); return new MqttUnsubAckPacket { @@ -364,7 +364,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttUnsubscribePacket { @@ -373,7 +373,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter while (!_bufferReader.EndOfStream) { - packet.TopicFilters.Add(_bufferReader.ReadString()); + packet.TopicFilters!.Add(_bufferReader.ReadString()); } return packet; @@ -694,9 +694,9 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter bufferWriter.WriteTwoByteInteger(packet.PacketIdentifier); - if (packet.ReasonCodes.Count != 0) + if (packet.ReasonCodes?.Count > 0) { - foreach (var packetSubscribeReturnCode in packet.ReasonCodes) + foreach (var packetSubscribeReturnCode in packet.ReasonCodes!) { if (packetSubscribeReturnCode == MqttSubscribeReasonCode.GrantedQoS0) { @@ -759,7 +759,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter static byte EncodeUnsubscribePacket(MqttUnsubscribePacket packet, MqttBufferWriter bufferWriter) { - if (packet.TopicFilters.Count == 0) + if (packet.TopicFilters?.Count == 0) { throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.10.3-2]."); } diff --git a/Source/MQTTnet/Formatter/V5/MqttV5PacketDecoder.cs b/Source/MQTTnet/Formatter/V5/MqttV5PacketDecoder.cs index 8997ae8f..1c529b49 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV5PacketDecoder.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV5PacketDecoder.cs @@ -15,7 +15,7 @@ public sealed class MqttV5PacketDecoder { readonly MqttBufferReader _bufferReader = new(); - public MqttPacket Decode(ReceivedMqttPacket receivedMqttPacket) + public MqttPacket? Decode(ReceivedMqttPacket receivedMqttPacket) { if (receivedMqttPacket.TotalLength == 0) { @@ -51,7 +51,7 @@ public sealed class MqttV5PacketDecoder MqttAuthPacket DecodeAuthPacket(ArraySegment body) { - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttAuthPacket(); @@ -95,7 +95,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var acknowledgeFlags = _bufferReader.ReadByte(); @@ -198,7 +198,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttConnectPacket { @@ -346,7 +346,7 @@ public sealed class MqttV5PacketDecoder }; } - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttDisconnectPacket { @@ -383,7 +383,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttPubAckPacket { @@ -420,7 +420,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttPubCompPacket { @@ -458,7 +458,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var retain = (header & 1) > 0; var qos = (MqttQualityOfServiceLevel)((header >> 1) & 3); @@ -533,7 +533,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttPubRecPacket { @@ -570,7 +570,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttPubRelPacket { @@ -607,7 +607,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttSubAckPacket { @@ -643,7 +643,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttSubscribePacket { @@ -693,7 +693,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttUnsubAckPacket { @@ -730,7 +730,7 @@ public sealed class MqttV5PacketDecoder { ThrowIfBodyIsEmpty(body); - _bufferReader.SetBuffer(body.Array, body.Offset, body.Count); + _bufferReader.SetBuffer(body.Array!, body.Offset, body.Count); var packet = new MqttUnsubscribePacket { @@ -747,7 +747,7 @@ public sealed class MqttV5PacketDecoder while (!_bufferReader.EndOfStream) { - packet.TopicFilters.Add(_bufferReader.ReadString()); + packet.TopicFilters!.Add(_bufferReader.ReadString()); } return packet; diff --git a/Source/MQTTnet/Formatter/V5/MqttV5PacketEncoder.cs b/Source/MQTTnet/Formatter/V5/MqttV5PacketEncoder.cs index 9c4e9013..1703fe50 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV5PacketEncoder.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV5PacketEncoder.cs @@ -30,7 +30,9 @@ public sealed class MqttV5PacketEncoder(MqttBufferWriter bufferWriter) var fixedHeader = EncodePacket(packet); var remainingLength = (uint)_bufferWriter.Length - reservedHeaderSize; - if (packet is MqttPublishPacket publishPacket) + var publishPacket = packet as MqttPublishPacket; + + if (publishPacket != null) { var payload = publishPacket.Payload; remainingLength += (uint)payload.Length; @@ -405,7 +407,7 @@ public sealed class MqttV5PacketEncoder(MqttBufferWriter bufferWriter) _propertiesWriter.WriteTo(_bufferWriter); _propertiesWriter.Reset(); - foreach (var reasonCode in packet.ReasonCodes) + foreach (var reasonCode in packet.ReasonCodes!) { _bufferWriter.WriteByte((byte)reasonCode); } @@ -476,7 +478,7 @@ public sealed class MqttV5PacketEncoder(MqttBufferWriter bufferWriter) _propertiesWriter.WriteTo(_bufferWriter); _propertiesWriter.Reset(); - foreach (var reasonCode in packet.ReasonCodes) + foreach (var reasonCode in packet.ReasonCodes!) { _bufferWriter.WriteByte((byte)reasonCode); } @@ -500,7 +502,7 @@ public sealed class MqttV5PacketEncoder(MqttBufferWriter bufferWriter) _propertiesWriter.WriteTo(_bufferWriter); _propertiesWriter.Reset(); - foreach (var topicFilter in packet.TopicFilters) + foreach (var topicFilter in packet.TopicFilters!) { _bufferWriter.WriteString(topicFilter); } diff --git a/Source/MQTTnet/Formatter/V5/MqttV5PacketFormatter.cs b/Source/MQTTnet/Formatter/V5/MqttV5PacketFormatter.cs index ec6a1229..90a66f5d 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV5PacketFormatter.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV5PacketFormatter.cs @@ -18,7 +18,7 @@ public sealed class MqttV5PacketFormatter : IMqttPacketFormatter _encoder = new MqttV5PacketEncoder(bufferWriter); } - public MqttPacket Decode(ReceivedMqttPacket receivedPacket) + public MqttPacket? Decode(ReceivedMqttPacket receivedPacket) { return _decoder.Decode(receivedPacket); } diff --git a/Source/MQTTnet/Formatter/V5/MqttV5PropertiesReader.cs b/Source/MQTTnet/Formatter/V5/MqttV5PropertiesReader.cs index 84983088..7faa5690 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV5PropertiesReader.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV5PropertiesReader.cs @@ -35,7 +35,7 @@ public struct MqttV5PropertiesReader CurrentPropertyId = MqttPropertyId.None; } - public List CollectedUserProperties { get; private set; } + public List? CollectedUserProperties { get; private set; } public MqttPropertyId CurrentPropertyId { get; private set; } diff --git a/Source/MQTTnet/Formatter/V5/MqttV5PropertiesWriter.cs b/Source/MQTTnet/Formatter/V5/MqttV5PropertiesWriter.cs index 5d138718..eb922f89 100644 --- a/Source/MQTTnet/Formatter/V5/MqttV5PropertiesWriter.cs +++ b/Source/MQTTnet/Formatter/V5/MqttV5PropertiesWriter.cs @@ -9,14 +9,9 @@ using MQTTnet.Protocol; namespace MQTTnet.Formatter.V5; -public sealed class MqttV5PropertiesWriter +public sealed class MqttV5PropertiesWriter(MqttBufferWriter bufferWriter) { - readonly MqttBufferWriter _bufferWriter; - - public MqttV5PropertiesWriter(MqttBufferWriter bufferWriter) - { - _bufferWriter = bufferWriter ?? throw new ArgumentNullException(nameof(bufferWriter)); - } + readonly MqttBufferWriter _bufferWriter = bufferWriter ?? throw new ArgumentNullException(nameof(bufferWriter)); public int Length => _bufferWriter.Length; @@ -26,27 +21,27 @@ public sealed class MqttV5PropertiesWriter _bufferWriter.Cleanup(); } - public void WriteAssignedClientIdentifier(string value) + public void WriteAssignedClientIdentifier(string? value) { Write(MqttPropertyId.AssignedClientIdentifier, value); } - public void WriteAuthenticationData(byte[] value) + public void WriteAuthenticationData(byte[]? value) { Write(MqttPropertyId.AuthenticationData, value); } - public void WriteAuthenticationMethod(string value) + public void WriteAuthenticationMethod(string? value) { Write(MqttPropertyId.AuthenticationMethod, value); } - public void WriteContentType(string value) + public void WriteContentType(string? value) { Write(MqttPropertyId.ContentType, value); } - public void WriteCorrelationData(byte[] value) + public void WriteCorrelationData(byte[]? value) { Write(MqttPropertyId.CorrelationData, value); } @@ -96,7 +91,7 @@ public sealed class MqttV5PropertiesWriter Write(MqttPropertyId.PayloadFormatIndicator, (byte)value); } - public void WriteReasonString(string value) + public void WriteReasonString(string? value) { Write(MqttPropertyId.ReasonString, value); } @@ -134,12 +129,12 @@ public sealed class MqttV5PropertiesWriter Write(MqttPropertyId.RequestResponseInformation, true); } - public void WriteResponseInformation(string value) + public void WriteResponseInformation(string? value) { Write(MqttPropertyId.ResponseInformation, value); } - public void WriteResponseTopic(string value) + public void WriteResponseTopic(string? value) { Write(MqttPropertyId.ResponseTopic, value); } @@ -165,7 +160,7 @@ public sealed class MqttV5PropertiesWriter Write(MqttPropertyId.ServerKeepAlive, value); } - public void WriteServerReference(string value) + public void WriteServerReference(string? value) { Write(MqttPropertyId.ServerReference, value); } @@ -197,7 +192,7 @@ public sealed class MqttV5PropertiesWriter WriteAsVariableByteInteger(MqttPropertyId.SubscriptionIdentifier, value); } - public void WriteSubscriptionIdentifiers(ICollection value) + public void WriteSubscriptionIdentifiers(ICollection? value) { if (value == null) { @@ -251,7 +246,7 @@ public sealed class MqttV5PropertiesWriter Write(MqttPropertyId.TopicAliasMaximum, value); } - public void WriteUserProperties(List userProperties) + public void WriteUserProperties(List? userProperties) { if (userProperties == null || userProperties.Count == 0) { @@ -306,7 +301,7 @@ public sealed class MqttV5PropertiesWriter _bufferWriter.WriteTwoByteInteger(value); } - void Write(MqttPropertyId id, string value) + void Write(MqttPropertyId id, string? value) { if (string.IsNullOrEmpty(value)) { @@ -317,7 +312,7 @@ public sealed class MqttV5PropertiesWriter _bufferWriter.WriteString(value); } - void Write(MqttPropertyId id, byte[] value) + void Write(MqttPropertyId id, byte[]? value) { if (value == null) { diff --git a/Source/MQTTnet/IMqttClient.cs b/Source/MQTTnet/IMqttClient.cs index 445fd4e1..4cc57c70 100644 --- a/Source/MQTTnet/IMqttClient.cs +++ b/Source/MQTTnet/IMqttClient.cs @@ -19,7 +19,7 @@ public interface IMqttClient : IDisposable bool IsConnected { get; } - MqttClientOptions Options { get; } + MqttClientOptions? Options { get; } Task ConnectAsync(MqttClientOptions options, CancellationToken cancellationToken = default); diff --git a/Source/MQTTnet/Implementations/CrossPlatformSocket.cs b/Source/MQTTnet/Implementations/CrossPlatformSocket.cs index dd923eb5..d514f24d 100644 --- a/Source/MQTTnet/Implementations/CrossPlatformSocket.cs +++ b/Source/MQTTnet/Implementations/CrossPlatformSocket.cs @@ -16,7 +16,7 @@ public sealed class CrossPlatformSocket : IDisposable { readonly Socket _socket; - NetworkStream _networkStream; + NetworkStream? _networkStream; public CrossPlatformSocket(AddressFamily addressFamily, ProtocolType protocolType) { @@ -50,13 +50,13 @@ public sealed class CrossPlatformSocket : IDisposable set => _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, value ? 1 : 0); } - public LingerOption LingerState + public LingerOption? LingerState { get => _socket.LingerState; - set => _socket.LingerState = value; + set => _socket.LingerState = value!; } - public EndPoint LocalEndPoint => _socket.LocalEndPoint; + public EndPoint? LocalEndPoint => _socket.LocalEndPoint; public bool NoDelay { @@ -70,7 +70,7 @@ public sealed class CrossPlatformSocket : IDisposable set => _socket.ReceiveBufferSize = value; } - public EndPoint RemoteEndPoint => _socket.RemoteEndPoint; + public EndPoint? RemoteEndPoint => _socket.RemoteEndPoint; public bool ReuseAddress { @@ -108,7 +108,7 @@ public sealed class CrossPlatformSocket : IDisposable set => _socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, value); } - public async Task AcceptAsync(CancellationToken cancellationToken) + public async Task AcceptAsync(CancellationToken cancellationToken) { try { diff --git a/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs b/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs index ef8f80ac..c36f28d5 100644 --- a/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs +++ b/Source/MQTTnet/Implementations/MqttClientAdapterFactory.cs @@ -12,7 +12,7 @@ namespace MQTTnet.Implementations; public sealed class MqttClientAdapterFactory : IMqttClientAdapterFactory { - public IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector packetInspector, IMqttNetLogger logger) + public IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector? packetInspector, IMqttNetLogger logger) { ArgumentNullException.ThrowIfNull(options); diff --git a/Source/MQTTnet/Implementations/MqttTcpChannel.cs b/Source/MQTTnet/Implementations/MqttTcpChannel.cs index 7333261c..ab2be271 100644 --- a/Source/MQTTnet/Implementations/MqttTcpChannel.cs +++ b/Source/MQTTnet/Implementations/MqttTcpChannel.cs @@ -20,10 +20,10 @@ namespace MQTTnet.Implementations; public sealed class MqttTcpChannel : IMqttChannel { - readonly MqttClientOptions _clientOptions; - readonly MqttClientTcpOptions _tcpOptions; + readonly MqttClientOptions? _clientOptions; + readonly MqttClientTcpOptions? _tcpOptions; - Stream _stream; + Stream? _stream; public MqttTcpChannel() { @@ -32,7 +32,7 @@ public sealed class MqttTcpChannel : IMqttChannel public MqttTcpChannel(MqttClientOptions clientOptions) : this() { _clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions)); - _tcpOptions = (MqttClientTcpOptions)clientOptions.ChannelOptions; + _tcpOptions = (MqttClientTcpOptions)clientOptions.ChannelOptions!; IsSecureConnection = clientOptions.ChannelOptions?.TlsOptions?.UseTls == true; } @@ -47,18 +47,18 @@ public sealed class MqttTcpChannel : IMqttChannel ClientCertificate = clientCertificate; } - public X509Certificate2 ClientCertificate { get; } + public X509Certificate2? ClientCertificate { get; } - public EndPoint RemoteEndPoint { get; private set; } + public EndPoint? RemoteEndPoint { get; private set; } public bool IsSecureConnection { get; } public async Task ConnectAsync(CancellationToken cancellationToken) { - CrossPlatformSocket socket = null; + CrossPlatformSocket? socket = null; try { - if (_tcpOptions.AddressFamily == AddressFamily.Unspecified) + if (_tcpOptions!.AddressFamily == AddressFamily.Unspecified) { socket = new CrossPlatformSocket(_tcpOptions.ProtocolType); } @@ -74,7 +74,7 @@ public sealed class MqttTcpChannel : IMqttChannel socket.ReceiveBufferSize = _tcpOptions.BufferSize; socket.SendBufferSize = _tcpOptions.BufferSize; - socket.SendTimeout = (int)_clientOptions.Timeout.TotalMilliseconds; + socket.SendTimeout = (int)_clientOptions!.Timeout.TotalMilliseconds; if (_tcpOptions.ProtocolType == ProtocolType.Tcp) { @@ -87,7 +87,7 @@ public sealed class MqttTcpChannel : IMqttChannel socket.LingerState = _tcpOptions.LingerState; } - if (_tcpOptions.DualMode.HasValue) + if (_tcpOptions.DualMode != null) { // It is important to avoid setting the flag if no specific value is set by the user // because on IPv4 only networks the setter will always throw an exception. Regardless @@ -95,7 +95,7 @@ public sealed class MqttTcpChannel : IMqttChannel socket.DualMode = _tcpOptions.DualMode.Value; } - await socket.ConnectAsync(_tcpOptions.RemoteEndpoint, cancellationToken).ConfigureAwait(false); + await socket.ConnectAsync(_tcpOptions.RemoteEndpoint!, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); @@ -285,13 +285,13 @@ public sealed class MqttTcpChannel : IMqttChannel object sender, string targetHost, X509CertificateCollection localCertificates, - X509Certificate remoteCertificate, + X509Certificate? remoteCertificate, string[] acceptableIssuers) { var certificateSelectionHandler = _tcpOptions?.TlsOptions?.CertificateSelectionHandler; if (certificateSelectionHandler != null) { - var eventArgs = new MqttClientCertificateSelectionEventArgs(targetHost, localCertificates, remoteCertificate, acceptableIssuers, _tcpOptions); + var eventArgs = new MqttClientCertificateSelectionEventArgs(targetHost, localCertificates, remoteCertificate, acceptableIssuers, _tcpOptions!); return certificateSelectionHandler(eventArgs); } @@ -300,15 +300,15 @@ public sealed class MqttTcpChannel : IMqttChannel return localCertificates[0]; } - return null; + return null!; } - bool InternalUserCertificateValidationCallback(object sender, X509Certificate x509Certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + bool InternalUserCertificateValidationCallback(object? sender, X509Certificate? x509Certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors) { var certificateValidationHandler = _tcpOptions?.TlsOptions?.CertificateValidationHandler; if (certificateValidationHandler != null) { - var eventArgs = new MqttClientCertificateValidationEventArgs(x509Certificate, chain, sslPolicyErrors, _tcpOptions); + var eventArgs = new MqttClientCertificateValidationEventArgs(x509Certificate, chain, sslPolicyErrors, _tcpOptions!); return certificateValidationHandler(eventArgs); } @@ -320,8 +320,8 @@ public sealed class MqttTcpChannel : IMqttChannel return sslPolicyErrors == SslPolicyErrors.None; } - X509CertificateCollection LoadCertificates() + X509CertificateCollection? LoadCertificates() { - return _tcpOptions.TlsOptions.ClientCertificatesProvider?.GetCertificates(); + return _tcpOptions!.TlsOptions.ClientCertificatesProvider?.GetCertificates(); } } \ No newline at end of file diff --git a/Source/MQTTnet/Implementations/MqttWebSocketChannel.cs b/Source/MQTTnet/Implementations/MqttWebSocketChannel.cs index 701cc279..9bd6f012 100644 --- a/Source/MQTTnet/Implementations/MqttWebSocketChannel.cs +++ b/Source/MQTTnet/Implementations/MqttWebSocketChannel.cs @@ -16,17 +16,17 @@ namespace MQTTnet.Implementations; public sealed class MqttWebSocketChannel : IMqttChannel { - readonly MqttClientWebSocketOptions _options; + readonly MqttClientWebSocketOptions? _options; - AsyncLock _sendLock = new(); - WebSocket _webSocket; + AsyncLock? _sendLock = new(); + WebSocket? _webSocket; public MqttWebSocketChannel(MqttClientWebSocketOptions options) { _options = options ?? throw new ArgumentNullException(nameof(options)); } - public MqttWebSocketChannel(WebSocket webSocket, EndPoint remoteEndPoint, bool isSecureConnection, X509Certificate2 clientCertificate) + public MqttWebSocketChannel(WebSocket webSocket, EndPoint? remoteEndPoint, bool isSecureConnection, X509Certificate2 clientCertificate) { _webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket)); @@ -35,15 +35,15 @@ public sealed class MqttWebSocketChannel : IMqttChannel ClientCertificate = clientCertificate; } - public X509Certificate2 ClientCertificate { get; } + public X509Certificate2? ClientCertificate { get; } - public EndPoint RemoteEndPoint { get; } + public EndPoint? RemoteEndPoint { get; } public bool IsSecureConnection { get; private set; } public async Task ConnectAsync(CancellationToken cancellationToken) { - var uri = _options.Uri; + var uri = _options!.Uri; if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase) && !uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase)) { if (_options.TlsOptions?.UseTls == true) @@ -96,7 +96,7 @@ public sealed class MqttWebSocketChannel : IMqttChannel public async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - var response = await _webSocket.ReceiveAsync(new ArraySegment(buffer, offset, count), cancellationToken).ConfigureAwait(false); + var response = await _webSocket!.ReceiveAsync(new ArraySegment(buffer, offset, count), cancellationToken).ConfigureAwait(false); return response.Count; } @@ -111,7 +111,7 @@ public sealed class MqttWebSocketChannel : IMqttChannel { length -= segment.Length; bool endOfPacket = isEndOfPacket && length == 0; - await _webSocket.SendAsync(segment, WebSocketMessageType.Binary, endOfPacket, cancellationToken).ConfigureAwait(false); + await _webSocket!.SendAsync(segment, WebSocketMessageType.Binary, endOfPacket, cancellationToken).ConfigureAwait(false); } } @@ -133,9 +133,9 @@ public sealed class MqttWebSocketChannel : IMqttChannel } } - WebProxy CreateProxy() + WebProxy? CreateProxy() { - if (string.IsNullOrEmpty(_options.ProxyOptions?.Address)) + if (string.IsNullOrEmpty(_options!.ProxyOptions?.Address)) { return null; } @@ -165,7 +165,7 @@ public sealed class MqttWebSocketChannel : IMqttChannel void SetupClientWebSocket(ClientWebSocket clientWebSocket) { - if (_options.ProxyOptions != null) + if (_options!.ProxyOptions != null) { clientWebSocket.Options.Proxy = CreateProxy(); } diff --git a/Source/MQTTnet/Internal/AsyncEventInvocator.cs b/Source/MQTTnet/Internal/AsyncEventInvocator.cs index d2527245..d952f52c 100644 --- a/Source/MQTTnet/Internal/AsyncEventInvocator.cs +++ b/Source/MQTTnet/Internal/AsyncEventInvocator.cs @@ -9,10 +9,10 @@ namespace MQTTnet.Internal; public readonly struct AsyncEventInvocator { - readonly Action _handler; - readonly Func _asyncHandler; + readonly Action? _handler; + readonly Func? _asyncHandler; - public AsyncEventInvocator(Action handler, Func asyncHandler) + public AsyncEventInvocator(Action? handler, Func? asyncHandler) { _handler = handler; _asyncHandler = asyncHandler; diff --git a/Source/MQTTnet/Internal/AsyncQueue.cs b/Source/MQTTnet/Internal/AsyncQueue.cs index f86a0902..f531cdac 100644 --- a/Source/MQTTnet/Internal/AsyncQueue.cs +++ b/Source/MQTTnet/Internal/AsyncQueue.cs @@ -70,7 +70,7 @@ public sealed class AsyncQueue : IDisposable { try { - Task task = null; + Task? task = null; lock (_syncRoot) { if (_isDisposed) diff --git a/Source/MQTTnet/Internal/AsyncQueueDequeueResult.cs b/Source/MQTTnet/Internal/AsyncQueueDequeueResult.cs index bdbf4f1b..f6778815 100644 --- a/Source/MQTTnet/Internal/AsyncQueueDequeueResult.cs +++ b/Source/MQTTnet/Internal/AsyncQueueDequeueResult.cs @@ -6,7 +6,7 @@ namespace MQTTnet.Internal; public sealed class AsyncQueueDequeueResult(bool isSuccess, TItem item) { - public static readonly AsyncQueueDequeueResult NonSuccess = new(false, default); + public static readonly AsyncQueueDequeueResult NonSuccess = new(false, default!); public bool IsSuccess { get; } = isSuccess; diff --git a/Source/MQTTnet/Internal/AsyncSignal.cs b/Source/MQTTnet/Internal/AsyncSignal.cs index d5f1589b..b8faa50a 100644 --- a/Source/MQTTnet/Internal/AsyncSignal.cs +++ b/Source/MQTTnet/Internal/AsyncSignal.cs @@ -14,7 +14,7 @@ public sealed class AsyncSignal : IDisposable bool _isDisposed; bool _isSignaled; - AsyncSignalWaiter _waiter; + AsyncSignalWaiter? _waiter; public void Dispose() { diff --git a/Source/MQTTnet/Internal/BlockingQueue.cs b/Source/MQTTnet/Internal/BlockingQueue.cs index 142c331f..f9cbf8db 100644 --- a/Source/MQTTnet/Internal/BlockingQueue.cs +++ b/Source/MQTTnet/Internal/BlockingQueue.cs @@ -15,7 +15,7 @@ public sealed class BlockingQueue : IDisposable readonly LinkedList _items = []; readonly object _syncRoot = new(); - ManualResetEventSlim _gate = new(false); + ManualResetEventSlim? _gate = new(false); public int Count { diff --git a/Source/MQTTnet/Internal/MqttPacketBus.cs b/Source/MQTTnet/Internal/MqttPacketBus.cs index e0b0652e..f7d24291 100644 --- a/Source/MQTTnet/Internal/MqttPacketBus.cs +++ b/Source/MQTTnet/Internal/MqttPacketBus.cs @@ -104,7 +104,7 @@ public sealed class MqttPacketBus : IDisposable _signal.Dispose(); } - public MqttPacketBusItem DropFirstItem(MqttPacketBusPartition partition) + public MqttPacketBusItem? DropFirstItem(MqttPacketBusPartition partition) { lock (_syncRoot) { diff --git a/Source/MQTTnet/Internal/MqttPacketBusItem.cs b/Source/MQTTnet/Internal/MqttPacketBusItem.cs index df02f726..9ac4bd37 100644 --- a/Source/MQTTnet/Internal/MqttPacketBusItem.cs +++ b/Source/MQTTnet/Internal/MqttPacketBusItem.cs @@ -8,18 +8,13 @@ using MQTTnet.Packets; namespace MQTTnet.Internal; -public sealed class MqttPacketBusItem +public sealed class MqttPacketBusItem(MqttPacket packet) { readonly AsyncTaskCompletionSource _promise = new(); - public MqttPacketBusItem(MqttPacket packet) - { - Packet = packet ?? throw new ArgumentNullException(nameof(packet)); - } + public event EventHandler? Completed; - public event EventHandler Completed; - - public MqttPacket Packet { get; } + public MqttPacket Packet { get; } = packet ?? throw new ArgumentNullException(nameof(packet)); public void Cancel() { diff --git a/Source/MQTTnet/Internal/TaskExtensions.cs b/Source/MQTTnet/Internal/TaskExtensions.cs index 753a6446..613a8f71 100644 --- a/Source/MQTTnet/Internal/TaskExtensions.cs +++ b/Source/MQTTnet/Internal/TaskExtensions.cs @@ -10,19 +10,19 @@ namespace MQTTnet.Internal; public static class TaskExtensions { - public static void RunInBackground(this Task task, MqttNetSourceLogger logger = null) + public static void RunInBackground(this Task? task, MqttNetSourceLogger? logger = null) { task?.ContinueWith( t => { // Consume the exception first so that we get no exception regarding the not observed exception. var exception = t.Exception; - logger?.Error(exception, "Unhandled exception in background task."); + logger?.Error(exception!, "Unhandled exception in background task."); }, TaskContinuationOptions.OnlyOnFaulted); } - public static async Task WaitAsync(this Task task, Task sender, MqttNetSourceLogger logger) + public static async Task WaitAsync(this Task? task, Task? sender, MqttNetSourceLogger logger) { ArgumentNullException.ThrowIfNull(logger); diff --git a/Source/MQTTnet/LowLevelClient/LowLevelMqttClient.cs b/Source/MQTTnet/LowLevelClient/LowLevelMqttClient.cs index eb839d8a..5c0ef6cf 100644 --- a/Source/MQTTnet/LowLevelClient/LowLevelMqttClient.cs +++ b/Source/MQTTnet/LowLevelClient/LowLevelMqttClient.cs @@ -21,7 +21,7 @@ public sealed class LowLevelMqttClient : ILowLevelMqttClient readonly MqttNetSourceLogger _logger; readonly IMqttNetLogger _rootLogger; - IMqttChannelAdapter _adapter; + IMqttChannelAdapter? _adapter; public LowLevelMqttClient(IMqttClientAdapterFactory clientAdapterFactory, IMqttNetLogger logger) { @@ -48,7 +48,7 @@ public sealed class LowLevelMqttClient : ILowLevelMqttClient throw new InvalidOperationException("Low level MQTT client is already connected. Disconnect first before connecting again."); } - MqttPacketInspector packetInspector = null; + MqttPacketInspector? packetInspector = null; if (_inspectPacketEvent.HasHandlers) { packetInspector = new MqttPacketInspector(_inspectPacketEvent, _rootLogger); diff --git a/Source/MQTTnet/MQTTnet.csproj b/Source/MQTTnet/MQTTnet.csproj index af4b7ca4..a89837ca 100644 --- a/Source/MQTTnet/MQTTnet.csproj +++ b/Source/MQTTnet/MQTTnet.csproj @@ -46,6 +46,8 @@ low latest-Recommended true + default + enable diff --git a/Source/MQTTnet/MqttApplicationMessage.cs b/Source/MQTTnet/MqttApplicationMessage.cs index ca7264f9..48952b91 100644 --- a/Source/MQTTnet/MqttApplicationMessage.cs +++ b/Source/MQTTnet/MqttApplicationMessage.cs @@ -18,7 +18,7 @@ public sealed class MqttApplicationMessage /// The content type must be a UTF-8 encoded string. The content type value identifies the kind of UTF-8 encoded /// payload. /// - public string ContentType { get; set; } + public string? ContentType { get; set; } /// /// Gets or sets the correlation data. @@ -26,7 +26,7 @@ public sealed class MqttApplicationMessage /// published message. /// Hint: MQTT 5 feature only. /// - public byte[] CorrelationData { get; set; } + public byte[]? CorrelationData { get; set; } /// /// If the DUP flag is set to 0, it indicates that this is the first occasion that the Client or Server has attempted @@ -94,7 +94,7 @@ public sealed class MqttApplicationMessage /// the request/response pattern between clients that is common in web applications. /// Hint: MQTT 5 feature only. /// - public string ResponseTopic { get; set; } + public string? ResponseTopic { get; set; } /// /// Gets or sets a value indicating whether the message should be retained or not. @@ -112,7 +112,7 @@ public sealed class MqttApplicationMessage /// the client when need to forward PUBLISH packets matching this subscription to this client. /// Hint: MQTT 5 feature only. /// - public List SubscriptionIdentifiers { get; set; } + public List? SubscriptionIdentifiers { get; set; } /// /// Gets or sets the MQTT topic. @@ -121,7 +121,7 @@ public sealed class MqttApplicationMessage /// The topic consists of one or more topic levels. Each topic level is separated by a forward slash (topic level /// separator). /// - public string Topic { get; set; } + public required string Topic { get; set; } /// /// Gets or sets the topic alias. @@ -141,5 +141,5 @@ public sealed class MqttApplicationMessage /// The feature is very similar to the HTTP header concept. /// Hint: MQTT 5 feature only. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } } \ No newline at end of file diff --git a/Source/MQTTnet/MqttApplicationMessageBuilder.cs b/Source/MQTTnet/MqttApplicationMessageBuilder.cs index 08a2a4a7..f1730444 100644 --- a/Source/MQTTnet/MqttApplicationMessageBuilder.cs +++ b/Source/MQTTnet/MqttApplicationMessageBuilder.cs @@ -18,19 +18,19 @@ namespace MQTTnet; public sealed class MqttApplicationMessageBuilder { - string _contentType; - byte[] _correlationData; + string? _contentType; + byte[]? _correlationData; uint _messageExpiryInterval; MqttPayloadFormatIndicator _payloadFormatIndicator; ReadOnlySequence _payload; MqttQualityOfServiceLevel _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce; - string _responseTopic; + string? _responseTopic; bool _retain; - List _subscriptionIdentifiers; - string _topic; + List? _subscriptionIdentifiers; + string? _topic; ushort _topicAlias; - List _userProperties; + List? _userProperties; public MqttApplicationMessage Build() { @@ -41,7 +41,7 @@ public sealed class MqttApplicationMessageBuilder var applicationMessage = new MqttApplicationMessage { - Topic = _topic, + Topic = _topic!, Payload = _payload, QualityOfServiceLevel = _qualityOfServiceLevel, Retain = _retain, @@ -88,7 +88,7 @@ public sealed class MqttApplicationMessageBuilder return this; } - public MqttApplicationMessageBuilder WithPayload(byte[] payload) + public MqttApplicationMessageBuilder WithPayload(byte[]? payload) { _payload = payload == null || payload.Length == 0 ? EmptyBuffer.ReadOnlySequence : new ReadOnlySequence(payload); return this; @@ -100,7 +100,7 @@ public sealed class MqttApplicationMessageBuilder return this; } - public MqttApplicationMessageBuilder WithPayload(IEnumerable payload) + public MqttApplicationMessageBuilder WithPayload(IEnumerable? payload) { if (payload == null) { @@ -120,12 +120,12 @@ public sealed class MqttApplicationMessageBuilder return WithPayload(payload.ToArray()); } - public MqttApplicationMessageBuilder WithPayload(Stream payload) + public MqttApplicationMessageBuilder WithPayload(Stream? payload) { return payload == null ? WithPayload(default(byte[])) : WithPayload(payload, payload.Length - payload.Position); } - public MqttApplicationMessageBuilder WithPayload(Stream payload, long length) + public MqttApplicationMessageBuilder WithPayload(Stream? payload, long length) { if (payload == null || length == 0) { @@ -148,7 +148,7 @@ public sealed class MqttApplicationMessageBuilder return WithPayload(payloadBuffer); } - public MqttApplicationMessageBuilder WithPayload(string payload) + public MqttApplicationMessageBuilder WithPayload(string? payload) { if (string.IsNullOrEmpty(payload)) { diff --git a/Source/MQTTnet/MqttApplicationMessageExtensions.cs b/Source/MQTTnet/MqttApplicationMessageExtensions.cs index eef59cb5..68e982ca 100644 --- a/Source/MQTTnet/MqttApplicationMessageExtensions.cs +++ b/Source/MQTTnet/MqttApplicationMessageExtensions.cs @@ -9,7 +9,7 @@ namespace MQTTnet; public static class MqttApplicationMessageExtensions { - public static string ConvertPayloadToString(this MqttApplicationMessage applicationMessage) + public static string? ConvertPayloadToString(this MqttApplicationMessage applicationMessage) { ArgumentNullException.ThrowIfNull(applicationMessage); diff --git a/Source/MQTTnet/MqttClient.cs b/Source/MQTTnet/MqttClient.cs index 8f278b85..4b2682f1 100644 --- a/Source/MQTTnet/MqttClient.cs +++ b/Source/MQTTnet/MqttClient.cs @@ -29,7 +29,7 @@ public sealed class MqttClient : Disposable, IMqttClient readonly MqttPacketIdentifierProvider _packetIdentifierProvider = new(); readonly IMqttNetLogger _rootLogger; - IMqttChannelAdapter _adapter; + IMqttChannelAdapter? _adapter; bool _cleanDisconnectInitiated; volatile int _connectionStatus; @@ -37,18 +37,18 @@ public sealed class MqttClient : Disposable, IMqttClient // The value for this field can be set from two different enums. // They contain the same values but the set is reduced in one case. int _disconnectReason; - string _disconnectReasonString; - List _disconnectUserProperties; + string? _disconnectReasonString; + List? _disconnectUserProperties; - Task _keepAlivePacketsSenderTask; + Task? _keepAlivePacketsSenderTask; DateTime _lastPacketSentTimestamp; - CancellationTokenSource _mqttClientAlive; - MqttPacketDispatcher _packetDispatcher; - Task _packetReceiverTask; - AsyncQueue _publishPacketReceiverQueue; - Task _publishPacketReceiverTask; - MqttDisconnectPacket _unexpectedDisconnectPacket; + CancellationTokenSource? _mqttClientAlive; + MqttPacketDispatcher? _packetDispatcher; + Task? _packetReceiverTask; + AsyncQueue? _publishPacketReceiverQueue; + Task? _publishPacketReceiverTask; + MqttDisconnectPacket? _unexpectedDisconnectPacket; public MqttClient(IMqttClientAdapterFactory channelFactory, IMqttNetLogger logger) { @@ -89,7 +89,7 @@ public sealed class MqttClient : Disposable, IMqttClient public bool IsConnected => (MqttClientConnectionStatus)_connectionStatus == MqttClientConnectionStatus.Connected; - public MqttClientOptions Options { get; private set; } + public MqttClientOptions? Options { get; private set; } public async Task ConnectAsync(MqttClientOptions options, CancellationToken cancellationToken = default) { @@ -102,7 +102,7 @@ public sealed class MqttClient : Disposable, IMqttClient throw new InvalidOperationException("Not allowed to connect while connect/disconnect is pending."); } - MqttClientConnectResult connectResult = null; + MqttClientConnectResult? connectResult = null; try { @@ -202,9 +202,9 @@ public sealed class MqttClient : Disposable, IMqttClient _disconnectReason = (int)options.Reason; _cleanDisconnectInitiated = true; - if (Options.ValidateFeatures) + if (Options!.ValidateFeatures) { - MqttClientDisconnectOptionsValidator.ThrowIfNotSupported(options, _adapter.PacketFormatterAdapter.ProtocolVersion); + MqttClientDisconnectOptionsValidator.ThrowIfNotSupported(options, _adapter!.PacketFormatterAdapter.ProtocolVersion); } // Sending the DISCONNECT may fail due to connection issues. The resulting exception @@ -240,7 +240,7 @@ public sealed class MqttClient : Disposable, IMqttClient } else { - using var timeout = new CancellationTokenSource(Options.Timeout); + using var timeout = new CancellationTokenSource(Options!.Timeout); await Request(MqttPingReqPacket.Instance, timeout.Token).ConfigureAwait(false); } } @@ -254,9 +254,9 @@ public sealed class MqttClient : Disposable, IMqttClient ThrowIfDisposed(); ThrowIfNotConnected(); - if (Options.ValidateFeatures) + if (Options!.ValidateFeatures) { - MqttApplicationMessageValidator.ThrowIfNotSupported(applicationMessage, _adapter.PacketFormatterAdapter.ProtocolVersion); + MqttApplicationMessageValidator.ThrowIfNotSupported(applicationMessage, _adapter!.PacketFormatterAdapter.ProtocolVersion); } var publishPacket = MqttPublishPacketFactory.Create(applicationMessage); @@ -292,7 +292,7 @@ public sealed class MqttClient : Disposable, IMqttClient var authPacket = new MqttAuthPacket { // This must always be equal to the value from the CONNECT packet. So we use it here to ensure that. - AuthenticationMethod = Options.AuthenticationMethod, + AuthenticationMethod = Options!.AuthenticationMethod, AuthenticationData = data.AuthenticationData, ReasonString = data.ReasonString, ReasonCode = data.ReasonCode, @@ -314,9 +314,9 @@ public sealed class MqttClient : Disposable, IMqttClient ThrowIfDisposed(); ThrowIfNotConnected(); - if (Options.ValidateFeatures) + if (Options!.ValidateFeatures) { - MqttClientSubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter.PacketFormatterAdapter.ProtocolVersion); + MqttClientSubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter!.PacketFormatterAdapter.ProtocolVersion); } var subscribePacket = MqttSubscribePacketFactory.Create(options); @@ -348,9 +348,9 @@ public sealed class MqttClient : Disposable, IMqttClient ThrowIfDisposed(); ThrowIfNotConnected(); - if (Options.ValidateFeatures) + if (Options!.ValidateFeatures) { - MqttClientUnsubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter.PacketFormatterAdapter.ProtocolVersion); + MqttClientUnsubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter!.PacketFormatterAdapter.ProtocolVersion); } var unsubscribePacket = MqttUnsubscribePacketFactory.Create(options); @@ -465,8 +465,8 @@ public sealed class MqttClient : Disposable, IMqttClient Task HandleEnhancedAuthentication(MqttAuthPacket authPacket, CancellationToken cancellationToken) { - var eventArgs = new MqttEnhancedAuthenticationEventArgs(authPacket, _adapter, cancellationToken); - return Options.EnhancedAuthenticationHandler.HandleEnhancedAuthenticationAsync(eventArgs); + var eventArgs = new MqttEnhancedAuthenticationEventArgs(authPacket, _adapter!, cancellationToken); + return Options!.EnhancedAuthenticationHandler!.HandleEnhancedAuthenticationAsync(eventArgs); } void Cleanup() @@ -498,10 +498,10 @@ public sealed class MqttClient : Disposable, IMqttClient async Task ConnectInternal(IMqttChannelAdapter channelAdapter, CancellationToken cancellationToken) { - var backgroundCancellationToken = _mqttClientAlive.Token; + var backgroundCancellationToken = _mqttClientAlive!.Token; using var effectiveCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(backgroundCancellationToken, cancellationToken); - _logger.Verbose("Trying to connect with server '{0}'", Options.ChannelOptions); + _logger.Verbose("Trying to connect with server '{0}'", Options!.ChannelOptions); await channelAdapter.ConnectAsync(effectiveCancellationToken.Token).ConfigureAwait(false); _logger.Verbose("Connection with server established"); @@ -520,7 +520,7 @@ public sealed class MqttClient : Disposable, IMqttClient return connectResult; } - async Task DisconnectCore(Task sender, Exception exception, MqttClientConnectResult connectResult, bool clientWasConnected) + async Task DisconnectCore(Task? sender, Exception? exception, MqttClientConnectResult? connectResult, bool clientWasConnected) { TryInitiateDisconnect(); @@ -528,7 +528,7 @@ public sealed class MqttClient : Disposable, IMqttClient { if (_adapter != null) { - _logger.Verbose("Disconnecting [Timeout={0}]", Options.Timeout); + _logger.Verbose("Disconnecting [Timeout={0}]", Options!.Timeout); using var timeout = new CancellationTokenSource(Options.Timeout); await _adapter.DisconnectAsync(timeout.Token).ConfigureAwait(false); @@ -543,7 +543,7 @@ public sealed class MqttClient : Disposable, IMqttClient try { - _packetDispatcher?.Dispose(new MqttClientDisconnectedException(exception)); + _packetDispatcher?.Dispose(new MqttClientDisconnectedException(exception!)); var receiverTask = _packetReceiverTask.WaitAsync(sender, _logger); var publishPacketReceiverTask = _publishPacketReceiverTask.WaitAsync(sender, _logger); @@ -577,7 +577,7 @@ public sealed class MqttClient : Disposable, IMqttClient } } - Task DisconnectInternal(Task sender, Exception exception, MqttClientConnectResult connectResult) + Task DisconnectInternal(Task? sender, Exception? exception, MqttClientConnectResult? connectResult) { var clientWasConnected = IsConnected; @@ -615,7 +615,7 @@ public sealed class MqttClient : Disposable, IMqttClient { try { - _publishPacketReceiverQueue.Enqueue(publishPacket); + _publishPacketReceiverQueue!.Enqueue(publishPacket); } catch (Exception exception) { @@ -626,7 +626,7 @@ public sealed class MqttClient : Disposable, IMqttClient async Task HandleReceivedApplicationMessage(MqttPublishPacket publishPacket) { var applicationMessage = MqttApplicationMessageFactory.Create(publishPacket); - var eventArgs = new MqttApplicationMessageReceivedEventArgs(Options.ClientId, applicationMessage, publishPacket, AcknowledgeReceivedPublishPacket); + var eventArgs = new MqttApplicationMessageReceivedEventArgs(Options!.ClientId, applicationMessage, publishPacket, AcknowledgeReceivedPublishPacket); await _events.ApplicationMessageReceivedEvent.InvokeAsync(eventArgs).ConfigureAwait(false); return eventArgs; @@ -645,7 +645,7 @@ public sealed class MqttClient : Disposable, IMqttClient Task ProcessReceivedAuthPacket(MqttAuthPacket authPacket, CancellationToken cancellationToken) { - if (Options.EnhancedAuthenticationHandler == null) + if (Options!.EnhancedAuthenticationHandler == null) { // From RFC: If the re-authentication fails, the Client or Server SHOULD send DISCONNECT with an appropriate Reason Code // as described in section 4.13, and MUST close the Network Connection [MQTT-4.12.1-2]. @@ -661,7 +661,7 @@ public sealed class MqttClient : Disposable, IMqttClient return CompletedTask.Instance; } - var eventArgs = new MqttEnhancedAuthenticationEventArgs(authPacket, _adapter, cancellationToken); + var eventArgs = new MqttEnhancedAuthenticationEventArgs(authPacket, _adapter!, cancellationToken); return Options.EnhancedAuthenticationHandler.HandleEnhancedAuthenticationAsync(eventArgs); } @@ -673,7 +673,7 @@ public sealed class MqttClient : Disposable, IMqttClient _unexpectedDisconnectPacket = disconnectPacket; // Also dispatch disconnect to waiting threads to generate a proper exception. - _packetDispatcher.Dispose(new MqttClientUnexpectedDisconnectReceivedException(disconnectPacket)); + _packetDispatcher!.Dispose(new MqttClientUnexpectedDisconnectReceivedException(disconnectPacket)); return DisconnectInternal(_packetReceiverTask, null, null); } @@ -684,7 +684,7 @@ public sealed class MqttClient : Disposable, IMqttClient { try { - var publishPacketDequeueResult = await _publishPacketReceiverQueue.TryDequeueAsync(cancellationToken).ConfigureAwait(false); + var publishPacketDequeueResult = await _publishPacketReceiverQueue!.TryDequeueAsync(cancellationToken).ConfigureAwait(false); if (!publishPacketDequeueResult.IsSuccess) { return; @@ -713,7 +713,7 @@ public sealed class MqttClient : Disposable, IMqttClient Task ProcessReceivedPubRecPacket(MqttPubRecPacket pubRecPacket, CancellationToken cancellationToken) { - if (_packetDispatcher.TryDispatch(pubRecPacket)) + if (_packetDispatcher!.TryDispatch(pubRecPacket)) { return CompletedTask.Instance; } @@ -776,11 +776,11 @@ public sealed class MqttClient : Disposable, IMqttClient return MqttClientPublishResultFactory.Create(pubRecPacket, pubCompPacket); } - async Task Receive(CancellationToken cancellationToken) + async Task Receive(CancellationToken cancellationToken) { - var packetTask = _adapter.ReceivePacketAsync(cancellationToken); + var packetTask = _adapter!.ReceivePacketAsync(cancellationToken); - MqttPacket packet; + MqttPacket? packet; if (packetTask.IsCompleted) { packet = packetTask.Result; @@ -863,7 +863,7 @@ public sealed class MqttClient : Disposable, IMqttClient packetIdentifier = packetWithIdentifier.PacketIdentifier; } - using var packetAwaitable = _packetDispatcher.AddAwaitable(packetIdentifier); + using var packetAwaitable = _packetDispatcher?.AddAwaitable(packetIdentifier); try { await Send(requestPacket, cancellationToken).ConfigureAwait(false); @@ -871,12 +871,12 @@ public sealed class MqttClient : Disposable, IMqttClient catch (Exception exception) { _logger.Warning(exception, "Error when sending {0} request packet", requestPacket.GetType().Name); - packetAwaitable.Fail(exception); + packetAwaitable?.Fail(exception); } try { - return await packetAwaitable.WaitOneAsync(cancellationToken).ConfigureAwait(false); + return await packetAwaitable!.WaitOneAsync(cancellationToken).ConfigureAwait(false); } catch (Exception exception) { @@ -895,7 +895,7 @@ public sealed class MqttClient : Disposable, IMqttClient _lastPacketSentTimestamp = DateTime.UtcNow; - return _adapter.SendPacketAsync(packet, cancellationToken); + return _adapter!.SendPacketAsync(packet, cancellationToken); } void ThrowIfConnected(string message) @@ -971,13 +971,13 @@ public sealed class MqttClient : Disposable, IMqttClient await ProcessReceivedAuthPacket(authPacket, cancellationToken).ConfigureAwait(false); break; case MqttPingRespPacket _: - _packetDispatcher.TryDispatch(packet); + _packetDispatcher!.TryDispatch(packet); break; case MqttPingReqPacket _: throw new MqttProtocolViolationException("The PINGREQ Packet is sent from a client to the server only."); default: { - if (!_packetDispatcher.TryDispatch(packet)) + if (!_packetDispatcher!.TryDispatch(packet)) { throw new MqttProtocolViolationException($"Received packet '{packet}' at an unexpected time."); } @@ -1018,7 +1018,7 @@ public sealed class MqttClient : Disposable, IMqttClient { _logger.Verbose("Start sending keep alive packets"); - var keepAlivePeriod = Options.KeepAlivePeriod; + var keepAlivePeriod = Options!.KeepAlivePeriod; while (!cancellationToken.IsCancellationRequested) { diff --git a/Source/MQTTnet/MqttClientExtensions.cs b/Source/MQTTnet/MqttClientExtensions.cs index 58d9c9f0..8b81f0d7 100644 --- a/Source/MQTTnet/MqttClientExtensions.cs +++ b/Source/MQTTnet/MqttClientExtensions.cs @@ -18,9 +18,9 @@ public static class MqttClientExtensions public static Task DisconnectAsync( this IMqttClient client, MqttClientDisconnectOptionsReason reason = MqttClientDisconnectOptionsReason.NormalDisconnection, - string reasonString = null, + string? reasonString = null, uint sessionExpiryInterval = 0, - List userProperties = null, + List? userProperties = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(client); @@ -39,7 +39,7 @@ public static class MqttClientExtensions public static Task PublishBinaryAsync( this IMqttClient mqttClient, string topic, - IEnumerable payload = null, + IEnumerable? payload = null, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false, CancellationToken cancellationToken = default) @@ -79,7 +79,7 @@ public static class MqttClientExtensions public static Task PublishStringAsync( this IMqttClient mqttClient, string topic, - string payload = null, + string? payload = null, MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false, CancellationToken cancellationToken = default) @@ -133,7 +133,7 @@ public static class MqttClientExtensions public static async Task TryDisconnectAsync( this IMqttClient client, MqttClientDisconnectOptionsReason reason = MqttClientDisconnectOptionsReason.NormalDisconnection, - string reasonString = null) + string? reasonString = null) { ArgumentNullException.ThrowIfNull(client); diff --git a/Source/MQTTnet/MqttTopicFilterBuilder.cs b/Source/MQTTnet/MqttTopicFilterBuilder.cs index a927e5a7..236d4642 100644 --- a/Source/MQTTnet/MqttTopicFilterBuilder.cs +++ b/Source/MQTTnet/MqttTopicFilterBuilder.cs @@ -25,7 +25,7 @@ public sealed class MqttTopicFilterBuilder /// In MQTT, the word topic refers to an UTF-8 string that the broker uses to filter messages for each connected client. /// The topic consists of one or more topic levels. Each topic level is separated by a forward slash (topic level separator). /// - string _topic; + string? _topic; bool _noLocal; bool _retainAsPublished; MqttRetainHandling _retainHandling = MqttRetainHandling.SendAtSubscribe; diff --git a/Source/MQTTnet/Options/DefaultMqttCertificatesProvider.cs b/Source/MQTTnet/Options/DefaultMqttCertificatesProvider.cs index 5285a2a1..dfd1e659 100644 --- a/Source/MQTTnet/Options/DefaultMqttCertificatesProvider.cs +++ b/Source/MQTTnet/Options/DefaultMqttCertificatesProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; @@ -9,18 +10,17 @@ namespace MQTTnet; public sealed class DefaultMqttCertificatesProvider : IMqttClientCertificatesProvider { - readonly X509Certificate2Collection _certificates; + readonly X509Certificate2Collection _certificates = new(); public DefaultMqttCertificatesProvider(X509Certificate2Collection certificates) { - _certificates = certificates; + _certificates = certificates ?? throw new ArgumentNullException(nameof(certificates)); } - public DefaultMqttCertificatesProvider(IEnumerable certificates) + public DefaultMqttCertificatesProvider(IEnumerable? certificates) { if (certificates != null) { - _certificates = []; foreach (var certificate in certificates) { _certificates.Add(certificate); diff --git a/Source/MQTTnet/Options/IMqttClientChannelOptions.cs b/Source/MQTTnet/Options/IMqttClientChannelOptions.cs index 9642c7f9..60a53107 100644 --- a/Source/MQTTnet/Options/IMqttClientChannelOptions.cs +++ b/Source/MQTTnet/Options/IMqttClientChannelOptions.cs @@ -6,5 +6,5 @@ namespace MQTTnet; public interface IMqttClientChannelOptions { - MqttClientTlsOptions TlsOptions { get; } + MqttClientTlsOptions? TlsOptions { get; } } \ No newline at end of file diff --git a/Source/MQTTnet/Options/IMqttClientCredentialsProvider.cs b/Source/MQTTnet/Options/IMqttClientCredentialsProvider.cs index 394388d0..f26dbf7f 100644 --- a/Source/MQTTnet/Options/IMqttClientCredentialsProvider.cs +++ b/Source/MQTTnet/Options/IMqttClientCredentialsProvider.cs @@ -6,6 +6,6 @@ namespace MQTTnet; public interface IMqttClientCredentialsProvider { - byte[] GetPassword(MqttClientOptions clientOptions); + byte[]? GetPassword(MqttClientOptions clientOptions); string GetUserName(MqttClientOptions clientOptions); } \ No newline at end of file diff --git a/Source/MQTTnet/Options/MqttClientCertificateSelectionEventArgs.cs b/Source/MQTTnet/Options/MqttClientCertificateSelectionEventArgs.cs index ad688539..15cd1614 100644 --- a/Source/MQTTnet/Options/MqttClientCertificateSelectionEventArgs.cs +++ b/Source/MQTTnet/Options/MqttClientCertificateSelectionEventArgs.cs @@ -11,23 +11,26 @@ public sealed class MqttClientCertificateSelectionEventArgs : EventArgs { public MqttClientCertificateSelectionEventArgs( string targetHost, - X509CertificateCollection localCertificates, - X509Certificate remoteCertificate, + X509CertificateCollection? localCertificates, + X509Certificate? remoteCertificate, string[] acceptableIssuers, MqttClientTcpOptions tcpOptions) { TargetHost = targetHost; LocalCertificates = localCertificates; - RemoveCertificate = remoteCertificate; + RemoteCertificate = remoteCertificate; AcceptableIssuers = acceptableIssuers; TcpOptions = tcpOptions ?? throw new ArgumentNullException(nameof(tcpOptions)); } public string[] AcceptableIssuers { get; } - public X509CertificateCollection LocalCertificates { get; } + public X509CertificateCollection? LocalCertificates { get; } - public X509Certificate RemoveCertificate { get; } + [Obsolete("Typo! Use RemoteCertificate instead!")] + public X509Certificate? RemoveCertificate => RemoteCertificate; + + public X509Certificate? RemoteCertificate { get; } public string TargetHost { get; } diff --git a/Source/MQTTnet/Options/MqttClientCertificateValidationEventArgs.cs b/Source/MQTTnet/Options/MqttClientCertificateValidationEventArgs.cs index 8f1eed10..42ea55db 100644 --- a/Source/MQTTnet/Options/MqttClientCertificateValidationEventArgs.cs +++ b/Source/MQTTnet/Options/MqttClientCertificateValidationEventArgs.cs @@ -10,7 +10,7 @@ namespace MQTTnet; public sealed class MqttClientCertificateValidationEventArgs : EventArgs { - public MqttClientCertificateValidationEventArgs(X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors, IMqttClientChannelOptions clientOptions) + public MqttClientCertificateValidationEventArgs(X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors, IMqttClientChannelOptions clientOptions) { Certificate = certificate; Chain = chain; @@ -18,9 +18,9 @@ public sealed class MqttClientCertificateValidationEventArgs : EventArgs ClientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions)); } - public X509Certificate Certificate { get; } + public X509Certificate? Certificate { get; } - public X509Chain Chain { get; } + public X509Chain? Chain { get; } public IMqttClientChannelOptions ClientOptions { get; } diff --git a/Source/MQTTnet/Options/MqttClientCredentials.cs b/Source/MQTTnet/Options/MqttClientCredentials.cs index 0de96c0f..f0e7c8cb 100644 --- a/Source/MQTTnet/Options/MqttClientCredentials.cs +++ b/Source/MQTTnet/Options/MqttClientCredentials.cs @@ -6,16 +6,16 @@ namespace MQTTnet; public sealed class MqttClientCredentials : IMqttClientCredentialsProvider { - readonly byte[] _password; + readonly byte[]? _password; readonly string _userName; - public MqttClientCredentials(string userName, byte[] password = null) + public MqttClientCredentials(string userName, byte[]? password = null) { _userName = userName; _password = password; } - public byte[] GetPassword(MqttClientOptions clientOptions) + public byte[]? GetPassword(MqttClientOptions clientOptions) { return _password; } diff --git a/Source/MQTTnet/Options/MqttClientDefaultCertificateValidationHandler.cs b/Source/MQTTnet/Options/MqttClientDefaultCertificateValidationHandler.cs index 28ba4eaa..813825d9 100644 --- a/Source/MQTTnet/Options/MqttClientDefaultCertificateValidationHandler.cs +++ b/Source/MQTTnet/Options/MqttClientDefaultCertificateValidationHandler.cs @@ -17,7 +17,7 @@ public sealed class MqttClientDefaultCertificateValidationHandler return true; } - if (eventArgs.Chain.ChainStatus.Any( + if (eventArgs.Chain!.ChainStatus.Any( c => c.Status is X509ChainStatusFlags.RevocationStatusUnknown or X509ChainStatusFlags.Revoked or X509ChainStatusFlags.OfflineRevocation)) { if (eventArgs.ClientOptions?.TlsOptions?.IgnoreCertificateRevocationErrors != true) diff --git a/Source/MQTTnet/Options/MqttClientOptions.cs b/Source/MQTTnet/Options/MqttClientOptions.cs index 85fc5886..f85c0d65 100644 --- a/Source/MQTTnet/Options/MqttClientOptions.cs +++ b/Source/MQTTnet/Options/MqttClientOptions.cs @@ -24,15 +24,15 @@ public sealed class MqttClientOptions /// Gets or sets the authentication data. /// MQTT 5.0.0+ feature. /// - public byte[] AuthenticationData { get; set; } + public byte[]? AuthenticationData { get; set; } /// /// Gets or sets the authentication method. /// MQTT 5.0.0+ feature. /// - public string AuthenticationMethod { get; set; } + public string? AuthenticationMethod { get; set; } - public IMqttClientChannelOptions ChannelOptions { get; set; } + public IMqttClientChannelOptions? ChannelOptions { get; set; } /// /// Gets or sets a value indicating whether clean sessions are used or not. @@ -52,14 +52,14 @@ public sealed class MqttClientOptions /// public string ClientId { get; set; } = Guid.NewGuid().ToString("N"); - public IMqttClientCredentialsProvider Credentials { get; set; } + public IMqttClientCredentialsProvider? Credentials { get; set; } /// /// Gets or sets the handler for AUTH packets. /// This can happen when connecting or at any time while being already connected. /// MQTT 5.0.0+ feature. /// - public IMqttEnhancedAuthenticationHandler EnhancedAuthenticationHandler { get; set; } + public IMqttEnhancedAuthenticationHandler? EnhancedAuthenticationHandler { get; set; } /// /// Gets or sets the keep alive period. @@ -143,7 +143,7 @@ public sealed class MqttClientOptions /// The feature is very similar to the HTTP header concept. /// MQTT 5.0.0+ feature. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } /// /// When this feature is enabled the client will check if used properties are supported in the selected protocol @@ -158,13 +158,13 @@ public sealed class MqttClientOptions /// Gets or sets the content type of the will message. /// MQTT 5.0.0+ feature. /// - public string WillContentType { get; set; } + public string? WillContentType { get; set; } /// /// Gets or sets the correlation data of the will message. /// MQTT 5.0.0+ feature. /// - public byte[] WillCorrelationData { get; set; } + public byte[]? WillCorrelationData { get; set; } /// /// Gets or sets the will delay interval. @@ -182,7 +182,7 @@ public sealed class MqttClientOptions /// /// Gets or sets the payload of the will message. /// - public byte[] WillPayload { get; set; } + public byte[]? WillPayload { get; set; } /// /// Gets or sets the payload format indicator of the will message. @@ -199,7 +199,7 @@ public sealed class MqttClientOptions /// Gets or sets the response topic of the will message. /// MQTT 5.0.0+ feature. /// - public string WillResponseTopic { get; set; } + public string? WillResponseTopic { get; set; } /// /// Gets or sets the retain flag of the will message. @@ -209,13 +209,13 @@ public sealed class MqttClientOptions /// /// Gets or sets the topic of the will message. /// - public string WillTopic { get; set; } + public string? WillTopic { get; set; } /// /// Gets or sets the user properties of the will message. /// MQTT 5.0.0+ feature. /// - public List WillUserProperties { get; set; } + public List? WillUserProperties { get; set; } /// /// Gets or sets the default and initial size of the packet write buffer. diff --git a/Source/MQTTnet/Options/MqttClientOptionsBuilder.cs b/Source/MQTTnet/Options/MqttClientOptionsBuilder.cs index 3c2f589f..3d71e25b 100644 --- a/Source/MQTTnet/Options/MqttClientOptionsBuilder.cs +++ b/Source/MQTTnet/Options/MqttClientOptionsBuilder.cs @@ -18,10 +18,10 @@ public sealed class MqttClientOptionsBuilder readonly MqttClientOptions _options = new(); int? _port; - EndPoint _remoteEndPoint; - MqttClientTcpOptions _tcpOptions; - MqttClientTlsOptions _tlsOptions; - MqttClientWebSocketOptions _webSocketOptions; + EndPoint? _remoteEndPoint; + MqttClientTcpOptions? _tcpOptions; + MqttClientTlsOptions? _tlsOptions; + MqttClientWebSocketOptions? _webSocketOptions; public MqttClientOptions Build() { @@ -38,7 +38,7 @@ public sealed class MqttClientOptionsBuilder if (_tcpOptions != null) { - _tcpOptions.TlsOptions = tlsOptions; + _tcpOptions.TlsOptions = tlsOptions!; if (_remoteEndPoint == null) { @@ -49,7 +49,7 @@ public sealed class MqttClientOptionsBuilder { if (dns.Port == 0) { - if (_port.HasValue) + if (_port != null) { _remoteEndPoint = new DnsEndPoint(dns.Host, _port.Value, dns.AddressFamily); } @@ -64,7 +64,7 @@ public sealed class MqttClientOptionsBuilder { if (ip.Port == 0) { - if (_port.HasValue) + if (_port != null) { _remoteEndPoint = new IPEndPoint(ip.Address, _port.Value); } @@ -82,10 +82,10 @@ public sealed class MqttClientOptionsBuilder } else if (_webSocketOptions != null) { - _webSocketOptions.TlsOptions = tlsOptions; + _webSocketOptions.TlsOptions = tlsOptions!; } - _options.ChannelOptions = (IMqttClientChannelOptions)_tcpOptions ?? _webSocketOptions; + _options.ChannelOptions = (IMqttClientChannelOptions?)_tcpOptions ?? _webSocketOptions; MqttClientOptionsValidator.ThrowIfNotSupported(_options); @@ -94,7 +94,7 @@ public sealed class MqttClientOptionsBuilder public MqttClientOptionsBuilder WithAddressFamily(AddressFamily addressFamily) { - _tcpOptions.AddressFamily = addressFamily; + _tcpOptions!.AddressFamily = addressFamily; return this; } @@ -174,9 +174,9 @@ public sealed class MqttClientOptionsBuilder return WithConnectionUri(new Uri(uri, UriKind.Absolute)); } - public MqttClientOptionsBuilder WithCredentials(string username, string password) + public MqttClientOptionsBuilder WithCredentials(string username, string? password) { - byte[] passwordBuffer = null; + byte[]? passwordBuffer = null; if (password != null) { @@ -186,7 +186,7 @@ public sealed class MqttClientOptionsBuilder return WithCredentials(username, passwordBuffer); } - public MqttClientOptionsBuilder WithCredentials(string username, byte[] password = null) + public MqttClientOptionsBuilder WithCredentials(string username, byte[]? password = null) { return WithCredentials(new MqttClientCredentials(username, password)); } @@ -205,7 +205,7 @@ public sealed class MqttClientOptionsBuilder return this; } - public MqttClientOptionsBuilder WithEnhancedAuthentication(string method, byte[] data = null) + public MqttClientOptionsBuilder WithEnhancedAuthentication(string method, byte[]? data = null) { _options.AuthenticationMethod = method; _options.AuthenticationData = data; @@ -249,7 +249,7 @@ public sealed class MqttClientOptionsBuilder public MqttClientOptionsBuilder WithProtocolType(ProtocolType protocolType) { - _tcpOptions.ProtocolType = protocolType; + _tcpOptions!.ProtocolType = protocolType; return this; } @@ -405,7 +405,7 @@ public sealed class MqttClientOptionsBuilder return this; } - public MqttClientOptionsBuilder WithWillPayload(byte[] willPayload) + public MqttClientOptionsBuilder WithWillPayload(byte[]? willPayload) { _options.WillPayload = willPayload; return this; @@ -423,11 +423,11 @@ public sealed class MqttClientOptionsBuilder return this; } - public MqttClientOptionsBuilder WithWillPayload(string willPayload) + public MqttClientOptionsBuilder WithWillPayload(string? willPayload) { if (string.IsNullOrEmpty(willPayload)) { - return WithWillPayload((byte[])null); + return WithWillPayload((byte[]?)null); } _options.WillPayload = Encoding.UTF8.GetBytes(willPayload); diff --git a/Source/MQTTnet/Options/MqttClientTcpOptions.cs b/Source/MQTTnet/Options/MqttClientTcpOptions.cs index d0856f3b..529f9f13 100644 --- a/Source/MQTTnet/Options/MqttClientTcpOptions.cs +++ b/Source/MQTTnet/Options/MqttClientTcpOptions.cs @@ -26,7 +26,7 @@ public sealed class MqttClientTcpOptions : IMqttClientChannelOptions /// Gets the local endpoint (network card) which is used by the client. /// Set it to _null_ to let the OS select the network card. /// - public EndPoint LocalEndpoint { get; set; } + public EndPoint? LocalEndpoint { get; set; } /// /// Enables or disables the Nagle algorithm for the socket. @@ -42,7 +42,7 @@ public sealed class MqttClientTcpOptions : IMqttClientChannelOptions /// public ProtocolType ProtocolType { get; set; } = ProtocolType.Tcp; - public EndPoint RemoteEndpoint { get; set; } + public EndPoint? RemoteEndpoint { get; set; } public MqttClientTlsOptions TlsOptions { get; set; } = new(); diff --git a/Source/MQTTnet/Options/MqttClientTlsOptions.cs b/Source/MQTTnet/Options/MqttClientTlsOptions.cs index ab270fe1..9d3cf3a9 100644 --- a/Source/MQTTnet/Options/MqttClientTlsOptions.cs +++ b/Source/MQTTnet/Options/MqttClientTlsOptions.cs @@ -12,9 +12,9 @@ namespace MQTTnet; public sealed class MqttClientTlsOptions { - public Func CertificateValidationHandler { get; set; } + public Func? CertificateValidationHandler { get; set; } - public Func CertificateSelectionHandler { get; set; } + public Func? CertificateSelectionHandler { get; set; } public bool UseTls { get; set; } @@ -32,11 +32,11 @@ public sealed class MqttClientTlsOptions /// with the server and requires certificates for authentication. /// The implementation may return different certificates each time. /// - public IMqttClientCertificatesProvider ClientCertificatesProvider { get; set; } + public IMqttClientCertificatesProvider? ClientCertificatesProvider { get; set; } - public List ApplicationProtocols { get; set; } + public List? ApplicationProtocols { get; set; } - public CipherSuitesPolicy CipherSuitesPolicy { get; set; } + public CipherSuitesPolicy? CipherSuitesPolicy { get; set; } public EncryptionPolicy EncryptionPolicy { get; set; } = EncryptionPolicy.RequireEncryption; @@ -46,9 +46,9 @@ public sealed class MqttClientTlsOptions /// Gets or sets the target host. /// If the value is null or empty the same host as the TCP socket host will be used. /// - public string TargetHost { get; set; } + public string? TargetHost { get; set; } public SslProtocols SslProtocol { get; set; } = SslProtocols.Tls12 | SslProtocols.Tls13; - public X509Certificate2Collection TrustChain { get; set; } + public X509Certificate2Collection? TrustChain { get; set; } } \ No newline at end of file diff --git a/Source/MQTTnet/Options/MqttClientWebSocketOptions.cs b/Source/MQTTnet/Options/MqttClientWebSocketOptions.cs index b88e57b0..d32e815c 100644 --- a/Source/MQTTnet/Options/MqttClientWebSocketOptions.cs +++ b/Source/MQTTnet/Options/MqttClientWebSocketOptions.cs @@ -11,11 +11,11 @@ namespace MQTTnet; public sealed class MqttClientWebSocketOptions : IMqttClientChannelOptions { - public CookieContainer CookieContainer { get; set; } + public CookieContainer? CookieContainer { get; set; } - public WebSocketDeflateOptions DangerousDeflateOptions { get; set; } + public WebSocketDeflateOptions? DangerousDeflateOptions { get; set; } - public ICredentials Credentials { get; set; } + public ICredentials? Credentials { get; set; } /// /// Gets or sets the keep alive interval for the Web Socket connection. @@ -23,15 +23,15 @@ public sealed class MqttClientWebSocketOptions : IMqttClientChannelOptions /// public TimeSpan KeepAliveInterval { get; set; } = WebSocket.DefaultKeepAliveInterval; - public MqttClientWebSocketProxyOptions ProxyOptions { get; set; } + public MqttClientWebSocketProxyOptions? ProxyOptions { get; set; } - public IDictionary RequestHeaders { get; set; } + public IDictionary? RequestHeaders { get; set; } - public ICollection SubProtocols { get; set; } = ["mqtt"]; + public ICollection? SubProtocols { get; set; } = ["mqtt"]; public MqttClientTlsOptions TlsOptions { get; set; } = new(); - public string Uri { get; set; } + public required string Uri { get; set; } /// /// Gets or sets whether the default (system) credentials should be used when connecting via Web Socket connection. @@ -41,6 +41,6 @@ public sealed class MqttClientWebSocketOptions : IMqttClientChannelOptions public override string ToString() { - return Uri; + return Uri ?? string.Empty; } } \ No newline at end of file diff --git a/Source/MQTTnet/Options/MqttClientWebSocketOptionsBuilder.cs b/Source/MQTTnet/Options/MqttClientWebSocketOptionsBuilder.cs index 090c7257..a228c233 100644 --- a/Source/MQTTnet/Options/MqttClientWebSocketOptionsBuilder.cs +++ b/Source/MQTTnet/Options/MqttClientWebSocketOptionsBuilder.cs @@ -11,10 +11,19 @@ namespace MQTTnet; public sealed class MqttClientWebSocketOptionsBuilder { - readonly MqttClientWebSocketOptions _webSocketOptions = new(); + readonly MqttClientWebSocketOptions _webSocketOptions = new() + { + Uri = string.Empty + }; public MqttClientWebSocketOptions Build() { + + if (string.IsNullOrEmpty(_webSocketOptions.Uri)) + { + throw new InvalidOperationException("The URI is not set."); + } + return _webSocketOptions; } diff --git a/Source/MQTTnet/Options/MqttClientWebSocketProxyOptions.cs b/Source/MQTTnet/Options/MqttClientWebSocketProxyOptions.cs index b9baafa1..4424fb0b 100644 --- a/Source/MQTTnet/Options/MqttClientWebSocketProxyOptions.cs +++ b/Source/MQTTnet/Options/MqttClientWebSocketProxyOptions.cs @@ -6,17 +6,17 @@ namespace MQTTnet; public sealed class MqttClientWebSocketProxyOptions { - public string Address { get; set; } + public string? Address { get; set; } - public string[] BypassList { get; set; } + public string[]? BypassList { get; set; } public bool BypassOnLocal { get; set; } - public string Domain { get; set; } + public string? Domain { get; set; } - public string Password { get; set; } + public string? Password { get; set; } public bool UseDefaultCredentials { get; set; } - public string Username { get; set; } + public string? Username { get; set; } } \ No newline at end of file diff --git a/Source/MQTTnet/Options/MqttEnhancedAuthenticationEventArgs.cs b/Source/MQTTnet/Options/MqttEnhancedAuthenticationEventArgs.cs index 5d9b508a..c2b2a992 100644 --- a/Source/MQTTnet/Options/MqttEnhancedAuthenticationEventArgs.cs +++ b/Source/MQTTnet/Options/MqttEnhancedAuthenticationEventArgs.cs @@ -30,13 +30,13 @@ public class MqttEnhancedAuthenticationEventArgs : EventArgs /// Gets the authentication data. /// Hint: MQTT 5 feature only. /// - public byte[] AuthenticationData => _initialAuthPacket.AuthenticationData; + public byte[]? AuthenticationData => _initialAuthPacket.AuthenticationData; /// /// Gets the authentication method. /// Hint: MQTT 5 feature only. /// - public string AuthenticationMethod => _initialAuthPacket.AuthenticationMethod; + public string AuthenticationMethod => _initialAuthPacket.AuthenticationMethod!; public CancellationToken CancellationToken { get; } @@ -50,7 +50,7 @@ public class MqttEnhancedAuthenticationEventArgs : EventArgs /// Gets the reason string. /// Hint: MQTT 5 feature only. /// - public string ReasonString => _initialAuthPacket.ReasonString; + public string? ReasonString => _initialAuthPacket.ReasonString; /// /// Gets the user properties. @@ -61,7 +61,7 @@ public class MqttEnhancedAuthenticationEventArgs : EventArgs /// The feature is very similar to the HTTP header concept. /// Hint: MQTT 5 feature only. /// - public List UserProperties => _initialAuthPacket.UserProperties; + public List? UserProperties => _initialAuthPacket.UserProperties; public async Task ReceiveAsync(CancellationToken cancellationToken = default) { diff --git a/Source/MQTTnet/Options/MqttEnhancedAuthenticationExchangeData.cs b/Source/MQTTnet/Options/MqttEnhancedAuthenticationExchangeData.cs index 6fac2d76..4cb46478 100644 --- a/Source/MQTTnet/Options/MqttEnhancedAuthenticationExchangeData.cs +++ b/Source/MQTTnet/Options/MqttEnhancedAuthenticationExchangeData.cs @@ -18,7 +18,7 @@ public class MqttEnhancedAuthenticationExchangeData /// method. /// Hint: MQTT 5 feature only. /// - public byte[] AuthenticationData { get; set; } + public byte[]? AuthenticationData { get; set; } /// /// Gets or sets the reason code. @@ -30,7 +30,7 @@ public class MqttEnhancedAuthenticationExchangeData /// Gets or sets the reason string. /// Hint: MQTT 5 feature only. /// - public string ReasonString { get; set; } + public string? ReasonString { get; set; } /// /// Gets or sets the user properties. @@ -41,5 +41,5 @@ public class MqttEnhancedAuthenticationExchangeData /// The feature is very similar to the HTTP header concept. /// Hint: MQTT 5 feature only. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } } \ No newline at end of file diff --git a/Source/MQTTnet/Options/ReceiveMqttEnhancedAuthenticationDataResult.cs b/Source/MQTTnet/Options/ReceiveMqttEnhancedAuthenticationDataResult.cs index f2dc8cd2..f8ae2ce5 100644 --- a/Source/MQTTnet/Options/ReceiveMqttEnhancedAuthenticationDataResult.cs +++ b/Source/MQTTnet/Options/ReceiveMqttEnhancedAuthenticationDataResult.cs @@ -10,13 +10,13 @@ namespace MQTTnet; public sealed class ReceiveMqttEnhancedAuthenticationDataResult { - public byte[] AuthenticationData { get; init; } + public byte[]? AuthenticationData { get; init; } - public string AuthenticationMethod { get; init; } + public string? AuthenticationMethod { get; init; } public MqttAuthenticateReasonCode ReasonCode { get; init; } - public string ReasonString { get; init; } + public string? ReasonString { get; init; } - public List UserProperties { get; init; } + public List? UserProperties { get; init; } } \ No newline at end of file diff --git a/Source/MQTTnet/Options/SendMqttEnhancedAuthenticationDataOptions.cs b/Source/MQTTnet/Options/SendMqttEnhancedAuthenticationDataOptions.cs index 282b189d..7bc17e6c 100644 --- a/Source/MQTTnet/Options/SendMqttEnhancedAuthenticationDataOptions.cs +++ b/Source/MQTTnet/Options/SendMqttEnhancedAuthenticationDataOptions.cs @@ -9,9 +9,9 @@ namespace MQTTnet; public sealed class SendMqttEnhancedAuthenticationDataOptions { - public byte[] Data { get; init; } + public byte[]? Data { get; init; } - public string ReasonString { get; init; } + public string? ReasonString { get; init; } - public List UserProperties { get; init; } + public List? UserProperties { get; init; } } \ No newline at end of file diff --git a/Source/MQTTnet/PacketDispatcher/MqttPacketAwaitableFilter.cs b/Source/MQTTnet/PacketDispatcher/MqttPacketAwaitableFilter.cs index 6c551589..6a0473c0 100644 --- a/Source/MQTTnet/PacketDispatcher/MqttPacketAwaitableFilter.cs +++ b/Source/MQTTnet/PacketDispatcher/MqttPacketAwaitableFilter.cs @@ -8,7 +8,7 @@ namespace MQTTnet.PacketDispatcher; public sealed class MqttPacketAwaitableFilter { - public Type Type { get; set; } + public required Type Type { get; init; } - public ushort Identifier { get; set; } + public ushort Identifier { get; init; } } \ No newline at end of file diff --git a/Source/MQTTnet/Packets/MqttAuthPacket.cs b/Source/MQTTnet/Packets/MqttAuthPacket.cs index 8c1b710e..3bd10e9c 100644 --- a/Source/MQTTnet/Packets/MqttAuthPacket.cs +++ b/Source/MQTTnet/Packets/MqttAuthPacket.cs @@ -10,13 +10,13 @@ namespace MQTTnet.Packets; /// Added in MQTTv5.0.0. public sealed class MqttAuthPacket : MqttPacket { - public byte[] AuthenticationData { get; set; } + public byte[]? AuthenticationData { get; set; } - public string AuthenticationMethod { get; set; } + public string? AuthenticationMethod { get; set; } public MqttAuthenticateReasonCode ReasonCode { get; set; } - public string ReasonString { get; set; } + public string? ReasonString { get; set; } - public List UserProperties { get; set; } + public List? UserProperties { get; set; } } \ No newline at end of file diff --git a/Source/MQTTnet/Packets/MqttConnAckPacket.cs b/Source/MQTTnet/Packets/MqttConnAckPacket.cs index 3906a900..b7d6f603 100644 --- a/Source/MQTTnet/Packets/MqttConnAckPacket.cs +++ b/Source/MQTTnet/Packets/MqttConnAckPacket.cs @@ -12,11 +12,11 @@ public sealed class MqttConnAckPacket : MqttPacket /// /// Added in MQTTv5. /// - public string AssignedClientIdentifier { get; set; } + public string? AssignedClientIdentifier { get; set; } - public byte[] AuthenticationData { get; set; } + public byte[]? AuthenticationData { get; set; } - public string AuthenticationMethod { get; set; } + public string? AuthenticationMethod { get; set; } /// /// Added in MQTTv3.1.1. @@ -32,11 +32,11 @@ public sealed class MqttConnAckPacket : MqttPacket /// public MqttConnectReasonCode ReasonCode { get; set; } - public string ReasonString { get; set; } + public string? ReasonString { get; set; } public ushort ReceiveMaximum { get; set; } - public string ResponseInformation { get; set; } + public string? ResponseInformation { get; set; } public bool RetainAvailable { get; set; } @@ -44,7 +44,7 @@ public sealed class MqttConnAckPacket : MqttPacket public ushort ServerKeepAlive { get; set; } - public string ServerReference { get; set; } + public string? ServerReference { get; set; } public uint SessionExpiryInterval { get; set; } @@ -54,7 +54,7 @@ public sealed class MqttConnAckPacket : MqttPacket public ushort TopicAliasMaximum { get; set; } - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public bool WildcardSubscriptionAvailable { get; set; } diff --git a/Source/MQTTnet/Packets/MqttConnectPacket.cs b/Source/MQTTnet/Packets/MqttConnectPacket.cs index b91ee9f3..cf9472f7 100644 --- a/Source/MQTTnet/Packets/MqttConnectPacket.cs +++ b/Source/MQTTnet/Packets/MqttConnectPacket.cs @@ -9,24 +9,24 @@ namespace MQTTnet.Packets; public sealed class MqttConnectPacket : MqttPacket { - public byte[] AuthenticationData { get; set; } + public byte[]? AuthenticationData { get; set; } - public string AuthenticationMethod { get; set; } + public string? AuthenticationMethod { get; set; } /// /// Also called "Clean Start" in MQTTv5. /// public bool CleanSession { get; set; } - public string ClientId { get; set; } + public string? ClientId { get; set; } - public byte[] WillCorrelationData { get; set; } + public byte[]? WillCorrelationData { get; set; } public ushort KeepAlivePeriod { get; set; } public uint MaximumPacketSize { get; set; } - public byte[] Password { get; set; } + public byte[]? Password { get; set; } public ushort ReceiveMaximum { get; set; } @@ -34,23 +34,23 @@ public sealed class MqttConnectPacket : MqttPacket public bool RequestResponseInformation { get; set; } - public string WillResponseTopic { get; set; } + public string? WillResponseTopic { get; set; } public uint SessionExpiryInterval { get; set; } public ushort TopicAliasMaximum { get; set; } - public string Username { get; set; } + public string? Username { get; set; } - public List UserProperties { get; set; } + public List? UserProperties { get; set; } - public string WillContentType { get; set; } + public string? WillContentType { get; set; } public uint WillDelayInterval { get; set; } public bool WillFlag { get; set; } - public byte[] WillMessage { get; set; } + public byte[]? WillMessage { get; set; } public uint WillMessageExpiryInterval { get; set; } @@ -60,9 +60,9 @@ public sealed class MqttConnectPacket : MqttPacket public bool WillRetain { get; set; } - public string WillTopic { get; set; } + public string? WillTopic { get; set; } - public List WillUserProperties { get; set; } + public List? WillUserProperties { get; set; } public bool TryPrivate { get; set; } diff --git a/Source/MQTTnet/Packets/MqttDisconnectPacket.cs b/Source/MQTTnet/Packets/MqttDisconnectPacket.cs index 54698170..6f6a1867 100644 --- a/Source/MQTTnet/Packets/MqttDisconnectPacket.cs +++ b/Source/MQTTnet/Packets/MqttDisconnectPacket.cs @@ -17,12 +17,12 @@ public sealed class MqttDisconnectPacket : MqttPacket /// /// Added in MQTTv5. /// - public string ReasonString { get; set; } + public string? ReasonString { get; set; } /// /// Added in MQTTv5. /// - public string ServerReference { get; set; } + public string? ServerReference { get; set; } /// /// Added in MQTTv5. @@ -32,7 +32,7 @@ public sealed class MqttDisconnectPacket : MqttPacket /// /// Added in MQTTv5. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public override string ToString() { diff --git a/Source/MQTTnet/Packets/MqttPubAckPacket.cs b/Source/MQTTnet/Packets/MqttPubAckPacket.cs index 6b0c0c5b..61f389ad 100644 --- a/Source/MQTTnet/Packets/MqttPubAckPacket.cs +++ b/Source/MQTTnet/Packets/MqttPubAckPacket.cs @@ -17,12 +17,12 @@ public sealed class MqttPubAckPacket : MqttPacketWithIdentifier /// /// Added in MQTTv5. /// - public string ReasonString { get; set; } + public string? ReasonString { get; set; } /// /// Added in MQTTv5. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public override string ToString() { diff --git a/Source/MQTTnet/Packets/MqttPubCompPacket.cs b/Source/MQTTnet/Packets/MqttPubCompPacket.cs index 557bccff..5a42770d 100644 --- a/Source/MQTTnet/Packets/MqttPubCompPacket.cs +++ b/Source/MQTTnet/Packets/MqttPubCompPacket.cs @@ -17,12 +17,12 @@ public sealed class MqttPubCompPacket : MqttPacketWithIdentifier /// /// Added in MQTTv5. /// - public string ReasonString { get; set; } + public string? ReasonString { get; set; } /// /// Added in MQTTv5. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public override string ToString() { diff --git a/Source/MQTTnet/Packets/MqttPubRecPacket.cs b/Source/MQTTnet/Packets/MqttPubRecPacket.cs index 624c3315..165b20e3 100644 --- a/Source/MQTTnet/Packets/MqttPubRecPacket.cs +++ b/Source/MQTTnet/Packets/MqttPubRecPacket.cs @@ -17,12 +17,12 @@ public sealed class MqttPubRecPacket : MqttPacketWithIdentifier /// /// Added in MQTTv5. /// - public string ReasonString { get; set; } + public string? ReasonString { get; set; } /// /// Added in MQTTv5. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public override string ToString() { diff --git a/Source/MQTTnet/Packets/MqttPubRelPacket.cs b/Source/MQTTnet/Packets/MqttPubRelPacket.cs index 190fde9c..aa26044e 100644 --- a/Source/MQTTnet/Packets/MqttPubRelPacket.cs +++ b/Source/MQTTnet/Packets/MqttPubRelPacket.cs @@ -17,12 +17,12 @@ public sealed class MqttPubRelPacket : MqttPacketWithIdentifier /// /// Added in MQTTv5. /// - public string ReasonString { get; set; } + public string? ReasonString { get; set; } /// /// Added in MQTTv5. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public override string ToString() { diff --git a/Source/MQTTnet/Packets/MqttPublishPacket.cs b/Source/MQTTnet/Packets/MqttPublishPacket.cs index 11e70969..30262197 100644 --- a/Source/MQTTnet/Packets/MqttPublishPacket.cs +++ b/Source/MQTTnet/Packets/MqttPublishPacket.cs @@ -11,9 +11,9 @@ namespace MQTTnet.Packets; public sealed class MqttPublishPacket : MqttPacketWithIdentifier { - public string ContentType { get; set; } + public string? ContentType { get; set; } - public byte[] CorrelationData { get; set; } + public byte[]? CorrelationData { get; set; } public bool Dup { get; set; } @@ -27,17 +27,17 @@ public sealed class MqttPublishPacket : MqttPacketWithIdentifier public MqttQualityOfServiceLevel QualityOfServiceLevel { get; set; } = MqttQualityOfServiceLevel.AtMostOnce; - public string ResponseTopic { get; set; } + public string? ResponseTopic { get; set; } public bool Retain { get; set; } - public List SubscriptionIdentifiers { get; set; } + public List? SubscriptionIdentifiers { get; set; } - public string Topic { get; set; } + public required string Topic { get; set; } public ushort TopicAlias { get; set; } - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public override string ToString() { diff --git a/Source/MQTTnet/Packets/MqttSubAckPacket.cs b/Source/MQTTnet/Packets/MqttSubAckPacket.cs index 013d7c25..8cbd352c 100644 --- a/Source/MQTTnet/Packets/MqttSubAckPacket.cs +++ b/Source/MQTTnet/Packets/MqttSubAckPacket.cs @@ -13,21 +13,21 @@ public sealed class MqttSubAckPacket : MqttPacketWithIdentifier /// /// Reason Code is used in MQTTv5.0.0 and backward compatible to v.3.1.1. Return Code is used in MQTTv3.1.1 /// - public List ReasonCodes { get; set; } + public List? ReasonCodes { get; set; } /// /// Added in MQTTv5. /// - public string ReasonString { get; set; } + public string? ReasonString { get; set; } /// /// Added in MQTTv5. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public override string ToString() { - var reasonCodesText = string.Join(",", ReasonCodes.Select(f => f.ToString())); + var reasonCodesText = string.Join(",", ReasonCodes?.Select(f => f.ToString()) ?? []); return $"SubAck: [PacketIdentifier={PacketIdentifier}] [ReasonCode={reasonCodesText}]"; } diff --git a/Source/MQTTnet/Packets/MqttSubscribePacket.cs b/Source/MQTTnet/Packets/MqttSubscribePacket.cs index 853037ed..2040fe12 100644 --- a/Source/MQTTnet/Packets/MqttSubscribePacket.cs +++ b/Source/MQTTnet/Packets/MqttSubscribePacket.cs @@ -19,7 +19,7 @@ public sealed class MqttSubscribePacket : MqttPacketWithIdentifier /// /// Added in MQTTv5. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public override string ToString() { diff --git a/Source/MQTTnet/Packets/MqttTopicFilter.cs b/Source/MQTTnet/Packets/MqttTopicFilter.cs index 196be2aa..12bb8529 100644 --- a/Source/MQTTnet/Packets/MqttTopicFilter.cs +++ b/Source/MQTTnet/Packets/MqttTopicFilter.cs @@ -44,7 +44,7 @@ public sealed class MqttTopicFilter /// The topic consists of one or more topic levels. Each topic level is separated by a forward slash (topic level /// separator). /// - public string Topic { get; set; } + public required string Topic { get; set; } public override string ToString() { diff --git a/Source/MQTTnet/Packets/MqttUnsubAckPacket.cs b/Source/MQTTnet/Packets/MqttUnsubAckPacket.cs index 1c79ebfb..95326904 100644 --- a/Source/MQTTnet/Packets/MqttUnsubAckPacket.cs +++ b/Source/MQTTnet/Packets/MqttUnsubAckPacket.cs @@ -13,24 +13,24 @@ public sealed class MqttUnsubAckPacket : MqttPacketWithIdentifier /// /// Added in MQTTv5. /// - public List ReasonCodes { get; set; } + public List? ReasonCodes { get; set; } /// /// Added in MQTTv5. /// - public string ReasonString { get; set; } + public string? ReasonString { get; set; } /// /// Added in MQTTv5. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public override string ToString() { var reasonCodesText = string.Empty; if (ReasonCodes != null) { - reasonCodesText = string.Join(",", ReasonCodes?.Select(f => f.ToString())); + reasonCodesText = string.Join(",", ReasonCodes?.Select(f => f.ToString()) ?? []); } return $"UnsubAck: [PacketIdentifier={PacketIdentifier}] [ReasonCodes={reasonCodesText}] [ReasonString={ReasonString}]"; diff --git a/Source/MQTTnet/Packets/MqttUnsubscribePacket.cs b/Source/MQTTnet/Packets/MqttUnsubscribePacket.cs index 4053c1fe..60eb4d63 100644 --- a/Source/MQTTnet/Packets/MqttUnsubscribePacket.cs +++ b/Source/MQTTnet/Packets/MqttUnsubscribePacket.cs @@ -8,16 +8,16 @@ namespace MQTTnet.Packets; public sealed class MqttUnsubscribePacket : MqttPacketWithIdentifier { - public List TopicFilters { get; set; } = []; + public List? TopicFilters { get; set; } = []; /// /// Added in MQTTv5. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } public override string ToString() { - var topicFiltersText = string.Join(",", TopicFilters); + var topicFiltersText = string.Join(",", TopicFilters ?? []); return $"Unsubscribe: [PacketIdentifier={PacketIdentifier}] [TopicFilters={topicFiltersText}]"; } } \ No newline at end of file diff --git a/Source/MQTTnet/Packets/MqttUserProperty.cs b/Source/MQTTnet/Packets/MqttUserProperty.cs index 43cbad35..2032b478 100644 --- a/Source/MQTTnet/Packets/MqttUserProperty.cs +++ b/Source/MQTTnet/Packets/MqttUserProperty.cs @@ -18,12 +18,12 @@ public sealed class MqttUserProperty public string Value { get; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as MqttUserProperty); } - public bool Equals(MqttUserProperty other) + public bool Equals(MqttUserProperty? other) { if (other == null) { diff --git a/Source/MQTTnet/Publishing/MqttClientPublishResult.cs b/Source/MQTTnet/Publishing/MqttClientPublishResult.cs index c85a1a3c..3780f7fe 100644 --- a/Source/MQTTnet/Publishing/MqttClientPublishResult.cs +++ b/Source/MQTTnet/Publishing/MqttClientPublishResult.cs @@ -9,7 +9,7 @@ namespace MQTTnet; public sealed class MqttClientPublishResult { - public MqttClientPublishResult(ushort? packetIdentifier, MqttClientPublishReasonCode reasonCode, string reasonString, IReadOnlyCollection userProperties) + public MqttClientPublishResult(ushort? packetIdentifier, MqttClientPublishReasonCode reasonCode, string? reasonString, IReadOnlyCollection userProperties) { PacketIdentifier = packetIdentifier; ReasonCode = reasonCode; @@ -40,7 +40,7 @@ public sealed class MqttClientPublishResult /// Gets or sets the reason string. /// MQTT 5.0.0+ feature. /// - public string ReasonString { get; } + public string? ReasonString { get; } /// /// Gets or sets the user properties. diff --git a/Source/MQTTnet/Publishing/MqttClientPublishResultFactory.cs b/Source/MQTTnet/Publishing/MqttClientPublishResultFactory.cs index 7a947ef9..21e4faaa 100644 --- a/Source/MQTTnet/Publishing/MqttClientPublishResultFactory.cs +++ b/Source/MQTTnet/Publishing/MqttClientPublishResultFactory.cs @@ -13,7 +13,7 @@ public sealed class MqttClientPublishResultFactory static readonly IReadOnlyCollection EmptyUserProperties = []; static readonly MqttClientPublishResult AtMostOnceSuccessResult = new(null, MqttClientPublishReasonCode.Success, null, EmptyUserProperties); - public static MqttClientPublishResult Create(MqttPubAckPacket pubAckPacket) + public static MqttClientPublishResult Create(MqttPubAckPacket? pubAckPacket) { // QoS 0 has no response. So we treat it as a success always. if (pubAckPacket == null) @@ -31,7 +31,7 @@ public sealed class MqttClientPublishResultFactory return result; } - public static MqttClientPublishResult Create(MqttPubRecPacket pubRecPacket, MqttPubCompPacket pubCompPacket) + public static MqttClientPublishResult Create(MqttPubRecPacket? pubRecPacket, MqttPubCompPacket? pubCompPacket) { if (pubRecPacket == null || pubCompPacket == null) { diff --git a/Source/MQTTnet/Receiving/MqttApplicationMessageReceivedEventArgs.cs b/Source/MQTTnet/Receiving/MqttApplicationMessageReceivedEventArgs.cs index d1a2c499..e4e35809 100644 --- a/Source/MQTTnet/Receiving/MqttApplicationMessageReceivedEventArgs.cs +++ b/Source/MQTTnet/Receiving/MqttApplicationMessageReceivedEventArgs.cs @@ -66,14 +66,14 @@ public sealed class MqttApplicationMessageReceivedEventArgs : EventArgs /// /// Gets or sets the reason string which will be sent to the server in the ACK packet. /// - public string ResponseReasonString { get; set; } + public string? ResponseReasonString { get; set; } /// /// Gets or sets the user properties which will be sent to the server in the ACK packet etc. /// public List ResponseUserProperties { get; } = []; - public object Tag { get; set; } + public object? Tag { get; set; } internal MqttPublishPacket PublishPacket { get; set; } diff --git a/Source/MQTTnet/Subscribing/MqttClientSubscribeOptions.cs b/Source/MQTTnet/Subscribing/MqttClientSubscribeOptions.cs index 2b1434a6..9bdd3609 100644 --- a/Source/MQTTnet/Subscribing/MqttClientSubscribeOptions.cs +++ b/Source/MQTTnet/Subscribing/MqttClientSubscribeOptions.cs @@ -35,5 +35,5 @@ public sealed class MqttClientSubscribeOptions /// The feature is very similar to the HTTP header concept. /// MQTT 5.0.0+ feature. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } } \ No newline at end of file diff --git a/Source/MQTTnet/Subscribing/MqttClientSubscribeResult.cs b/Source/MQTTnet/Subscribing/MqttClientSubscribeResult.cs index 1dfa86f8..b0d08884 100644 --- a/Source/MQTTnet/Subscribing/MqttClientSubscribeResult.cs +++ b/Source/MQTTnet/Subscribing/MqttClientSubscribeResult.cs @@ -13,7 +13,7 @@ public sealed class MqttClientSubscribeResult public MqttClientSubscribeResult( ushort packetIdentifier, IReadOnlyCollection items, - string reasonString, + string? reasonString, IReadOnlyCollection userProperties) { PacketIdentifier = packetIdentifier; @@ -36,7 +36,7 @@ public sealed class MqttClientSubscribeResult /// Gets the reason string. /// MQTT 5.0.0+ feature. /// - public string ReasonString { get; } + public string? ReasonString { get; } /// /// Gets the user properties which were part of the SUBACK packet. diff --git a/Source/MQTTnet/Subscribing/MqttClientSubscribeResultFactory.cs b/Source/MQTTnet/Subscribing/MqttClientSubscribeResultFactory.cs index e21636c1..f82e2ae8 100644 --- a/Source/MQTTnet/Subscribing/MqttClientSubscribeResultFactory.cs +++ b/Source/MQTTnet/Subscribing/MqttClientSubscribeResultFactory.cs @@ -19,7 +19,7 @@ public sealed class MqttClientSubscribeResultFactory ArgumentNullException.ThrowIfNull(subAckPacket); // MQTTv5.0.0 handling. - if (subAckPacket.ReasonCodes.Count != 0 && subAckPacket.ReasonCodes.Count != subscribePacket.TopicFilters.Count) + if (subAckPacket.ReasonCodes!.Count != 0 && subAckPacket.ReasonCodes.Count != subscribePacket.TopicFilters.Count) { throw new MqttProtocolViolationException("The reason codes are not matching the topic filters [MQTT-3.9.3-1]."); } @@ -35,7 +35,7 @@ public sealed class MqttClientSubscribeResultFactory static MqttClientSubscribeResultItem CreateSubscribeResultItem(int index, MqttSubscribePacket subscribePacket, MqttSubAckPacket subAckPacket) { - var resultCode = (MqttClientSubscribeResultCode)subAckPacket.ReasonCodes[index]; + var resultCode = (MqttClientSubscribeResultCode)subAckPacket.ReasonCodes![index]; return new MqttClientSubscribeResultItem(subscribePacket.TopicFilters[index], resultCode); } } \ No newline at end of file diff --git a/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeOptions.cs b/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeOptions.cs index f2c0e7ba..5c3e0e25 100644 --- a/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeOptions.cs +++ b/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeOptions.cs @@ -24,5 +24,5 @@ public sealed class MqttClientUnsubscribeOptions /// The feature is very similar to the HTTP header concept. /// MQTT 5.0.0+ feature. /// - public List UserProperties { get; set; } + public List? UserProperties { get; set; } } \ No newline at end of file diff --git a/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResult.cs b/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResult.cs index 716dec03..7ca602c6 100644 --- a/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResult.cs +++ b/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResult.cs @@ -13,7 +13,7 @@ public sealed class MqttClientUnsubscribeResult public MqttClientUnsubscribeResult( ushort packetIdentifier, IReadOnlyCollection items, - string reasonString, + string? reasonString, IReadOnlyCollection userProperties) { PacketIdentifier = packetIdentifier; @@ -36,7 +36,7 @@ public sealed class MqttClientUnsubscribeResult /// Gets the reason string. /// MQTT 5.0.0+ feature. /// - public string ReasonString { get; } + public string? ReasonString { get; } /// /// Gets the user properties which were part of the UNSUBACK packet. diff --git a/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResultFactory.cs b/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResultFactory.cs index c18ba3fa..122cb31c 100644 --- a/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResultFactory.cs +++ b/Source/MQTTnet/Unsubscribing/MqttClientUnsubscribeResultFactory.cs @@ -19,13 +19,13 @@ public sealed class MqttClientUnsubscribeResultFactory ArgumentNullException.ThrowIfNull(unsubAckPacket); // MQTTv3.1.1 has no reason code at all! - if (unsubAckPacket.ReasonCodes != null && unsubAckPacket.ReasonCodes.Count != unsubscribePacket.TopicFilters.Count) + if (unsubAckPacket.ReasonCodes != null && unsubAckPacket.ReasonCodes.Count != unsubscribePacket.TopicFilters!.Count) { throw new MqttProtocolViolationException("The return codes are not matching the topic filters [MQTT-3.9.3-1]."); } var items = new List(); - for (var i = 0; i < unsubscribePacket.TopicFilters.Count; i++) + for (var i = 0; i < unsubscribePacket.TopicFilters!.Count; i++) { items.Add(CreateUnsubscribeResultItem(i, unsubscribePacket, unsubAckPacket)); } @@ -43,6 +43,6 @@ public sealed class MqttClientUnsubscribeResultFactory resultCode = (MqttClientUnsubscribeResultCode)unsubAckPacket.ReasonCodes[index]; } - return new MqttClientUnsubscribeResultItem(unsubscribePacket.TopicFilters[index], resultCode); + return new MqttClientUnsubscribeResultItem(unsubscribePacket.TopicFilters![index], resultCode); } } \ No newline at end of file