Skip to content

Commit

Permalink
Merge pull request #227 from quinmars/clean-up
Browse files Browse the repository at this point in the history
Clean up
  • Loading branch information
awcullen authored Feb 18, 2022
2 parents 1f1c774 + daace73 commit 34f6150
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 75 deletions.
3 changes: 1 addition & 2 deletions UaClient.UnitTests/IntegrationTests/IntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
5 changes: 1 addition & 4 deletions UaClient/ServiceModel/Ua/Channels/BinaryDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,7 @@ public int Position

public void Dispose()
{
if (_reader != null)
{
_reader.Dispose();
}
_reader?.Dispose();
}

public void PushNamespace(string namespaceUri)
Expand Down
5 changes: 1 addition & 4 deletions UaClient/ServiceModel/Ua/Channels/BinaryEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ public int Position

public void Dispose()
{
if (_writer != null)
{
_writer.Dispose();
}
_writer?.Dispose();
}

public void PushNamespace(string namespaceUri)
Expand Down
20 changes: 7 additions & 13 deletions UaClient/ServiceModel/Ua/Channels/ClientSecureChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand All @@ -475,13 +474,12 @@ 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
// 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);

Expand All @@ -500,10 +498,6 @@ private async Task ReceiveResponsesAsync(CancellationToken token = default)

return response;
}
finally
{
bodyDecoder.Dispose();
}
}
finally
{
Expand Down
14 changes: 2 additions & 12 deletions UaClient/ServiceModel/Ua/Channels/UaClientConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ public async Task<TransportConnectionOptions> 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);
Expand All @@ -89,10 +88,6 @@ public async Task<TransportConnectionOptions> 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);
Expand All @@ -102,8 +97,7 @@ public async Task<TransportConnectionOptions> 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);
Expand Down Expand Up @@ -139,10 +133,6 @@ public async Task<TransportConnectionOptions> OpenAsync(uint protocolVersion, Tr

throw new InvalidOperationException($"{nameof(UaClientConnection)}.{nameof(OpenAsync)} received unexpected message type.");
}
finally
{
decoder.Dispose();
}
}

/// <inheritdoc />
Expand Down
21 changes: 3 additions & 18 deletions UaClient/ServiceModel/Ua/Channels/UaSecureConversation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();
}
}
}

Expand All @@ -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);
Expand Down Expand Up @@ -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();
}
}
}

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);

Expand Down
44 changes: 22 additions & 22 deletions UaClient/ServiceModel/Ua/SubscriptionBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down

0 comments on commit 34f6150

Please sign in to comment.