From bc96f926b67d1fc5052e852a2cc2236000fd0581 Mon Sep 17 00:00:00 2001 From: Peter Wehrfritz Date: Thu, 13 Jan 2022 00:44:04 +0100 Subject: [PATCH 1/3] Use "using" instead of "try .. finally Dispose" --- .../ServiceModel/Ua/Channels/BinaryDecoder.cs | 5 +---- .../ServiceModel/Ua/Channels/BinaryEncoder.cs | 5 +---- .../Ua/Channels/ClientSecureChannel.cs | 9 ++------ .../Ua/Channels/UaClientConnection.cs | 14 ++----------- .../Ua/Channels/UaSecureConversation.cs | 21 +++---------------- 5 files changed, 9 insertions(+), 45 deletions(-) diff --git a/UaClient/ServiceModel/Ua/Channels/BinaryDecoder.cs b/UaClient/ServiceModel/Ua/Channels/BinaryDecoder.cs index cc53731..8744a1f 100644 --- a/UaClient/ServiceModel/Ua/Channels/BinaryDecoder.cs +++ b/UaClient/ServiceModel/Ua/Channels/BinaryDecoder.cs @@ -48,10 +48,7 @@ public int Position public void Dispose() { - if (_reader != null) - { - _reader.Dispose(); - } + _reader?.Dispose(); } public void PushNamespace(string namespaceUri) diff --git a/UaClient/ServiceModel/Ua/Channels/BinaryEncoder.cs b/UaClient/ServiceModel/Ua/Channels/BinaryEncoder.cs index 0642849..083c378 100644 --- a/UaClient/ServiceModel/Ua/Channels/BinaryEncoder.cs +++ b/UaClient/ServiceModel/Ua/Channels/BinaryEncoder.cs @@ -46,10 +46,7 @@ public int Position public void Dispose() { - if (_writer != null) - { - _writer.Dispose(); - } + _writer?.Dispose(); } public void PushNamespace(string namespaceUri) diff --git a/UaClient/ServiceModel/Ua/Channels/ClientSecureChannel.cs b/UaClient/ServiceModel/Ua/Channels/ClientSecureChannel.cs index 078a26e..3ecdbae 100644 --- a/UaClient/ServiceModel/Ua/Channels/ClientSecureChannel.cs +++ b/UaClient/ServiceModel/Ua/Channels/ClientSecureChannel.cs @@ -464,8 +464,7 @@ private async Task ReceiveResponsesAsync(CancellationToken token = default) ThrowIfClosedOrNotOpening(); var bodyStream = _streamManager.GetStream("ReceiveResponseAsync"); - var bodyDecoder = StackProfile.EncodingProvider.CreateDecoder(bodyStream, this, keepStreamOpen: false); - try + using (var bodyDecoder = StackProfile.EncodingProvider.CreateDecoder(bodyStream, this, keepStreamOpen: false)) { var ret = await _conversation!.DecryptMessageAsync(bodyStream, ReceiveAsync, token).ConfigureAwait(false); if (ret == (0, 0)) @@ -475,7 +474,7 @@ private async Task ReceiveResponsesAsync(CancellationToken token = default) bodyStream.Seek(0L, SeekOrigin.Begin); var response = (IServiceResponse)bodyDecoder.ReadResponse(); - + _logger?.LogTrace($"Received {response.GetType().Name}, Handle: {response.ResponseHeader!.RequestHandle} Result: {response.ResponseHeader.ServiceResult}"); // special inline processing for token renewal because we need to @@ -500,10 +499,6 @@ private async Task ReceiveResponsesAsync(CancellationToken token = default) return response; } - finally - { - bodyDecoder.Dispose(); - } } finally { diff --git a/UaClient/ServiceModel/Ua/Channels/UaClientConnection.cs b/UaClient/ServiceModel/Ua/Channels/UaClientConnection.cs index 2eaa22f..e77d263 100644 --- a/UaClient/ServiceModel/Ua/Channels/UaClientConnection.cs +++ b/UaClient/ServiceModel/Ua/Channels/UaClientConnection.cs @@ -71,8 +71,7 @@ public async Task OpenAsync(uint protocolVersion, Tr // send 'hello'. int count; - var encoder = new BinaryEncoder(new MemoryStream(sendBuffer, 0, MinBufferSize, true, false)); - try + using (var encoder = new BinaryEncoder(new MemoryStream(sendBuffer, 0, MinBufferSize, true, false))) { encoder.WriteUInt32(null, MessageTypes.HELF); encoder.WriteUInt32(null, 0u); @@ -89,10 +88,6 @@ public async Task OpenAsync(uint protocolVersion, Tr await SendAsync(sendBuffer, 0, count, token).ConfigureAwait(false); } - finally - { - encoder.Dispose(); - } // receive response count = await ReceiveAsync(receiveBuffer, 0, MinBufferSize, token).ConfigureAwait(false); @@ -102,8 +97,7 @@ public async Task OpenAsync(uint protocolVersion, Tr } // decode 'ack' or 'err'. - var decoder = new BinaryDecoder(new MemoryStream(receiveBuffer, 0, count, false, false)); - try + using (var decoder = new BinaryDecoder(new MemoryStream(receiveBuffer, 0, count, false, false))) { var type = decoder.ReadUInt32(null); var len = decoder.ReadUInt32(null); @@ -139,10 +133,6 @@ public async Task OpenAsync(uint protocolVersion, Tr throw new InvalidOperationException($"{nameof(UaClientConnection)}.{nameof(OpenAsync)} received unexpected message type."); } - finally - { - decoder.Dispose(); - } } /// diff --git a/UaClient/ServiceModel/Ua/Channels/UaSecureConversation.cs b/UaClient/ServiceModel/Ua/Channels/UaSecureConversation.cs index f148709..fbc579a 100644 --- a/UaClient/ServiceModel/Ua/Channels/UaSecureConversation.cs +++ b/UaClient/ServiceModel/Ua/Channels/UaSecureConversation.cs @@ -403,8 +403,7 @@ private async Task EncryptRequestMessage(Stream bodyStream, uint messageType, ui } var stream = new MemoryStream(_sendBuffer, 0, (int)_options.ReceiveBufferSize, true, true); - var encoder = new BinaryEncoder(stream); - try + using (var encoder = new BinaryEncoder(stream)) { // header encoder.WriteUInt32(null, messageType); @@ -527,10 +526,6 @@ private async Task EncryptRequestMessage(Stream bodyStream, uint messageType, ui // pass buffer to transport await consume(_sendBuffer, 0, position, token).ConfigureAwait(false); } - finally - { - encoder.Dispose(); - } } } @@ -547,8 +542,7 @@ private async Task EncryptOpenMessage(Stream bodyStream, uint messageType, uint } var stream = new MemoryStream(_sendBuffer, 0, (int)_options.ReceiveBufferSize, true, true); - var encoder = new BinaryEncoder(stream); - try + using (var encoder = new BinaryEncoder(stream)) { // header encoder.WriteUInt32(null, messageType); @@ -681,10 +675,6 @@ private async Task EncryptOpenMessage(Stream bodyStream, uint messageType, uint // pass buffer to transport await consume(_sendBuffer!, 0, encoder.Position, token).ConfigureAwait(false); } - finally - { - encoder.Dispose(); - } } } @@ -716,8 +706,7 @@ private async Task EncryptOpenMessage(Stream bodyStream, uint messageType, uint } var stream = new MemoryStream(_receiveBuffer, 0, count, true, true); - var decoder = new BinaryDecoder(stream); - try + using (var decoder = new BinaryDecoder(stream)) { uint channelId; messageType = decoder.ReadUInt32(null); @@ -913,10 +902,6 @@ private async Task EncryptOpenMessage(Stream bodyStream, uint messageType, uint throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded); } } - finally - { - decoder.Dispose(); // also disposes stream. - } } while (!isFinal); From e966f49cc2991bab29dbb7e92c9d0f280c2039a5 Mon Sep 17 00:00:00 2001 From: Peter Wehrfritz Date: Thu, 13 Jan 2022 00:44:41 +0100 Subject: [PATCH 2/3] Indentation --- UaClient/ServiceModel/Ua/SubscriptionBase.cs | 44 ++++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/UaClient/ServiceModel/Ua/SubscriptionBase.cs b/UaClient/ServiceModel/Ua/SubscriptionBase.cs index 19dd221..0c74aa5 100644 --- a/UaClient/ServiceModel/Ua/SubscriptionBase.cs +++ b/UaClient/ServiceModel/Ua/SubscriptionBase.cs @@ -576,35 +576,35 @@ private async Task StateMachineAsync(CancellationToken token = default) requests_chunk = new MonitoredItemCreateRequest[chunk_size]; Array.Copy(requests, i_chunk, requests_chunk, 0, chunk_size); - var itemsRequest = new CreateMonitoredItemsRequest - { - SubscriptionId = id, - ItemsToCreate = requests_chunk, - }; - var itemsResponse = await this.innerChannel.CreateMonitoredItemsAsync(itemsRequest); - - if (itemsResponse.Results is { } results) - { - for (int i = 0; i < results.Length; i++) + var itemsRequest = new CreateMonitoredItemsRequest { - var item = items[i]; - var result = results[i]; + SubscriptionId = id, + ItemsToCreate = requests_chunk, + }; + var itemsResponse = await this.innerChannel.CreateMonitoredItemsAsync(itemsRequest); - if (result is null) - { - this.logger?.LogError($"Error creating MonitoredItem for {item.NodeId}. The result is null."); - continue; - } - - item.OnCreateResult(result); - if (StatusCode.IsBad(result.StatusCode)) + if (itemsResponse.Results is { } results) + { + for (int i = 0; i < results.Length; i++) { - this.logger?.LogError($"Error creating MonitoredItem for {item.NodeId}. {StatusCodes.GetDefaultMessage(result.StatusCode)}"); + var item = items[i]; + var result = results[i]; + + if (result is null) + { + this.logger?.LogError($"Error creating MonitoredItem for {item.NodeId}. The result is null."); + continue; + } + + item.OnCreateResult(result); + if (StatusCode.IsBad(result.StatusCode)) + { + this.logger?.LogError($"Error creating MonitoredItem for {item.NodeId}. {StatusCodes.GetDefaultMessage(result.StatusCode)}"); + } } } } } - } this.progress.Report(CommunicationState.Opened); From daace73c991d4e794fbac0d52aed7731467c5a7b Mon Sep 17 00:00:00 2001 From: Peter Wehrfritz Date: Thu, 13 Jan 2022 01:07:44 +0100 Subject: [PATCH 3/3] Use pattern matching --- .../IntegrationTests/IntegrationTests.cs | 3 +-- .../ServiceModel/Ua/Channels/ClientSecureChannel.cs | 11 +++++------ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/UaClient.UnitTests/IntegrationTests/IntegrationTests.cs b/UaClient.UnitTests/IntegrationTests/IntegrationTests.cs index 14326bf..02222dd 100644 --- a/UaClient.UnitTests/IntegrationTests/IntegrationTests.cs +++ b/UaClient.UnitTests/IntegrationTests/IntegrationTests.cs @@ -83,8 +83,7 @@ public IntegrationTests(ITestOutputHelper output) using (var keyStream = new StreamReader(userKeyInfo.OpenRead())) { var keyReader = new PemReader(keyStream); - var keyPair = keyReader.ReadObject() as AsymmetricCipherKeyPair; - if (keyPair != null) + if (keyReader.ReadObject() is AsymmetricCipherKeyPair keyPair) { userKey = keyPair.Private as RsaKeyParameters; } diff --git a/UaClient/ServiceModel/Ua/Channels/ClientSecureChannel.cs b/UaClient/ServiceModel/Ua/Channels/ClientSecureChannel.cs index 3ecdbae..5d302e7 100644 --- a/UaClient/ServiceModel/Ua/Channels/ClientSecureChannel.cs +++ b/UaClient/ServiceModel/Ua/Channels/ClientSecureChannel.cs @@ -292,13 +292,13 @@ private async Task SendRequestAsync(ServiceOperation operation, CancellationToke _logger?.LogTrace($"Sending {request.GetType().Name}, Handle: {header.RequestHandle}"); _pendingCompletions.TryAdd(header.RequestHandle, operation); - if (request is OpenSecureChannelRequest) + if (request is OpenSecureChannelRequest openRequest) { - await SendOpenSecureChannelRequestAsync((OpenSecureChannelRequest)request, token).ConfigureAwait(false); + await SendOpenSecureChannelRequestAsync(openRequest, token).ConfigureAwait(false); } - else if (request is CloseSecureChannelRequest) + else if (request is CloseSecureChannelRequest closeRequest) { - await SendCloseSecureChannelRequestAsync((CloseSecureChannelRequest)request, token).ConfigureAwait(false); + await SendCloseSecureChannelRequestAsync(closeRequest, token).ConfigureAwait(false); operation.TrySetResult(new CloseSecureChannelResponse { ResponseHeader = new ResponseHeader { RequestHandle = header.RequestHandle, Timestamp = DateTime.UtcNow } }); } else @@ -479,8 +479,7 @@ private async Task ReceiveResponsesAsync(CancellationToken token = default) // special inline processing for token renewal because we need to // hold both the sending and receiving semaphores to update the security keys. - var openSecureChannelResponse = response as OpenSecureChannelResponse; - if (openSecureChannelResponse != null && StatusCode.IsGood(openSecureChannelResponse.ResponseHeader!.ServiceResult)) + if (response is OpenSecureChannelResponse openSecureChannelResponse && StatusCode.IsGood(openSecureChannelResponse.ResponseHeader!.ServiceResult)) { _tokenRenewalTime = DateTime.UtcNow.AddMilliseconds(0.8 * openSecureChannelResponse.SecurityToken!.RevisedLifetime);