From cc2a8c53755734c993994be438a7bb01037e7763 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:05:37 -0400 Subject: [PATCH 01/82] Removed redundant qualifiers --- .../src/Amqp/ActiveClientLinkManager.cs | 64 +- .../src/Amqp/ActiveClientLinkObject.cs | 10 +- .../src/Amqp/ActiveRequestResponseLink.cs | 4 +- .../src/Amqp/ActiveSendReceiveClientLink.cs | 4 +- .../src/Amqp/AmqpConnectionHelper.cs | 4 +- .../src/Amqp/AmqpExceptionHelper.cs | 4 +- .../src/Amqp/AmqpLinkCreator.cs | 22 +- .../src/Amqp/AmqpMessageConverter.cs | 6 +- .../src/Amqp/AmqpRequestMessage.cs | 12 +- .../Amqp/AmqpRequestResponseLinkCreator.cs | 6 +- .../src/Amqp/AmqpResponseMessage.cs | 22 +- .../src/Amqp/AmqpSendReceiveLinkCreator.cs | 4 +- .../src/Amqp/AmqpSubscriptionClient.cs | 60 +- .../src/Amqp/AmqpTransactionEnlistment.cs | 46 +- .../src/Amqp/AmqpTransactionManager.cs | 12 +- .../Framing/AmqpCorrelationFilterCodec.cs | 60 +- .../Amqp/Framing/AmqpRuleDescriptionCodec.cs | 24 +- .../src/Amqp/Framing/AmqpSqlFilterCodec.cs | 16 +- .../Amqp/Framing/AmqpSqlRuleActionCodec.cs | 16 +- .../src/ClientEntity.cs | 28 +- .../src/Core/MessageReceiver.cs | 520 ++++++++-------- .../src/Core/MessageSender.cs | 214 +++---- .../src/EntityNameHelper.cs | 6 +- .../src/ExceptionReceivedEventArgs.cs | 4 +- .../DataContractBinarySerializer.cs | 18 +- .../src/Filters/CorrelationFilter.cs | 58 +- .../Filters/CorrelationFilterExtensions.cs | 4 +- .../src/Filters/FilterExtensions.cs | 2 +- .../src/Filters/RuleActionExtensions.cs | 4 +- .../src/Filters/RuleDescription.cs | 32 +- .../src/Filters/RuleDescriptionExtensions.cs | 4 +- .../src/Filters/SqlFilter.cs | 22 +- .../src/Filters/SqlFilterExtensions.cs | 4 +- .../src/Filters/SqlRuleAction.cs | 22 +- .../src/Filters/XmlObjectConvertor.cs | 2 +- .../src/ISessionClient.cs | 2 +- .../src/Management/AuthorizationRules.cs | 6 +- .../src/Management/ManagementClient.cs | 68 +-- .../src/Management/QueueDescription.cs | 90 +-- .../src/Management/QueueRuntimeInfo.cs | 2 +- .../SharedAccessAuthorizationRule.cs | 66 +-- .../src/Management/SubscriptionDescription.cs | 84 +-- .../src/Management/SubscriptionRuntimeInfo.cs | 4 +- .../src/Management/TopicDescription.cs | 52 +- .../src/Management/TopicRuntimeInfo.cs | 2 +- .../Microsoft.Azure.ServiceBus/src/Message.cs | 114 ++-- .../src/MessageHandlerOptions.cs | 22 +- .../src/MessageReceivePump.cs | 104 ++-- .../src/MessageSession.cs | 74 +-- .../src/MessagingEventSource.cs | 558 +++++++++--------- .../AzureActiveDirectoryTokenProvider.cs | 6 +- .../src/Primitives/ConcurrentExpiringSet.cs | 34 +- .../src/Primitives/ExceptionUtility.cs | 2 +- .../src/Primitives/Fx.cs | 38 +- .../ManagedIdentityTokenProvider.cs | 2 +- .../src/Primitives/PropertyDictionary.cs | 44 +- .../src/Primitives/SecurityToken.cs | 10 +- .../SharedAccessSignatureTokenProvider.cs | 16 +- .../src/Primitives/TimeoutHelper.cs | 28 +- .../src/Primitives/TokenProviderAdapter.cs | 2 +- .../src/QueueClient.cs | 200 +++---- .../src/RetryExponential.cs | 14 +- .../src/RetryPolicy.cs | 44 +- .../src/ServiceBusConnection.cs | 54 +- .../src/ServiceBusConnectionStringBuilder.cs | 114 ++-- .../src/ServiceBusDiagnosticsSource.cs | 152 ++--- .../src/ServiceBusException.cs | 12 +- .../src/SessionClient.cs | 100 ++-- .../src/SessionHandlerOptions.cs | 28 +- .../src/SessionPumpHost.cs | 50 +- .../src/SessionReceivePump.cs | 116 ++-- .../src/SubscriptionClient.cs | 222 +++---- .../src/TopicClient.cs | 76 +-- .../tests/AmqpConverterTests.cs | 2 +- .../tests/Diagnostics/DiagnosticsTests.cs | 2 +- .../Diagnostics/FakeDiagnosticListener.cs | 14 +- .../QueueClientDiagnosticsTests.cs | 60 +- .../Diagnostics/SessionDiagnosticsTests.cs | 52 +- .../SubscriptionClientDiagnosticsTests.cs | 6 +- .../tests/ExpectedMessagingExceptionTests.cs | 2 +- .../FakeDiagnosticsListenerTests.cs | 32 +- .../DisplayTestMethodNameAttribute.cs | 2 +- .../tests/Management/ManagementClientTests.cs | 2 +- .../tests/MessageInterop/TestBook.cs | 12 +- .../tests/MessageTests.cs | 2 +- .../tests/OnMessageQueueTests.cs | 10 +- .../tests/OnMessageTopicSubscriptionTests.cs | 6 +- .../tests/OnSessionQueueTests.cs | 6 +- .../tests/OnSessionTopicSubscriptionTests.cs | 4 +- .../tests/Performance/Program.cs | 4 +- .../tests/PluginTests.cs | 6 +- .../tests/QueueClientTests.cs | 14 +- .../tests/QueueSessionTests.cs | 4 +- .../tests/RetryTests.cs | 6 +- .../tests/SenderReceiverTests.cs | 10 +- .../ServiceBusConnectionStringBuilderTests.cs | 2 +- .../tests/TestSessionHandler.cs | 26 +- .../tests/TokenProviderTests.cs | 2 +- .../tests/TopicClientTests.cs | 14 +- 99 files changed, 2127 insertions(+), 2127 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs index 9278dd9d3ce7..ca1e6ef6005c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs @@ -26,43 +26,43 @@ sealed class ActiveClientLinkManager public ActiveClientLinkManager(ClientEntity client, ICbsTokenProvider tokenProvider) { - this.clientId = client.ClientId; - this.retryPolicy = client.RetryPolicy ?? RetryPolicy.Default; - this.cbsTokenProvider = tokenProvider; - this.sendReceiveLinkCbsTokenRenewalTimer = new Timer(OnRenewSendReceiveCbsToken, this, Timeout.Infinite, Timeout.Infinite); - this.requestResponseLinkCbsTokenRenewalTimer = new Timer(OnRenewRequestResponseCbsToken, this, Timeout.Infinite, Timeout.Infinite); + clientId = client.ClientId; + retryPolicy = client.RetryPolicy ?? RetryPolicy.Default; + cbsTokenProvider = tokenProvider; + sendReceiveLinkCbsTokenRenewalTimer = new Timer(OnRenewSendReceiveCbsToken, this, Timeout.Infinite, Timeout.Infinite); + requestResponseLinkCbsTokenRenewalTimer = new Timer(OnRenewRequestResponseCbsToken, this, Timeout.Infinite, Timeout.Infinite); } public void Close() { - this.sendReceiveLinkCbsTokenRenewalTimer.Dispose(); - this.sendReceiveLinkCbsTokenRenewalTimer = null; - this.requestResponseLinkCbsTokenRenewalTimer.Dispose(); - this.requestResponseLinkCbsTokenRenewalTimer = null; + sendReceiveLinkCbsTokenRenewalTimer.Dispose(); + sendReceiveLinkCbsTokenRenewalTimer = null; + requestResponseLinkCbsTokenRenewalTimer.Dispose(); + requestResponseLinkCbsTokenRenewalTimer = null; } public void SetActiveSendReceiveLink(ActiveSendReceiveClientLink sendReceiveClientLink) { - this.activeSendReceiveClientLink = sendReceiveClientLink; - this.activeSendReceiveClientLink.Link.Closed += this.OnSendReceiveLinkClosed; - if (this.activeSendReceiveClientLink.Link.State == AmqpObjectState.Opened) + activeSendReceiveClientLink = sendReceiveClientLink; + activeSendReceiveClientLink.Link.Closed += OnSendReceiveLinkClosed; + if (activeSendReceiveClientLink.Link.State == AmqpObjectState.Opened) { - this.SetRenewCbsTokenTimer(sendReceiveClientLink); + SetRenewCbsTokenTimer(sendReceiveClientLink); } } void OnSendReceiveLinkClosed(object sender, EventArgs e) { - this.ChangeRenewTimer(this.activeSendReceiveClientLink, Timeout.InfiniteTimeSpan); + ChangeRenewTimer(activeSendReceiveClientLink, Timeout.InfiniteTimeSpan); } public void SetActiveRequestResponseLink(ActiveRequestResponseLink requestResponseLink) { - this.activeRequestResponseClientLink = requestResponseLink; - this.activeRequestResponseClientLink.Link.Closed += this.OnRequestResponseLinkClosed; - if (this.activeRequestResponseClientLink.Link.State == AmqpObjectState.Opened) + activeRequestResponseClientLink = requestResponseLink; + activeRequestResponseClientLink.Link.Closed += OnRequestResponseLinkClosed; + if (activeRequestResponseClientLink.Link.State == AmqpObjectState.Opened) { - this.SetRenewCbsTokenTimer(requestResponseLink); + SetRenewCbsTokenTimer(requestResponseLink); } } @@ -89,38 +89,38 @@ async Task RenewCbsTokenAsync(ActiveClientLinkObject activeClientLinkObject) { MessagingEventSource.Log.AmqpSendAuthenticationTokenStart(activeClientLinkObject.EndpointUri, resource, resource, activeClientLinkObject.RequiredClaims); - await this.retryPolicy.RunOperation( + await retryPolicy.RunOperation( async () => { cbsTokenExpiresAtUtc = TimeoutHelper.Min( cbsTokenExpiresAtUtc, await cbsLink.SendTokenAsync( - this.cbsTokenProvider, + cbsTokenProvider, activeClientLinkObject.EndpointUri, resource, resource, activeClientLinkObject.RequiredClaims, - ActiveClientLinkManager.SendTokenTimeout).ConfigureAwait(false)); - }, ActiveClientLinkManager.SendTokenTimeout).ConfigureAwait(false); + SendTokenTimeout).ConfigureAwait(false)); + }, SendTokenTimeout).ConfigureAwait(false); MessagingEventSource.Log.AmqpSendAuthenticationTokenStop(); } activeClientLinkObject.AuthorizationValidUntilUtc = cbsTokenExpiresAtUtc; - this.SetRenewCbsTokenTimer(activeClientLinkObject); + SetRenewCbsTokenTimer(activeClientLinkObject); } catch (Exception e) { // failed to refresh token, no need to do anything since the server will shut the link itself - MessagingEventSource.Log.AmqpSendAuthenticationTokenException(this.clientId, e); + MessagingEventSource.Log.AmqpSendAuthenticationTokenException(clientId, e); - this.ChangeRenewTimer(activeClientLinkObject, Timeout.InfiniteTimeSpan); + ChangeRenewTimer(activeClientLinkObject, Timeout.InfiniteTimeSpan); } } void OnRequestResponseLinkClosed(object sender, EventArgs e) { - this.ChangeRenewTimer(this.activeRequestResponseClientLink, Timeout.InfiniteTimeSpan); + ChangeRenewTimer(activeRequestResponseClientLink, Timeout.InfiniteTimeSpan); } void SetRenewCbsTokenTimer(ActiveClientLinkObject activeClientLinkObject) @@ -131,24 +131,24 @@ void SetRenewCbsTokenTimer(ActiveClientLinkObject activeClientLinkObject) return; } - var interval = activeClientLinkObject.AuthorizationValidUntilUtc.Subtract(utcNow) - ActiveClientLinkManager.TokenRefreshBuffer; - if (interval < ActiveClientLinkManager.TokenRefreshBuffer) + var interval = activeClientLinkObject.AuthorizationValidUntilUtc.Subtract(utcNow) - TokenRefreshBuffer; + if (interval < TokenRefreshBuffer) interval = TimeSpan.Zero; - interval = TimeoutHelper.Min(interval, ActiveClientLinkManager.MaxTokenRefreshTime); + interval = TimeoutHelper.Min(interval, MaxTokenRefreshTime); - this.ChangeRenewTimer(activeClientLinkObject, interval); + ChangeRenewTimer(activeClientLinkObject, interval); } void ChangeRenewTimer(ActiveClientLinkObject activeClientLinkObject, TimeSpan dueTime) { if (activeClientLinkObject is ActiveSendReceiveClientLink) { - this.sendReceiveLinkCbsTokenRenewalTimer?.Change(dueTime, Timeout.InfiniteTimeSpan); + sendReceiveLinkCbsTokenRenewalTimer?.Change(dueTime, Timeout.InfiniteTimeSpan); } else { - this.requestResponseLinkCbsTokenRenewalTimer?.Change(dueTime, Timeout.InfiniteTimeSpan); + requestResponseLinkCbsTokenRenewalTimer?.Change(dueTime, Timeout.InfiniteTimeSpan); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs index 4aaed8eed5df..131a38f34cd7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs @@ -12,11 +12,11 @@ abstract class ActiveClientLinkObject protected ActiveClientLinkObject(AmqpObject amqpLinkObject, Uri endpointUri, string[] audience, string[] requiredClaims, DateTime authorizationValidUntilUtc) { - this.LinkObject = amqpLinkObject; - this.EndpointUri = endpointUri; - this.Audience = audience; + LinkObject = amqpLinkObject; + EndpointUri = endpointUri; + Audience = audience; this.requiredClaims = requiredClaims; - this.AuthorizationValidUntilUtc = authorizationValidUntilUtc; + AuthorizationValidUntilUtc = authorizationValidUntilUtc; } public AmqpObject LinkObject { get; } @@ -25,7 +25,7 @@ protected ActiveClientLinkObject(AmqpObject amqpLinkObject, Uri endpointUri, st public Uri EndpointUri { get; } - public string[] RequiredClaims => (string[])this.requiredClaims.Clone(); + public string[] RequiredClaims => (string[])requiredClaims.Clone(); public DateTime AuthorizationValidUntilUtc { get; set; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveRequestResponseLink.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveRequestResponseLink.cs index 8f6b502f32a8..ded0ce6e8886 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveRequestResponseLink.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveRequestResponseLink.cs @@ -11,11 +11,11 @@ sealed class ActiveRequestResponseLink : ActiveClientLinkObject public ActiveRequestResponseLink(RequestResponseAmqpLink link, Uri endpointUri, string[] audience, string[] requiredClaims, DateTime authorizationValidUntilUtc) : base(link, endpointUri, audience, requiredClaims, authorizationValidUntilUtc) { - this.Link = link; + Link = link; } public RequestResponseAmqpLink Link { get; } - public override AmqpConnection Connection => this.Link.Session.Connection; + public override AmqpConnection Connection => Link.Session.Connection; } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveSendReceiveClientLink.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveSendReceiveClientLink.cs index 9fa0269befb2..bc2eebce195f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveSendReceiveClientLink.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveSendReceiveClientLink.cs @@ -11,11 +11,11 @@ sealed class ActiveSendReceiveClientLink : ActiveClientLinkObject public ActiveSendReceiveClientLink(AmqpLink link, Uri endpointUri, string[] audience, string[] requiredClaims, DateTime authorizationValidUntilUtc) : base(link, endpointUri, audience, requiredClaims, authorizationValidUntilUtc) { - this.Link = link; + Link = link; } public AmqpLink Link { get; } - public override AmqpConnection Connection => this.Link.Session.Connection; + public override AmqpConnection Connection => Link.Session.Connection; } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpConnectionHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpConnectionHelper.cs index d6d7d11d0246..8552b6f74cfd 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpConnectionHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpConnectionHelper.cs @@ -8,7 +8,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp using Microsoft.Azure.Amqp; using Microsoft.Azure.Amqp.Sasl; using Microsoft.Azure.Amqp.Transport; - using Microsoft.Azure.ServiceBus.Primitives; + using Primitives; internal class AmqpConnectionHelper { @@ -21,7 +21,7 @@ public static AmqpSettings CreateAmqpSettings( string sslHostName = null, bool useWebSockets = false, bool sslStreamUpgrade = false, - System.Net.NetworkCredential networkCredential = null, + NetworkCredential networkCredential = null, bool forceTokenProvider = true) { var amqpSettings = new AmqpSettings(); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs index 62b7f7ecdff0..18e16bbcb786 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs @@ -74,9 +74,9 @@ public static AmqpResponseStatusCode GetResponseStatusCode(this AmqpMessage resp public static Exception ToMessagingContractException(this AmqpMessage responseMessage, AmqpResponseStatusCode statusCode) { - AmqpSymbol errorCondition = AmqpExceptionHelper.GetResponseErrorCondition(responseMessage, statusCode); + AmqpSymbol errorCondition = GetResponseErrorCondition(responseMessage, statusCode); var statusDescription = responseMessage.ApplicationProperties.Map[ManagementConstants.Response.StatusDescription] as string ?? errorCondition.Value; - return AmqpExceptionHelper.ToMessagingContractException(errorCondition.Value, statusDescription); + return ToMessagingContractException(errorCondition.Value, statusDescription); } public static Exception ToMessagingContractException(this Error error, bool connectionError = false) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs index 848e6a7c4219..dba68cbcfebe 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs @@ -7,7 +7,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp using System.Threading.Tasks; using Microsoft.Azure.Amqp; using Microsoft.Azure.Amqp.Framing; - using Microsoft.Azure.ServiceBus.Primitives; + using Primitives; internal abstract class AmqpLinkCreator { @@ -28,29 +28,29 @@ protected AmqpLinkCreator(string entityPath, ServiceBusConnection serviceBusConn this.requiredClaims = requiredClaims; this.cbsTokenProvider = cbsTokenProvider; this.amqpLinkSettings = amqpLinkSettings; - this.ClientId = clientId; + ClientId = clientId; } protected string ClientId { get; } public async Task> CreateAndOpenAmqpLinkAsync() { - var timeoutHelper = new TimeoutHelper(this.serviceBusConnection.OperationTimeout, true); + var timeoutHelper = new TimeoutHelper(serviceBusConnection.OperationTimeout, true); MessagingEventSource.Log.AmqpGetOrCreateConnectionStart(); - var amqpConnection = await this.serviceBusConnection.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); - MessagingEventSource.Log.AmqpGetOrCreateConnectionStop(this.entityPath, amqpConnection.ToString(), amqpConnection.State.ToString()); + var amqpConnection = await serviceBusConnection.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); + MessagingEventSource.Log.AmqpGetOrCreateConnectionStop(entityPath, amqpConnection.ToString(), amqpConnection.State.ToString()); // Authenticate over CBS var cbsLink = amqpConnection.Extensions.Find(); DateTime cbsTokenExpiresAtUtc = DateTime.MaxValue; - foreach (var resource in this.audience) + foreach (var resource in audience) { - MessagingEventSource.Log.AmqpSendAuthenticationTokenStart(this.endpointAddress, resource, resource, this.requiredClaims); + MessagingEventSource.Log.AmqpSendAuthenticationTokenStart(endpointAddress, resource, resource, requiredClaims); cbsTokenExpiresAtUtc = TimeoutHelper.Min( cbsTokenExpiresAtUtc, - await cbsLink.SendTokenAsync(this.cbsTokenProvider, this.endpointAddress, resource, resource, this.requiredClaims, timeoutHelper.RemainingTime()).ConfigureAwait(false)); + await cbsLink.SendTokenAsync(cbsTokenProvider, endpointAddress, resource, resource, requiredClaims, timeoutHelper.RemainingTime()).ConfigureAwait(false)); MessagingEventSource.Log.AmqpSendAuthenticationTokenStop(); } @@ -64,7 +64,7 @@ public async Task> CreateAndOpenAmqpLinkAsync() } catch (Exception exception) { - MessagingEventSource.Log.AmqpSessionCreationException(this.entityPath, amqpConnection, exception); + MessagingEventSource.Log.AmqpSessionCreationException(entityPath, amqpConnection, exception); session?.Abort(); throw AmqpExceptionHelper.GetClientException(exception, null, session.GetInnerException(), amqpConnection.IsClosing()); } @@ -73,14 +73,14 @@ public async Task> CreateAndOpenAmqpLinkAsync() try { // Create Link - link = this.OnCreateAmqpLink(amqpConnection, this.amqpLinkSettings, session); + link = OnCreateAmqpLink(amqpConnection, amqpLinkSettings, session); await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); return new Tuple(link, cbsTokenExpiresAtUtc); } catch (Exception exception) { MessagingEventSource.Log.AmqpLinkCreationException( - this.entityPath, + entityPath, session, amqpConnection, exception); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index 5d23960a4806..bd879bad88ae 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -48,7 +48,7 @@ public static AmqpMessage BatchSBMessagesAsAmqpMessage(IEnumerable sb { messageCount++; - amqpMessage = AmqpMessageConverter.SBMessageToAmqpMessage(sbMessage); + amqpMessage = SBMessageToAmqpMessage(sbMessage); if (firstAmqpMessage == null) { firstAmqpMessage = amqpMessage; @@ -84,13 +84,13 @@ public static AmqpMessage BatchSBMessagesAsAmqpMessage(IEnumerable sb if (firstMessage.PartitionKey != null) { - amqpMessage.MessageAnnotations.Map[AmqpMessageConverter.PartitionKeyName] = + amqpMessage.MessageAnnotations.Map[PartitionKeyName] = firstMessage.PartitionKey; } if (firstMessage.ViaPartitionKey != null) { - amqpMessage.MessageAnnotations.Map[AmqpMessageConverter.ViaPartitionKeyName] = + amqpMessage.MessageAnnotations.Map[ViaPartitionKeyName] = firstMessage.ViaPartitionKey; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs index 62176d7b0210..a7f72d076417 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs @@ -14,14 +14,14 @@ internal sealed class AmqpRequestMessage AmqpRequestMessage(string operation, TimeSpan timeout, string trackingId) { - this.Map = new AmqpMap(); - this.requestMessage = AmqpMessage.Create(new AmqpValue { Value = this.Map }); - this.requestMessage.ApplicationProperties.Map[ManagementConstants.Request.Operation] = operation; - this.requestMessage.ApplicationProperties.Map[ManagementConstants.Properties.ServerTimeout] = (uint)timeout.TotalMilliseconds; - this.requestMessage.ApplicationProperties.Map[ManagementConstants.Properties.TrackingId] = trackingId ?? Guid.NewGuid().ToString(); + Map = new AmqpMap(); + requestMessage = AmqpMessage.Create(new AmqpValue { Value = Map }); + requestMessage.ApplicationProperties.Map[ManagementConstants.Request.Operation] = operation; + requestMessage.ApplicationProperties.Map[ManagementConstants.Properties.ServerTimeout] = (uint)timeout.TotalMilliseconds; + requestMessage.ApplicationProperties.Map[ManagementConstants.Properties.TrackingId] = trackingId ?? Guid.NewGuid().ToString(); } - public AmqpMessage AmqpMessage => this.requestMessage; + public AmqpMessage AmqpMessage => requestMessage; public AmqpMap Map { get; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs index 8f2c212a7f8f..25a44b690fc5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp { using System; using Microsoft.Azure.Amqp; - using Microsoft.Azure.ServiceBus.Primitives; + using Primitives; internal class AmqpRequestResponseLinkCreator : AmqpLinkCreator { @@ -19,8 +19,8 @@ public AmqpRequestResponseLinkCreator(string entityPath, ServiceBusConnection se protected override AmqpObject OnCreateAmqpLink(AmqpConnection connection, AmqpLinkSettings linkSettings, AmqpSession amqpSession) { - AmqpObject link = new RequestResponseAmqpLink(AmqpClientConstants.EntityTypeManagement, amqpSession, this.entityPath, linkSettings.Properties); - linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{amqpSession.Identifier}:{link.Identifier}:{this.ClientId}"; + AmqpObject link = new RequestResponseAmqpLink(AmqpClientConstants.EntityTypeManagement, amqpSession, entityPath, linkSettings.Properties); + linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{amqpSession.Identifier}:{link.Identifier}:{ClientId}"; return link; } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs index 2cdd36381f66..a782e06894b3 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs @@ -17,19 +17,19 @@ internal sealed class AmqpResponseMessage AmqpResponseMessage(AmqpMessage responseMessage) { this.responseMessage = responseMessage; - this.StatusCode = this.responseMessage.GetResponseStatusCode(); + StatusCode = this.responseMessage.GetResponseStatusCode(); if (this.responseMessage.ApplicationProperties.Map.TryGetValue(ManagementConstants.Properties.TrackingId, out var trackingId)) { - this.TrackingId = trackingId; + TrackingId = trackingId; } if (responseMessage.ValueBody != null) { - this.Map = responseMessage.ValueBody.Value as AmqpMap; + Map = responseMessage.ValueBody.Value as AmqpMap; } } - public AmqpMessage AmqpMessage => this.responseMessage; + public AmqpMessage AmqpMessage => responseMessage; public AmqpResponseStatusCode StatusCode { get; } @@ -44,12 +44,12 @@ public static AmqpResponseMessage CreateResponse(AmqpMessage response) public TValue GetValue(MapKey key) { - if (this.Map == null) + if (Map == null) { throw new ArgumentException(AmqpValue.Name); } - var valueObject = this.Map[key]; + var valueObject = Map[key]; if (valueObject == null) { throw new ArgumentException(key.ToString()); @@ -60,31 +60,31 @@ public TValue GetValue(MapKey key) throw new ArgumentException(key.ToString()); } - return (TValue)this.Map[key]; + return (TValue)Map[key]; } public IEnumerable GetListValue(MapKey key) { - if (this.Map == null) + if (Map == null) { throw new ArgumentException(AmqpValue.Name); } - var list = (List)this.Map[key]; + var list = (List)Map[key]; return list.Cast(); } public AmqpSymbol GetResponseErrorCondition() { - var condition = this.responseMessage.ApplicationProperties.Map[ManagementConstants.Response.ErrorCondition]; + var condition = responseMessage.ApplicationProperties.Map[ManagementConstants.Response.ErrorCondition]; return condition is AmqpSymbol amqpSymbol ? amqpSymbol : null; } public Exception ToMessagingContractException() { - return this.responseMessage.ToMessagingContractException(this.StatusCode); + return responseMessage.ToMessagingContractException(StatusCode); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs index 8d61b99bcfd8..2f63cd56c6f3 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp { using System; using Microsoft.Azure.Amqp; - using Microsoft.Azure.ServiceBus.Primitives; + using Primitives; internal class AmqpSendReceiveLinkCreator : AmqpLinkCreator { @@ -25,7 +25,7 @@ protected override AmqpObject OnCreateAmqpLink(AmqpConnection connection, AmqpLi { amqpLink = new SendingAmqpLink(linkSettings); } - linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{amqpSession.Identifier}:{amqpLink.Identifier}:{linkSettings.Source.ToString()}:{this.ClientId}"; + linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{amqpSession.Identifier}:{amqpLink.Identifier}:{linkSettings.Source.ToString()}:{ClientId}"; amqpLink.AttachTo(amqpSession); return amqpLink; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs index 38e3d1029be9..6d53599e874d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs @@ -37,38 +37,38 @@ public AmqpSubscriptionClient( int prefetchCount = 0, ReceiveMode mode = ReceiveMode.ReceiveAndDelete) { - this.syncLock = new object(); - this.Path = path; - this.ServiceBusConnection = servicebusConnection; - this.RetryPolicy = retryPolicy; - this.CbsTokenProvider = cbsTokenProvider; - this.PrefetchCount = prefetchCount; - this.ReceiveMode = mode; + syncLock = new object(); + Path = path; + ServiceBusConnection = servicebusConnection; + RetryPolicy = retryPolicy; + CbsTokenProvider = cbsTokenProvider; + PrefetchCount = prefetchCount; + ReceiveMode = mode; } public MessageReceiver InnerReceiver { get { - if (this.innerReceiver == null) + if (innerReceiver == null) { - lock (this.syncLock) + lock (syncLock) { - if (this.innerReceiver == null) + if (innerReceiver == null) { - this.innerReceiver = new MessageReceiver( - this.Path, + innerReceiver = new MessageReceiver( + Path, MessagingEntityType.Subscriber, - this.ReceiveMode, - this.ServiceBusConnection, - this.CbsTokenProvider, - this.RetryPolicy, - this.PrefetchCount); + ReceiveMode, + ServiceBusConnection, + CbsTokenProvider, + RetryPolicy, + PrefetchCount); } } } - return this.innerReceiver; + return innerReceiver; } } @@ -78,17 +78,17 @@ public MessageReceiver InnerReceiver /// The number of messages that the subscription client can simultaneously request. public int PrefetchCount { - get => this.prefetchCount; + get => prefetchCount; set { if (value < 0) { - throw Fx.Exception.ArgumentOutOfRange(nameof(this.PrefetchCount), value, "Value cannot be less than 0."); + throw Fx.Exception.ArgumentOutOfRange(nameof(PrefetchCount), value, "Value cannot be less than 0."); } - this.prefetchCount = value; - if (this.innerReceiver != null) + prefetchCount = value; + if (innerReceiver != null) { - this.innerReceiver.PrefetchCount = value; + innerReceiver.PrefetchCount = value; } } } @@ -105,7 +105,7 @@ public int PrefetchCount public Task CloseAsync() { - return this.innerReceiver?.CloseAsync(); + return innerReceiver?.CloseAsync(); } public async Task OnAddRuleAsync(RuleDescription description) @@ -114,13 +114,13 @@ public async Task OnAddRuleAsync(RuleDescription description) { var amqpRequestMessage = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.AddRuleOperation, - this.ServiceBusConnection.OperationTimeout, + ServiceBusConnection.OperationTimeout, null); amqpRequestMessage.Map[ManagementConstants.Properties.RuleName] = description.Name; amqpRequestMessage.Map[ManagementConstants.Properties.RuleDescription] = AmqpMessageConverter.GetRuleDescriptionMap(description); - var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); + var response = await InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); if (response.StatusCode != AmqpResponseStatusCode.OK) { @@ -140,11 +140,11 @@ public async Task OnRemoveRuleAsync(string ruleName) var amqpRequestMessage = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.RemoveRuleOperation, - this.ServiceBusConnection.OperationTimeout, + ServiceBusConnection.OperationTimeout, null); amqpRequestMessage.Map[ManagementConstants.Properties.RuleName] = ruleName; - var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); + var response = await InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); if (response.StatusCode != AmqpResponseStatusCode.OK) { @@ -164,12 +164,12 @@ public async Task> OnGetRulesAsync(int top, int skip) var amqpRequestMessage = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.EnumerateRulesOperation, - this.ServiceBusConnection.OperationTimeout, + ServiceBusConnection.OperationTimeout, null); amqpRequestMessage.Map[ManagementConstants.Properties.Top] = top; amqpRequestMessage.Map[ManagementConstants.Properties.Skip] = skip; - var response = await this.InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); + var response = await InnerReceiver.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); var ruleDescriptions = new List(); if (response.StatusCode == AmqpResponseStatusCode.OK) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs index a7223b79b59f..55b55f3eb2ff 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs @@ -7,7 +7,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp using System.Threading.Tasks; using System.Transactions; using Microsoft.Azure.Amqp; - using Microsoft.Azure.ServiceBus.Primitives; + using Primitives; class AmqpTransactionEnlistment : Singleton, IPromotableSinglePhaseNotification { @@ -20,7 +20,7 @@ public AmqpTransactionEnlistment( AmqpTransactionManager transactionManager, ServiceBusConnection serviceBusConnection) { - this.transactionId = transaction.TransactionInformation.LocalIdentifier; + transactionId = transaction.TransactionInformation.LocalIdentifier; this.transactionManager = transactionManager; this.serviceBusConnection = serviceBusConnection; } @@ -31,16 +31,16 @@ protected override async Task OnCreateAsync(TimeSpan { try { - var faultTolerantController = this.serviceBusConnection.TransactionController; - var controller = await faultTolerantController.GetOrCreateAsync(this.serviceBusConnection.OperationTimeout).ConfigureAwait(false); - this.AmqpTransactionId = await controller.DeclareAsync().ConfigureAwait(false); - MessagingEventSource.Log.AmqpTransactionDeclared(this.transactionId, this.AmqpTransactionId); + var faultTolerantController = serviceBusConnection.TransactionController; + var controller = await faultTolerantController.GetOrCreateAsync(serviceBusConnection.OperationTimeout).ConfigureAwait(false); + AmqpTransactionId = await controller.DeclareAsync().ConfigureAwait(false); + MessagingEventSource.Log.AmqpTransactionDeclared(transactionId, AmqpTransactionId); return this; } catch (Exception exception) { - MessagingEventSource.Log.AmqpTransactionInitializeException(this.transactionId, exception); - this.transactionManager.RemoveEnlistment(this.transactionId); + MessagingEventSource.Log.AmqpTransactionInitializeException(transactionId, exception); + transactionManager.RemoveEnlistment(transactionId); throw; } } @@ -55,51 +55,51 @@ void IPromotableSinglePhaseNotification.Initialize() void IPromotableSinglePhaseNotification.SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment) { - this.transactionManager.RemoveEnlistment(this.transactionId); - TaskExtensionHelper.Schedule(() => this.SinglePhaseCommitAsync(singlePhaseEnlistment)); + transactionManager.RemoveEnlistment(transactionId); + TaskExtensionHelper.Schedule(() => SinglePhaseCommitAsync(singlePhaseEnlistment)); } async Task SinglePhaseCommitAsync(SinglePhaseEnlistment singlePhaseEnlistment) { try { - var faultTolerantController = this.serviceBusConnection.TransactionController; - var controller = await faultTolerantController.GetOrCreateAsync(this.serviceBusConnection.OperationTimeout).ConfigureAwait(false); + var faultTolerantController = serviceBusConnection.TransactionController; + var controller = await faultTolerantController.GetOrCreateAsync(serviceBusConnection.OperationTimeout).ConfigureAwait(false); - await controller.DischargeAsync(this.AmqpTransactionId, fail: false).ConfigureAwait(false); + await controller.DischargeAsync(AmqpTransactionId, fail: false).ConfigureAwait(false); singlePhaseEnlistment.Committed(); - MessagingEventSource.Log.AmqpTransactionDischarged(this.transactionId, this.AmqpTransactionId, false); - await this.CloseAsync().ConfigureAwait(false); + MessagingEventSource.Log.AmqpTransactionDischarged(transactionId, AmqpTransactionId, false); + await CloseAsync().ConfigureAwait(false); } catch (Exception e) { Exception exception = AmqpExceptionHelper.GetClientException(e, null); - MessagingEventSource.Log.AmqpTransactionDischargeException(this.transactionId, this.AmqpTransactionId, exception); + MessagingEventSource.Log.AmqpTransactionDischargeException(transactionId, AmqpTransactionId, exception); singlePhaseEnlistment.InDoubt(exception); } } void IPromotableSinglePhaseNotification.Rollback(SinglePhaseEnlistment singlePhaseEnlistment) { - this.transactionManager.RemoveEnlistment(this.transactionId); - TaskExtensionHelper.Schedule(() => this.RollbackAsync(singlePhaseEnlistment)); + transactionManager.RemoveEnlistment(transactionId); + TaskExtensionHelper.Schedule(() => RollbackAsync(singlePhaseEnlistment)); } async Task RollbackAsync(SinglePhaseEnlistment singlePhaseEnlistment) { try { - var faultTolerantController = this.serviceBusConnection.TransactionController; - var controller = await faultTolerantController.GetOrCreateAsync(this.serviceBusConnection.OperationTimeout).ConfigureAwait(false); + var faultTolerantController = serviceBusConnection.TransactionController; + var controller = await faultTolerantController.GetOrCreateAsync(serviceBusConnection.OperationTimeout).ConfigureAwait(false); - await controller.DischargeAsync(this.AmqpTransactionId, fail: true).ConfigureAwait(false); + await controller.DischargeAsync(AmqpTransactionId, fail: true).ConfigureAwait(false); singlePhaseEnlistment.Aborted(); - MessagingEventSource.Log.AmqpTransactionDischarged(this.transactionId, this.AmqpTransactionId, true); + MessagingEventSource.Log.AmqpTransactionDischarged(transactionId, AmqpTransactionId, true); } catch (Exception e) { Exception exception = AmqpExceptionHelper.GetClientException(e, null); - MessagingEventSource.Log.AmqpTransactionDischargeException(this.transactionId, this.AmqpTransactionId, exception); + MessagingEventSource.Log.AmqpTransactionDischargeException(transactionId, AmqpTransactionId, exception); singlePhaseEnlistment.Aborted(exception); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs index 0cbf94031d65..ff78de04f9a4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs @@ -27,16 +27,16 @@ public async Task> EnlistAsync( string transactionId = transaction.TransactionInformation.LocalIdentifier; AmqpTransactionEnlistment transactionEnlistment; - lock (this.syncRoot) + lock (syncRoot) { - if (!this.enlistmentMap.TryGetValue(transactionId, out transactionEnlistment)) + if (!enlistmentMap.TryGetValue(transactionId, out transactionEnlistment)) { transactionEnlistment = new AmqpTransactionEnlistment(transaction, this, serviceBusConnection); - this.enlistmentMap.Add(transactionId, transactionEnlistment); + enlistmentMap.Add(transactionId, transactionEnlistment); if (!transaction.EnlistPromotableSinglePhase(transactionEnlistment)) { - this.enlistmentMap.Remove(transactionId); + enlistmentMap.Remove(transactionId); throw new InvalidOperationException("Local transactions are not supported with other resource managers/DTC."); } } @@ -48,9 +48,9 @@ public async Task> EnlistAsync( public void RemoveEnlistment(string transactionId) { - lock (this.syncRoot) + lock (syncRoot) { - this.enlistmentMap.Remove(transactionId); + enlistmentMap.Remove(transactionId); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs index babc3f272b6b..c62fafb9b815 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs @@ -17,7 +17,7 @@ sealed class AmqpCorrelationFilterCodec : AmqpFilterCodec public AmqpCorrelationFilterCodec() : base(Name, Code) { - this.properties = new AmqpMap(); + properties = new AmqpMap(); } public string CorrelationId { get; set; } @@ -36,7 +36,7 @@ public AmqpCorrelationFilterCodec() : base(Name, Code) public string ContentType { get; set; } - public AmqpMap Properties => this.properties; + public AmqpMap Properties => properties; protected override int FieldCount => Fields; @@ -44,83 +44,83 @@ public override string ToString() { var stringBuilder = new StringBuilder("correlation("); var count = 0; - this.AddFieldToString(this.CorrelationId != null, stringBuilder, "id", this.CorrelationId, ref count); + AddFieldToString(CorrelationId != null, stringBuilder, "id", CorrelationId, ref count); stringBuilder.Append(')'); return stringBuilder.ToString(); } protected override void OnEncode(ByteBuffer buffer) { - AmqpCodec.EncodeString(this.CorrelationId, buffer); - AmqpCodec.EncodeString(this.MessageId, buffer); - AmqpCodec.EncodeString(this.To, buffer); - AmqpCodec.EncodeString(this.ReplyTo, buffer); - AmqpCodec.EncodeString(this.Label, buffer); - AmqpCodec.EncodeString(this.SessionId, buffer); - AmqpCodec.EncodeString(this.ReplyToSessionId, buffer); - AmqpCodec.EncodeString(this.ContentType, buffer); - AmqpCodec.EncodeMap(this.properties, buffer); + AmqpCodec.EncodeString(CorrelationId, buffer); + AmqpCodec.EncodeString(MessageId, buffer); + AmqpCodec.EncodeString(To, buffer); + AmqpCodec.EncodeString(ReplyTo, buffer); + AmqpCodec.EncodeString(Label, buffer); + AmqpCodec.EncodeString(SessionId, buffer); + AmqpCodec.EncodeString(ReplyToSessionId, buffer); + AmqpCodec.EncodeString(ContentType, buffer); + AmqpCodec.EncodeMap(properties, buffer); } protected override void OnDecode(ByteBuffer buffer, int count) { if (count-- > 0) { - this.CorrelationId = AmqpCodec.DecodeString(buffer); + CorrelationId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { - this.MessageId = AmqpCodec.DecodeString(buffer); + MessageId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { - this.To = AmqpCodec.DecodeString(buffer); + To = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { - this.ReplyTo = AmqpCodec.DecodeString(buffer); + ReplyTo = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { - this.Label = AmqpCodec.DecodeString(buffer); + Label = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { - this.SessionId = AmqpCodec.DecodeString(buffer); + SessionId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { - this.ReplyToSessionId = AmqpCodec.DecodeString(buffer); + ReplyToSessionId = AmqpCodec.DecodeString(buffer); } if (count-- > 0) { - this.ContentType = AmqpCodec.DecodeString(buffer); + ContentType = AmqpCodec.DecodeString(buffer); } if (count > 0) { - this.properties = AmqpCodec.DecodeMap(buffer); + properties = AmqpCodec.DecodeMap(buffer); } } protected override int OnValueSize() { - return AmqpCodec.GetStringEncodeSize(this.CorrelationId) + - AmqpCodec.GetStringEncodeSize(this.MessageId) + - AmqpCodec.GetStringEncodeSize(this.To) + - AmqpCodec.GetStringEncodeSize(this.ReplyTo) + - AmqpCodec.GetStringEncodeSize(this.Label) + - AmqpCodec.GetStringEncodeSize(this.SessionId) + - AmqpCodec.GetStringEncodeSize(this.ReplyToSessionId) + - AmqpCodec.GetStringEncodeSize(this.ContentType) + - AmqpCodec.GetMapEncodeSize(this.properties); + return AmqpCodec.GetStringEncodeSize(CorrelationId) + + AmqpCodec.GetStringEncodeSize(MessageId) + + AmqpCodec.GetStringEncodeSize(To) + + AmqpCodec.GetStringEncodeSize(ReplyTo) + + AmqpCodec.GetStringEncodeSize(Label) + + AmqpCodec.GetStringEncodeSize(SessionId) + + AmqpCodec.GetStringEncodeSize(ReplyToSessionId) + + AmqpCodec.GetStringEncodeSize(ContentType) + + AmqpCodec.GetMapEncodeSize(properties); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleDescriptionCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleDescriptionCodec.cs index 0b0be07f8eff..7dee6d14f418 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleDescriptionCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleDescriptionCodec.cs @@ -39,41 +39,41 @@ public string RuleName protected override void OnEncode(ByteBuffer buffer) { - AmqpCodec.EncodeSerializable(this.Filter, buffer); - AmqpCodec.EncodeSerializable(this.Action, buffer); - AmqpCodec.EncodeString(this.RuleName, buffer); - AmqpCodec.EncodeTimeStamp(this.CreatedAt, buffer); + AmqpCodec.EncodeSerializable(Filter, buffer); + AmqpCodec.EncodeSerializable(Action, buffer); + AmqpCodec.EncodeString(RuleName, buffer); + AmqpCodec.EncodeTimeStamp(CreatedAt, buffer); } protected override void OnDecode(ByteBuffer buffer, int count) { if (count-- > 0) { - this.Filter = (AmqpFilterCodec)AmqpCodec.DecodeAmqpDescribed(buffer); + Filter = (AmqpFilterCodec)AmqpCodec.DecodeAmqpDescribed(buffer); } if (count-- > 0) { - this.Action = (AmqpRuleActionCodec)AmqpCodec.DecodeAmqpDescribed(buffer); + Action = (AmqpRuleActionCodec)AmqpCodec.DecodeAmqpDescribed(buffer); } if (count-- > 0) { - this.RuleName = AmqpCodec.DecodeString(buffer); + RuleName = AmqpCodec.DecodeString(buffer); } if (count > 0) { - this.CreatedAt = AmqpCodec.DecodeTimeStamp(buffer); + CreatedAt = AmqpCodec.DecodeTimeStamp(buffer); } } protected override int OnValueSize() { - return AmqpCodec.GetSerializableEncodeSize(this.Filter) + - AmqpCodec.GetSerializableEncodeSize(this.Action) + - AmqpCodec.GetStringEncodeSize(this.RuleName) + - AmqpCodec.GetTimeStampEncodeSize(this.CreatedAt); + return AmqpCodec.GetSerializableEncodeSize(Filter) + + AmqpCodec.GetSerializableEncodeSize(Action) + + AmqpCodec.GetStringEncodeSize(RuleName) + + AmqpCodec.GetTimeStampEncodeSize(CreatedAt); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlFilterCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlFilterCodec.cs index 8325350d26e5..fac21fb72a83 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlFilterCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlFilterCodec.cs @@ -24,35 +24,35 @@ public override string ToString() { var stringBuilder = new StringBuilder("sql("); var count = 0; - this.AddFieldToString(this.Expression != null, stringBuilder, "expression", this.Expression, ref count); - this.AddFieldToString(this.CompatibilityLevel != null, stringBuilder, "level", this.CompatibilityLevel, ref count); + AddFieldToString(Expression != null, stringBuilder, "expression", Expression, ref count); + AddFieldToString(CompatibilityLevel != null, stringBuilder, "level", CompatibilityLevel, ref count); stringBuilder.Append(')'); return stringBuilder.ToString(); } protected override void OnEncode(ByteBuffer buffer) { - AmqpCodec.EncodeString(this.Expression, buffer); - AmqpCodec.EncodeInt(this.CompatibilityLevel, buffer); + AmqpCodec.EncodeString(Expression, buffer); + AmqpCodec.EncodeInt(CompatibilityLevel, buffer); } protected override void OnDecode(ByteBuffer buffer, int count) { if (count-- > 0) { - this.Expression = AmqpCodec.DecodeString(buffer); + Expression = AmqpCodec.DecodeString(buffer); } if (count > 0) { - this.CompatibilityLevel = AmqpCodec.DecodeInt(buffer); + CompatibilityLevel = AmqpCodec.DecodeInt(buffer); } } protected override int OnValueSize() { - return AmqpCodec.GetStringEncodeSize(this.Expression) + - AmqpCodec.GetIntEncodeSize(this.CompatibilityLevel); + return AmqpCodec.GetStringEncodeSize(Expression) + + AmqpCodec.GetIntEncodeSize(CompatibilityLevel); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlRuleActionCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlRuleActionCodec.cs index f79ae793766f..a46b47f1ed91 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlRuleActionCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlRuleActionCodec.cs @@ -32,35 +32,35 @@ public override string ToString() { var sb = new StringBuilder("sql-rule-action("); var count = 0; - this.AddFieldToString(this.SqlExpression != null, sb, "expression", this.SqlExpression, ref count); - this.AddFieldToString(this.CompatibilityLevel != null, sb, "level", this.CompatibilityLevel, ref count); + AddFieldToString(SqlExpression != null, sb, "expression", SqlExpression, ref count); + AddFieldToString(CompatibilityLevel != null, sb, "level", CompatibilityLevel, ref count); sb.Append(')'); return sb.ToString(); } protected override void OnEncode(ByteBuffer buffer) { - AmqpCodec.EncodeString(this.SqlExpression, buffer); - AmqpCodec.EncodeInt(this.CompatibilityLevel, buffer); + AmqpCodec.EncodeString(SqlExpression, buffer); + AmqpCodec.EncodeInt(CompatibilityLevel, buffer); } protected override void OnDecode(ByteBuffer buffer, int count) { if (count-- > 0) { - this.SqlExpression = AmqpCodec.DecodeString(buffer); + SqlExpression = AmqpCodec.DecodeString(buffer); } if (count > 0) { - this.CompatibilityLevel = AmqpCodec.DecodeInt(buffer); + CompatibilityLevel = AmqpCodec.DecodeInt(buffer); } } protected override int OnValueSize() { - return AmqpCodec.GetStringEncodeSize(this.SqlExpression) + - AmqpCodec.GetIntEncodeSize(this.CompatibilityLevel); + return AmqpCodec.GetStringEncodeSize(SqlExpression) + + AmqpCodec.GetIntEncodeSize(CompatibilityLevel); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs index 14cf1234374f..8c0d425afd22 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs @@ -23,9 +23,9 @@ public abstract class ClientEntity : IClientEntity protected ClientEntity(string clientTypeName, string postfix, RetryPolicy retryPolicy) { this.clientTypeName = clientTypeName; - this.ClientId = GenerateClientId(clientTypeName, postfix); - this.RetryPolicy = retryPolicy ?? RetryPolicy.Default; - this.syncLock = new object(); + ClientId = GenerateClientId(clientTypeName, postfix); + RetryPolicy = retryPolicy ?? RetryPolicy.Default; + syncLock = new object(); } /// @@ -86,21 +86,21 @@ internal set public async Task CloseAsync() { var callClose = false; - lock (this.syncLock) + lock (syncLock) { - if (!this.IsClosedOrClosing) + if (!IsClosedOrClosing) { - this.IsClosedOrClosing = true; + IsClosedOrClosing = true; callClose = true; } } if (callClose) { - await this.OnClosingAsync().ConfigureAwait(false); - if (OwnsConnection && this.ServiceBusConnection.IsClosedOrClosing == false) + await OnClosingAsync().ConfigureAwait(false); + if (OwnsConnection && ServiceBusConnection.IsClosedOrClosing == false) { - await this.ServiceBusConnection.CloseAsync().ConfigureAwait(false); + await ServiceBusConnection.CloseAsync().ConfigureAwait(false); } } } @@ -143,10 +143,10 @@ protected static string GenerateClientId(string clientTypeName, string postfix = /// protected virtual void ThrowIfClosed() { - this.ServiceBusConnection.ThrowIfClosed(); - if (this.IsClosedOrClosing) + ServiceBusConnection.ThrowIfClosed(); + if (IsClosedOrClosing) { - throw new ObjectDisposedException($"{this.clientTypeName} with Id '{this.ClientId}' has already been closed. Please create a new {this.clientTypeName}."); + throw new ObjectDisposedException($"{clientTypeName} with Id '{ClientId}' has already been closed. Please create a new {clientTypeName}."); } } @@ -155,8 +155,8 @@ protected virtual void ThrowIfClosed() /// internal void UpdateClientId(string newClientId) { - MessagingEventSource.Log.UpdateClientId(this.ClientId, newClientId); - this.ClientId = newClientId; + MessagingEventSource.Log.UpdateClientId(ClientId, newClientId); + ClientId = newClientId; } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index a55266d092c4..58c2ae72e917 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -13,8 +13,8 @@ namespace Microsoft.Azure.ServiceBus.Core using Microsoft.Azure.Amqp; using Microsoft.Azure.Amqp.Encoding; using Microsoft.Azure.Amqp.Framing; - using Microsoft.Azure.ServiceBus.Amqp; - using Microsoft.Azure.ServiceBus.Primitives; + using Amqp; + using Primitives; /// /// The MessageReceiver can be used to receive messages from Queues and Subscriptions and acknowledge them. @@ -98,7 +98,7 @@ public MessageReceiver( throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -123,7 +123,7 @@ public MessageReceiver( int prefetchCount = Constants.DefaultClientPrefetchCount) : this(entityPath, null, receiveMode, new ServiceBusConnection(endpoint, transportType, retryPolicy) {TokenProvider = tokenProvider}, null, retryPolicy, prefetchCount) { - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -144,7 +144,7 @@ public MessageReceiver( int prefetchCount = Constants.DefaultClientPrefetchCount) : this(entityPath, null, receiveMode, serviceBusConnection, null, retryPolicy, prefetchCount) { - this.OwnsConnection = false; + OwnsConnection = false; } internal MessageReceiver( @@ -166,35 +166,35 @@ internal MessageReceiver( throw Fx.Exception.ArgumentNullOrWhiteSpace(entityPath); } - this.ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); - this.ReceiveMode = receiveMode; - this.Path = entityPath; - this.EntityType = entityType; - this.ServiceBusConnection.ThrowIfClosed(); + ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); + ReceiveMode = receiveMode; + Path = entityPath; + EntityType = entityType; + ServiceBusConnection.ThrowIfClosed(); if (cbsTokenProvider != null) { - this.CbsTokenProvider = cbsTokenProvider; + CbsTokenProvider = cbsTokenProvider; } - else if (this.ServiceBusConnection.TokenProvider != null) + else if (ServiceBusConnection.TokenProvider != null) { - this.CbsTokenProvider = new TokenProviderAdapter(this.ServiceBusConnection.TokenProvider, this.ServiceBusConnection.OperationTimeout); + CbsTokenProvider = new TokenProviderAdapter(ServiceBusConnection.TokenProvider, ServiceBusConnection.OperationTimeout); } else { throw new ArgumentNullException($"{nameof(ServiceBusConnection)} doesn't have a valid token provider"); } - this.SessionIdInternal = sessionId; + SessionIdInternal = sessionId; this.isSessionReceiver = isSessionReceiver; - this.ReceiveLinkManager = new FaultTolerantAmqpObject(this.CreateLinkAsync, CloseSession); - this.RequestResponseLinkManager = new FaultTolerantAmqpObject(this.CreateRequestResponseLinkAsync, CloseRequestResponseSession); - this.requestResponseLockedMessages = new ConcurrentExpiringSet(); - this.PrefetchCount = prefetchCount; - this.messageReceivePumpSyncLock = new object(); - this.clientLinkManager = new ActiveClientLinkManager(this, this.CbsTokenProvider); - this.diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); - MessagingEventSource.Log.MessageReceiverCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, this.ClientId); + ReceiveLinkManager = new FaultTolerantAmqpObject(CreateLinkAsync, CloseSession); + RequestResponseLinkManager = new FaultTolerantAmqpObject(CreateRequestResponseLinkAsync, CloseRequestResponseSession); + requestResponseLockedMessages = new ConcurrentExpiringSet(); + PrefetchCount = prefetchCount; + messageReceivePumpSyncLock = new object(); + clientLinkManager = new ActiveClientLinkManager(this, CbsTokenProvider); + diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); + MessagingEventSource.Log.MessageReceiverCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, ClientId); } /// @@ -229,16 +229,16 @@ internal MessageReceiver( /// public int PrefetchCount { - get => this.prefetchCount; + get => prefetchCount; set { if (value < 0) { - throw Fx.Exception.ArgumentOutOfRange(nameof(this.PrefetchCount), value, "Value cannot be less than 0."); + throw Fx.Exception.ArgumentOutOfRange(nameof(PrefetchCount), value, "Value cannot be less than 0."); } - this.prefetchCount = value; - if (this.ReceiveLinkManager.TryGetOpenedObject(out var link)) + prefetchCount = value; + if (ReceiveLinkManager.TryGetOpenedObject(out var link)) { link.SetTotalLinkCredit((uint)value, true, true); } @@ -249,16 +249,16 @@ public int PrefetchCount /// public long LastPeekedSequenceNumber { - get => this.lastPeekedSequenceNumber; + get => lastPeekedSequenceNumber; internal set { if (value < 0) { - throw new ArgumentOutOfRangeException(nameof(this.LastPeekedSequenceNumber), value.ToString()); + throw new ArgumentOutOfRangeException(nameof(LastPeekedSequenceNumber), value.ToString()); } - this.lastPeekedSequenceNumber = value; + lastPeekedSequenceNumber = value; } } @@ -269,8 +269,8 @@ internal set /// Duration after which individual operations will timeout. /// public override TimeSpan OperationTimeout { - get => this.ServiceBusConnection.OperationTimeout; - set => this.ServiceBusConnection.OperationTimeout = value; + get => ServiceBusConnection.OperationTimeout; + set => ServiceBusConnection.OperationTimeout = value; } /// @@ -305,7 +305,7 @@ public override TimeSpan OperationTimeout { /// Operation will time out after duration of public Task ReceiveAsync() { - return this.ReceiveAsync(this.OperationTimeout); + return ReceiveAsync(OperationTimeout); } /// @@ -320,7 +320,7 @@ public Task ReceiveAsync() /// public async Task ReceiveAsync(TimeSpan operationTimeout) { - var messages = await this.ReceiveAsync(1, operationTimeout).ConfigureAwait(false); + var messages = await ReceiveAsync(1, operationTimeout).ConfigureAwait(false); if (messages != null && messages.Count > 0) { return messages[0]; @@ -337,7 +337,7 @@ public async Task ReceiveAsync(TimeSpan operationTimeout) /// Receiving less than messages is not an indication of empty entity. public Task> ReceiveAsync(int maxMessageCount) { - return this.ReceiveAsync(maxMessageCount, this.OperationTimeout); + return ReceiveAsync(maxMessageCount, OperationTimeout); } /// @@ -353,26 +353,26 @@ public Task> ReceiveAsync(int maxMessageCount) /// public async Task> ReceiveAsync(int maxMessageCount, TimeSpan operationTimeout) { - this.ThrowIfClosed(); + ThrowIfClosed(); if (operationTimeout <= TimeSpan.Zero) { throw Fx.Exception.ArgumentOutOfRange(nameof(operationTimeout), operationTimeout, Resources.TimeoutMustBePositiveNonZero.FormatForUser(nameof(operationTimeout), operationTimeout)); } - MessagingEventSource.Log.MessageReceiveStart(this.ClientId, maxMessageCount); + MessagingEventSource.Log.MessageReceiveStart(ClientId, maxMessageCount); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.ReceiveStart(maxMessageCount) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.ReceiveStart(maxMessageCount) : null; Task receiveTask = null; IList unprocessedMessageList = null; try { - receiveTask = this.RetryPolicy.RunOperation( + receiveTask = RetryPolicy.RunOperation( async () => { - unprocessedMessageList = await this.OnReceiveAsync(maxMessageCount, operationTimeout) + unprocessedMessageList = await OnReceiveAsync(maxMessageCount, operationTimeout) .ConfigureAwait(false); }, operationTimeout); await receiveTask.ConfigureAwait(false); @@ -382,25 +382,25 @@ public async Task> ReceiveAsync(int maxMessageCount, TimeSpan ope { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageReceiveException(this.ClientId, exception); + MessagingEventSource.Log.MessageReceiveException(ClientId, exception); throw; } finally { - this.diagnosticSource.ReceiveStop(activity, maxMessageCount, receiveTask?.Status, unprocessedMessageList); + diagnosticSource.ReceiveStop(activity, maxMessageCount, receiveTask?.Status, unprocessedMessageList); } - MessagingEventSource.Log.MessageReceiveStop(this.ClientId, unprocessedMessageList?.Count ?? 0); + MessagingEventSource.Log.MessageReceiveStop(ClientId, unprocessedMessageList?.Count ?? 0); if (unprocessedMessageList == null) { return unprocessedMessageList; } - return await this.ProcessMessages(unprocessedMessageList).ConfigureAwait(false); + return await ProcessMessages(unprocessedMessageList).ConfigureAwait(false); } /// @@ -412,7 +412,7 @@ public async Task> ReceiveAsync(int maxMessageCount, TimeSpan ope /// public async Task ReceiveDeferredMessageAsync(long sequenceNumber) { - var messages = await this.ReceiveDeferredMessageAsync(new[] { sequenceNumber }).ConfigureAwait(false); + var messages = await ReceiveDeferredMessageAsync(new[] { sequenceNumber }).ConfigureAwait(false); if (messages != null && messages.Count > 0) { return messages[0]; @@ -430,8 +430,8 @@ public async Task ReceiveDeferredMessageAsync(long sequenceNumber) /// public async Task> ReceiveDeferredMessageAsync(IEnumerable sequenceNumbers) { - this.ThrowIfClosed(); - this.ThrowIfNotPeekLockMode(); + ThrowIfClosed(); + ThrowIfNotPeekLockMode(); if (sequenceNumbers == null) { @@ -443,37 +443,37 @@ public async Task> ReceiveDeferredMessageAsync(IEnumerable throw Fx.Exception.ArgumentNull(nameof(sequenceNumbers)); } - MessagingEventSource.Log.MessageReceiveDeferredMessageStart(this.ClientId, sequenceNumberList.Length, sequenceNumberList); + MessagingEventSource.Log.MessageReceiveDeferredMessageStart(ClientId, sequenceNumberList.Length, sequenceNumberList); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.ReceiveDeferredStart(sequenceNumberList) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.ReceiveDeferredStart(sequenceNumberList) : null; Task receiveTask = null; IList messages = null; try { - receiveTask = this.RetryPolicy.RunOperation( + receiveTask = RetryPolicy.RunOperation( async () => { - messages = await this.OnReceiveDeferredMessageAsync(sequenceNumberList).ConfigureAwait(false); - }, this.OperationTimeout); + messages = await OnReceiveDeferredMessageAsync(sequenceNumberList).ConfigureAwait(false); + }, OperationTimeout); await receiveTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageReceiveDeferredMessageException(this.ClientId, exception); + MessagingEventSource.Log.MessageReceiveDeferredMessageException(ClientId, exception); throw; } finally { - this.diagnosticSource.ReceiveDeferredStop(activity, sequenceNumberList, receiveTask?.Status, messages); + diagnosticSource.ReceiveDeferredStop(activity, sequenceNumberList, receiveTask?.Status, messages); } - MessagingEventSource.Log.MessageReceiveDeferredMessageStop(this.ClientId, messages?.Count ?? 0); + MessagingEventSource.Log.MessageReceiveDeferredMessageStop(ClientId, messages?.Count ?? 0); return messages; } @@ -489,7 +489,7 @@ public async Task> ReceiveDeferredMessageAsync(IEnumerable /// public Task CompleteAsync(string lockToken) { - return this.CompleteAsync(new[] { lockToken }); + return CompleteAsync(new[] { lockToken }); } /// @@ -503,8 +503,8 @@ public Task CompleteAsync(string lockToken) /// An containing the lock tokens of the corresponding messages to complete. public async Task CompleteAsync(IEnumerable lockTokens) { - this.ThrowIfClosed(); - this.ThrowIfNotPeekLockMode(); + ThrowIfClosed(); + ThrowIfNotPeekLockMode(); if (lockTokens == null) { throw Fx.Exception.ArgumentNull(nameof(lockTokens)); @@ -515,34 +515,34 @@ public async Task CompleteAsync(IEnumerable lockTokens) throw Fx.Exception.Argument(nameof(lockTokens), Resources.ListOfLockTokensCannotBeEmpty); } - MessagingEventSource.Log.MessageCompleteStart(this.ClientId, lockTokenList.Count, lockTokenList); + MessagingEventSource.Log.MessageCompleteStart(ClientId, lockTokenList.Count, lockTokenList); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.CompleteStart(lockTokenList) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.CompleteStart(lockTokenList) : null; Task completeTask = null; try { completeTask = - this.RetryPolicy.RunOperation(() => this.OnCompleteAsync(lockTokenList), this.OperationTimeout); + RetryPolicy.RunOperation(() => OnCompleteAsync(lockTokenList), OperationTimeout); await completeTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageCompleteException(this.ClientId, exception); + MessagingEventSource.Log.MessageCompleteException(ClientId, exception); throw; } finally { - this.diagnosticSource.CompleteStop(activity, lockTokenList, completeTask?.Status); + diagnosticSource.CompleteStop(activity, lockTokenList, completeTask?.Status); } - MessagingEventSource.Log.MessageCompleteStop(this.ClientId); + MessagingEventSource.Log.MessageCompleteStop(ClientId); } /// @@ -557,37 +557,37 @@ public async Task CompleteAsync(IEnumerable lockTokens) /// public async Task AbandonAsync(string lockToken, IDictionary propertiesToModify = null) { - this.ThrowIfClosed(); - this.ThrowIfNotPeekLockMode(); + ThrowIfClosed(); + ThrowIfNotPeekLockMode(); - MessagingEventSource.Log.MessageAbandonStart(this.ClientId, 1, lockToken); + MessagingEventSource.Log.MessageAbandonStart(ClientId, 1, lockToken); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("Abandon", lockToken) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.DisposeStart("Abandon", lockToken) : null; Task abandonTask = null; try { - abandonTask = this.RetryPolicy.RunOperation(() => this.OnAbandonAsync(lockToken, propertiesToModify), - this.OperationTimeout); + abandonTask = RetryPolicy.RunOperation(() => OnAbandonAsync(lockToken, propertiesToModify), + OperationTimeout); await abandonTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageAbandonException(this.ClientId, exception); + MessagingEventSource.Log.MessageAbandonException(ClientId, exception); throw; } finally { - this.diagnosticSource.DisposeStop(activity, lockToken, abandonTask?.Status); + diagnosticSource.DisposeStop(activity, lockToken, abandonTask?.Status); } - MessagingEventSource.Log.MessageAbandonStop(this.ClientId); + MessagingEventSource.Log.MessageAbandonStop(ClientId); } /// Indicates that the receiver wants to defer the processing for the message. @@ -603,35 +603,35 @@ public async Task AbandonAsync(string lockToken, IDictionary pro /// public async Task DeferAsync(string lockToken, IDictionary propertiesToModify = null) { - this.ThrowIfClosed(); - this.ThrowIfNotPeekLockMode(); + ThrowIfClosed(); + ThrowIfNotPeekLockMode(); - MessagingEventSource.Log.MessageDeferStart(this.ClientId, 1, lockToken); + MessagingEventSource.Log.MessageDeferStart(ClientId, 1, lockToken); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("Defer", lockToken) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.DisposeStart("Defer", lockToken) : null; Task deferTask = null; try { - deferTask = this.RetryPolicy.RunOperation(() => this.OnDeferAsync(lockToken, propertiesToModify), - this.OperationTimeout); + deferTask = RetryPolicy.RunOperation(() => OnDeferAsync(lockToken, propertiesToModify), + OperationTimeout); await deferTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageDeferException(this.ClientId, exception); + MessagingEventSource.Log.MessageDeferException(ClientId, exception); throw; } finally { - this.diagnosticSource.DisposeStop(activity, lockToken, deferTask?.Status); + diagnosticSource.DisposeStop(activity, lockToken, deferTask?.Status); } - MessagingEventSource.Log.MessageDeferStop(this.ClientId); + MessagingEventSource.Log.MessageDeferStop(ClientId); } /// @@ -648,35 +648,35 @@ public async Task DeferAsync(string lockToken, IDictionary prope /// public async Task DeadLetterAsync(string lockToken, IDictionary propertiesToModify = null) { - this.ThrowIfClosed(); - this.ThrowIfNotPeekLockMode(); + ThrowIfClosed(); + ThrowIfNotPeekLockMode(); - MessagingEventSource.Log.MessageDeadLetterStart(this.ClientId, 1, lockToken); + MessagingEventSource.Log.MessageDeadLetterStart(ClientId, 1, lockToken); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; Task deadLetterTask = null; try { - deadLetterTask = this.RetryPolicy.RunOperation(() => this.OnDeadLetterAsync(lockToken, propertiesToModify), - this.OperationTimeout); + deadLetterTask = RetryPolicy.RunOperation(() => OnDeadLetterAsync(lockToken, propertiesToModify), + OperationTimeout); await deadLetterTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageDeadLetterException(this.ClientId, exception); + MessagingEventSource.Log.MessageDeadLetterException(ClientId, exception); throw; } finally { - this.diagnosticSource.DisposeStop(activity, lockToken, deadLetterTask?.Status); + diagnosticSource.DisposeStop(activity, lockToken, deadLetterTask?.Status); } - MessagingEventSource.Log.MessageDeadLetterStop(this.ClientId); + MessagingEventSource.Log.MessageDeadLetterStop(ClientId); } /// @@ -694,38 +694,38 @@ public async Task DeadLetterAsync(string lockToken, IDictionary /// public async Task DeadLetterAsync(string lockToken, string deadLetterReason, string deadLetterErrorDescription = null) { - this.ThrowIfClosed(); - this.ThrowIfNotPeekLockMode(); + ThrowIfClosed(); + ThrowIfNotPeekLockMode(); - MessagingEventSource.Log.MessageDeadLetterStart(this.ClientId, 1, lockToken); + MessagingEventSource.Log.MessageDeadLetterStart(ClientId, 1, lockToken); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; Task deadLetterTask = null; try { deadLetterTask = - this.RetryPolicy.RunOperation( - () => this.OnDeadLetterAsync(lockToken, null, deadLetterReason, deadLetterErrorDescription), - this.OperationTimeout); + RetryPolicy.RunOperation( + () => OnDeadLetterAsync(lockToken, null, deadLetterReason, deadLetterErrorDescription), + OperationTimeout); await deadLetterTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageDeadLetterException(this.ClientId, exception); + MessagingEventSource.Log.MessageDeadLetterException(ClientId, exception); throw; } finally { - this.diagnosticSource.DisposeStop(activity, lockToken, deadLetterTask?.Status); + diagnosticSource.DisposeStop(activity, lockToken, deadLetterTask?.Status); } - MessagingEventSource.Log.MessageDeadLetterStop(this.ClientId); + MessagingEventSource.Log.MessageDeadLetterStop(ClientId); } /// @@ -755,38 +755,38 @@ public async Task RenewLockAsync(Message message) /// public async Task RenewLockAsync(string lockToken) { - this.ThrowIfClosed(); - this.ThrowIfNotPeekLockMode(); + ThrowIfClosed(); + ThrowIfNotPeekLockMode(); - MessagingEventSource.Log.MessageRenewLockStart(this.ClientId, 1, lockToken); + MessagingEventSource.Log.MessageRenewLockStart(ClientId, 1, lockToken); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.RenewLockStart(lockToken) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.RenewLockStart(lockToken) : null; Task renewTask = null; var lockedUntilUtc = DateTime.MinValue; try { - renewTask = this.RetryPolicy.RunOperation( - async () => lockedUntilUtc = await this.OnRenewLockAsync(lockToken).ConfigureAwait(false), - this.OperationTimeout); + renewTask = RetryPolicy.RunOperation( + async () => lockedUntilUtc = await OnRenewLockAsync(lockToken).ConfigureAwait(false), + OperationTimeout); await renewTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageRenewLockException(this.ClientId, exception); + MessagingEventSource.Log.MessageRenewLockException(ClientId, exception); throw; } finally { - this.diagnosticSource.RenewLockStop(activity, lockToken, renewTask?.Status, lockedUntilUtc); + diagnosticSource.RenewLockStop(activity, lockToken, renewTask?.Status, lockedUntilUtc); } - MessagingEventSource.Log.MessageRenewLockStop(this.ClientId); + MessagingEventSource.Log.MessageRenewLockStop(ClientId); return lockedUntilUtc; } @@ -803,7 +803,7 @@ public async Task RenewLockAsync(string lockToken) /// The that represents the next message to be read. Returns null when nothing to peek. public Task PeekAsync() { - return this.PeekBySequenceNumberAsync(this.lastPeekedSequenceNumber + 1); + return PeekBySequenceNumberAsync(lastPeekedSequenceNumber + 1); } /// @@ -818,7 +818,7 @@ public Task PeekAsync() /// List of that represents the next message to be read. Returns null when nothing to peek. public Task> PeekAsync(int maxMessageCount) { - return this.PeekBySequenceNumberAsync(this.lastPeekedSequenceNumber + 1, maxMessageCount); + return PeekBySequenceNumberAsync(lastPeekedSequenceNumber + 1, maxMessageCount); } /// @@ -828,7 +828,7 @@ public Task> PeekAsync(int maxMessageCount) /// The asynchronous operation that returns the that represents the next message to be read. public async Task PeekBySequenceNumberAsync(long fromSequenceNumber) { - var messages = await this.PeekBySequenceNumberAsync(fromSequenceNumber, 1).ConfigureAwait(false); + var messages = await PeekBySequenceNumberAsync(fromSequenceNumber, 1).ConfigureAwait(false); return messages?.FirstOrDefault(); } @@ -838,21 +838,21 @@ public async Task PeekBySequenceNumberAsync(long fromSequenceNumber) /// A batch of messages peeked. public async Task> PeekBySequenceNumberAsync(long fromSequenceNumber, int messageCount) { - this.ThrowIfClosed(); + ThrowIfClosed(); IList messages = null; - MessagingEventSource.Log.MessagePeekStart(this.ClientId, fromSequenceNumber, messageCount); + MessagingEventSource.Log.MessagePeekStart(ClientId, fromSequenceNumber, messageCount); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.PeekStart(fromSequenceNumber, messageCount) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.PeekStart(fromSequenceNumber, messageCount) : null; Task peekTask = null; try { - peekTask = this.RetryPolicy.RunOperation( + peekTask = RetryPolicy.RunOperation( async () => { - messages = await this.OnPeekAsync(fromSequenceNumber, messageCount).ConfigureAwait(false); - }, this.OperationTimeout); + messages = await OnPeekAsync(fromSequenceNumber, messageCount).ConfigureAwait(false); + }, OperationTimeout); await peekTask.ConfigureAwait(false); } @@ -860,18 +860,18 @@ public async Task> PeekBySequenceNumberAsync(long fromSequenceNum { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessagePeekException(this.ClientId, exception); + MessagingEventSource.Log.MessagePeekException(ClientId, exception); throw; } finally { - this.diagnosticSource.PeekStop(activity, fromSequenceNumber, messageCount, peekTask?.Status, messages); + diagnosticSource.PeekStop(activity, fromSequenceNumber, messageCount, peekTask?.Status, messages); } - MessagingEventSource.Log.MessagePeekStop(this.ClientId, messages?.Count ?? 0); + MessagingEventSource.Log.MessagePeekStop(ClientId, messages?.Count ?? 0); return messages; } @@ -883,7 +883,7 @@ public async Task> PeekBySequenceNumberAsync(long fromSequenceNum /// A that is used to notify exceptions. public void RegisterMessageHandler(Func handler, Func exceptionReceivedHandler) { - this.RegisterMessageHandler(handler, new MessageHandlerOptions(exceptionReceivedHandler)); + RegisterMessageHandler(handler, new MessageHandlerOptions(exceptionReceivedHandler)); } /// @@ -895,8 +895,8 @@ public void RegisterMessageHandler(Func handle /// Enable prefetch to speed up the receive rate. public void RegisterMessageHandler(Func handler, MessageHandlerOptions messageHandlerOptions) { - this.ThrowIfClosed(); - this.OnMessageHandler(messageHandlerOptions, handler); + ThrowIfClosed(); + OnMessageHandler(messageHandlerOptions, handler); } /// @@ -904,16 +904,16 @@ public void RegisterMessageHandler(Func handle /// public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) { - this.ThrowIfClosed(); + ThrowIfClosed(); if (serviceBusPlugin == null) { throw new ArgumentNullException(nameof(serviceBusPlugin), Resources.ArgumentNullOrWhiteSpace.FormatForUser(nameof(serviceBusPlugin))); } - if (this.RegisteredPlugins.Any(p => p.Name == serviceBusPlugin.Name)) + if (RegisteredPlugins.Any(p => p.Name == serviceBusPlugin.Name)) { throw new ArgumentException(nameof(serviceBusPlugin), Resources.PluginAlreadyRegistered.FormatForUser(serviceBusPlugin.Name)); } - this.RegisteredPlugins.Add(serviceBusPlugin); + RegisteredPlugins.Add(serviceBusPlugin); } /// @@ -922,8 +922,8 @@ public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) /// The of the plugin to be unregistered. public override void UnregisterPlugin(string serviceBusPluginName) { - this.ThrowIfClosed(); - if (this.RegisteredPlugins == null) + ThrowIfClosed(); + if (RegisteredPlugins == null) { return; } @@ -931,17 +931,17 @@ public override void UnregisterPlugin(string serviceBusPluginName) { throw new ArgumentNullException(nameof(serviceBusPluginName), Resources.ArgumentNullOrWhiteSpace.FormatForUser(nameof(serviceBusPluginName))); } - if (this.RegisteredPlugins.Any(p => p.Name == serviceBusPluginName)) + if (RegisteredPlugins.Any(p => p.Name == serviceBusPluginName)) { - var plugin = this.RegisteredPlugins.First(p => p.Name == serviceBusPluginName); - this.RegisteredPlugins.Remove(plugin); + var plugin = RegisteredPlugins.First(p => p.Name == serviceBusPluginName); + RegisteredPlugins.Remove(plugin); } } internal async Task GetSessionReceiverLinkAsync(TimeSpan serverWaitTime) { var timeoutHelper = new TimeoutHelper(serverWaitTime, true); - var receivingAmqpLink = await this.ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); + var receivingAmqpLink = await ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); var source = (Source)receivingAmqpLink.Settings.Source; if (!source.FilterSet.TryGetValue(AmqpClientConstants.SessionFilterName, out var tempSessionId)) @@ -956,9 +956,9 @@ internal async Task GetSessionReceiverLinkAsync(TimeSpan serverWaitTime) throw new ServiceBusException(true, Resources.AmqpFieldSessionId); } - receivingAmqpLink.Closed += this.OnSessionReceiverLinkClosed; - this.SessionIdInternal = tempSessionId; - this.LockedUntilUtcInternal = receivingAmqpLink.Settings.Properties.TryGetValue(AmqpClientConstants.LockedUntilUtc, out var lockedUntilUtcTicks) + receivingAmqpLink.Closed += OnSessionReceiverLinkClosed; + SessionIdInternal = tempSessionId; + LockedUntilUtcInternal = receivingAmqpLink.Settings.Properties.TryGetValue(AmqpClientConstants.LockedUntilUtc, out var lockedUntilUtcTicks) ? new DateTime(lockedUntilUtcTicks, DateTimeKind.Utc) : DateTime.MinValue; } @@ -966,24 +966,24 @@ internal async Task GetSessionReceiverLinkAsync(TimeSpan serverWaitTime) internal async Task ExecuteRequestResponseAsync(AmqpRequestMessage amqpRequestMessage) { var amqpMessage = amqpRequestMessage.AmqpMessage; - if (this.isSessionReceiver) + if (isSessionReceiver) { - this.ThrowIfSessionLockLost(); + ThrowIfSessionLockLost(); } - var timeoutHelper = new TimeoutHelper(this.OperationTimeout, true); + var timeoutHelper = new TimeoutHelper(OperationTimeout, true); ArraySegment transactionId = AmqpConstants.NullBinary; var ambientTransaction = Transaction.Current; if (ambientTransaction != null) { - transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, this.ServiceBusConnection).ConfigureAwait(false); + transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, ServiceBusConnection).ConfigureAwait(false); } - if (!this.RequestResponseLinkManager.TryGetOpenedObject(out var requestResponseAmqpLink)) + if (!RequestResponseLinkManager.TryGetOpenedObject(out var requestResponseAmqpLink)) { - MessagingEventSource.Log.CreatingNewLink(this.ClientId, this.isSessionReceiver, this.SessionIdInternal, true, this.LinkException); - requestResponseAmqpLink = await this.RequestResponseLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); + MessagingEventSource.Log.CreatingNewLink(ClientId, isSessionReceiver, SessionIdInternal, true, LinkException); + requestResponseAmqpLink = await RequestResponseLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } var responseAmqpMessage = await Task.Factory.FromAsync( @@ -996,41 +996,41 @@ internal async Task ExecuteRequestResponseAsync(AmqpRequest protected override async Task OnClosingAsync() { - this.clientLinkManager.Close(); - lock (this.messageReceivePumpSyncLock) + clientLinkManager.Close(); + lock (messageReceivePumpSyncLock) { - if (this.receivePump != null) + if (receivePump != null) { - this.receivePumpCancellationTokenSource.Cancel(); - this.receivePumpCancellationTokenSource.Dispose(); - this.receivePump = null; + receivePumpCancellationTokenSource.Cancel(); + receivePumpCancellationTokenSource.Dispose(); + receivePump = null; } } - await this.ReceiveLinkManager.CloseAsync().ConfigureAwait(false); - await this.RequestResponseLinkManager.CloseAsync().ConfigureAwait(false); - this.requestResponseLockedMessages.Close(); + await ReceiveLinkManager.CloseAsync().ConfigureAwait(false); + await RequestResponseLinkManager.CloseAsync().ConfigureAwait(false); + requestResponseLockedMessages.Close(); } protected virtual async Task> OnReceiveAsync(int maxMessageCount, TimeSpan serverWaitTime) { ReceivingAmqpLink receiveLink = null; - if (this.isSessionReceiver) + if (isSessionReceiver) { - this.ThrowIfSessionLockLost(); + ThrowIfSessionLockLost(); } try { var timeoutHelper = new TimeoutHelper(serverWaitTime, true); - if(!this.ReceiveLinkManager.TryGetOpenedObject(out receiveLink)) + if(!ReceiveLinkManager.TryGetOpenedObject(out receiveLink)) { - MessagingEventSource.Log.CreatingNewLink(this.ClientId, this.isSessionReceiver, this.SessionIdInternal, false, this.LinkException); - receiveLink = await this.ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); + MessagingEventSource.Log.CreatingNewLink(ClientId, isSessionReceiver, SessionIdInternal, false, LinkException); + receiveLink = await ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } IList brokeredMessages = null; - this.ThrowIfClosed(); + ThrowIfClosed(); IEnumerable amqpMessages = null; var hasMessages = await Task.Factory.FromAsync( @@ -1047,7 +1047,7 @@ protected virtual async Task> OnReceiveAsync(int maxMessageCount, { foreach (var amqpMessage in amqpMessages) { - if (this.ReceiveMode == ReceiveMode.ReceiveAndDelete) + if (ReceiveMode == ReceiveMode.ReceiveAndDelete) { receiveLink.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome); } @@ -1076,10 +1076,10 @@ protected virtual async Task> OnPeekAsync(long fromSequenceNumber { var amqpRequestMessage = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.PeekMessageOperation, - this.OperationTimeout, + OperationTimeout, null); - if (this.ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) + if (ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) { amqpRequestMessage.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = receiveLink.Name; } @@ -1087,14 +1087,14 @@ protected virtual async Task> OnPeekAsync(long fromSequenceNumber amqpRequestMessage.Map[ManagementConstants.Properties.FromSequenceNumber] = fromSequenceNumber; amqpRequestMessage.Map[ManagementConstants.Properties.MessageCount] = messageCount; - if (!string.IsNullOrWhiteSpace(this.SessionIdInternal)) + if (!string.IsNullOrWhiteSpace(SessionIdInternal)) { - amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = this.SessionIdInternal; + amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = SessionIdInternal; } var messages = new List(); - var amqpResponseMessage = await this.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); + var amqpResponseMessage = await ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); if (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.OK) { Message message = null; @@ -1109,7 +1109,7 @@ protected virtual async Task> OnPeekAsync(long fromSequenceNumber if (message != null) { - this.LastPeekedSequenceNumber = message.SystemProperties.SequenceNumber; + LastPeekedSequenceNumber = message.SystemProperties.SequenceNumber; } return messages; @@ -1134,20 +1134,20 @@ protected virtual async Task> OnReceiveDeferredMessageAsync(long[ var messages = new List(); try { - var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.ReceiveBySequenceNumberOperation, this.OperationTimeout, null); + var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.ReceiveBySequenceNumberOperation, OperationTimeout, null); - if (this.ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) + if (ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) { amqpRequestMessage.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = receiveLink.Name; } amqpRequestMessage.Map[ManagementConstants.Properties.SequenceNumbers] = sequenceNumbers; - amqpRequestMessage.Map[ManagementConstants.Properties.ReceiverSettleMode] = (uint)(this.ReceiveMode == ReceiveMode.ReceiveAndDelete ? 0 : 1); - if (!string.IsNullOrWhiteSpace(this.SessionIdInternal)) + amqpRequestMessage.Map[ManagementConstants.Properties.ReceiverSettleMode] = (uint)(ReceiveMode == ReceiveMode.ReceiveAndDelete ? 0 : 1); + if (!string.IsNullOrWhiteSpace(SessionIdInternal)) { - amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = this.SessionIdInternal; + amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = SessionIdInternal; } - var response = await this.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); + var response = await ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); if (response.StatusCode == AmqpResponseStatusCode.OK) { @@ -1160,7 +1160,7 @@ protected virtual async Task> OnReceiveDeferredMessageAsync(long[ if (entry.TryGetValue(ManagementConstants.Properties.LockToken, out var lockToken)) { message.SystemProperties.LockTokenGuid = lockToken; - this.requestResponseLockedMessages.AddOrUpdate(lockToken, message.SystemProperties.LockedUntilUtc); + requestResponseLockedMessages.AddOrUpdate(lockToken, message.SystemProperties.LockedUntilUtc); } messages.Add(message); @@ -1182,31 +1182,31 @@ protected virtual async Task> OnReceiveDeferredMessageAsync(long[ protected virtual Task OnCompleteAsync(IEnumerable lockTokens) { var lockTokenGuids = lockTokens.Select(lt => new Guid(lt)).ToArray(); - if (lockTokenGuids.Any(lt => this.requestResponseLockedMessages.Contains(lt))) + if (lockTokenGuids.Any(lt => requestResponseLockedMessages.Contains(lt))) { - return this.DisposeMessageRequestResponseAsync(lockTokenGuids, DispositionStatus.Completed); + return DisposeMessageRequestResponseAsync(lockTokenGuids, DispositionStatus.Completed); } - return this.DisposeMessagesAsync(lockTokenGuids, AmqpConstants.AcceptedOutcome); + return DisposeMessagesAsync(lockTokenGuids, AmqpConstants.AcceptedOutcome); } protected virtual Task OnAbandonAsync(string lockToken, IDictionary propertiesToModify = null) { var lockTokens = new[] { new Guid(lockToken) }; - if (lockTokens.Any(lt => this.requestResponseLockedMessages.Contains(lt))) + if (lockTokens.Any(lt => requestResponseLockedMessages.Contains(lt))) { - return this.DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Abandoned, propertiesToModify); + return DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Abandoned, propertiesToModify); } - return this.DisposeMessagesAsync(lockTokens, GetAbandonOutcome(propertiesToModify)); + return DisposeMessagesAsync(lockTokens, GetAbandonOutcome(propertiesToModify)); } protected virtual Task OnDeferAsync(string lockToken, IDictionary propertiesToModify = null) { var lockTokens = new[] { new Guid(lockToken) }; - if (lockTokens.Any(lt => this.requestResponseLockedMessages.Contains(lt))) + if (lockTokens.Any(lt => requestResponseLockedMessages.Contains(lt))) { - return this.DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Defered, propertiesToModify); + return DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Defered, propertiesToModify); } - return this.DisposeMessagesAsync(lockTokens, GetDeferOutcome(propertiesToModify)); + return DisposeMessagesAsync(lockTokens, GetDeferOutcome(propertiesToModify)); } protected virtual Task OnDeadLetterAsync(string lockToken, IDictionary propertiesToModify = null, string deadLetterReason = null, string deadLetterErrorDescription = null) @@ -1222,12 +1222,12 @@ protected virtual Task OnDeadLetterAsync(string lockToken, IDictionary this.requestResponseLockedMessages.Contains(lt))) + if (lockTokens.Any(lt => requestResponseLockedMessages.Contains(lt))) { - return this.DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Suspended, propertiesToModify, deadLetterReason, deadLetterErrorDescription); + return DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Suspended, propertiesToModify, deadLetterReason, deadLetterErrorDescription); } - return this.DisposeMessagesAsync(lockTokens, GetRejectedOutcome(propertiesToModify, deadLetterReason, deadLetterErrorDescription)); + return DisposeMessagesAsync(lockTokens, GetRejectedOutcome(propertiesToModify, deadLetterReason, deadLetterErrorDescription)); } protected virtual async Task OnRenewLockAsync(string lockToken) @@ -1236,15 +1236,15 @@ protected virtual async Task OnRenewLockAsync(string lockToken) try { // Create an AmqpRequest Message to renew lock - var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.RenewLockOperation, this.OperationTimeout, null); + var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.RenewLockOperation, OperationTimeout, null); - if (this.ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) + if (ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) { amqpRequestMessage.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = receiveLink.Name; } amqpRequestMessage.Map[ManagementConstants.Properties.LockTokens] = new[] { new Guid(lockToken) }; - var amqpResponseMessage = await this.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); + var amqpResponseMessage = await ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); if (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.OK) { @@ -1269,40 +1269,40 @@ protected virtual void OnMessageHandler( MessageHandlerOptions registerHandlerOptions, Func callback) { - MessagingEventSource.Log.RegisterOnMessageHandlerStart(this.ClientId, registerHandlerOptions); + MessagingEventSource.Log.RegisterOnMessageHandlerStart(ClientId, registerHandlerOptions); - lock (this.messageReceivePumpSyncLock) + lock (messageReceivePumpSyncLock) { - if (this.receivePump != null) + if (receivePump != null) { throw new InvalidOperationException(Resources.MessageHandlerAlreadyRegistered); } - this.receivePumpCancellationTokenSource = new CancellationTokenSource(); - this.receivePump = new MessageReceivePump(this, registerHandlerOptions, callback, this.ServiceBusConnection.Endpoint, this.receivePumpCancellationTokenSource.Token); + receivePumpCancellationTokenSource = new CancellationTokenSource(); + receivePump = new MessageReceivePump(this, registerHandlerOptions, callback, ServiceBusConnection.Endpoint, receivePumpCancellationTokenSource.Token); } try { - this.receivePump.StartPump(); + receivePump.StartPump(); } catch (Exception exception) { - MessagingEventSource.Log.RegisterOnMessageHandlerException(this.ClientId, exception); - lock (this.messageReceivePumpSyncLock) + MessagingEventSource.Log.RegisterOnMessageHandlerException(ClientId, exception); + lock (messageReceivePumpSyncLock) { - if (this.receivePump != null) + if (receivePump != null) { - this.receivePumpCancellationTokenSource.Cancel(); - this.receivePumpCancellationTokenSource.Dispose(); - this.receivePump = null; + receivePumpCancellationTokenSource.Cancel(); + receivePumpCancellationTokenSource.Dispose(); + receivePump = null; } } throw; } - MessagingEventSource.Log.RegisterOnMessageHandlerStop(this.ClientId); + MessagingEventSource.Log.RegisterOnMessageHandlerStop(ClientId); } static void CloseSession(ReceivingAmqpLink link) @@ -1318,7 +1318,7 @@ static void CloseRequestResponseSession(RequestResponseAmqpLink requestResponseA async Task ProcessMessage(Message message) { var processedMessage = message; - foreach (var plugin in this.RegisteredPlugins) + foreach (var plugin in RegisteredPlugins) { try { @@ -1340,7 +1340,7 @@ async Task ProcessMessage(Message message) async Task> ProcessMessages(IList messageList) { - if (this.RegisteredPlugins.Count < 1) + if (RegisteredPlugins.Count < 1) { return messageList; } @@ -1348,7 +1348,7 @@ async Task> ProcessMessages(IList messageList) var processedMessageList = new List(); foreach (var message in messageList) { - var processedMessage = await this.ProcessMessage(message).ConfigureAwait(false); + var processedMessage = await ProcessMessage(message).ConfigureAwait(false); processedMessageList.Add(processedMessage); } @@ -1357,13 +1357,13 @@ async Task> ProcessMessages(IList messageList) async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome outcome) { - if(this.isSessionReceiver) + if(isSessionReceiver) { - this.ThrowIfSessionLockLost(); + ThrowIfSessionLockLost(); } - var timeoutHelper = new TimeoutHelper(this.OperationTimeout, true); - List> deliveryTags = this.ConvertLockTokensToDeliveryTags(lockTokens); + var timeoutHelper = new TimeoutHelper(OperationTimeout, true); + List> deliveryTags = ConvertLockTokensToDeliveryTags(lockTokens); ReceivingAmqpLink receiveLink = null; try @@ -1372,13 +1372,13 @@ async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome outcome) var ambientTransaction = Transaction.Current; if (ambientTransaction != null) { - transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, this.ServiceBusConnection).ConfigureAwait(false); + transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, ServiceBusConnection).ConfigureAwait(false); } - if (!this.ReceiveLinkManager.TryGetOpenedObject(out receiveLink)) + if (!ReceiveLinkManager.TryGetOpenedObject(out receiveLink)) { - MessagingEventSource.Log.CreatingNewLink(this.ClientId, this.isSessionReceiver, this.SessionIdInternal, false, this.LinkException); - receiveLink = await this.ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); + MessagingEventSource.Log.CreatingNewLink(ClientId, isSessionReceiver, SessionIdInternal, false, LinkException); + receiveLink = await ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } var disposeMessageTasks = new Task[deliveryTags.Count]; @@ -1400,7 +1400,7 @@ async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome outcome) { if (error.Condition.Equals(AmqpErrorCode.NotFound)) { - if (this.isSessionReceiver) + if (isSessionReceiver) { throw new SessionLockLostException(Resources.SessionLockExpiredOnMessageSession); } @@ -1418,8 +1418,8 @@ async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome outcome) receiveLink != null && receiveLink.State != AmqpObjectState.Opened) { // The link state is lost, We need to return a non-retriable error. - MessagingEventSource.Log.LinkStateLost(this.ClientId, receiveLink.Name, receiveLink.State, this.isSessionReceiver, exception); - if (this.isSessionReceiver) + MessagingEventSource.Log.LinkStateLost(ClientId, receiveLink.Name, receiveLink.State, isSessionReceiver, exception); + if (isSessionReceiver) { throw new SessionLockLostException(Resources.SessionLockExpiredOnMessageSession); } @@ -1436,9 +1436,9 @@ async Task DisposeMessageRequestResponseAsync(Guid[] lockTokens, DispositionStat try { // Create an AmqpRequest Message to update disposition - var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.UpdateDispositionOperation, this.OperationTimeout, null); + var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.UpdateDispositionOperation, OperationTimeout, null); - if (this.ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) + if (ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) { amqpRequestMessage.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = receiveLink.Name; } @@ -1477,12 +1477,12 @@ async Task DisposeMessageRequestResponseAsync(Guid[] lockTokens, DispositionStat } } - if (!string.IsNullOrWhiteSpace(this.SessionIdInternal)) + if (!string.IsNullOrWhiteSpace(SessionIdInternal)) { - amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = this.SessionIdInternal; + amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = SessionIdInternal; } - var amqpResponseMessage = await this.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); + var amqpResponseMessage = await ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); if (amqpResponseMessage.StatusCode != AmqpResponseStatusCode.OK) { throw amqpResponseMessage.ToMessagingContractException(); @@ -1498,40 +1498,40 @@ async Task CreateLinkAsync(TimeSpan timeout) { FilterSet filterMap = null; - MessagingEventSource.Log.AmqpReceiveLinkCreateStart(this.ClientId, false, this.EntityType, this.Path); + MessagingEventSource.Log.AmqpReceiveLinkCreateStart(ClientId, false, EntityType, Path); - if (this.isSessionReceiver) + if (isSessionReceiver) { - filterMap = new FilterSet { { AmqpClientConstants.SessionFilterName, this.SessionIdInternal } }; + filterMap = new FilterSet { { AmqpClientConstants.SessionFilterName, SessionIdInternal } }; } var amqpLinkSettings = new AmqpLinkSettings { Role = true, - TotalLinkCredit = (uint)this.PrefetchCount, - AutoSendFlow = this.PrefetchCount > 0, - Source = new Source { Address = this.Path, FilterSet = filterMap }, - SettleType = (this.ReceiveMode == ReceiveMode.PeekLock) ? SettleMode.SettleOnDispose : SettleMode.SettleOnSend + TotalLinkCredit = (uint)PrefetchCount, + AutoSendFlow = PrefetchCount > 0, + Source = new Source { Address = Path, FilterSet = filterMap }, + SettleType = (ReceiveMode == ReceiveMode.PeekLock) ? SettleMode.SettleOnDispose : SettleMode.SettleOnSend }; - if (this.EntityType != null) + if (EntityType != null) { - amqpLinkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)this.EntityType); + amqpLinkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)EntityType); } amqpLinkSettings.AddProperty(AmqpClientConstants.TimeoutName, (uint)timeout.TotalMilliseconds); - var endpointUri = new Uri(this.ServiceBusConnection.Endpoint, this.Path); + var endpointUri = new Uri(ServiceBusConnection.Endpoint, Path); var claims = new[] { ClaimConstants.Listen }; var amqpSendReceiveLinkCreator = new AmqpSendReceiveLinkCreator( - this.Path, - this.ServiceBusConnection, + Path, + ServiceBusConnection, endpointUri, new string[] { endpointUri.AbsoluteUri }, claims, - this.CbsTokenProvider, + CbsTokenProvider, amqpLinkSettings, - this.ClientId); + ClientId); Tuple linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); @@ -1543,9 +1543,9 @@ async Task CreateLinkAsync(TimeSpan timeout) claims, linkDetails.Item2); - this.clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); + clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); - MessagingEventSource.Log.AmqpReceiveLinkCreateStop(this.ClientId); + MessagingEventSource.Log.AmqpReceiveLinkCreateStop(ClientId); return receivingAmqpLink; } @@ -1553,23 +1553,23 @@ async Task CreateLinkAsync(TimeSpan timeout) // TODO: Consolidate the link creation paths async Task CreateRequestResponseLinkAsync(TimeSpan timeout) { - var entityPath = this.Path + '/' + AmqpClientConstants.ManagementAddress; + var entityPath = Path + '/' + AmqpClientConstants.ManagementAddress; - MessagingEventSource.Log.AmqpReceiveLinkCreateStart(this.ClientId, true, this.EntityType, entityPath); + MessagingEventSource.Log.AmqpReceiveLinkCreateStart(ClientId, true, EntityType, entityPath); var amqpLinkSettings = new AmqpLinkSettings(); amqpLinkSettings.AddProperty(AmqpClientConstants.EntityTypeName, AmqpClientConstants.EntityTypeManagement); - var endpointUri = new Uri(this.ServiceBusConnection.Endpoint, entityPath); + var endpointUri = new Uri(ServiceBusConnection.Endpoint, entityPath); string[] claims = { ClaimConstants.Manage, ClaimConstants.Listen }; var amqpRequestResponseLinkCreator = new AmqpRequestResponseLinkCreator( entityPath, - this.ServiceBusConnection, + ServiceBusConnection, endpointUri, new string[] { endpointUri.AbsoluteUri }, claims, - this.CbsTokenProvider, + CbsTokenProvider, amqpLinkSettings, - this.ClientId); + ClientId); var linkDetails = await amqpRequestResponseLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); @@ -1580,9 +1580,9 @@ async Task CreateRequestResponseLinkAsync(TimeSpan time new string[] { endpointUri.AbsoluteUri }, claims, linkDetails.Item2); - this.clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); + clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); - MessagingEventSource.Log.AmqpReceiveLinkCreateStop(this.ClientId); + MessagingEventSource.Log.AmqpReceiveLinkCreateStop(ClientId); return requestResponseAmqpLink; } @@ -1597,8 +1597,8 @@ void OnSessionReceiverLinkClosed(object sender, EventArgs e) exception = new SessionLockLostException("Session lock lost. Accept a new session", exception); } - this.LinkException = exception; - MessagingEventSource.Log.SessionReceiverLinkClosed(this.ClientId, this.SessionIdInternal, this.LinkException); + LinkException = exception; + MessagingEventSource.Log.SessionReceiverLinkClosed(ClientId, SessionIdInternal, LinkException); } } @@ -1609,7 +1609,7 @@ List> ConvertLockTokensToDeliveryTags(IEnumerable lockT void ThrowIfNotPeekLockMode() { - if (this.ReceiveMode != ReceiveMode.PeekLock) + if (ReceiveMode != ReceiveMode.PeekLock) { throw Fx.Exception.AsError(new InvalidOperationException("The operation is only supported in 'PeekLock' receive mode.")); } @@ -1617,20 +1617,20 @@ void ThrowIfNotPeekLockMode() void ThrowIfSessionLockLost() { - if (this.LinkException != null) + if (LinkException != null) { - throw this.LinkException; + throw LinkException; } } Outcome GetAbandonOutcome(IDictionary propertiesToModify) { - return this.GetModifiedOutcome(propertiesToModify, false); + return GetModifiedOutcome(propertiesToModify, false); } Outcome GetDeferOutcome(IDictionary propertiesToModify) { - return this.GetModifiedOutcome(propertiesToModify, true); + return GetModifiedOutcome(propertiesToModify, true); } Outcome GetModifiedOutcome(IDictionary propertiesToModify, bool undeliverableHere) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs index 18d22681cc86..2fe3316cf66c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs @@ -13,8 +13,8 @@ namespace Microsoft.Azure.ServiceBus.Core using Microsoft.Azure.Amqp; using Microsoft.Azure.Amqp.Encoding; using Microsoft.Azure.Amqp.Framing; - using Microsoft.Azure.ServiceBus.Amqp; - using Microsoft.Azure.ServiceBus.Primitives; + using Amqp; + using Primitives; /// /// The MessageSender can be used to send messages to Queues or Topics. @@ -72,7 +72,7 @@ public MessageSender( throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -92,7 +92,7 @@ public MessageSender( RetryPolicy retryPolicy = null) : this(entityPath, null, null, new ServiceBusConnection(endpoint, transportType, retryPolicy) {TokenProvider = tokenProvider}, null, retryPolicy) { - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -107,7 +107,7 @@ public MessageSender( RetryPolicy retryPolicy = null) : this(entityPath, null, null, serviceBusConnection, null, retryPolicy) { - this.OwnsConnection = false; + OwnsConnection = false; } /// @@ -130,7 +130,7 @@ public MessageSender( RetryPolicy retryPolicy = null) :this(viaEntityPath, entityPath, null, serviceBusConnection, null, retryPolicy) { - this.OwnsConnection = false; + OwnsConnection = false; } internal MessageSender( @@ -149,38 +149,38 @@ internal MessageSender( throw Fx.Exception.ArgumentNullOrWhiteSpace(entityPath); } - this.ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); - this.Path = entityPath; - this.SendingLinkDestination = entityPath; - this.EntityType = entityType; - this.ServiceBusConnection.ThrowIfClosed(); + ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); + Path = entityPath; + SendingLinkDestination = entityPath; + EntityType = entityType; + ServiceBusConnection.ThrowIfClosed(); if (cbsTokenProvider != null) { - this.CbsTokenProvider = cbsTokenProvider; + CbsTokenProvider = cbsTokenProvider; } - else if (this.ServiceBusConnection.TokenProvider != null) + else if (ServiceBusConnection.TokenProvider != null) { - this.CbsTokenProvider = new TokenProviderAdapter(this.ServiceBusConnection.TokenProvider, this.ServiceBusConnection.OperationTimeout); + CbsTokenProvider = new TokenProviderAdapter(ServiceBusConnection.TokenProvider, ServiceBusConnection.OperationTimeout); } else { throw new ArgumentNullException($"{nameof(ServiceBusConnection)} doesn't have a valid token provider"); } - this.SendLinkManager = new FaultTolerantAmqpObject(this.CreateLinkAsync, CloseSession); - this.RequestResponseLinkManager = new FaultTolerantAmqpObject(this.CreateRequestResponseLinkAsync, CloseRequestResponseSession); - this.clientLinkManager = new ActiveClientLinkManager(this, this.CbsTokenProvider); - this.diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); + SendLinkManager = new FaultTolerantAmqpObject(CreateLinkAsync, CloseSession); + RequestResponseLinkManager = new FaultTolerantAmqpObject(CreateRequestResponseLinkAsync, CloseRequestResponseSession); + clientLinkManager = new ActiveClientLinkManager(this, CbsTokenProvider); + diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); if (!string.IsNullOrWhiteSpace(transferDestinationPath)) { - this.isViaSender = true; - this.TransferDestinationPath = transferDestinationPath; - this.ViaEntityPath = entityPath; + isViaSender = true; + TransferDestinationPath = transferDestinationPath; + ViaEntityPath = entityPath; } - MessagingEventSource.Log.MessageSenderCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, this.ClientId); + MessagingEventSource.Log.MessageSenderCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, ClientId); } /// @@ -210,8 +210,8 @@ internal MessageSender( /// public override TimeSpan OperationTimeout { - get => this.ServiceBusConnection.OperationTimeout; - set => this.ServiceBusConnection.OperationTimeout = value; + get => ServiceBusConnection.OperationTimeout; + set => ServiceBusConnection.OperationTimeout = value; } /// @@ -234,7 +234,7 @@ public override TimeSpan OperationTimeout /// public Task SendAsync(Message message) { - return this.SendAsync(new[] { message }); + return SendAsync(new[] { message }); } /// @@ -243,43 +243,43 @@ public Task SendAsync(Message message) /// public async Task SendAsync(IList messageList) { - this.ThrowIfClosed(); + ThrowIfClosed(); - var count = MessageSender.ValidateMessages(messageList); + var count = ValidateMessages(messageList); if (count <= 0) { return; } - MessagingEventSource.Log.MessageSendStart(this.ClientId, count); + MessagingEventSource.Log.MessageSendStart(ClientId, count); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.SendStart(messageList) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.SendStart(messageList) : null; Task sendTask = null; try { - var processedMessages = await this.ProcessMessages(messageList).ConfigureAwait(false); + var processedMessages = await ProcessMessages(messageList).ConfigureAwait(false); - sendTask = this.RetryPolicy.RunOperation(() => this.OnSendAsync(processedMessages), this.OperationTimeout); + sendTask = RetryPolicy.RunOperation(() => OnSendAsync(processedMessages), OperationTimeout); await sendTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageSendException(this.ClientId, exception); + MessagingEventSource.Log.MessageSendException(ClientId, exception); throw; } finally { - this.diagnosticSource.SendStop(activity, messageList, sendTask?.Status); + diagnosticSource.SendStop(activity, messageList, sendTask?.Status); } - MessagingEventSource.Log.MessageSendStop(this.ClientId); + MessagingEventSource.Log.MessageSendStop(ClientId); } /// @@ -290,7 +290,7 @@ public async Task SendAsync(IList messageList) /// The sequence number of the message that was scheduled. public async Task ScheduleMessageAsync(Message message, DateTimeOffset scheduleEnqueueTimeUtc) { - this.ThrowIfClosed(); + ThrowIfClosed(); if (message == null) { throw Fx.Exception.ArgumentNull(nameof(message)); @@ -304,47 +304,47 @@ public async Task ScheduleMessageAsync(Message message, DateTimeOffset sch "Cannot schedule messages in the past"); } - if (this.isViaSender && Transaction.Current != null) + if (isViaSender && Transaction.Current != null) { throw new ServiceBusException(false, $"{nameof(ScheduleMessageAsync)} method is not supported in a Via-Sender with transactions."); } message.ScheduledEnqueueTimeUtc = scheduleEnqueueTimeUtc.UtcDateTime; - MessageSender.ValidateMessage(message); - MessagingEventSource.Log.ScheduleMessageStart(this.ClientId, scheduleEnqueueTimeUtc); + ValidateMessage(message); + MessagingEventSource.Log.ScheduleMessageStart(ClientId, scheduleEnqueueTimeUtc); long result = 0; bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.ScheduleStart(message, scheduleEnqueueTimeUtc) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.ScheduleStart(message, scheduleEnqueueTimeUtc) : null; Task scheduleTask = null; try { - var processedMessage = await this.ProcessMessage(message).ConfigureAwait(false); + var processedMessage = await ProcessMessage(message).ConfigureAwait(false); - scheduleTask = this.RetryPolicy.RunOperation( + scheduleTask = RetryPolicy.RunOperation( async () => { - result = await this.OnScheduleMessageAsync(processedMessage).ConfigureAwait(false); - }, this.OperationTimeout); + result = await OnScheduleMessageAsync(processedMessage).ConfigureAwait(false); + }, OperationTimeout); await scheduleTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.ScheduleMessageException(this.ClientId, exception); + MessagingEventSource.Log.ScheduleMessageException(ClientId, exception); throw; } finally { - this.diagnosticSource.ScheduleStop(activity, message, scheduleEnqueueTimeUtc, scheduleTask?.Status, result); + diagnosticSource.ScheduleStop(activity, message, scheduleEnqueueTimeUtc, scheduleTask?.Status, result); } - MessagingEventSource.Log.ScheduleMessageStop(this.ClientId); + MessagingEventSource.Log.ScheduleMessageStop(ClientId); return result; } @@ -354,39 +354,39 @@ public async Task ScheduleMessageAsync(Message message, DateTimeOffset sch /// The of the message to be cancelled. public async Task CancelScheduledMessageAsync(long sequenceNumber) { - this.ThrowIfClosed(); + ThrowIfClosed(); if (Transaction.Current != null) { throw new ServiceBusException(false, $"{nameof(CancelScheduledMessageAsync)} method is not supported within a transaction."); } - MessagingEventSource.Log.CancelScheduledMessageStart(this.ClientId, sequenceNumber); + MessagingEventSource.Log.CancelScheduledMessageStart(ClientId, sequenceNumber); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.CancelStart(sequenceNumber) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.CancelStart(sequenceNumber) : null; Task cancelTask = null; try { - cancelTask = this.RetryPolicy.RunOperation(() => this.OnCancelScheduledMessageAsync(sequenceNumber), - this.OperationTimeout); + cancelTask = RetryPolicy.RunOperation(() => OnCancelScheduledMessageAsync(sequenceNumber), + OperationTimeout); await cancelTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.CancelScheduledMessageException(this.ClientId, exception); + MessagingEventSource.Log.CancelScheduledMessageException(ClientId, exception); throw; } finally { - this.diagnosticSource.CancelStop(activity, sequenceNumber, cancelTask?.Status); + diagnosticSource.CancelStop(activity, sequenceNumber, cancelTask?.Status); } - MessagingEventSource.Log.CancelScheduledMessageStop(this.ClientId); + MessagingEventSource.Log.CancelScheduledMessageStop(ClientId); } /// @@ -395,17 +395,17 @@ public async Task CancelScheduledMessageAsync(long sequenceNumber) /// The to register. public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) { - this.ThrowIfClosed(); + ThrowIfClosed(); if (serviceBusPlugin == null) { throw new ArgumentNullException(nameof(serviceBusPlugin), Resources.ArgumentNullOrWhiteSpace.FormatForUser(nameof(serviceBusPlugin))); } - if (this.RegisteredPlugins.Any(p => p.GetType() == serviceBusPlugin.GetType())) + if (RegisteredPlugins.Any(p => p.GetType() == serviceBusPlugin.GetType())) { throw new ArgumentException(nameof(serviceBusPlugin), Resources.PluginAlreadyRegistered.FormatForUser(serviceBusPlugin.Name)); } - this.RegisteredPlugins.Add(serviceBusPlugin); + RegisteredPlugins.Add(serviceBusPlugin); } /// @@ -414,33 +414,33 @@ public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) /// The name to be unregistered public override void UnregisterPlugin(string serviceBusPluginName) { - this.ThrowIfClosed(); + ThrowIfClosed(); if (string.IsNullOrWhiteSpace(serviceBusPluginName)) { throw new ArgumentNullException(nameof(serviceBusPluginName), Resources.ArgumentNullOrWhiteSpace.FormatForUser(nameof(serviceBusPluginName))); } - if (this.RegisteredPlugins.Any(p => p.Name == serviceBusPluginName)) + if (RegisteredPlugins.Any(p => p.Name == serviceBusPluginName)) { - var plugin = this.RegisteredPlugins.First(p => p.Name == serviceBusPluginName); - this.RegisteredPlugins.Remove(plugin); + var plugin = RegisteredPlugins.First(p => p.Name == serviceBusPluginName); + RegisteredPlugins.Remove(plugin); } } internal async Task ExecuteRequestResponseAsync(AmqpRequestMessage amqpRequestMessage) { var amqpMessage = amqpRequestMessage.AmqpMessage; - var timeoutHelper = new TimeoutHelper(this.OperationTimeout, true); + var timeoutHelper = new TimeoutHelper(OperationTimeout, true); ArraySegment transactionId = AmqpConstants.NullBinary; var ambientTransaction = Transaction.Current; if (ambientTransaction != null) { - transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, this.ServiceBusConnection).ConfigureAwait(false); + transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, ServiceBusConnection).ConfigureAwait(false); } - if (!this.RequestResponseLinkManager.TryGetOpenedObject(out var requestResponseAmqpLink)) + if (!RequestResponseLinkManager.TryGetOpenedObject(out var requestResponseAmqpLink)) { - requestResponseAmqpLink = await this.RequestResponseLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); + requestResponseAmqpLink = await RequestResponseLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } var responseAmqpMessage = await Task.Factory.FromAsync( @@ -454,9 +454,9 @@ internal async Task ExecuteRequestResponseAsync(AmqpRequest /// Closes the connection. protected override async Task OnClosingAsync() { - this.clientLinkManager.Close(); - await this.SendLinkManager.CloseAsync().ConfigureAwait(false); - await this.RequestResponseLinkManager.CloseAsync().ConfigureAwait(false); + clientLinkManager.Close(); + await SendLinkManager.CloseAsync().ConfigureAwait(false); + await RequestResponseLinkManager.CloseAsync().ConfigureAwait(false); } static int ValidateMessages(IList messageList) @@ -498,7 +498,7 @@ static void CloseRequestResponseSession(RequestResponseAmqpLink requestResponseA async Task ProcessMessage(Message message) { var processedMessage = message; - foreach (var plugin in this.RegisteredPlugins) + foreach (var plugin in RegisteredPlugins) { try { @@ -520,7 +520,7 @@ async Task ProcessMessage(Message message) async Task> ProcessMessages(IList messageList) { - if (this.RegisteredPlugins.Count < 1) + if (RegisteredPlugins.Count < 1) { return messageList; } @@ -528,7 +528,7 @@ async Task> ProcessMessages(IList messageList) var processedMessageList = new List(); foreach (var message in messageList) { - var processedMessage = await this.ProcessMessage(message).ConfigureAwait(false); + var processedMessage = await ProcessMessage(message).ConfigureAwait(false); processedMessageList.Add(processedMessage); } @@ -537,7 +537,7 @@ async Task> ProcessMessages(IList messageList) async Task OnSendAsync(IList messageList) { - var timeoutHelper = new TimeoutHelper(this.OperationTimeout, true); + var timeoutHelper = new TimeoutHelper(OperationTimeout, true); using (var amqpMessage = AmqpMessageConverter.BatchSBMessagesAsAmqpMessage(messageList)) { SendingAmqpLink amqpLink = null; @@ -547,12 +547,12 @@ async Task OnSendAsync(IList messageList) var ambientTransaction = Transaction.Current; if (ambientTransaction != null) { - transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, this.ServiceBusConnection).ConfigureAwait(false); + transactionId = await AmqpTransactionManager.Instance.EnlistAsync(ambientTransaction, ServiceBusConnection).ConfigureAwait(false); } - if (!this.SendLinkManager.TryGetOpenedObject(out amqpLink)) + if (!SendLinkManager.TryGetOpenedObject(out amqpLink)) { - amqpLink = await this.SendLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); + amqpLink = await SendLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } if (amqpLink.Settings.MaxMessageSize.HasValue) { @@ -563,7 +563,7 @@ async Task OnSendAsync(IList messageList) } } - var outcome = await amqpLink.SendMessageAsync(amqpMessage, this.GetNextDeliveryTag(), transactionId, timeoutHelper.RemainingTime()).ConfigureAwait(false); + var outcome = await amqpLink.SendMessageAsync(amqpMessage, GetNextDeliveryTag(), transactionId, timeoutHelper.RemainingTime()).ConfigureAwait(false); if (outcome.DescriptorCode != Accepted.Code) { @@ -584,14 +584,14 @@ async Task OnScheduleMessageAsync(Message message) { var request = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.ScheduleMessageOperation, - this.OperationTimeout, + OperationTimeout, null); SendingAmqpLink sendLink = null; try { - if (this.SendLinkManager.TryGetOpenedObject(out sendLink)) + if (SendLinkManager.TryGetOpenedObject(out sendLink)) { request.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = sendLink.Name; } @@ -623,7 +623,7 @@ async Task OnScheduleMessageAsync(Message message) request.Map[ManagementConstants.Properties.Messages] = new List { entry }; - var response = await this.ExecuteRequestResponseAsync(request).ConfigureAwait(false); + var response = await ExecuteRequestResponseAsync(request).ConfigureAwait(false); if (response.StatusCode == AmqpResponseStatusCode.OK) { var sequenceNumbers = response.GetValue(ManagementConstants.Properties.SequenceNumbers); @@ -652,21 +652,21 @@ async Task OnCancelScheduledMessageAsync(long sequenceNumber) var request = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.CancelScheduledMessageOperation, - this.OperationTimeout, + OperationTimeout, null); SendingAmqpLink sendLink = null; try { - if (this.SendLinkManager.TryGetOpenedObject(out sendLink)) + if (SendLinkManager.TryGetOpenedObject(out sendLink)) { request.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = sendLink.Name; } request.Map[ManagementConstants.Properties.SequenceNumbers] = new[] { sequenceNumber }; - var response = await this.ExecuteRequestResponseAsync(request).ConfigureAwait(false); + var response = await ExecuteRequestResponseAsync(request).ConfigureAwait(false); if (response.StatusCode != AmqpResponseStatusCode.OK) { @@ -681,28 +681,28 @@ async Task OnCancelScheduledMessageAsync(long sequenceNumber) async Task CreateLinkAsync(TimeSpan timeout) { - MessagingEventSource.Log.AmqpSendLinkCreateStart(this.ClientId, this.EntityType, this.SendingLinkDestination); + MessagingEventSource.Log.AmqpSendLinkCreateStart(ClientId, EntityType, SendingLinkDestination); var amqpLinkSettings = new AmqpLinkSettings { Role = false, InitialDeliveryCount = 0, - Target = new Target { Address = this.SendingLinkDestination }, - Source = new Source { Address = this.ClientId }, + Target = new Target { Address = SendingLinkDestination }, + Source = new Source { Address = ClientId }, }; - if (this.EntityType != null) + if (EntityType != null) { - amqpLinkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)this.EntityType); + amqpLinkSettings.AddProperty(AmqpClientConstants.EntityTypeName, (int)EntityType); } - var endpointUri = new Uri(this.ServiceBusConnection.Endpoint, this.SendingLinkDestination); + var endpointUri = new Uri(ServiceBusConnection.Endpoint, SendingLinkDestination); string[] audience; - if (this.isViaSender) + if (isViaSender) { - var transferDestinationEndpointUri = new Uri(this.ServiceBusConnection.Endpoint, this.TransferDestinationPath); + var transferDestinationEndpointUri = new Uri(ServiceBusConnection.Endpoint, TransferDestinationPath); audience = new string[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; - amqpLinkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, this.TransferDestinationPath); + amqpLinkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, TransferDestinationPath); } else { @@ -710,7 +710,7 @@ async Task CreateLinkAsync(TimeSpan timeout) } string[] claims = {ClaimConstants.Send}; - var amqpSendReceiveLinkCreator = new AmqpSendReceiveLinkCreator(this.SendingLinkDestination, this.ServiceBusConnection, endpointUri, audience, claims, this.CbsTokenProvider, amqpLinkSettings, this.ClientId); + var amqpSendReceiveLinkCreator = new AmqpSendReceiveLinkCreator(SendingLinkDestination, ServiceBusConnection, endpointUri, audience, claims, CbsTokenProvider, amqpLinkSettings, ClientId); Tuple linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); var sendingAmqpLink = (SendingAmqpLink) linkDetails.Item1; @@ -721,26 +721,26 @@ async Task CreateLinkAsync(TimeSpan timeout) claims, linkDetails.Item2); - this.clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); + clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); - MessagingEventSource.Log.AmqpSendLinkCreateStop(this.ClientId); + MessagingEventSource.Log.AmqpSendLinkCreateStop(ClientId); return sendingAmqpLink; } async Task CreateRequestResponseLinkAsync(TimeSpan timeout) { - var entityPath = this.SendingLinkDestination + '/' + AmqpClientConstants.ManagementAddress; + var entityPath = SendingLinkDestination + '/' + AmqpClientConstants.ManagementAddress; var amqpLinkSettings = new AmqpLinkSettings(); amqpLinkSettings.AddProperty(AmqpClientConstants.EntityTypeName, AmqpClientConstants.EntityTypeManagement); - var endpointUri = new Uri(this.ServiceBusConnection.Endpoint, entityPath); + var endpointUri = new Uri(ServiceBusConnection.Endpoint, entityPath); string[] audience; - if (this.isViaSender) + if (isViaSender) { - var transferDestinationEndpointUri = new Uri(this.ServiceBusConnection.Endpoint, this.TransferDestinationPath); + var transferDestinationEndpointUri = new Uri(ServiceBusConnection.Endpoint, TransferDestinationPath); audience = new string[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; - amqpLinkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, this.TransferDestinationPath); + amqpLinkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, TransferDestinationPath); } else { @@ -750,13 +750,13 @@ async Task CreateRequestResponseLinkAsync(TimeSpan time string[] claims = { ClaimConstants.Manage, ClaimConstants.Send }; var amqpRequestResponseLinkCreator = new AmqpRequestResponseLinkCreator( entityPath, - this.ServiceBusConnection, + ServiceBusConnection, endpointUri, audience, claims, - this.CbsTokenProvider, + CbsTokenProvider, amqpLinkSettings, - this.ClientId); + ClientId); Tuple linkDetails = await amqpRequestResponseLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); @@ -768,14 +768,14 @@ async Task CreateRequestResponseLinkAsync(TimeSpan time audience, claims, linkDetails.Item2); - this.clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); + clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); return requestResponseAmqpLink; } ArraySegment GetNextDeliveryTag() { - var deliveryId = Interlocked.Increment(ref this.deliveryCount); + var deliveryId = Interlocked.Increment(ref deliveryCount); return new ArraySegment(BitConverter.GetBytes(deliveryId)); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/EntityNameHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/EntityNameHelper.cs index 3e5394cd54e1..551d19beba86 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/EntityNameHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/EntityNameHelper.cs @@ -4,7 +4,7 @@ namespace Microsoft.Azure.ServiceBus { using System; - using Microsoft.Azure.ServiceBus.Management; + using Management; /// /// This class can be used to format the path for different Service Bus entity types. @@ -27,7 +27,7 @@ public static class EntityNameHelper /// The path as a string of the dead letter entity. public static string FormatDeadLetterPath(string entityPath) { - return EntityNameHelper.FormatSubQueuePath(entityPath, EntityNameHelper.DeadLetterQueueName); + return FormatSubQueuePath(entityPath, DeadLetterQueueName); } /// @@ -37,7 +37,7 @@ public static string FormatDeadLetterPath(string entityPath) /// The path as a string of the subqueue entity. public static string FormatSubQueuePath(string entityPath, string subQueueName) { - return string.Concat(entityPath, EntityNameHelper.PathDelimiter, subQueueName); + return string.Concat(entityPath, PathDelimiter, subQueueName); } /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ExceptionReceivedEventArgs.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ExceptionReceivedEventArgs.cs index 5627b76764f7..fda6d30a05bc 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ExceptionReceivedEventArgs.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ExceptionReceivedEventArgs.cs @@ -18,8 +18,8 @@ public sealed class ExceptionReceivedEventArgs : EventArgs /// The Client Id can be used to associate with the , , or that encountered the exception. public ExceptionReceivedEventArgs(Exception exception, string action, string endpoint, string entityName, string clientId) { - this.Exception = exception; - this.ExceptionReceivedContext = new ExceptionReceivedContext(action, endpoint, entityName, clientId); + Exception = exception; + ExceptionReceivedContext = new ExceptionReceivedContext(action, endpoint, entityName, clientId); } /// Gets the parent class exception to which this event data belongs. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs index ad04498600f4..f8eb32c098d6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs @@ -23,7 +23,7 @@ sealed class DataContractBinarySerializer : XmlObjectSerializer /// public DataContractBinarySerializer(Type type) { - this.dataContractSerializer = new DataContractSerializer(type); + dataContractSerializer = new DataContractSerializer(type); } /// @@ -33,7 +33,7 @@ public DataContractBinarySerializer(Type type) /// Override the default (Text) and use Binary Xml Reader instead public override object ReadObject(Stream stream) { - return this.ReadObject(XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)); + return ReadObject(XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)); } /// @@ -48,7 +48,7 @@ public override void WriteObject(Stream stream, object graph) } var xmlDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, null, null, false); - this.WriteObject(xmlDictionaryWriter, graph); + WriteObject(xmlDictionaryWriter, graph); xmlDictionaryWriter.Flush(); } @@ -62,7 +62,7 @@ public override void WriteObject(XmlDictionaryWriter writer, object graph) throw new ArgumentNullException(nameof(writer)); } - this.dataContractSerializer.WriteObject(writer, graph); + dataContractSerializer.WriteObject(writer, graph); } /// @@ -70,7 +70,7 @@ public override void WriteObject(XmlDictionaryWriter writer, object graph) /// public override bool IsStartObject(XmlDictionaryReader reader) { - return this.dataContractSerializer.IsStartObject(reader); + return dataContractSerializer.IsStartObject(reader); } /// @@ -78,7 +78,7 @@ public override bool IsStartObject(XmlDictionaryReader reader) /// public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { - return this.dataContractSerializer.ReadObject(reader, verifyObjectName); + return dataContractSerializer.ReadObject(reader, verifyObjectName); } /// @@ -86,7 +86,7 @@ public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectN /// public override void WriteEndObject(XmlDictionaryWriter writer) { - this.dataContractSerializer.WriteEndObject(writer); + dataContractSerializer.WriteEndObject(writer); } /// @@ -94,7 +94,7 @@ public override void WriteEndObject(XmlDictionaryWriter writer) /// public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { - this.dataContractSerializer.WriteObjectContent(writer, graph); + dataContractSerializer.WriteObjectContent(writer, graph); } /// @@ -102,7 +102,7 @@ public override void WriteObjectContent(XmlDictionaryWriter writer, object graph /// public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { - this.dataContractSerializer.WriteStartObject(writer, graph); + dataContractSerializer.WriteStartObject(writer, graph); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs index 4e0000eb36cd..00a50bf25143 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs @@ -52,7 +52,7 @@ public CorrelationFilter(string correlationId) throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(correlationId)); } - this.CorrelationId = correlationId; + CorrelationId = correlationId; } /// @@ -148,7 +148,7 @@ public string ContentType /// bool, Guid, string, Uri, DateTime, DateTimeOffset, TimeSpan, Stream, byte[], /// and IList / IDictionary of supported types /// - public IDictionary Properties => this.properties ?? (this.properties = new PropertyDictionary()); + public IDictionary Properties => properties ?? (properties = new PropertyDictionary()); /// /// Converts the value of the current instance to its equivalent string representation. @@ -162,21 +162,21 @@ public override string ToString() var isFirstExpression = true; - this.AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.CorrelationId", this.CorrelationId); - this.AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.MessageId", this.MessageId); - this.AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.To", this.To); - this.AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ReplyTo", this.ReplyTo); - this.AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.Label", this.Label); - this.AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.SessionId", this.SessionId); - this.AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ReplyToSessionId", this.ReplyToSessionId); - this.AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ContentType", this.ContentType); + AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.CorrelationId", CorrelationId); + AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.MessageId", MessageId); + AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.To", To); + AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ReplyTo", ReplyTo); + AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.Label", Label); + AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.SessionId", SessionId); + AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ReplyToSessionId", ReplyToSessionId); + AppendPropertyExpression(ref isFirstExpression, stringBuilder, "sys.ContentType", ContentType); - foreach (var pair in this.Properties) + foreach (var pair in Properties) { string propertyName = pair.Key; object propertyValue = pair.Value; - this.AppendPropertyExpression(ref isFirstExpression, stringBuilder, propertyName, propertyValue); + AppendPropertyExpression(ref isFirstExpression, stringBuilder, propertyName, propertyValue); } return stringBuilder.ToString(); @@ -204,9 +204,9 @@ public override int GetHashCode() int hash = 13; unchecked { - hash = (hash * 7) + this.CorrelationId?.GetHashCode() ?? 0; - hash = (hash * 7) + this.MessageId?.GetHashCode() ?? 0; - hash = (hash * 7) + this.SessionId?.GetHashCode() ?? 0; + hash = (hash * 7) + CorrelationId?.GetHashCode() ?? 0; + hash = (hash * 7) + MessageId?.GetHashCode() ?? 0; + hash = (hash * 7) + SessionId?.GetHashCode() ?? 0; } return hash; @@ -215,32 +215,32 @@ public override int GetHashCode() public override bool Equals(object obj) { var other = obj as CorrelationFilter; - return this.Equals(other); + return Equals(other); } public override bool Equals(Filter other) { if (other is CorrelationFilter correlationFilter) { - if (string.Equals(this.CorrelationId, correlationFilter.CorrelationId, StringComparison.OrdinalIgnoreCase) - && string.Equals(this.MessageId, correlationFilter.MessageId, StringComparison.OrdinalIgnoreCase) - && string.Equals(this.To, correlationFilter.To, StringComparison.OrdinalIgnoreCase) - && string.Equals(this.ReplyTo, correlationFilter.ReplyTo, StringComparison.OrdinalIgnoreCase) - && string.Equals(this.Label, correlationFilter.Label, StringComparison.OrdinalIgnoreCase) - && string.Equals(this.SessionId, correlationFilter.SessionId, StringComparison.OrdinalIgnoreCase) - && string.Equals(this.ReplyToSessionId, correlationFilter.ReplyToSessionId, StringComparison.OrdinalIgnoreCase) - && string.Equals(this.ContentType, correlationFilter.ContentType, StringComparison.OrdinalIgnoreCase) - && (this.properties != null && correlationFilter.properties != null - || this.properties == null && correlationFilter.properties == null)) + if (string.Equals(CorrelationId, correlationFilter.CorrelationId, StringComparison.OrdinalIgnoreCase) + && string.Equals(MessageId, correlationFilter.MessageId, StringComparison.OrdinalIgnoreCase) + && string.Equals(To, correlationFilter.To, StringComparison.OrdinalIgnoreCase) + && string.Equals(ReplyTo, correlationFilter.ReplyTo, StringComparison.OrdinalIgnoreCase) + && string.Equals(Label, correlationFilter.Label, StringComparison.OrdinalIgnoreCase) + && string.Equals(SessionId, correlationFilter.SessionId, StringComparison.OrdinalIgnoreCase) + && string.Equals(ReplyToSessionId, correlationFilter.ReplyToSessionId, StringComparison.OrdinalIgnoreCase) + && string.Equals(ContentType, correlationFilter.ContentType, StringComparison.OrdinalIgnoreCase) + && (properties != null && correlationFilter.properties != null + || properties == null && correlationFilter.properties == null)) { - if (this.properties != null) + if (properties != null) { - if (this.properties.Count != correlationFilter.properties.Count) + if (properties.Count != correlationFilter.properties.Count) { return false; } - foreach (var param in this.properties) + foreach (var param in properties) { if (!correlationFilter.properties.TryGetValue(param.Key, out var otherParamValue) || (param.Value == null ^ otherParamValue == null) || diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs index eb4d58f6b511..dc68e3d98302 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs @@ -4,8 +4,8 @@ namespace Microsoft.Azure.ServiceBus { using System.Xml.Linq; - using Microsoft.Azure.ServiceBus.Filters; - using Microsoft.Azure.ServiceBus.Management; + using Filters; + using Management; internal static class CorrelationFilterExtensions { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FilterExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FilterExtensions.cs index 00cd64744835..c3de4a7792e9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FilterExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FilterExtensions.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus { using System; using System.Xml.Linq; - using Microsoft.Azure.ServiceBus.Management; + using Management; internal static class FilterExtensions { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs index 54b67505feb3..edf81f615d5e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs @@ -5,8 +5,8 @@ namespace Microsoft.Azure.ServiceBus { using System; using System.Xml.Linq; - using Microsoft.Azure.ServiceBus.Filters; - using Microsoft.Azure.ServiceBus.Management; + using Filters; + using Management; internal static class RuleActionExtensions { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs index a7de9bbaa032..007dd977fcb2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs @@ -4,8 +4,8 @@ namespace Microsoft.Azure.ServiceBus { using System; - using Microsoft.Azure.ServiceBus.Management; - using Microsoft.Azure.ServiceBus.Primitives; + using Management; + using Primitives; /// /// Represents a description of a rule. @@ -28,7 +28,7 @@ public sealed class RuleDescription : IEquatable /// Initializes a new instance of the class with default values. /// public RuleDescription() - : this(RuleDescription.DefaultRuleName, TrueFilter.Default) + : this(DefaultRuleName, TrueFilter.Default) { } @@ -47,7 +47,7 @@ public RuleDescription(string name) [Obsolete("This constructor will be removed in next version, please use RuleDescription(string, Filter) instead.")] public RuleDescription(Filter filter) { - this.Filter = filter ?? throw Fx.Exception.ArgumentNull(nameof(filter)); + Filter = filter ?? throw Fx.Exception.ArgumentNull(nameof(filter)); } /// @@ -56,8 +56,8 @@ public RuleDescription(Filter filter) /// The filter expression used to match messages. public RuleDescription(string name, Filter filter) { - this.Filter = filter ?? throw Fx.Exception.ArgumentNull(nameof(filter)); - this.Name = name; + Filter = filter ?? throw Fx.Exception.ArgumentNull(nameof(filter)); + Name = name; } /// @@ -67,9 +67,9 @@ public RuleDescription(string name, Filter filter) /// null (Nothing in Visual Basic) is assigned. public Filter Filter { - get => this.filter; + get => filter; - set => this.filter = value ?? throw Fx.Exception.ArgumentNull(nameof(this.Filter)); + set => filter = value ?? throw Fx.Exception.ArgumentNull(nameof(Filter)); } /// @@ -85,12 +85,12 @@ public Filter Filter /// Max allowed length of rule name is 50 chars. public string Name { - get => this.name; + get => name; set { EntityNameHelper.CheckValidRuleName(value); - this.name = value; + name = value; } } @@ -105,8 +105,8 @@ public override int GetHashCode() int hash = 13; unchecked { - hash = (hash * 7) + this.filter?.GetHashCode() ?? 0; - hash = (hash * 7) + this.Action?.GetHashCode() ?? 0; + hash = (hash * 7) + filter?.GetHashCode() ?? 0; + hash = (hash * 7) + Action?.GetHashCode() ?? 0; } return hash; } @@ -114,15 +114,15 @@ public override int GetHashCode() public override bool Equals(object obj) { var other = obj as RuleDescription; - return this.Equals(other); + return Equals(other); } public bool Equals(RuleDescription otherRule) { if (otherRule is RuleDescription other - && string.Equals(this.Name, other.Name, StringComparison.OrdinalIgnoreCase) - && (this.Filter == null || this.Filter.Equals(other.Filter)) - && (this.Action == null || this.Action.Equals(other.Action))) + && string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase) + && (Filter == null || Filter.Equals(other.Filter)) + && (Action == null || Action.Equals(other.Action))) { return true; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs index b5c5d044b85d..bf926084f17b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs @@ -6,8 +6,8 @@ namespace Microsoft.Azure.ServiceBus using System; using System.Collections.Generic; using System.Xml.Linq; - using Microsoft.Azure.ServiceBus.Management; - using Microsoft.Azure.ServiceBus.Primitives; + using Management; + using Primitives; internal static class RuleDescriptionExtensions { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs index 7b07e1ea556c..8d995e89e131 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs @@ -42,7 +42,7 @@ public SqlFilter(string sqlExpression) Constants.MaximumSqlFilterStatementLength)); } - this.SqlExpression = sqlExpression; + SqlExpression = sqlExpression; } /// @@ -57,7 +57,7 @@ public SqlFilter(string sqlExpression) /// Allowed types: string, int, long, bool, double /// /// The value of a filter expression. - public IDictionary Parameters => this.parameters ?? (this.parameters = new PropertyDictionary()); + public IDictionary Parameters => parameters ?? (parameters = new PropertyDictionary()); /// /// Returns a string representation of . @@ -65,36 +65,36 @@ public SqlFilter(string sqlExpression) /// The string representation of . public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "SqlFilter: {0}", this.SqlExpression); + return string.Format(CultureInfo.InvariantCulture, "SqlFilter: {0}", SqlExpression); } public override int GetHashCode() { - return this.SqlExpression?.GetHashCode() ?? base.GetHashCode(); + return SqlExpression?.GetHashCode() ?? base.GetHashCode(); } public override bool Equals(object obj) { var other = obj as Filter; - return this.Equals(other); + return Equals(other); } public override bool Equals(Filter other) { if (other is SqlFilter sqlFilter) { - if (string.Equals(this.SqlExpression, sqlFilter.SqlExpression, StringComparison.OrdinalIgnoreCase) - && (this.parameters != null && sqlFilter.parameters != null - || this.parameters == null && sqlFilter.parameters == null)) + if (string.Equals(SqlExpression, sqlFilter.SqlExpression, StringComparison.OrdinalIgnoreCase) + && (parameters != null && sqlFilter.parameters != null + || parameters == null && sqlFilter.parameters == null)) { - if (this.parameters != null) + if (parameters != null) { - if (this.parameters.Count != sqlFilter.parameters.Count) + if (parameters.Count != sqlFilter.parameters.Count) { return false; } - foreach (var param in this.parameters) + foreach (var param in parameters) { if (!sqlFilter.parameters.TryGetValue(param.Key, out var otherParamValue) || (param.Value == null ^ otherParamValue == null) || diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs index 179d6b153f3c..061b0ec424e1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs @@ -4,8 +4,8 @@ namespace Microsoft.Azure.ServiceBus { using System.Xml.Linq; - using Microsoft.Azure.ServiceBus.Filters; - using Microsoft.Azure.ServiceBus.Management; + using Filters; + using Management; internal static class SqlFilterExtensions { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs index 38195cf15d33..88aadf5ef3ea 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs @@ -36,7 +36,7 @@ public SqlRuleAction(string sqlExpression) Constants.MaximumSqlRuleActionStatementLength)); } - this.SqlExpression = sqlExpression; + SqlExpression = sqlExpression; } /// @@ -50,7 +50,7 @@ public SqlRuleAction(string sqlExpression) /// Sets the value of a rule action. /// /// The value of a rule action. - public IDictionary Parameters => this.parameters ?? (this.parameters = new PropertyDictionary()); + public IDictionary Parameters => parameters ?? (parameters = new PropertyDictionary()); /// /// Returns a string representation of . @@ -58,36 +58,36 @@ public SqlRuleAction(string sqlExpression) /// The string representation of . public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "SqlRuleAction: {0}", this.SqlExpression); + return string.Format(CultureInfo.InvariantCulture, "SqlRuleAction: {0}", SqlExpression); } public override int GetHashCode() { - return this.SqlExpression?.GetHashCode() ?? base.GetHashCode(); + return SqlExpression?.GetHashCode() ?? base.GetHashCode(); } public override bool Equals(object obj) { var other = obj as RuleAction; - return this.Equals(other); + return Equals(other); } public override bool Equals(RuleAction other) { if (other is SqlRuleAction sqlAction) { - if (string.Equals(this.SqlExpression, sqlAction.SqlExpression, StringComparison.OrdinalIgnoreCase) - && (this.parameters != null && sqlAction.parameters != null - || this.parameters == null && sqlAction.parameters == null)) + if (string.Equals(SqlExpression, sqlAction.SqlExpression, StringComparison.OrdinalIgnoreCase) + && (parameters != null && sqlAction.parameters != null + || parameters == null && sqlAction.parameters == null)) { - if (this.parameters != null) + if (parameters != null) { - if (this.parameters.Count != sqlAction.parameters.Count) + if (parameters.Count != sqlAction.parameters.Count) { return false; } - foreach (var param in this.parameters) + foreach (var param in parameters) { if (!sqlAction.parameters.TryGetValue(param.Key, out var otherParamValue) || (param.Value == null ^ otherParamValue == null) || diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/XmlObjectConvertor.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/XmlObjectConvertor.cs index 194c16b2ed63..22b465809bdb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/XmlObjectConvertor.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/XmlObjectConvertor.cs @@ -6,7 +6,7 @@ namespace Microsoft.Azure.ServiceBus.Filters using System; using System.Xml; using System.Xml.Linq; - using Microsoft.Azure.ServiceBus.Management; + using Management; internal class XmlObjectConvertor { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ISessionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ISessionClient.cs index 8ff2a641b7a5..121592bb215b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ISessionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ISessionClient.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus { using System; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; /// /// Describes a Session client. A session client can be used to accept session objects which can be used to interact with all messages with the same sessionId. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs index 5756c30e7a22..cdf60779b5e2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs @@ -10,7 +10,7 @@ namespace Microsoft.Azure.ServiceBus.Management public class AuthorizationRules : List, IEquatable { - private bool RequiresEncryption => this.Count > 0; + private bool RequiresEncryption => Count > 0; internal XElement Serialize() { @@ -46,12 +46,12 @@ public override int GetHashCode() public override bool Equals(object obj) { var other = obj as AuthorizationRules; - return this.Equals(other); + return Equals(other); } public bool Equals(AuthorizationRules other) { - if (ReferenceEquals(other, null) || this.Count != other.Count) + if (ReferenceEquals(other, null) || Count != other.Count) { return false; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs index 4af36b22c91e..dab05a16af2f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs @@ -11,7 +11,7 @@ namespace Microsoft.Azure.ServiceBus.Management using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; - using Microsoft.Azure.ServiceBus.Primitives; + using Primitives; public class ManagementClient { @@ -47,13 +47,13 @@ public ManagementClient(string endpoint, ITokenProvider tokenProvider) /// Token provider which will generate security tokens for authorization. public ManagementClient(ServiceBusConnectionStringBuilder connectionStringBuilder, ITokenProvider tokenProvider = default) { - this.httpClient = new HttpClient { Timeout = connectionStringBuilder.OperationTimeout }; - this.endpointFQDN = connectionStringBuilder.Endpoint; + httpClient = new HttpClient { Timeout = connectionStringBuilder.OperationTimeout }; + endpointFQDN = connectionStringBuilder.Endpoint; this.tokenProvider = tokenProvider ?? CreateTokenProvider(connectionStringBuilder); - this.port = GetPort(connectionStringBuilder.Endpoint); - this.clientId = nameof(ManagementClient) + Guid.NewGuid().ToString("N").Substring(0, 6); + port = GetPort(connectionStringBuilder.Endpoint); + clientId = nameof(ManagementClient) + Guid.NewGuid().ToString("N").Substring(0, 6); - MessagingEventSource.Log.ManagementClientCreated(this.clientId, this.httpClient.Timeout.TotalSeconds, this.tokenProvider.ToString()); + MessagingEventSource.Log.ManagementClientCreated(clientId, httpClient.Timeout.TotalSeconds, this.tokenProvider.ToString()); } public static HttpRequestMessage CloneRequest(HttpRequestMessage req) @@ -582,7 +582,7 @@ public virtual async Task> GetSubscriptionsRuntim /// An internal error or unexpected exception occurs. public virtual Task CreateQueueAsync(string queuePath, CancellationToken cancellationToken = default) { - return this.CreateQueueAsync(new QueueDescription(queuePath), cancellationToken); + return CreateQueueAsync(new QueueDescription(queuePath), cancellationToken); } /// @@ -602,7 +602,7 @@ public virtual Task CreateQueueAsync(string queuePath, Cancell public virtual async Task CreateQueueAsync(QueueDescription queueDescription, CancellationToken cancellationToken = default) { queueDescription = queueDescription ?? throw new ArgumentNullException(nameof(queueDescription)); - queueDescription.NormalizeDescription(this.endpointFQDN); + queueDescription.NormalizeDescription(endpointFQDN); var atomRequest = queueDescription.Serialize().ToString(); var content = await PutEntity( queueDescription.Path, @@ -631,7 +631,7 @@ public virtual async Task CreateQueueAsync(QueueDescription qu /// An internal error or unexpected exception occurs. public virtual Task CreateTopicAsync(string topicPath, CancellationToken cancellationToken = default) { - return this.CreateTopicAsync(new TopicDescription(topicPath), cancellationToken); + return CreateTopicAsync(new TopicDescription(topicPath), cancellationToken); } /// @@ -678,7 +678,7 @@ public virtual async Task CreateTopicAsync(TopicDescription to /// An internal error or unexpected exception occurs. public virtual Task CreateSubscriptionAsync(string topicPath, string subscriptionName, CancellationToken cancellationToken = default) { - return this.CreateSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName), cancellationToken); + return CreateSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName), cancellationToken); } /// @@ -700,7 +700,7 @@ public virtual Task CreateSubscriptionAsync(string topi public virtual Task CreateSubscriptionAsync(SubscriptionDescription subscriptionDescription, CancellationToken cancellationToken = default) { subscriptionDescription = subscriptionDescription ?? throw new ArgumentNullException(nameof(subscriptionDescription)); - return this.CreateSubscriptionAsync(subscriptionDescription, null, cancellationToken); + return CreateSubscriptionAsync(subscriptionDescription, null, cancellationToken); } /// @@ -721,7 +721,7 @@ public virtual Task CreateSubscriptionAsync(Subscriptio public virtual async Task CreateSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule, CancellationToken cancellationToken = default) { subscriptionDescription = subscriptionDescription ?? throw new ArgumentNullException(nameof(subscriptionDescription)); - subscriptionDescription.NormalizeDescription(this.endpointFQDN); + subscriptionDescription.NormalizeDescription(endpointFQDN); subscriptionDescription.DefaultRuleDescription = defaultRule; var atomRequest = subscriptionDescription.Serialize().ToString(); var content = await PutEntity( @@ -787,7 +787,7 @@ public virtual async Task CreateRuleAsync(string topicPath, str public virtual async Task UpdateQueueAsync(QueueDescription queueDescription, CancellationToken cancellationToken = default) { queueDescription = queueDescription ?? throw new ArgumentNullException(nameof(queueDescription)); - queueDescription.NormalizeDescription(this.endpointFQDN); + queueDescription.NormalizeDescription(endpointFQDN); var atomRequest = queueDescription.Serialize().ToString(); @@ -841,7 +841,7 @@ public virtual async Task UpdateTopicAsync(TopicDescription to public virtual async Task UpdateSubscriptionAsync(SubscriptionDescription subscriptionDescription, CancellationToken cancellationToken = default) { subscriptionDescription = subscriptionDescription ?? throw new ArgumentNullException(nameof(subscriptionDescription)); - subscriptionDescription.NormalizeDescription(this.endpointFQDN); + subscriptionDescription.NormalizeDescription(endpointFQDN); var atomRequest = subscriptionDescription.Serialize().ToString(); var content = await PutEntity( EntityNameHelper.FormatSubscriptionPath(subscriptionDescription.TopicPath, subscriptionDescription.SubscriptionName), @@ -1099,29 +1099,29 @@ private static ITokenProvider CreateTokenProvider(ServiceBusConnectionStringBuil private Task GetToken(Uri requestUri) { - return this.GetToken(requestUri.GetLeftPart(UriPartial.Path)); + return GetToken(requestUri.GetLeftPart(UriPartial.Path)); } private async Task GetToken(string requestUri) { - var token = await this.tokenProvider.GetTokenAsync(requestUri, TimeSpan.FromHours(1)).ConfigureAwait(false); + var token = await tokenProvider.GetTokenAsync(requestUri, TimeSpan.FromHours(1)).ConfigureAwait(false); return token.TokenValue; } private async Task GetEntity(string path, string query, bool enrich, CancellationToken cancellationToken) { - MessagingEventSource.Log.ManagementOperationStart(this.clientId, nameof(GetEntity), $"path:{path},query:{query},enrich:{enrich}"); + MessagingEventSource.Log.ManagementOperationStart(clientId, nameof(GetEntity), $"path:{path},query:{query},enrich:{enrich}"); var queryString = $"{ManagementClientConstants.apiVersionQuery}&enrich={enrich}"; if (query != null) { queryString = queryString + "&" + query; } - var uri = new UriBuilder(this.endpointFQDN) + var uri = new UriBuilder(endpointFQDN) { Path = path, Scheme = Uri.UriSchemeHttps, - Port = this.port, + Port = port, Query = queryString }.Uri; @@ -1129,18 +1129,18 @@ private async Task GetEntity(string path, string query, bool enrich, Can HttpResponseMessage response = await SendHttpRequest(request, cancellationToken).ConfigureAwait(false); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - MessagingEventSource.Log.ManagementOperationEnd(this.clientId, nameof(GetEntity), $"path:{path},query:{query},enrich:{enrich}"); + MessagingEventSource.Log.ManagementOperationEnd(clientId, nameof(GetEntity), $"path:{path},query:{query},enrich:{enrich}"); return result; } private async Task PutEntity(string path, string requestBody, bool isUpdate, string forwardTo, string fwdDeadLetterTo, CancellationToken cancellationToken) { - MessagingEventSource.Log.ManagementOperationStart(this.clientId, nameof(PutEntity), $"path:{path},isUpdate:{isUpdate}"); + MessagingEventSource.Log.ManagementOperationStart(clientId, nameof(PutEntity), $"path:{path},isUpdate:{isUpdate}"); - var uri = new UriBuilder(this.endpointFQDN) + var uri = new UriBuilder(endpointFQDN) { Path = path, - Port = this.port, + Port = port, Scheme = Uri.UriSchemeHttps, Query = $"{ManagementClientConstants.apiVersionQuery}" }.Uri; @@ -1159,38 +1159,38 @@ private async Task PutEntity(string path, string requestBody, bool isUpd if (!string.IsNullOrWhiteSpace(forwardTo)) { - var token = await this.GetToken(forwardTo).ConfigureAwait(false); + var token = await GetToken(forwardTo).ConfigureAwait(false); request.Headers.Add(ManagementClientConstants.ServiceBusSupplementartyAuthorizationHeaderName, token); } if (!string.IsNullOrWhiteSpace(fwdDeadLetterTo)) { - var token = await this.GetToken(fwdDeadLetterTo).ConfigureAwait(false); + var token = await GetToken(fwdDeadLetterTo).ConfigureAwait(false); request.Headers.Add(ManagementClientConstants.ServiceBusDlqSupplementaryAuthorizationHeaderName, token); } HttpResponseMessage response = await SendHttpRequest(request, cancellationToken).ConfigureAwait(false); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - MessagingEventSource.Log.ManagementOperationEnd(this.clientId, nameof(PutEntity), $"path:{path},isUpdate:{isUpdate}"); + MessagingEventSource.Log.ManagementOperationEnd(clientId, nameof(PutEntity), $"path:{path},isUpdate:{isUpdate}"); return result; } private async Task DeleteEntity(string path, CancellationToken cancellationToken) { - MessagingEventSource.Log.ManagementOperationStart(this.clientId, nameof(DeleteEntity), path); + MessagingEventSource.Log.ManagementOperationStart(clientId, nameof(DeleteEntity), path); - var uri = new UriBuilder(this.endpointFQDN) + var uri = new UriBuilder(endpointFQDN) { Path = path, Scheme = Uri.UriSchemeHttps, - Port = this.port, + Port = port, Query = ManagementClientConstants.apiVersionQuery }.Uri; var request = new HttpRequestMessage(HttpMethod.Delete, uri); await SendHttpRequest(request, cancellationToken).ConfigureAwait(false); - MessagingEventSource.Log.ManagementOperationEnd(this.clientId, nameof(DeleteEntity), path); + MessagingEventSource.Log.ManagementOperationEnd(clientId, nameof(DeleteEntity), path); } private async Task SendHttpRequest(HttpRequestMessage request, CancellationToken cancellationToken) @@ -1198,7 +1198,7 @@ private async Task SendHttpRequest(HttpRequestMessage reque if (request.Headers.Authorization == null) { // First attempt. - var token = await this.GetToken(request.RequestUri).ConfigureAwait(false); + var token = await GetToken(request.RequestUri).ConfigureAwait(false); request.Headers.Add("Authorization", token); request.Headers.Add("UserAgent", $"SERVICEBUS/{ManagementClientConstants.ApiVersion}(api-origin={ClientInfo.Framework};os={ClientInfo.Platform};version={ClientInfo.Version};product={ClientInfo.Product})"); } @@ -1211,11 +1211,11 @@ private async Task SendHttpRequest(HttpRequestMessage reque HttpResponseMessage response; try { - response = await this.httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); + response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); } catch (HttpRequestException exception) { - MessagingEventSource.Log.ManagementOperationException(this.clientId, nameof(SendHttpRequest), exception); + MessagingEventSource.Log.ManagementOperationException(clientId, nameof(SendHttpRequest), exception); throw new ServiceBusException(true, exception); } @@ -1226,7 +1226,7 @@ private async Task SendHttpRequest(HttpRequestMessage reque } else { - MessagingEventSource.Log.ManagementOperationException(this.clientId, nameof(SendHttpRequest), exceptionReturned); + MessagingEventSource.Log.ManagementOperationException(clientId, nameof(SendHttpRequest), exceptionReturned); throw exceptionReturned; } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index be5fd4badea5..9528a0944088 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Management { using System; using System.Collections.Generic; - using Microsoft.Azure.ServiceBus.Primitives; + using Primitives; /// /// Represents the metadata description of the queue. @@ -28,7 +28,7 @@ public class QueueDescription : IEquatable /// Path of the queue relative to the namespace base address. public QueueDescription(string path) { - this.Path = path; + Path = path; } /// @@ -38,11 +38,11 @@ public QueueDescription(string path) /// Cannot have restricted characters: '@','?','#','*' public string Path { - get => this.path; + get => path; set { EntityNameHelper.CheckValidQueueName(value, nameof(Path)); - this.path = value; + path = value; } } @@ -53,11 +53,11 @@ public string Path /// Max value is 5 minutes. Default value is 60 seconds. public TimeSpan LockDuration { - get => this.lockDuration; + get => lockDuration; set { TimeoutHelper.ThrowIfNonPositiveArgument(value, nameof(LockDuration)); - this.lockDuration = value; + lockDuration = value; } } @@ -95,7 +95,7 @@ public TimeSpan LockDuration /// public TimeSpan DefaultMessageTimeToLive { - get => this.defaultMessageTimeToLive; + get => defaultMessageTimeToLive; set { if (value < ManagementClientConstants.MinimumAllowedTimeToLive || value > ManagementClientConstants.MaximumAllowedTimeToLive) @@ -104,7 +104,7 @@ public TimeSpan DefaultMessageTimeToLive $"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); } - this.defaultMessageTimeToLive = value; + defaultMessageTimeToLive = value; } } @@ -114,7 +114,7 @@ public TimeSpan DefaultMessageTimeToLive /// The minimum duration is 5 minutes. Default value is . public TimeSpan AutoDeleteOnIdle { - get => this.autoDeleteOnIdle; + get => autoDeleteOnIdle; set { if (value < ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle) @@ -123,7 +123,7 @@ public TimeSpan AutoDeleteOnIdle $"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } - this.autoDeleteOnIdle = value; + autoDeleteOnIdle = value; } } @@ -141,7 +141,7 @@ public TimeSpan AutoDeleteOnIdle /// public TimeSpan DuplicateDetectionHistoryTimeWindow { - get => this.duplicateDetectionHistoryTimeWindow; + get => duplicateDetectionHistoryTimeWindow; set { if (value < ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow || value > ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow) @@ -150,7 +150,7 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow $"The value must be between {ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow} and {ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow}"); } - this.duplicateDetectionHistoryTimeWindow = value; + duplicateDetectionHistoryTimeWindow = value; } } @@ -162,7 +162,7 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow /// Default value is 10. Minimum value is 1. public int MaxDeliveryCount { - get => this.maxDeliveryCount; + get => maxDeliveryCount; set { if (value < ManagementClientConstants.MinAllowedMaxDeliveryCount) @@ -171,7 +171,7 @@ public int MaxDeliveryCount $"The value must be greater than {ManagementClientConstants.MinAllowedMaxDeliveryCount}"); } - this.maxDeliveryCount = value; + maxDeliveryCount = value; } } @@ -199,22 +199,22 @@ public int MaxDeliveryCount /// must be an already existing entity. public string ForwardTo { - get => this.forwardTo; + get => forwardTo; set { if (string.IsNullOrWhiteSpace(value)) { - this.forwardTo = value; + forwardTo = value; return; } EntityNameHelper.CheckValidQueueName(value, nameof(ForwardTo)); - if (this.path.Equals(value, StringComparison.CurrentCultureIgnoreCase)) + if (path.Equals(value, StringComparison.CurrentCultureIgnoreCase)) { throw new InvalidOperationException("Entity cannot have auto-forwarding policy to itself"); } - this.forwardTo = value; + forwardTo = value; } } @@ -225,22 +225,22 @@ public string ForwardTo /// entity must already exist. public string ForwardDeadLetteredMessagesTo { - get => this.forwardDeadLetteredMessagesTo; + get => forwardDeadLetteredMessagesTo; set { if (string.IsNullOrWhiteSpace(value)) { - this.forwardDeadLetteredMessagesTo = value; + forwardDeadLetteredMessagesTo = value; return; } EntityNameHelper.CheckValidQueueName(value, nameof(ForwardDeadLetteredMessagesTo)); - if (this.path.Equals(value, StringComparison.CurrentCultureIgnoreCase)) + if (path.Equals(value, StringComparison.CurrentCultureIgnoreCase)) { throw new InvalidOperationException("Entity cannot have auto-forwarding policy to itself"); } - this.forwardDeadLetteredMessagesTo = value; + forwardDeadLetteredMessagesTo = value; } } @@ -256,7 +256,7 @@ public string ForwardDeadLetteredMessagesTo /// Cannot be null. Max length is 1024 chars. public string UserMetadata { - get => this.userMetadata; + get => userMetadata; set { if (value == null) @@ -269,7 +269,7 @@ public string UserMetadata throw new ArgumentOutOfRangeException(nameof(UserMetadata), $"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } - this.userMetadata = value; + userMetadata = value; } } @@ -281,37 +281,37 @@ public string UserMetadata public override int GetHashCode() { - return this.Path?.GetHashCode() ?? base.GetHashCode(); + return Path?.GetHashCode() ?? base.GetHashCode(); } public override bool Equals(object obj) { var other = obj as QueueDescription; - return this.Equals(other); + return Equals(other); } public bool Equals(QueueDescription otherDescription) { if (otherDescription is QueueDescription other - && this.Path.Equals(other.Path, StringComparison.OrdinalIgnoreCase) - && this.AutoDeleteOnIdle.Equals(other.AutoDeleteOnIdle) - && this.DefaultMessageTimeToLive.Equals(other.DefaultMessageTimeToLive) - && (!this.RequiresDuplicateDetection || this.DuplicateDetectionHistoryTimeWindow.Equals(other.DuplicateDetectionHistoryTimeWindow)) - && this.EnableBatchedOperations == other.EnableBatchedOperations - && this.EnableDeadLetteringOnMessageExpiration == other.EnableDeadLetteringOnMessageExpiration - && this.EnablePartitioning == other.EnablePartitioning - && string.Equals(this.ForwardDeadLetteredMessagesTo, other.ForwardDeadLetteredMessagesTo, StringComparison.OrdinalIgnoreCase) - && string.Equals(this.ForwardTo, other.ForwardTo, StringComparison.OrdinalIgnoreCase) - && this.LockDuration.Equals(other.LockDuration) - && this.MaxDeliveryCount == other.MaxDeliveryCount - && this.MaxSizeInMB == other.MaxSizeInMB - && this.RequiresDuplicateDetection.Equals(other.RequiresDuplicateDetection) - && this.RequiresSession.Equals(other.RequiresSession) - && this.Status.Equals(other.Status) - && string.Equals(this.userMetadata, other.userMetadata, StringComparison.OrdinalIgnoreCase) - && (this.AuthorizationRules != null && other.AuthorizationRules != null - || this.AuthorizationRules == null && other.AuthorizationRules == null) - && (this.AuthorizationRules == null || this.AuthorizationRules.Equals(other.AuthorizationRules))) + && Path.Equals(other.Path, StringComparison.OrdinalIgnoreCase) + && AutoDeleteOnIdle.Equals(other.AutoDeleteOnIdle) + && DefaultMessageTimeToLive.Equals(other.DefaultMessageTimeToLive) + && (!RequiresDuplicateDetection || DuplicateDetectionHistoryTimeWindow.Equals(other.DuplicateDetectionHistoryTimeWindow)) + && EnableBatchedOperations == other.EnableBatchedOperations + && EnableDeadLetteringOnMessageExpiration == other.EnableDeadLetteringOnMessageExpiration + && EnablePartitioning == other.EnablePartitioning + && string.Equals(ForwardDeadLetteredMessagesTo, other.ForwardDeadLetteredMessagesTo, StringComparison.OrdinalIgnoreCase) + && string.Equals(ForwardTo, other.ForwardTo, StringComparison.OrdinalIgnoreCase) + && LockDuration.Equals(other.LockDuration) + && MaxDeliveryCount == other.MaxDeliveryCount + && MaxSizeInMB == other.MaxSizeInMB + && RequiresDuplicateDetection.Equals(other.RequiresDuplicateDetection) + && RequiresSession.Equals(other.RequiresSession) + && Status.Equals(other.Status) + && string.Equals(userMetadata, other.userMetadata, StringComparison.OrdinalIgnoreCase) + && (AuthorizationRules != null && other.AuthorizationRules != null + || AuthorizationRules == null && other.AuthorizationRules == null) + && (AuthorizationRules == null || AuthorizationRules.Equals(other.AuthorizationRules))) { return true; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueRuntimeInfo.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueRuntimeInfo.cs index a5570a82fbd6..741343f23876 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueRuntimeInfo.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueRuntimeInfo.cs @@ -12,7 +12,7 @@ public class QueueRuntimeInfo { internal QueueRuntimeInfo(string path) { - this.Path = path; + Path = path; } /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs index 43e68c92c906..92ceccd96213 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs @@ -11,7 +11,7 @@ namespace Microsoft.Azure.ServiceBus.Management using System.Web; using System.Xml; using System.Xml.Linq; - using Microsoft.Azure.ServiceBus.Primitives; + using Primitives; /// /// Defines the authorization rule for an entity using SAS. @@ -34,7 +34,7 @@ internal SharedAccessAuthorizationRule() /// The authorization rule key name. /// The list of rights. public SharedAccessAuthorizationRule(string keyName, IEnumerable rights) - : this(keyName, SharedAccessAuthorizationRule.GenerateRandomKey(), SharedAccessAuthorizationRule.GenerateRandomKey(), rights) + : this(keyName, GenerateRandomKey(), GenerateRandomKey(), rights) { } @@ -43,7 +43,7 @@ public SharedAccessAuthorizationRule(string keyName, IEnumerable r /// The primary key for the authorization rule. /// The list of rights. public SharedAccessAuthorizationRule(string keyName, string primaryKey, IEnumerable rights) - : this(keyName, primaryKey, SharedAccessAuthorizationRule.GenerateRandomKey(), rights) + : this(keyName, primaryKey, GenerateRandomKey(), rights) { } @@ -54,10 +54,10 @@ public SharedAccessAuthorizationRule(string keyName, string primaryKey, IEnumera /// The list of rights. public SharedAccessAuthorizationRule(string keyName, string primaryKey, string secondaryKey, IEnumerable rights) { - this.PrimaryKey = primaryKey; - this.SecondaryKey = secondaryKey; - this.Rights = new List(rights); - this.KeyName = keyName; + PrimaryKey = primaryKey; + SecondaryKey = secondaryKey; + Rights = new List(rights); + KeyName = keyName; } public override string ClaimType => FixedClaimType; @@ -68,7 +68,7 @@ public SharedAccessAuthorizationRule(string keyName, string primaryKey, string s /// The authorization rule key name. public override sealed string KeyName { - get { return this.internalKeyName; } + get { return internalKeyName; } set { if (string.IsNullOrWhiteSpace(value)) @@ -87,7 +87,7 @@ public override sealed string KeyName throw new ArgumentException("The key name specified contains invalid characters"); } - this.internalKeyName = value; + internalKeyName = value; } } @@ -95,7 +95,7 @@ public override sealed string KeyName /// The primary key for the authorization rule. public string PrimaryKey { - get { return this.internalPrimaryKey; } + get { return internalPrimaryKey; } set { if (string.IsNullOrWhiteSpace(value)) @@ -113,7 +113,7 @@ public string PrimaryKey throw new ArgumentException(nameof(PrimaryKey), $"{nameof(SharedAccessAuthorizationRule)} only supports base64 keys."); } - this.internalPrimaryKey = value; + internalPrimaryKey = value; } } @@ -121,7 +121,7 @@ public string PrimaryKey /// The secondary key for the authorization rule. public string SecondaryKey { - get { return this.internalSecondaryKey; } + get { return internalSecondaryKey; } set { if (string.IsNullOrWhiteSpace(value)) @@ -139,13 +139,13 @@ public string SecondaryKey throw new ArgumentException(nameof(SecondaryKey), $"{nameof(SharedAccessAuthorizationRule)} only supports base64 keys."); } - this.internalSecondaryKey = value; + internalSecondaryKey = value; } } public override List Rights { - get => this.internalRights; + get => internalRights; set { if (value == null || value.Count < 0 || value.Count > ManagementClientConstants.SupportedClaimsCount) @@ -164,7 +164,7 @@ public override List Rights throw new ArgumentException(nameof(Rights), "Manage permission should also include Send and Listen"); } - this.internalRights = value; + internalRights = value; } } @@ -174,10 +174,10 @@ public override int GetHashCode() int hash = 13; unchecked { - hash = (hash * 7) + this.KeyName?.GetHashCode() ?? 0; - hash = (hash * 7) + this.PrimaryKey?.GetHashCode() ?? 0; - hash = (hash * 7) + this.SecondaryKey?.GetHashCode() ?? 0; - hash = (hash * 7) + this.Rights.GetHashCode(); + hash = (hash * 7) + KeyName?.GetHashCode() ?? 0; + hash = (hash * 7) + PrimaryKey?.GetHashCode() ?? 0; + hash = (hash * 7) + SecondaryKey?.GetHashCode() ?? 0; + hash = (hash * 7) + Rights.GetHashCode(); } return hash; @@ -186,7 +186,7 @@ public override int GetHashCode() public override bool Equals(object obj) { var other = obj as AuthorizationRule; - return this.Equals(other); + return Equals(other); } /// Determines whether the specified object is equal to the current object. @@ -200,22 +200,22 @@ public override bool Equals(AuthorizationRule other) } SharedAccessAuthorizationRule comparand = (SharedAccessAuthorizationRule)other; - if (!string.Equals(this.KeyName, comparand.KeyName, StringComparison.OrdinalIgnoreCase) || - !string.Equals(this.PrimaryKey, comparand.PrimaryKey, StringComparison.Ordinal) || - !string.Equals(this.SecondaryKey, comparand.SecondaryKey, StringComparison.Ordinal)) + if (!string.Equals(KeyName, comparand.KeyName, StringComparison.OrdinalIgnoreCase) || + !string.Equals(PrimaryKey, comparand.PrimaryKey, StringComparison.Ordinal) || + !string.Equals(SecondaryKey, comparand.SecondaryKey, StringComparison.Ordinal)) { return false; } - if ((this.Rights != null && comparand.Rights == null) || - (this.Rights == null && comparand.Rights != null)) + if ((Rights != null && comparand.Rights == null) || + (Rights == null && comparand.Rights != null)) { return false; } - if (this.Rights != null && comparand.Rights != null) + if (Rights != null && comparand.Rights != null) { - HashSet thisRights = new HashSet(this.Rights); + HashSet thisRights = new HashSet(Rights); if (comparand.Rights.Count != thisRights.Count) { return false; @@ -314,13 +314,13 @@ internal override XElement Serialize() XElement rule = new XElement( XName.Get("AuthorizationRule", ManagementClientConstants.ServiceBusNamespace), new XAttribute(XName.Get("type", ManagementClientConstants.XmlSchemaInstanceNamespace), nameof(SharedAccessAuthorizationRule)), - new XElement(XName.Get("ClaimType", ManagementClientConstants.ServiceBusNamespace), this.ClaimType), - new XElement(XName.Get("ClaimValue", ManagementClientConstants.ServiceBusNamespace), this.ClaimValue), + new XElement(XName.Get("ClaimType", ManagementClientConstants.ServiceBusNamespace), ClaimType), + new XElement(XName.Get("ClaimValue", ManagementClientConstants.ServiceBusNamespace), ClaimValue), new XElement(XName.Get("Rights", ManagementClientConstants.ServiceBusNamespace), - this.Rights.Select(right => new XElement(XName.Get("AccessRights", ManagementClientConstants.ServiceBusNamespace), right.ToString()))), - new XElement(XName.Get("KeyName", ManagementClientConstants.ServiceBusNamespace), this.KeyName), - new XElement(XName.Get("PrimaryKey", ManagementClientConstants.ServiceBusNamespace), this.PrimaryKey), - new XElement(XName.Get("SecondaryKey", ManagementClientConstants.ServiceBusNamespace), this.SecondaryKey) + Rights.Select(right => new XElement(XName.Get("AccessRights", ManagementClientConstants.ServiceBusNamespace), right.ToString()))), + new XElement(XName.Get("KeyName", ManagementClientConstants.ServiceBusNamespace), KeyName), + new XElement(XName.Get("PrimaryKey", ManagementClientConstants.ServiceBusNamespace), PrimaryKey), + new XElement(XName.Get("SecondaryKey", ManagementClientConstants.ServiceBusNamespace), SecondaryKey) ); return rule; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs index c0e0dea405c2..77dc77bd0b21 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Management { using System; using System.Collections.Generic; - using Microsoft.Azure.ServiceBus.Primitives; + using Primitives; /// /// Represents the metadata description of the subscription. @@ -28,8 +28,8 @@ public class SubscriptionDescription : IEquatable /// Name of the subscription. public SubscriptionDescription(string topicPath, string subscriptionName) { - this.TopicPath = topicPath; - this.SubscriptionName = subscriptionName; + TopicPath = topicPath; + SubscriptionName = subscriptionName; } /// @@ -39,11 +39,11 @@ public SubscriptionDescription(string topicPath, string subscriptionName) /// Max value is 5 minutes. Default value is 60 seconds. public TimeSpan LockDuration { - get => this.lockDuration; + get => lockDuration; set { TimeoutHelper.ThrowIfNonPositiveArgument(value, nameof(LockDuration)); - this.lockDuration = value; + lockDuration = value; } } @@ -67,7 +67,7 @@ public TimeSpan LockDuration /// public TimeSpan DefaultMessageTimeToLive { - get => this.defaultMessageTimeToLive; + get => defaultMessageTimeToLive; set { if (value < ManagementClientConstants.MinimumAllowedTimeToLive || value > ManagementClientConstants.MaximumAllowedTimeToLive) @@ -76,7 +76,7 @@ public TimeSpan DefaultMessageTimeToLive $"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); } - this.defaultMessageTimeToLive = value; + defaultMessageTimeToLive = value; } } @@ -86,7 +86,7 @@ public TimeSpan DefaultMessageTimeToLive /// The minimum duration is 5 minutes. Default value is . public TimeSpan AutoDeleteOnIdle { - get => this.autoDeleteOnIdle; + get => autoDeleteOnIdle; set { if (value < ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle) @@ -95,7 +95,7 @@ public TimeSpan AutoDeleteOnIdle $"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } - this.autoDeleteOnIdle = value; + autoDeleteOnIdle = value; } } @@ -118,11 +118,11 @@ public TimeSpan AutoDeleteOnIdle /// Cannot have restricted characters: '@','?','#','*' public string TopicPath { - get => this.topicPath; + get => topicPath; set { EntityNameHelper.CheckValidTopicName(value, nameof(TopicPath)); - this.topicPath = value; + topicPath = value; } } @@ -133,11 +133,11 @@ public string TopicPath /// Cannot have restricted characters: '@','?','#','*','/','\' public string SubscriptionName { - get => this.subscriptionName; + get => subscriptionName; set { EntityNameHelper.CheckValidSubscriptionName(value, nameof(SubscriptionName)); - this.subscriptionName = value; + subscriptionName = value; } } @@ -149,7 +149,7 @@ public string SubscriptionName /// Default value is 10. Minimum value is 1. public int MaxDeliveryCount { - get => this.maxDeliveryCount; + get => maxDeliveryCount; set { if (value < ManagementClientConstants.MinAllowedMaxDeliveryCount) @@ -158,7 +158,7 @@ public int MaxDeliveryCount $"The value must be greater than {ManagementClientConstants.MinAllowedMaxDeliveryCount}"); } - this.maxDeliveryCount = value; + maxDeliveryCount = value; } } @@ -175,22 +175,22 @@ public int MaxDeliveryCount /// must be an already existing entity. public string ForwardTo { - get => this.forwardTo; + get => forwardTo; set { if (string.IsNullOrWhiteSpace(value)) { - this.forwardTo = value; + forwardTo = value; return; } EntityNameHelper.CheckValidQueueName(value, nameof(ForwardTo)); - if (this.topicPath.Equals(value, StringComparison.CurrentCultureIgnoreCase)) + if (topicPath.Equals(value, StringComparison.CurrentCultureIgnoreCase)) { throw new InvalidOperationException("Entity cannot have auto-forwarding policy to itself"); } - this.forwardTo = value; + forwardTo = value; } } @@ -201,22 +201,22 @@ public string ForwardTo /// entity must already exist. public string ForwardDeadLetteredMessagesTo { - get => this.forwardDeadLetteredMessagesTo; + get => forwardDeadLetteredMessagesTo; set { if (string.IsNullOrWhiteSpace(value)) { - this.forwardDeadLetteredMessagesTo = value; + forwardDeadLetteredMessagesTo = value; return; } EntityNameHelper.CheckValidQueueName(value, nameof(ForwardDeadLetteredMessagesTo)); - if (this.topicPath.Equals(value, StringComparison.CurrentCultureIgnoreCase)) + if (topicPath.Equals(value, StringComparison.CurrentCultureIgnoreCase)) { throw new InvalidOperationException("Entity cannot have auto-forwarding policy to itself"); } - this.forwardDeadLetteredMessagesTo = value; + forwardDeadLetteredMessagesTo = value; } } @@ -232,7 +232,7 @@ public string ForwardDeadLetteredMessagesTo /// Cannot be null. Max length is 1024 chars. public string UserMetadata { - get => this.userMetadata; + get => userMetadata; set { if (value == null) @@ -245,7 +245,7 @@ public string UserMetadata throw new ArgumentOutOfRangeException(nameof(UserMetadata), $"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } - this.userMetadata = value; + userMetadata = value; } } @@ -262,8 +262,8 @@ public override int GetHashCode() int hash = 7; unchecked { - hash = (hash * 7) + this.TopicPath?.GetHashCode() ?? 0; - hash = (hash * 7) + this.SubscriptionName?.GetHashCode() ?? 0; + hash = (hash * 7) + TopicPath?.GetHashCode() ?? 0; + hash = (hash * 7) + SubscriptionName?.GetHashCode() ?? 0; } return hash; @@ -272,26 +272,26 @@ public override int GetHashCode() public override bool Equals(object obj) { var other = obj as SubscriptionDescription; - return this.Equals(other); + return Equals(other); } public bool Equals(SubscriptionDescription otherDescription) { if (otherDescription is SubscriptionDescription other - && this.SubscriptionName.Equals(other.SubscriptionName, StringComparison.OrdinalIgnoreCase) - && this.TopicPath.Equals(other.TopicPath, StringComparison.OrdinalIgnoreCase) - && this.AutoDeleteOnIdle.Equals(other.AutoDeleteOnIdle) - && this.DefaultMessageTimeToLive.Equals(other.DefaultMessageTimeToLive) - && this.EnableBatchedOperations == other.EnableBatchedOperations - && this.EnableDeadLetteringOnMessageExpiration == other.EnableDeadLetteringOnMessageExpiration - && this.EnableDeadLetteringOnFilterEvaluationExceptions == other.EnableDeadLetteringOnFilterEvaluationExceptions - && string.Equals(this.ForwardDeadLetteredMessagesTo, other.ForwardDeadLetteredMessagesTo, StringComparison.OrdinalIgnoreCase) - && string.Equals(this.ForwardTo, other.ForwardTo, StringComparison.OrdinalIgnoreCase) - && this.LockDuration.Equals(other.LockDuration) - && this.MaxDeliveryCount == other.MaxDeliveryCount - && this.RequiresSession.Equals(other.RequiresSession) - && this.Status.Equals(other.Status) - && string.Equals(this.userMetadata, other.userMetadata, StringComparison.OrdinalIgnoreCase)) + && SubscriptionName.Equals(other.SubscriptionName, StringComparison.OrdinalIgnoreCase) + && TopicPath.Equals(other.TopicPath, StringComparison.OrdinalIgnoreCase) + && AutoDeleteOnIdle.Equals(other.AutoDeleteOnIdle) + && DefaultMessageTimeToLive.Equals(other.DefaultMessageTimeToLive) + && EnableBatchedOperations == other.EnableBatchedOperations + && EnableDeadLetteringOnMessageExpiration == other.EnableDeadLetteringOnMessageExpiration + && EnableDeadLetteringOnFilterEvaluationExceptions == other.EnableDeadLetteringOnFilterEvaluationExceptions + && string.Equals(ForwardDeadLetteredMessagesTo, other.ForwardDeadLetteredMessagesTo, StringComparison.OrdinalIgnoreCase) + && string.Equals(ForwardTo, other.ForwardTo, StringComparison.OrdinalIgnoreCase) + && LockDuration.Equals(other.LockDuration) + && MaxDeliveryCount == other.MaxDeliveryCount + && RequiresSession.Equals(other.RequiresSession) + && Status.Equals(other.Status) + && string.Equals(userMetadata, other.userMetadata, StringComparison.OrdinalIgnoreCase)) { return true; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionRuntimeInfo.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionRuntimeInfo.cs index a0f2297d78c8..e2361becb70a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionRuntimeInfo.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionRuntimeInfo.cs @@ -12,8 +12,8 @@ public class SubscriptionRuntimeInfo { internal SubscriptionRuntimeInfo(string topicPath, string subscriptionName) { - this.TopicPath = topicPath; - this.SubscriptionName = subscriptionName; + TopicPath = topicPath; + SubscriptionName = subscriptionName; } /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs index cfa5aa59a0bd..9759f71e6e98 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs @@ -23,7 +23,7 @@ public class TopicDescription : IEquatable /// Path of the topic relative to the namespace base address. public TopicDescription(string path) { - this.Path = path; + Path = path; } /// @@ -37,7 +37,7 @@ public TopicDescription(string path) /// public TimeSpan DefaultMessageTimeToLive { - get => this.defaultMessageTimeToLive; + get => defaultMessageTimeToLive; set { if (value < ManagementClientConstants.MinimumAllowedTimeToLive || value > ManagementClientConstants.MaximumAllowedTimeToLive) @@ -46,7 +46,7 @@ public TimeSpan DefaultMessageTimeToLive $"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); } - this.defaultMessageTimeToLive = value; + defaultMessageTimeToLive = value; } } @@ -56,7 +56,7 @@ public TimeSpan DefaultMessageTimeToLive /// The minimum duration is 5 minutes. Default value is . public TimeSpan AutoDeleteOnIdle { - get => this.autoDeleteOnIdle; + get => autoDeleteOnIdle; set { if (value < ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle) @@ -65,7 +65,7 @@ public TimeSpan AutoDeleteOnIdle $"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } - this.autoDeleteOnIdle = value; + autoDeleteOnIdle = value; } } @@ -91,7 +91,7 @@ public TimeSpan AutoDeleteOnIdle /// public TimeSpan DuplicateDetectionHistoryTimeWindow { - get => this.duplicateDetectionHistoryTimeWindow; + get => duplicateDetectionHistoryTimeWindow; set { if (value < ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow || value > ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow) @@ -100,7 +100,7 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow $"The value must be between {ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow} and {ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow}"); } - this.duplicateDetectionHistoryTimeWindow = value; + duplicateDetectionHistoryTimeWindow = value; } } @@ -111,11 +111,11 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow /// Cannot have restricted characters: '@','?','#','*' public string Path { - get => this.path; + get => path; set { EntityNameHelper.CheckValidTopicName(value, nameof(Path)); - this.path = value; + path = value; } } @@ -155,7 +155,7 @@ public string Path /// Cannot be null. Max length is 1024 chars. public string UserMetadata { - get => this.userMetadata; + get => userMetadata; set { if (value == null) @@ -168,7 +168,7 @@ public string UserMetadata throw new ArgumentOutOfRangeException(nameof(UserMetadata), $"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } - this.userMetadata = value; + userMetadata = value; } } @@ -180,31 +180,31 @@ public string UserMetadata public override int GetHashCode() { - return this.Path?.GetHashCode() ?? base.GetHashCode(); + return Path?.GetHashCode() ?? base.GetHashCode(); } public override bool Equals(object obj) { var other = obj as TopicDescription; - return this.Equals(other); + return Equals(other); } public bool Equals(TopicDescription otherDescription) { if (otherDescription is TopicDescription other - && this.Path.Equals(other.Path, StringComparison.OrdinalIgnoreCase) - && this.AutoDeleteOnIdle.Equals(other.AutoDeleteOnIdle) - && this.DefaultMessageTimeToLive.Equals(other.DefaultMessageTimeToLive) - && (!this.RequiresDuplicateDetection || this.DuplicateDetectionHistoryTimeWindow.Equals(other.DuplicateDetectionHistoryTimeWindow)) - && this.EnableBatchedOperations == other.EnableBatchedOperations - && this.EnablePartitioning == other.EnablePartitioning - && this.MaxSizeInMB == other.MaxSizeInMB - && this.RequiresDuplicateDetection.Equals(other.RequiresDuplicateDetection) - && this.Status.Equals(other.Status) - && string.Equals(this.userMetadata, other.userMetadata, StringComparison.OrdinalIgnoreCase) - && (this.AuthorizationRules != null && other.AuthorizationRules != null - || this.AuthorizationRules == null && other.AuthorizationRules == null) - && (this.AuthorizationRules == null || this.AuthorizationRules.Equals(other.AuthorizationRules))) + && Path.Equals(other.Path, StringComparison.OrdinalIgnoreCase) + && AutoDeleteOnIdle.Equals(other.AutoDeleteOnIdle) + && DefaultMessageTimeToLive.Equals(other.DefaultMessageTimeToLive) + && (!RequiresDuplicateDetection || DuplicateDetectionHistoryTimeWindow.Equals(other.DuplicateDetectionHistoryTimeWindow)) + && EnableBatchedOperations == other.EnableBatchedOperations + && EnablePartitioning == other.EnablePartitioning + && MaxSizeInMB == other.MaxSizeInMB + && RequiresDuplicateDetection.Equals(other.RequiresDuplicateDetection) + && Status.Equals(other.Status) + && string.Equals(userMetadata, other.userMetadata, StringComparison.OrdinalIgnoreCase) + && (AuthorizationRules != null && other.AuthorizationRules != null + || AuthorizationRules == null && other.AuthorizationRules == null) + && (AuthorizationRules == null || AuthorizationRules.Equals(other.AuthorizationRules))) { return true; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicRuntimeInfo.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicRuntimeInfo.cs index 924568df806e..e83847e145f3 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicRuntimeInfo.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicRuntimeInfo.cs @@ -12,7 +12,7 @@ public class TopicRuntimeInfo { internal TopicRuntimeInfo(string path) { - this.Path = path; + Path = path; } /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs index 3d04fcfb1eb9..137a7e295c5c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs @@ -47,9 +47,9 @@ public Message() /// The payload of the message in bytes public Message(byte[] body) { - this.Body = body; - this.SystemProperties = new SystemPropertiesCollection(); - this.UserProperties = new Dictionary(); + Body = body; + SystemProperties = new SystemPropertiesCollection(); + UserProperties = new Dictionary(); } /// @@ -76,12 +76,12 @@ public Message(byte[] body) /// public string MessageId { - get => this.messageId; + get => messageId; set { - Message.ValidateMessageId(value); - this.messageId = value; + ValidateMessageId(value); + messageId = value; } } @@ -95,12 +95,12 @@ public string MessageId /// public string PartitionKey { - get => this.partitionKey; + get => partitionKey; set { - Message.ValidatePartitionKey(nameof(this.PartitionKey), value); - this.partitionKey = value; + ValidatePartitionKey(nameof(PartitionKey), value); + partitionKey = value; } } @@ -114,12 +114,12 @@ public string PartitionKey /// public string ViaPartitionKey { - get => this.viaPartitionKey; + get => viaPartitionKey; set { - Message.ValidatePartitionKey(nameof(this.ViaPartitionKey), value); - this.viaPartitionKey = value; + ValidatePartitionKey(nameof(ViaPartitionKey), value); + viaPartitionKey = value; } } @@ -134,12 +134,12 @@ public string ViaPartitionKey /// public string SessionId { - get => this.sessionId; + get => sessionId; set { - Message.ValidateSessionId(nameof(this.SessionId), value); - this.sessionId = value; + ValidateSessionId(nameof(SessionId), value); + sessionId = value; } } @@ -151,12 +151,12 @@ public string SessionId /// public string ReplyToSessionId { - get => this.replyToSessionId; + get => replyToSessionId; set { - Message.ValidateSessionId(nameof(this.ReplyToSessionId), value); - this.replyToSessionId = value; + ValidateSessionId(nameof(ReplyToSessionId), value); + replyToSessionId = value; } } @@ -171,12 +171,12 @@ public DateTime ExpiresAtUtc { get { - if (this.TimeToLive >= DateTime.MaxValue.Subtract(this.SystemProperties.EnqueuedTimeUtc)) + if (TimeToLive >= DateTime.MaxValue.Subtract(SystemProperties.EnqueuedTimeUtc)) { return DateTime.MaxValue; } - return this.SystemProperties.EnqueuedTimeUtc.Add(this.TimeToLive); + return SystemProperties.EnqueuedTimeUtc.Add(TimeToLive); } } @@ -196,18 +196,18 @@ public TimeSpan TimeToLive { get { - if (this.timeToLive == TimeSpan.Zero) + if (timeToLive == TimeSpan.Zero) { return TimeSpan.MaxValue; } - return this.timeToLive; + return timeToLive; } set { TimeoutHelper.ThrowIfNonPositiveArgument(value); - this.timeToLive = value; + timeToLive = value; } } @@ -268,7 +268,7 @@ public TimeSpan TimeToLive /// /// Gets the total size of the message body in bytes. /// - public long Size => this.Body != null ? this.Body.Length : 0; + public long Size => Body != null ? Body.Length : 0; /// /// Gets the "user properties" bag, which can be used for custom message metadata. @@ -289,7 +289,7 @@ public TimeSpan TimeToLive /// The string representation of the current message. public override string ToString() { - return string.Format(CultureInfo.CurrentCulture, "{{MessageId:{0}}}", this.MessageId); + return string.Format(CultureInfo.CurrentCulture, "{{MessageId:{0}}}", MessageId); } /// Clones a message, so that it is possible to send a clone of an already received @@ -298,13 +298,13 @@ public override string ToString() /// A cloned . public Message Clone() { - var clone = (Message)this.MemberwiseClone(); + var clone = (Message)MemberwiseClone(); clone.SystemProperties = new SystemPropertiesCollection(); - if (this.Body != null) + if (Body != null) { - var clonedBody = new byte[this.Body.Length]; - Array.Copy(this.Body, clonedBody, this.Body.Length); + var clonedBody = new byte[Body.Length]; + Array.Copy(Body, clonedBody, Body.Length); clone.Body = clonedBody; } return clone; @@ -356,7 +356,7 @@ public sealed class SystemPropertiesCollection /// Specifies whether or not there is a lock token set on the current message. /// /// A lock token will only be specified if the message was received using - public bool IsLockTokenSet => this.lockTokenGuid != default; + public bool IsLockTokenSet => lockTokenGuid != default; /// /// Gets the lock token for the current message. @@ -367,10 +367,10 @@ public sealed class SystemPropertiesCollection /// The token can also be used to pin the lock permanently through the Deferral API and, with that, take the message out of the /// regular delivery state flow. This property is read-only. /// - public string LockToken => this.LockTokenGuid.ToString(); + public string LockToken => LockTokenGuid.ToString(); /// Specifies if the message has been obtained from the broker. - public bool IsReceived => this.sequenceNumber > -1; + public bool IsReceived => sequenceNumber > -1; /// /// Get the current delivery count. @@ -384,11 +384,11 @@ public int DeliveryCount { get { - this.ThrowIfNotReceived(); - return this.deliveryCount; + ThrowIfNotReceived(); + return deliveryCount; } - internal set => this.deliveryCount = value; + internal set => deliveryCount = value; } /// Gets the date and time in UTC until which the message will be locked in the queue/subscription. @@ -402,11 +402,11 @@ public DateTime LockedUntilUtc { get { - this.ThrowIfNotReceived(); - return this.lockedUntilUtc; + ThrowIfNotReceived(); + return lockedUntilUtc; } - internal set => this.lockedUntilUtc = value; + internal set => lockedUntilUtc = value; } /// Gets the unique number assigned to a message by Service Bus. @@ -420,11 +420,11 @@ public long SequenceNumber { get { - this.ThrowIfNotReceived(); - return this.sequenceNumber; + ThrowIfNotReceived(); + return sequenceNumber; } - internal set => this.sequenceNumber = value; + internal set => sequenceNumber = value; } /// @@ -438,22 +438,22 @@ public string DeadLetterSource { get { - this.ThrowIfNotReceived(); - return this.deadLetterSource; + ThrowIfNotReceived(); + return deadLetterSource; } - internal set => this.deadLetterSource = value; + internal set => deadLetterSource = value; } internal short PartitionId { get { - this.ThrowIfNotReceived(); - return this.partitionId; + ThrowIfNotReceived(); + return partitionId; } - set => this.partitionId = value; + set => partitionId = value; } /// Gets or sets the original sequence number of the message. @@ -466,11 +466,11 @@ public long EnqueuedSequenceNumber { get { - this.ThrowIfNotReceived(); - return this.enqueuedSequenceNumber; + ThrowIfNotReceived(); + return enqueuedSequenceNumber; } - internal set => this.enqueuedSequenceNumber = value; + internal set => enqueuedSequenceNumber = value; } /// Gets or sets the date and time of the sent time in UTC. @@ -484,22 +484,22 @@ public DateTime EnqueuedTimeUtc { get { - this.ThrowIfNotReceived(); - return this.enqueuedTimeUtc; + ThrowIfNotReceived(); + return enqueuedTimeUtc; } - internal set => this.enqueuedTimeUtc = value; + internal set => enqueuedTimeUtc = value; } internal Guid LockTokenGuid { get { - this.ThrowIfNotReceived(); - return this.lockTokenGuid; + ThrowIfNotReceived(); + return lockTokenGuid; } - set => this.lockTokenGuid = value; + set => lockTokenGuid = value; } internal object BodyObject @@ -510,7 +510,7 @@ internal object BodyObject void ThrowIfNotReceived() { - if (!this.IsReceived) + if (!IsReceived) { throw Fx.Exception.AsError(new InvalidOperationException()); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs index 790765d25fea..7a0797e73fc9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs @@ -27,11 +27,11 @@ public sealed class MessageHandlerOptions /// contains contextual information regarding the exception. public MessageHandlerOptions(Func exceptionReceivedHandler) { - this.MaxConcurrentCalls = 1; - this.AutoComplete = true; - this.ReceiveTimeOut = Constants.DefaultOperationTimeout; - this.MaxAutoRenewDuration = Constants.ClientPumpRenewLockTimeout; - this.ExceptionReceivedHandler = exceptionReceivedHandler ?? throw new ArgumentNullException(nameof(exceptionReceivedHandler)); + MaxConcurrentCalls = 1; + AutoComplete = true; + ReceiveTimeOut = Constants.DefaultOperationTimeout; + MaxAutoRenewDuration = Constants.ClientPumpRenewLockTimeout; + ExceptionReceivedHandler = exceptionReceivedHandler ?? throw new ArgumentNullException(nameof(exceptionReceivedHandler)); } /// Occurs when an exception is received. Enables you to be notified of any errors encountered by the message pump. @@ -42,7 +42,7 @@ public MessageHandlerOptions(Func exceptionRec /// The maximum number of concurrent calls to the callback. public int MaxConcurrentCalls { - get => this.maxConcurrentCalls; + get => maxConcurrentCalls; set { @@ -51,7 +51,7 @@ public int MaxConcurrentCalls throw new ArgumentOutOfRangeException(Resources.MaxConcurrentCallsMustBeGreaterThanZero.FormatForUser(value)); } - this.maxConcurrentCalls = value; + maxConcurrentCalls = value; } } @@ -68,16 +68,16 @@ public int MaxConcurrentCalls /// after completion of message and result in a few false MessageLockLostExceptions temporarily. public TimeSpan MaxAutoRenewDuration { - get => this.maxAutoRenewDuration; + get => maxAutoRenewDuration; set { TimeoutHelper.ThrowIfNegativeArgument(value, nameof(value)); - this.maxAutoRenewDuration = value; + maxAutoRenewDuration = value; } } - internal bool AutoRenewLock => this.MaxAutoRenewDuration > TimeSpan.Zero; + internal bool AutoRenewLock => MaxAutoRenewDuration > TimeSpan.Zero; internal TimeSpan ReceiveTimeOut { get; } @@ -85,7 +85,7 @@ internal async Task RaiseExceptionReceived(ExceptionReceivedEventArgs eventArgs) { try { - await this.ExceptionReceivedHandler(eventArgs).ConfigureAwait(false); + await ExceptionReceivedHandler(eventArgs).ConfigureAwait(false); } catch (Exception exception) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs index f918b32e146d..475d332f0e6b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs @@ -28,58 +28,58 @@ public MessageReceivePump(IMessageReceiver messageReceiver, { this.messageReceiver = messageReceiver ?? throw new ArgumentNullException(nameof(messageReceiver)); this.registerHandlerOptions = registerHandlerOptions; - this.onMessageCallback = callback; + onMessageCallback = callback; this.endpoint = endpoint.Authority; this.pumpCancellationToken = pumpCancellationToken; - this.maxConcurrentCallsSemaphoreSlim = new SemaphoreSlim(this.registerHandlerOptions.MaxConcurrentCalls); - this.diagnosticSource = new ServiceBusDiagnosticSource(messageReceiver.Path, endpoint); + maxConcurrentCallsSemaphoreSlim = new SemaphoreSlim(this.registerHandlerOptions.MaxConcurrentCalls); + diagnosticSource = new ServiceBusDiagnosticSource(messageReceiver.Path, endpoint); } public void StartPump() { - TaskExtensionHelper.Schedule(() => this.MessagePumpTaskAsync()); + TaskExtensionHelper.Schedule(() => MessagePumpTaskAsync()); } bool ShouldRenewLock() { return - this.messageReceiver.ReceiveMode == ReceiveMode.PeekLock && - this.registerHandlerOptions.AutoRenewLock; + messageReceiver.ReceiveMode == ReceiveMode.PeekLock && + registerHandlerOptions.AutoRenewLock; } Task RaiseExceptionReceived(Exception e, string action) { - var eventArgs = new ExceptionReceivedEventArgs(e, action, this.endpoint, this.messageReceiver.Path, this.messageReceiver.ClientId); - return this.registerHandlerOptions.RaiseExceptionReceived(eventArgs); + var eventArgs = new ExceptionReceivedEventArgs(e, action, endpoint, messageReceiver.Path, messageReceiver.ClientId); + return registerHandlerOptions.RaiseExceptionReceived(eventArgs); } async Task MessagePumpTaskAsync() { - while (!this.pumpCancellationToken.IsCancellationRequested) + while (!pumpCancellationToken.IsCancellationRequested) { try { - await this.maxConcurrentCallsSemaphoreSlim.WaitAsync(this.pumpCancellationToken).ConfigureAwait(false); + await maxConcurrentCallsSemaphoreSlim.WaitAsync(pumpCancellationToken).ConfigureAwait(false); TaskExtensionHelper.Schedule(async () => { Message message = null; try { - message = await this.messageReceiver.ReceiveAsync(this.registerHandlerOptions.ReceiveTimeOut).ConfigureAwait(false); + message = await messageReceiver.ReceiveAsync(registerHandlerOptions.ReceiveTimeOut).ConfigureAwait(false); if (message != null) { - MessagingEventSource.Log.MessageReceiverPumpTaskStart(this.messageReceiver.ClientId, message, this.maxConcurrentCallsSemaphoreSlim.CurrentCount); + MessagingEventSource.Log.MessageReceiverPumpTaskStart(messageReceiver.ClientId, message, maxConcurrentCallsSemaphoreSlim.CurrentCount); TaskExtensionHelper.Schedule(() => { if (ServiceBusDiagnosticSource.IsEnabled()) { - return this.MessageDispatchTaskInstrumented(message); + return MessageDispatchTaskInstrumented(message); } else { - return this.MessageDispatchTask(message); + return MessageDispatchTask(message); } }); } @@ -94,16 +94,16 @@ async Task MessagePumpTaskAsync() } catch (Exception exception) { - MessagingEventSource.Log.MessageReceivePumpTaskException(this.messageReceiver.ClientId, string.Empty, exception); - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Receive).ConfigureAwait(false); + MessagingEventSource.Log.MessageReceivePumpTaskException(messageReceiver.ClientId, string.Empty, exception); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Receive).ConfigureAwait(false); } finally { // Either an exception or for some reason message was null, release semaphore and retry. if (message == null) { - this.maxConcurrentCallsSemaphoreSlim.Release(); - MessagingEventSource.Log.MessageReceiverPumpTaskStop(this.messageReceiver.ClientId, this.maxConcurrentCallsSemaphoreSlim.CurrentCount); + maxConcurrentCallsSemaphoreSlim.Release(); + MessagingEventSource.Log.MessageReceiverPumpTaskStop(messageReceiver.ClientId, maxConcurrentCallsSemaphoreSlim.CurrentCount); } } }); @@ -118,15 +118,15 @@ async Task MessagePumpTaskAsync() } catch (Exception exception) { - MessagingEventSource.Log.MessageReceivePumpTaskException(this.messageReceiver.ClientId, string.Empty, exception); - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Receive).ConfigureAwait(false); + MessagingEventSource.Log.MessageReceivePumpTaskException(messageReceiver.ClientId, string.Empty, exception); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Receive).ConfigureAwait(false); } } } async Task MessageDispatchTaskInstrumented(Message message) { - Activity activity = this.diagnosticSource.ProcessStart(message); + Activity activity = diagnosticSource.ProcessStart(message); Task processTask = null; try { @@ -135,12 +135,12 @@ async Task MessageDispatchTaskInstrumented(Message message) } catch (Exception e) { - this.diagnosticSource.ReportException(e); + diagnosticSource.ReportException(e); throw; } finally { - this.diagnosticSource.ProcessStop(activity, message, processTask?.Status); + diagnosticSource.ProcessStop(activity, message, processTask?.Status); } } @@ -149,41 +149,41 @@ async Task MessageDispatchTask(Message message) CancellationTokenSource renewLockCancellationTokenSource = null; Timer autoRenewLockCancellationTimer = null; - MessagingEventSource.Log.MessageReceiverPumpDispatchTaskStart(this.messageReceiver.ClientId, message); + MessagingEventSource.Log.MessageReceiverPumpDispatchTaskStart(messageReceiver.ClientId, message); - if (this.ShouldRenewLock()) + if (ShouldRenewLock()) { renewLockCancellationTokenSource = new CancellationTokenSource(); - TaskExtensionHelper.Schedule(() => this.RenewMessageLockTask(message, renewLockCancellationTokenSource.Token)); + TaskExtensionHelper.Schedule(() => RenewMessageLockTask(message, renewLockCancellationTokenSource.Token)); // After a threshold time of renewal('AutoRenewTimeout'), create timer to cancel anymore renewals. - autoRenewLockCancellationTimer = new Timer(this.CancelAutoRenewLock, renewLockCancellationTokenSource, this.registerHandlerOptions.MaxAutoRenewDuration, TimeSpan.FromMilliseconds(-1)); + autoRenewLockCancellationTimer = new Timer(CancelAutoRenewLock, renewLockCancellationTokenSource, registerHandlerOptions.MaxAutoRenewDuration, TimeSpan.FromMilliseconds(-1)); } try { - MessagingEventSource.Log.MessageReceiverPumpUserCallbackStart(this.messageReceiver.ClientId, message); - await this.onMessageCallback(message, this.pumpCancellationToken).ConfigureAwait(false); + MessagingEventSource.Log.MessageReceiverPumpUserCallbackStart(messageReceiver.ClientId, message); + await onMessageCallback(message, pumpCancellationToken).ConfigureAwait(false); - MessagingEventSource.Log.MessageReceiverPumpUserCallbackStop(this.messageReceiver.ClientId, message); + MessagingEventSource.Log.MessageReceiverPumpUserCallbackStop(messageReceiver.ClientId, message); } catch (Exception exception) { - MessagingEventSource.Log.MessageReceiverPumpUserCallbackException(this.messageReceiver.ClientId, message, exception); - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.UserCallback).ConfigureAwait(false); + MessagingEventSource.Log.MessageReceiverPumpUserCallbackException(messageReceiver.ClientId, message, exception); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.UserCallback).ConfigureAwait(false); // Nothing much to do if UserCallback throws, Abandon message and Release semaphore. if (!(exception is MessageLockLostException)) { - await this.AbandonMessageIfNeededAsync(message).ConfigureAwait(false); + await AbandonMessageIfNeededAsync(message).ConfigureAwait(false); } if (ServiceBusDiagnosticSource.IsEnabled()) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } // AbandonMessageIfNeededAsync should take care of not throwing exception - this.maxConcurrentCallsSemaphoreSlim.Release(); + maxConcurrentCallsSemaphoreSlim.Release(); return; } @@ -195,10 +195,10 @@ async Task MessageDispatchTask(Message message) } // If we've made it this far, user callback completed fine. Complete message and Release semaphore. - await this.CompleteMessageIfNeededAsync(message).ConfigureAwait(false); - this.maxConcurrentCallsSemaphoreSlim.Release(); + await CompleteMessageIfNeededAsync(message).ConfigureAwait(false); + maxConcurrentCallsSemaphoreSlim.Release(); - MessagingEventSource.Log.MessageReceiverPumpDispatchTaskStop(this.messageReceiver.ClientId, message, this.maxConcurrentCallsSemaphoreSlim.CurrentCount); + MessagingEventSource.Log.MessageReceiverPumpDispatchTaskStop(messageReceiver.ClientId, message, maxConcurrentCallsSemaphoreSlim.CurrentCount); } void CancelAutoRenewLock(object state) @@ -218,14 +218,14 @@ async Task AbandonMessageIfNeededAsync(Message message) { try { - if (this.messageReceiver.ReceiveMode == ReceiveMode.PeekLock) + if (messageReceiver.ReceiveMode == ReceiveMode.PeekLock) { - await this.messageReceiver.AbandonAsync(message.SystemProperties.LockToken).ConfigureAwait(false); + await messageReceiver.AbandonAsync(message.SystemProperties.LockToken).ConfigureAwait(false); } } catch (Exception exception) { - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Abandon).ConfigureAwait(false); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Abandon).ConfigureAwait(false); } } @@ -233,27 +233,27 @@ async Task CompleteMessageIfNeededAsync(Message message) { try { - if (this.messageReceiver.ReceiveMode == ReceiveMode.PeekLock && - this.registerHandlerOptions.AutoComplete) + if (messageReceiver.ReceiveMode == ReceiveMode.PeekLock && + registerHandlerOptions.AutoComplete) { - await this.messageReceiver.CompleteAsync(new[] { message.SystemProperties.LockToken }).ConfigureAwait(false); + await messageReceiver.CompleteAsync(new[] { message.SystemProperties.LockToken }).ConfigureAwait(false); } } catch (Exception exception) { - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Complete).ConfigureAwait(false); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Complete).ConfigureAwait(false); } } async Task RenewMessageLockTask(Message message, CancellationToken renewLockCancellationToken) { - while (!this.pumpCancellationToken.IsCancellationRequested && + while (!pumpCancellationToken.IsCancellationRequested && !renewLockCancellationToken.IsCancellationRequested) { try { var amount = MessagingUtilities.CalculateRenewAfterDuration(message.SystemProperties.LockedUntilUtc); - MessagingEventSource.Log.MessageReceiverPumpRenewMessageStart(this.messageReceiver.ClientId, message, amount); + MessagingEventSource.Log.MessageReceiverPumpRenewMessageStart(messageReceiver.ClientId, message, amount); // We're awaiting the task created by 'ContinueWith' to avoid awaiting the Delay task which may be canceled // by the renewLockCancellationToken. This way we prevent a TaskCanceledException. @@ -265,11 +265,11 @@ async Task RenewMessageLockTask(Message message, CancellationToken renewLockCanc break; } - if (!this.pumpCancellationToken.IsCancellationRequested && + if (!pumpCancellationToken.IsCancellationRequested && !renewLockCancellationToken.IsCancellationRequested) { - await this.messageReceiver.RenewLockAsync(message).ConfigureAwait(false); - MessagingEventSource.Log.MessageReceiverPumpRenewMessageStop(this.messageReceiver.ClientId, message); + await messageReceiver.RenewLockAsync(message).ConfigureAwait(false); + MessagingEventSource.Log.MessageReceiverPumpRenewMessageStop(messageReceiver.ClientId, message); } else { @@ -278,13 +278,13 @@ async Task RenewMessageLockTask(Message message, CancellationToken renewLockCanc } catch (Exception exception) { - MessagingEventSource.Log.MessageReceiverPumpRenewMessageException(this.messageReceiver.ClientId, message, exception); + MessagingEventSource.Log.MessageReceiverPumpRenewMessageException(messageReceiver.ClientId, message, exception); // ObjectDisposedException should only happen here because the CancellationToken was disposed at which point // this renew exception is not relevant anymore. Lets not bother user with this exception. if (!(exception is ObjectDisposedException)) { - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.RenewLock).ConfigureAwait(false); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.RenewLock).ConfigureAwait(false); } if (!MessagingUtilities.ShouldRetry(exception)) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs index 249fa2c3e3e6..5d628a03bd83 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs @@ -28,7 +28,7 @@ public MessageSession( bool isSessionReceiver = false) : base(entityPath, entityType, receiveMode, serviceBusConnection, cbsTokenProvider, retryPolicy, prefetchCount, sessionId, isSessionReceiver) { - this.diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); + diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); } /// @@ -36,31 +36,31 @@ public MessageSession( /// public DateTime LockedUntilUtc { - get => this.LockedUntilUtcInternal; - internal set => this.LockedUntilUtcInternal = value; + get => LockedUntilUtcInternal; + internal set => LockedUntilUtcInternal = value; } /// /// Gets the SessionId. /// - public string SessionId => this.SessionIdInternal; + public string SessionId => SessionIdInternal; public Task GetStateAsync() { - this.ThrowIfClosed(); - return ServiceBusDiagnosticSource.IsEnabled() ? this.OnGetStateInstrumentedAsync() : this.OnGetStateAsync(); + ThrowIfClosed(); + return ServiceBusDiagnosticSource.IsEnabled() ? OnGetStateInstrumentedAsync() : OnGetStateAsync(); } public Task SetStateAsync(byte[] sessionState) { - this.ThrowIfClosed(); - return ServiceBusDiagnosticSource.IsEnabled() ? this.OnSetStateInstrumentedAsync(sessionState) : this.OnSetStateAsync(sessionState); + ThrowIfClosed(); + return ServiceBusDiagnosticSource.IsEnabled() ? OnSetStateInstrumentedAsync(sessionState) : OnSetStateAsync(sessionState); } public Task RenewSessionLockAsync() { - this.ThrowIfClosed(); - return ServiceBusDiagnosticSource.IsEnabled() ? this.OnRenewSessionLockInstrumentedAsync() : this.OnRenewSessionLockAsync(); + ThrowIfClosed(); + return ServiceBusDiagnosticSource.IsEnabled() ? OnRenewSessionLockInstrumentedAsync() : OnRenewSessionLockAsync(); } protected override void OnMessageHandler(MessageHandlerOptions registerHandlerOptions, Func callback) @@ -77,16 +77,16 @@ protected async Task OnGetStateAsync() { try { - var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.GetSessionStateOperation, this.OperationTimeout, null); + var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.GetSessionStateOperation, OperationTimeout, null); - if (this.ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) + if (ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) { amqpRequestMessage.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = receiveLink.Name; } - amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = this.SessionIdInternal; + amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = SessionIdInternal; - var amqpResponseMessage = await this.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); + var amqpResponseMessage = await ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); byte[] sessionState = null; if (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.OK) @@ -113,14 +113,14 @@ protected async Task OnSetStateAsync(byte[] sessionState) { try { - var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.SetSessionStateOperation, this.OperationTimeout, null); + var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.SetSessionStateOperation, OperationTimeout, null); - if (this.ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) + if (ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) { amqpRequestMessage.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = receiveLink.Name; } - amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = this.SessionIdInternal; + amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = SessionIdInternal; if (sessionState != null) { @@ -132,7 +132,7 @@ protected async Task OnSetStateAsync(byte[] sessionState) amqpRequestMessage.Map[ManagementConstants.Properties.SessionState] = null; } - var amqpResponseMessage = await this.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); + var amqpResponseMessage = await ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); if (amqpResponseMessage.StatusCode != AmqpResponseStatusCode.OK) { throw amqpResponseMessage.ToMessagingContractException(); @@ -148,20 +148,20 @@ protected async Task OnRenewSessionLockAsync() { try { - var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.RenewSessionLockOperation, this.OperationTimeout, null); + var amqpRequestMessage = AmqpRequestMessage.CreateRequest(ManagementConstants.Operations.RenewSessionLockOperation, OperationTimeout, null); - if (this.ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) + if (ReceiveLinkManager.TryGetOpenedObject(out var receiveLink)) { amqpRequestMessage.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = receiveLink.Name; } - amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = this.SessionIdInternal; + amqpRequestMessage.Map[ManagementConstants.Properties.SessionId] = SessionIdInternal; - var amqpResponseMessage = await this.ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); + var amqpResponseMessage = await ExecuteRequestResponseAsync(amqpRequestMessage).ConfigureAwait(false); if (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.OK) { - this.LockedUntilUtcInternal = amqpResponseMessage.GetValue(ManagementConstants.Properties.Expiration); + LockedUntilUtcInternal = amqpResponseMessage.GetValue(ManagementConstants.Properties.Expiration); } else { @@ -179,74 +179,74 @@ protected async Task OnRenewSessionLockAsync() /// protected override void ThrowIfClosed() { - if (this.IsClosedOrClosing) + if (IsClosedOrClosing) { - throw new ObjectDisposedException($"MessageSession with Id '{this.ClientId}' has already been closed. Please accept a new MessageSession."); + throw new ObjectDisposedException($"MessageSession with Id '{ClientId}' has already been closed. Please accept a new MessageSession."); } } private async Task OnGetStateInstrumentedAsync() { - Activity activity = this.diagnosticSource.GetSessionStateStart(this.SessionId); + Activity activity = diagnosticSource.GetSessionStateStart(SessionId); Task getStateTask = null; byte[] state = null; try { - getStateTask = this.OnGetStateAsync(); + getStateTask = OnGetStateAsync(); state = await getStateTask.ConfigureAwait(false); return state; } catch (Exception ex) { - this.diagnosticSource.ReportException(ex); + diagnosticSource.ReportException(ex); throw; } finally { - this.diagnosticSource.GetSessionStateStop(activity, this.SessionId, state, getStateTask?.Status); + diagnosticSource.GetSessionStateStop(activity, SessionId, state, getStateTask?.Status); } } private async Task OnSetStateInstrumentedAsync(byte[] sessionState) { - Activity activity = this.diagnosticSource.SetSessionStateStart(this.SessionId, sessionState); + Activity activity = diagnosticSource.SetSessionStateStart(SessionId, sessionState); Task setStateTask = null; try { - setStateTask = this.OnSetStateAsync(sessionState); + setStateTask = OnSetStateAsync(sessionState); await setStateTask.ConfigureAwait(false); } catch (Exception ex) { - this.diagnosticSource.ReportException(ex); + diagnosticSource.ReportException(ex); throw; } finally { - this.diagnosticSource.SetSessionStateStop(activity, sessionState, this.SessionId, setStateTask?.Status); + diagnosticSource.SetSessionStateStop(activity, sessionState, SessionId, setStateTask?.Status); } } private async Task OnRenewSessionLockInstrumentedAsync() { - Activity activity = this.diagnosticSource.RenewSessionLockStart(this.SessionId); + Activity activity = diagnosticSource.RenewSessionLockStart(SessionId); Task renewTask = null; try { - renewTask = this.OnRenewSessionLockAsync(); + renewTask = OnRenewSessionLockAsync(); await renewTask.ConfigureAwait(false); } catch (Exception ex) { - this.diagnosticSource.ReportException(ex); + diagnosticSource.ReportException(ex); throw; } finally { - this.diagnosticSource.RenewSessionLockStop(activity, this.SessionId, renewTask?.Status); + diagnosticSource.RenewSessionLockStop(activity, SessionId, renewTask?.Status); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingEventSource.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingEventSource.cs index b647b1b8b04e..05139bd93b87 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingEventSource.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingEventSource.cs @@ -10,8 +10,8 @@ namespace Microsoft.Azure.ServiceBus using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Amqp; - using Microsoft.Azure.ServiceBus.Amqp; - using Microsoft.Azure.ServiceBus.Primitives; + using Amqp; + using Primitives; [EventSource(Name = "Microsoft-Azure-ServiceBus")] internal sealed class MessagingEventSource : EventSource @@ -21,333 +21,333 @@ internal sealed class MessagingEventSource : EventSource [Event(1, Level = EventLevel.Informational, Message = "Creating QueueClient (Namespace '{0}'; Queue '{1}'; ReceiveMode '{2}').")] public void QueueClientCreateStart(string namespaceName, string queueName, string receiveMode) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(1, namespaceName ?? string.Empty, queueName, receiveMode); + WriteEvent(1, namespaceName ?? string.Empty, queueName, receiveMode); } } [Event(2, Level = EventLevel.Informational, Message = "QueueClient (Namespace '{0}'; Queue '{1}'; ClientId: '{2}' created).")] public void QueueClientCreateStop(string namespaceName, string queueName, string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(2, namespaceName, queueName, clientId); + WriteEvent(2, namespaceName, queueName, clientId); } } [Event(3, Level = EventLevel.Informational, Message = "Creating TopicClient (Namespace '{0}'; Topic '{1}').")] public void TopicClientCreateStart(string namespaceName, string topicName) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(3, namespaceName ?? string.Empty, topicName); + WriteEvent(3, namespaceName ?? string.Empty, topicName); } } [Event(4, Level = EventLevel.Informational, Message = "TopicClient (Namespace '{0}'; Topic '{1}'; ClientId: '{2}' created).")] public void TopicClientCreateStop(string namespaceName, string topicName, string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(4, namespaceName, topicName, clientId); + WriteEvent(4, namespaceName, topicName, clientId); } } [Event(5, Level = EventLevel.Informational, Message = "Creating SubscriptionClient (Namespace '{0}'; Topic '{1}'; Subscription '{2}'; ReceiveMode '{3}').")] public void SubscriptionClientCreateStart(string namespaceName, string topicName, string subscriptionName, string receiveMode) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(5, namespaceName, topicName ?? string.Empty, subscriptionName, receiveMode); + WriteEvent(5, namespaceName, topicName ?? string.Empty, subscriptionName, receiveMode); } } [Event(6, Level = EventLevel.Informational, Message = "SubscriptionClient (Namespace '{0}'; Topic '{1}'; Subscription '{2}'; ClientId: '{3}' created).")] public void SubscriptionClientCreateStop(string namespaceName, string topicName, string subscriptionName, string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(6, namespaceName, topicName, subscriptionName, clientId); + WriteEvent(6, namespaceName, topicName, subscriptionName, clientId); } } [Event(7, Level = EventLevel.Informational, Message = "{0}: SendAsync start. MessageCount = {1}")] public void MessageSendStart(string clientId, int messageCount) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(7, clientId, messageCount); + WriteEvent(7, clientId, messageCount); } } [Event(8, Level = EventLevel.Informational, Message = "{0}: SendAsync done.")] public void MessageSendStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(8, clientId); + WriteEvent(8, clientId); } } [NonEvent] public void MessageSendException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageSendException(clientId, exception.ToString()); + MessageSendException(clientId, exception.ToString()); } } [Event(9, Level = EventLevel.Error, Message = "{0}: SendAsync Exception: {1}.")] void MessageSendException(string clientId, string exception) { - this.WriteEvent(9, clientId, exception); + WriteEvent(9, clientId, exception); } [Event(10, Level = EventLevel.Informational, Message = "{0}: ReceiveAsync start. MessageCount = {1}")] public void MessageReceiveStart(string clientId, int messageCount) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(10, clientId, messageCount); + WriteEvent(10, clientId, messageCount); } } [Event(11, Level = EventLevel.Informational, Message = "{0}: ReceiveAsync done. Received '{1}' messages")] public void MessageReceiveStop(string clientId, int messageCount) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(11, clientId, messageCount); + WriteEvent(11, clientId, messageCount); } } [NonEvent] public void MessageReceiveException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiveException(clientId, exception.ToString()); + MessageReceiveException(clientId, exception.ToString()); } } [Event(12, Level = EventLevel.Error, Message = "{0}: ReceiveAsync Exception: {1}.")] void MessageReceiveException(string clientId, string exception) { - this.WriteEvent(12, clientId, exception); + WriteEvent(12, clientId, exception); } [NonEvent] public void MessageCompleteStart(string clientId, int messageCount, IEnumerable lockTokens) { - if (this.IsEnabled()) + if (IsEnabled()) { var formattedLockTokens = StringUtility.GetFormattedLockTokens(lockTokens); - this.MessageCompleteStart(clientId, messageCount, formattedLockTokens); + MessageCompleteStart(clientId, messageCount, formattedLockTokens); } } [Event(13, Level = EventLevel.Informational, Message = "{0}: CompleteAsync start. MessageCount = {1}, LockTokens = {2}")] void MessageCompleteStart(string clientId, int messageCount, string lockTokens) { - this.WriteEvent(13, clientId, messageCount, lockTokens); + WriteEvent(13, clientId, messageCount, lockTokens); } [Event(14, Level = EventLevel.Informational, Message = "{0}: CompleteAsync done.")] public void MessageCompleteStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(14, clientId); + WriteEvent(14, clientId); } } [NonEvent] public void MessageCompleteException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageCompleteException(clientId, exception.ToString()); + MessageCompleteException(clientId, exception.ToString()); } } [Event(15, Level = EventLevel.Error, Message = "{0}: CompleteAsync Exception: {1}.")] void MessageCompleteException(string clientId, string exception) { - this.WriteEvent(15, clientId, exception); + WriteEvent(15, clientId, exception); } [Event(16, Level = EventLevel.Informational, Message = "{0}: AbandonAsync start. MessageCount = {1}, LockToken = {2}")] public void MessageAbandonStart(string clientId, int messageCount, string lockToken) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(16, clientId, messageCount, lockToken); + WriteEvent(16, clientId, messageCount, lockToken); } } [Event(17, Level = EventLevel.Informational, Message = "{0}: AbandonAsync done.")] public void MessageAbandonStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(17, clientId); + WriteEvent(17, clientId); } } [NonEvent] public void MessageAbandonException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageAbandonException(clientId, exception.ToString()); + MessageAbandonException(clientId, exception.ToString()); } } [Event(18, Level = EventLevel.Error, Message = "{0}: AbandonAsync Exception: {1}.")] void MessageAbandonException(string clientId, string exception) { - this.WriteEvent(18, clientId, exception); + WriteEvent(18, clientId, exception); } [Event(19, Level = EventLevel.Informational, Message = "{0}: DeferAsync start. MessageCount = {1}, LockToken = {2}")] public void MessageDeferStart(string clientId, int messageCount, string lockToken) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(19, clientId, messageCount, lockToken); + WriteEvent(19, clientId, messageCount, lockToken); } } [Event(20, Level = EventLevel.Informational, Message = "{0}: DeferAsync done.")] public void MessageDeferStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(20, clientId); + WriteEvent(20, clientId); } } [NonEvent] public void MessageDeferException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageDeferException(clientId, exception.ToString()); + MessageDeferException(clientId, exception.ToString()); } } [Event(21, Level = EventLevel.Error, Message = "{0}: DeferAsync Exception: {1}.")] void MessageDeferException(string clientId, string exception) { - this.WriteEvent(21, clientId, exception); + WriteEvent(21, clientId, exception); } [Event(22, Level = EventLevel.Informational, Message = "{0}: DeadLetterAsync start. MessageCount = {1}, LockToken = {2}")] public void MessageDeadLetterStart(string clientId, int messageCount, string lockToken) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(22, clientId, messageCount, lockToken); + WriteEvent(22, clientId, messageCount, lockToken); } } [Event(23, Level = EventLevel.Informational, Message = "{0}: DeadLetterAsync done.")] public void MessageDeadLetterStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(23, clientId); + WriteEvent(23, clientId); } } [NonEvent] public void MessageDeadLetterException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageDeadLetterException(clientId, exception.ToString()); + MessageDeadLetterException(clientId, exception.ToString()); } } [Event(24, Level = EventLevel.Error, Message = "{0}: DeadLetterAsync Exception: {1}.")] void MessageDeadLetterException(string clientId, string exception) { - this.WriteEvent(24, clientId, exception); + WriteEvent(24, clientId, exception); } [Event(25, Level = EventLevel.Informational, Message = "{0}: RenewLockAsync start. MessageCount = {1}, LockToken = {2}")] public void MessageRenewLockStart(string clientId, int messageCount, string lockToken) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(25, clientId, messageCount, lockToken); + WriteEvent(25, clientId, messageCount, lockToken); } } [Event(26, Level = EventLevel.Informational, Message = "{0}: RenewLockAsync done.")] public void MessageRenewLockStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(26, clientId); + WriteEvent(26, clientId); } } [NonEvent] public void MessageRenewLockException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageRenewLockException(clientId, exception.ToString()); + MessageRenewLockException(clientId, exception.ToString()); } } [Event(27, Level = EventLevel.Error, Message = "{0}: RenewLockAsync Exception: {1}.")] void MessageRenewLockException(string clientId, string exception) { - this.WriteEvent(27, clientId, exception); + WriteEvent(27, clientId, exception); } [NonEvent] public void MessageReceiveDeferredMessageStart(string clientId, int messageCount, IEnumerable sequenceNumbers) { - if (this.IsEnabled()) + if (IsEnabled()) { var formattedSequenceNumbers = StringUtility.GetFormattedSequenceNumbers(sequenceNumbers); - this.MessageReceiveDeferredMessageStart(clientId, messageCount, formattedSequenceNumbers); + MessageReceiveDeferredMessageStart(clientId, messageCount, formattedSequenceNumbers); } } [Event(28, Level = EventLevel.Informational, Message = "{0}: ReceiveDeferredMessageAsync start. MessageCount = {1}, LockTokens = {2}")] void MessageReceiveDeferredMessageStart(string clientId, int messageCount, string sequenceNumbers) { - this.WriteEvent(28, clientId, messageCount, sequenceNumbers); + WriteEvent(28, clientId, messageCount, sequenceNumbers); } [Event(29, Level = EventLevel.Informational, Message = "{0}: ReceiveDeferredMessageAsync done. Received '{1}' messages")] public void MessageReceiveDeferredMessageStop(string clientId, int messageCount) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(29, clientId, messageCount); + WriteEvent(29, clientId, messageCount); } } [NonEvent] public void MessageReceiveDeferredMessageException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiveDeferredMessageException(clientId, exception.ToString()); + MessageReceiveDeferredMessageException(clientId, exception.ToString()); } } [Event(30, Level = EventLevel.Error, Message = "{0}: ReceiveDeferredMessageAsync Exception: {1}.")] void MessageReceiveDeferredMessageException(string clientId, string exception) { - this.WriteEvent(30, clientId, exception); + WriteEvent(30, clientId, exception); } // Unused - 31;32;33 @@ -355,780 +355,780 @@ void MessageReceiveDeferredMessageException(string clientId, string exception) [NonEvent] public void AmqpSendLinkCreateStart(string clientId, MessagingEntityType? entityType, string entityPath) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpSendLinkCreateStart(clientId, entityType?.ToString() ?? string.Empty, entityPath); + AmqpSendLinkCreateStart(clientId, entityType?.ToString() ?? string.Empty, entityPath); } } [Event(34, Level = EventLevel.Informational, Message = "{0}: AmqpSendLinkCreate started. EntityType: {1}, EntityPath: {2}")] void AmqpSendLinkCreateStart(string clientId, string entityType, string entityPath) { - this.WriteEvent(34, clientId, entityType, entityPath); + WriteEvent(34, clientId, entityType, entityPath); } [Event(35, Level = EventLevel.Informational, Message = "{0}: AmqpSendLinkCreate done.")] public void AmqpSendLinkCreateStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(35, clientId); + WriteEvent(35, clientId); } } [NonEvent] public void AmqpReceiveLinkCreateStart(string clientId, bool isRequestResponseLink, MessagingEntityType? entityType, string entityPath) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpReceiveLinkCreateStart(clientId, isRequestResponseLink.ToString(), entityType?.ToString() ?? string.Empty, entityPath); + AmqpReceiveLinkCreateStart(clientId, isRequestResponseLink.ToString(), entityType?.ToString() ?? string.Empty, entityPath); } } [Event(36, Level = EventLevel.Informational, Message = "{0}: AmqpReceiveLinkCreate started. IsRequestResponseLink: {1}, EntityType: {1}, EntityPath: {2}")] void AmqpReceiveLinkCreateStart(string clientId, string isRequestResponseLink, string entityType, string entityPath) { - this.WriteEvent(36, clientId, isRequestResponseLink, entityType, entityPath); + WriteEvent(36, clientId, isRequestResponseLink, entityType, entityPath); } [Event(37, Level = EventLevel.Informational, Message = "{0}: AmqpReceiveLinkCreate done.")] public void AmqpReceiveLinkCreateStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(37, clientId); + WriteEvent(37, clientId); } } [Event(38, Level = EventLevel.Verbose, Message = "AmqpGetOrCreateConnection started.")] public void AmqpGetOrCreateConnectionStart() { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(38); + WriteEvent(38); } } [Event(39, Level = EventLevel.Verbose, Message = "AmqpGetOrCreateConnection done. EntityPath: {0}, ConnectionInfo: {1}, ConnectionState: {2}")] public void AmqpGetOrCreateConnectionStop(string entityPath, string connectionInfo, string connectionState) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(39, entityPath, connectionInfo, connectionState); + WriteEvent(39, entityPath, connectionInfo, connectionState); } } [NonEvent] public void AmqpSendAuthenticationTokenStart(Uri address, string audience, string resource, string[] claims) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpSendAuthenticationTokenStart(address.ToString(), audience, resource, claims.ToString()); + AmqpSendAuthenticationTokenStart(address.ToString(), audience, resource, claims.ToString()); } } [Event(40, Level = EventLevel.Verbose, Message = "AmqpSendAuthenticanToken started. Address: {0}, Audience: {1}, Resource: {2}, Claims: {3}")] void AmqpSendAuthenticationTokenStart(string address, string audience, string resource, string claims) { - this.WriteEvent(40, address, audience, resource, claims); + WriteEvent(40, address, audience, resource, claims); } [Event(41, Level = EventLevel.Verbose, Message = "AmqpSendAuthenticanToken done.")] public void AmqpSendAuthenticationTokenStop() { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(41); + WriteEvent(41); } } [Event(42, Level = EventLevel.Informational, Message = "{0}: MessagePeekAsync start. SequenceNumber = {1}, MessageCount = {2}")] public void MessagePeekStart(string clientId, long sequenceNumber, int messageCount) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(42, clientId, sequenceNumber, messageCount); + WriteEvent(42, clientId, sequenceNumber, messageCount); } } [Event(43, Level = EventLevel.Informational, Message = "{0}: MessagePeekAsync done. Peeked '{1}' messages")] public void MessagePeekStop(string clientId, int messageCount) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(43, clientId, messageCount); + WriteEvent(43, clientId, messageCount); } } [NonEvent] public void MessagePeekException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessagePeekException(clientId, exception.ToString()); + MessagePeekException(clientId, exception.ToString()); } } [Event(44, Level = EventLevel.Error, Message = "{0}: MessagePeekAsync Exception: {1}.")] void MessagePeekException(string clientId, string exception) { - this.WriteEvent(44, clientId, exception); + WriteEvent(44, clientId, exception); } [Event(45, Level = EventLevel.Informational, Message = "Creating MessageSender (Namespace '{0}'; Entity '{1}').")] public void MessageSenderCreateStart(string namespaceName, string entityName) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(45, namespaceName, entityName); + WriteEvent(45, namespaceName, entityName); } } [Event(46, Level = EventLevel.Informational, Message = "MessageSender (Namespace '{0}'; Entity '{1}'; ClientId '{2}' created).")] public void MessageSenderCreateStop(string namespaceName, string entityName, string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(46, namespaceName, entityName, clientId); + WriteEvent(46, namespaceName, entityName, clientId); } } [Event(47, Level = EventLevel.Informational, Message = "Creating MessageReceiver (Namespace '{0}'; Entity '{1}'; ReceiveMode '{2}').")] public void MessageReceiverCreateStart(string namespaceName, string entityName, string receiveMode) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(47, namespaceName, entityName, receiveMode); + WriteEvent(47, namespaceName, entityName, receiveMode); } } [Event(48, Level = EventLevel.Informational, Message = "MessageReceiver (Namespace '{0}'; Entity '{1}'; ClientId '{2}' created).")] public void MessageReceiverCreateStop(string namespaceName, string entityName, string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(48, namespaceName, entityName, clientId); + WriteEvent(48, namespaceName, entityName, clientId); } } [NonEvent] public void ScheduleMessageStart(string clientId, DateTimeOffset scheduleEnqueueTimeUtc) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.ScheduleMessageStart(clientId, scheduleEnqueueTimeUtc.ToString()); + ScheduleMessageStart(clientId, scheduleEnqueueTimeUtc.ToString()); } } [Event(49, Level = EventLevel.Informational, Message = "{0}: ScheduleMessageAsync start. ScheduleTimeUtc = {1}")] void ScheduleMessageStart(string clientId, string scheduleEnqueueTimeUtc) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(49, clientId, scheduleEnqueueTimeUtc); + WriteEvent(49, clientId, scheduleEnqueueTimeUtc); } } [Event(50, Level = EventLevel.Informational, Message = "{0}: ScheduleMessageAsync done.")] public void ScheduleMessageStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(50, clientId); + WriteEvent(50, clientId); } } [NonEvent] public void ScheduleMessageException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.ScheduleMessageException(clientId, exception.ToString()); + ScheduleMessageException(clientId, exception.ToString()); } } [Event(51, Level = EventLevel.Error, Message = "{0}: ScheduleMessageAsync Exception: {1}.")] void ScheduleMessageException(string clientId, string exception) { - this.WriteEvent(51, clientId, exception); + WriteEvent(51, clientId, exception); } [Event(52, Level = EventLevel.Informational, Message = "{0}: CancelScheduledMessageAsync start. SequenceNumber = {1}")] public void CancelScheduledMessageStart(string clientId, long sequenceNumber) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(52, clientId, sequenceNumber); + WriteEvent(52, clientId, sequenceNumber); } } [Event(53, Level = EventLevel.Informational, Message = "{0}: CancelScheduledMessageAsync done.")] public void CancelScheduledMessageStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(53, clientId); + WriteEvent(53, clientId); } } [NonEvent] public void CancelScheduledMessageException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.CancelScheduledMessageException(clientId, exception.ToString()); + CancelScheduledMessageException(clientId, exception.ToString()); } } [Event(54, Level = EventLevel.Error, Message = "{0}: CancelScheduledMessageAsync Exception: {1}.")] void CancelScheduledMessageException(string clientId, string exception) { - this.WriteEvent(54, clientId, exception); + WriteEvent(54, clientId, exception); } [Event(55, Level = EventLevel.Informational, Message = "{0}: AddRuleAsync start. RuleName = {1}")] public void AddRuleStart(string clientId, string ruleName) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(55, clientId, ruleName); + WriteEvent(55, clientId, ruleName); } } [Event(56, Level = EventLevel.Informational, Message = "{0}: AddRuleAsync done.")] public void AddRuleStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(56, clientId); + WriteEvent(56, clientId); } } [NonEvent] public void AddRuleException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AddRuleException(clientId, exception.ToString()); + AddRuleException(clientId, exception.ToString()); } } [Event(57, Level = EventLevel.Error, Message = "{0}: AddRuleAsync Exception: {1}.")] void AddRuleException(string clientId, string exception) { - this.WriteEvent(57, clientId, exception); + WriteEvent(57, clientId, exception); } [Event(58, Level = EventLevel.Informational, Message = "{0}: RemoveRuleAsync start. RuleName = {1}")] public void RemoveRuleStart(string clientId, string ruleName) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(58, clientId, ruleName); + WriteEvent(58, clientId, ruleName); } } [Event(59, Level = EventLevel.Informational, Message = "{0}: RemoveRuleAsync done.")] public void RemoveRuleStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(59, clientId); + WriteEvent(59, clientId); } } [NonEvent] public void RemoveRuleException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.RemoveRuleException(clientId, exception.ToString()); + RemoveRuleException(clientId, exception.ToString()); } } [Event(60, Level = EventLevel.Error, Message = "{0}: RemoveRuleAsync Exception: {1}.")] void RemoveRuleException(string clientId, string exception) { - this.WriteEvent(60, clientId, exception); + WriteEvent(60, clientId, exception); } [NonEvent] public void RegisterOnMessageHandlerStart(string clientId, MessageHandlerOptions registerHandlerOptions) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.RegisterOnMessageHandlerStart(clientId, registerHandlerOptions.AutoComplete, registerHandlerOptions.AutoRenewLock, registerHandlerOptions.MaxConcurrentCalls, (long)registerHandlerOptions.MaxAutoRenewDuration.TotalSeconds); + RegisterOnMessageHandlerStart(clientId, registerHandlerOptions.AutoComplete, registerHandlerOptions.AutoRenewLock, registerHandlerOptions.MaxConcurrentCalls, (long)registerHandlerOptions.MaxAutoRenewDuration.TotalSeconds); } } [Event(61, Level = EventLevel.Informational, Message = "{0}: Register OnMessageHandler start: OnMessage Options: AutoComplete: {1}, AutoRenewLock: {2}, MaxConcurrentCalls: {3}, AutoRenewTimeout: {4}")] void RegisterOnMessageHandlerStart(string clientId, bool autoComplete, bool autorenewLock, int maxConcurrentCalls, long autorenewTimeoutInSeconds) { - this.WriteEvent(61, clientId, autoComplete, autorenewLock, maxConcurrentCalls, autorenewTimeoutInSeconds); + WriteEvent(61, clientId, autoComplete, autorenewLock, maxConcurrentCalls, autorenewTimeoutInSeconds); } [Event(62, Level = EventLevel.Informational, Message = "{0}: Register OnMessageHandler done.")] public void RegisterOnMessageHandlerStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(62, clientId); + WriteEvent(62, clientId); } } [NonEvent] public void RegisterOnMessageHandlerException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.RegisterOnMessageHandlerException(clientId, exception.ToString()); + RegisterOnMessageHandlerException(clientId, exception.ToString()); } } [Event(63, Level = EventLevel.Error, Message = "{0}: Register OnMessageHandler Exception: {1}")] void RegisterOnMessageHandlerException(string clientId, string exception) { - this.WriteEvent(63, clientId, exception); + WriteEvent(63, clientId, exception); } [NonEvent] public void MessageReceiverPumpTaskStart(string clientId, Message message, int currentSemaphoreCount) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiverPumpTaskStart(clientId, message?.SystemProperties.SequenceNumber ?? -1, currentSemaphoreCount); + MessageReceiverPumpTaskStart(clientId, message?.SystemProperties.SequenceNumber ?? -1, currentSemaphoreCount); } } [Event(66, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump PumpTask Started: Message: SequenceNumber: {1}, Available Semaphore Count: {2}")] void MessageReceiverPumpTaskStart(string clientId, long sequenceNumber, int currentSemaphoreCount) { - this.WriteEvent(66, clientId, sequenceNumber, currentSemaphoreCount); + WriteEvent(66, clientId, sequenceNumber, currentSemaphoreCount); } [Event(67, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump PumpTask done: Available Semaphore Count: {1}")] public void MessageReceiverPumpTaskStop(string clientId, int currentSemaphoreCount) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(67, clientId, currentSemaphoreCount); + WriteEvent(67, clientId, currentSemaphoreCount); } } [NonEvent] public void MessageReceivePumpTaskException(string clientId, string sessionId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceivePumpTaskException(clientId, sessionId, exception.ToString()); + MessageReceivePumpTaskException(clientId, sessionId, exception.ToString()); } } [Event(68, Level = EventLevel.Error, Message = "{0}: MessageReceiverPump PumpTask Exception: SessionId: {1}, Exception: {2}")] void MessageReceivePumpTaskException(string clientId, string sessionId, string exception) { - this.WriteEvent(68, clientId, sessionId, exception); + WriteEvent(68, clientId, sessionId, exception); } [NonEvent] public void MessageReceiverPumpDispatchTaskStart(string clientId, Message message) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiverPumpDispatchTaskStart(clientId, message?.SystemProperties.SequenceNumber ?? -1); + MessageReceiverPumpDispatchTaskStart(clientId, message?.SystemProperties.SequenceNumber ?? -1); } } [Event(69, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump DispatchTask start: Message: SequenceNumber: {1}")] void MessageReceiverPumpDispatchTaskStart(string clientId, long sequenceNumber) { - this.WriteEvent(69, clientId, sequenceNumber); + WriteEvent(69, clientId, sequenceNumber); } [NonEvent] public void MessageReceiverPumpDispatchTaskStop(string clientId, Message message, int currentSemaphoreCount) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiverPumpDispatchTaskStop(clientId, message?.SystemProperties.SequenceNumber ?? -1, currentSemaphoreCount); + MessageReceiverPumpDispatchTaskStop(clientId, message?.SystemProperties.SequenceNumber ?? -1, currentSemaphoreCount); } } [Event(70, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump DispatchTask done: Message: SequenceNumber: {1}, Current Semaphore Count: {2}")] void MessageReceiverPumpDispatchTaskStop(string clientId, long sequenceNumber, int currentSemaphoreCount) { - this.WriteEvent(70, clientId, sequenceNumber, currentSemaphoreCount); + WriteEvent(70, clientId, sequenceNumber, currentSemaphoreCount); } [NonEvent] public void MessageReceiverPumpUserCallbackStart(string clientId, Message message) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiverPumpUserCallbackStart(clientId, message?.SystemProperties.SequenceNumber ?? -1); + MessageReceiverPumpUserCallbackStart(clientId, message?.SystemProperties.SequenceNumber ?? -1); } } [Event(71, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump UserCallback start: Message: SequenceNumber: {1}")] void MessageReceiverPumpUserCallbackStart(string clientId, long sequenceNumber) { - this.WriteEvent(71, clientId, sequenceNumber); + WriteEvent(71, clientId, sequenceNumber); } [NonEvent] public void MessageReceiverPumpUserCallbackStop(string clientId, Message message) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiverPumpUserCallbackStop(clientId, message?.SystemProperties.SequenceNumber ?? -1); + MessageReceiverPumpUserCallbackStop(clientId, message?.SystemProperties.SequenceNumber ?? -1); } } [Event(72, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump UserCallback done: Message: SequenceNumber: {1}")] void MessageReceiverPumpUserCallbackStop(string clientId, long sequenceNumber) { - this.WriteEvent(72, clientId, sequenceNumber); + WriteEvent(72, clientId, sequenceNumber); } [NonEvent] public void MessageReceiverPumpUserCallbackException(string clientId, Message message, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiverPumpUserCallbackException(clientId, message?.SystemProperties.SequenceNumber ?? -1, exception.ToString()); + MessageReceiverPumpUserCallbackException(clientId, message?.SystemProperties.SequenceNumber ?? -1, exception.ToString()); } } [Event(73, Level = EventLevel.Error, Message = "{0}: MessageReceiverPump UserCallback Exception: Message: SequenceNumber: {1}, Exception: {2}")] void MessageReceiverPumpUserCallbackException(string clientId, long sequenceNumber, string exception) { - this.WriteEvent(73, clientId, sequenceNumber, exception); + WriteEvent(73, clientId, sequenceNumber, exception); } [NonEvent] public void MessageReceiverPumpRenewMessageStart(string clientId, Message message, TimeSpan renewAfterTimeSpan) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiverPumpRenewMessageStart(clientId, message?.SystemProperties.SequenceNumber ?? -1, (long)renewAfterTimeSpan.TotalSeconds); + MessageReceiverPumpRenewMessageStart(clientId, message?.SystemProperties.SequenceNumber ?? -1, (long)renewAfterTimeSpan.TotalSeconds); } } [Event(74, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump RenewMessage start: Message: SequenceNumber: {1}, RenewAfterTimeInSeconds: {2}")] void MessageReceiverPumpRenewMessageStart(string clientId, long sequenceNumber, long renewAfterTimeSpanInSeconds) { - this.WriteEvent(74, clientId, sequenceNumber, renewAfterTimeSpanInSeconds); + WriteEvent(74, clientId, sequenceNumber, renewAfterTimeSpanInSeconds); } [NonEvent] public void MessageReceiverPumpRenewMessageStop(string clientId, Message message) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiverPumpRenewMessageStop(clientId, message?.SystemProperties.SequenceNumber ?? -1); + MessageReceiverPumpRenewMessageStop(clientId, message?.SystemProperties.SequenceNumber ?? -1); } } [Event(75, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump RenewMessage done: Message: SequenceNumber: {1}")] void MessageReceiverPumpRenewMessageStop(string clientId, long sequenceNumber) { - this.WriteEvent(75, clientId, sequenceNumber); + WriteEvent(75, clientId, sequenceNumber); } [NonEvent] public void MessageReceiverPumpRenewMessageException(string clientId, Message message, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.MessageReceiverPumpRenewMessageException(clientId, message?.SystemProperties.SequenceNumber ?? -1, exception.ToString()); + MessageReceiverPumpRenewMessageException(clientId, message?.SystemProperties.SequenceNumber ?? -1, exception.ToString()); } } [Event(76, Level = EventLevel.Error, Message = "{0}: MessageReceiverPump RenewMessage Exception: Message: SequenceNumber: {1}, Exception: {2}")] void MessageReceiverPumpRenewMessageException(string clientId, long sequenceNumber, string exception) { - this.WriteEvent(76, clientId, sequenceNumber, exception); + WriteEvent(76, clientId, sequenceNumber, exception); } [NonEvent] public void RunOperationExceptionEncountered(Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.RunOperationExceptionEncountered(exception.ToString()); + RunOperationExceptionEncountered(exception.ToString()); } } [Event(77, Level = EventLevel.Warning, Message = "RunOperation encountered an exception and will retry. Exception: {0}")] void RunOperationExceptionEncountered(string exception) { - this.WriteEvent(77, exception); + WriteEvent(77, exception); } [NonEvent] public void RegisterOnSessionHandlerStart(string clientId, SessionHandlerOptions sessionHandlerOptions) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.RegisterOnSessionHandlerStart(clientId, sessionHandlerOptions.AutoComplete, sessionHandlerOptions.MaxConcurrentSessions, (long)sessionHandlerOptions.MessageWaitTimeout.TotalSeconds, (long)sessionHandlerOptions.MaxAutoRenewDuration.TotalSeconds); + RegisterOnSessionHandlerStart(clientId, sessionHandlerOptions.AutoComplete, sessionHandlerOptions.MaxConcurrentSessions, (long)sessionHandlerOptions.MessageWaitTimeout.TotalSeconds, (long)sessionHandlerOptions.MaxAutoRenewDuration.TotalSeconds); } } [Event(78, Level = EventLevel.Informational, Message = "{0}: Register OnSessionHandler start: RegisterSessionHandler Options: AutoComplete: {1}, MaxConcurrentSessions: {2}, MessageWaitTimeout: {3}, AutoRenewTimeout: {4}")] void RegisterOnSessionHandlerStart(string clientId, bool autoComplete, int maxConcurrentSessions, long messageWaitTimeoutInSeconds, long autorenewTimeoutInSeconds) { - this.WriteEvent(78, clientId, autoComplete, maxConcurrentSessions, messageWaitTimeoutInSeconds, autorenewTimeoutInSeconds); + WriteEvent(78, clientId, autoComplete, maxConcurrentSessions, messageWaitTimeoutInSeconds, autorenewTimeoutInSeconds); } [Event(79, Level = EventLevel.Informational, Message = "{0}: Register OnSessionHandler done.")] public void RegisterOnSessionHandlerStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(79, clientId); + WriteEvent(79, clientId); } } [NonEvent] public void RegisterOnSessionHandlerException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.RegisterOnSessionHandlerException(clientId, exception.ToString()); + RegisterOnSessionHandlerException(clientId, exception.ToString()); } } [Event(80, Level = EventLevel.Error, Message = "{0}: Register OnSessionHandler Exception: {1}")] void RegisterOnSessionHandlerException(string clientId, string exception) { - this.WriteEvent(80, clientId, exception); + WriteEvent(80, clientId, exception); } [NonEvent] public void SessionReceivePumpSessionReceiveException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.SessionReceivePumpSessionReceiveException(clientId, exception.ToString()); + SessionReceivePumpSessionReceiveException(clientId, exception.ToString()); } } [Event(81, Level = EventLevel.Error, Message = "{0}: Exception while Receving a session: SessionId: {1}")] void SessionReceivePumpSessionReceiveException(string clientId, string exception) { - this.WriteEvent(81, clientId, exception); + WriteEvent(81, clientId, exception); } [Event(82, Level = EventLevel.Informational, Message = "{0}: Session has no more messages: SessionId: {1}")] public void SessionReceivePumpSessionEmpty(string clientId, string sessionId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(82, clientId, sessionId); + WriteEvent(82, clientId, sessionId); } } [Event(83, Level = EventLevel.Informational, Message = "{0}: Session closed: SessionId: {1}")] public void SessionReceivePumpSessionClosed(string clientId, string sessionId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(83, clientId, sessionId); + WriteEvent(83, clientId, sessionId); } } [NonEvent] public void SessionReceivePumpSessionCloseException(string clientId, string sessionId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.SessionReceivePumpSessionCloseException(clientId, sessionId, exception.ToString()); + SessionReceivePumpSessionCloseException(clientId, sessionId, exception.ToString()); } } [Event(84, Level = EventLevel.Error, Message = "{0}: Exception while closing session: SessionId: {1}, Exception: {2}")] void SessionReceivePumpSessionCloseException(string clientId, string sessionId, string exception) { - this.WriteEvent(84, clientId, sessionId, exception); + WriteEvent(84, clientId, sessionId, exception); } [NonEvent] public void SessionReceivePumpSessionRenewLockStart(string clientId, string sessionId, TimeSpan renewAfterTimeSpan) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.SessionReceivePumpSessionRenewLockStart(clientId, sessionId, (long)renewAfterTimeSpan.TotalSeconds); + SessionReceivePumpSessionRenewLockStart(clientId, sessionId, (long)renewAfterTimeSpan.TotalSeconds); } } [Event(85, Level = EventLevel.Informational, Message = "{0}: SessionRenewLock start. SessionId: {1}, RenewAfterTimeInSeconds: {2}")] void SessionReceivePumpSessionRenewLockStart(string clientId, string sessionId, long totalSeconds) { - this.WriteEvent(85, clientId, sessionId, totalSeconds); + WriteEvent(85, clientId, sessionId, totalSeconds); } [Event(86, Level = EventLevel.Informational, Message = "{0}: RenewSession done: SessionId: {1}")] public void SessionReceivePumpSessionRenewLockStop(string clientId, string sessionId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(86, clientId, sessionId); + WriteEvent(86, clientId, sessionId); } } [NonEvent] public void SessionReceivePumpSessionRenewLockException(string clientId, string sessionId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.SessionReceivePumpSessionRenewLockException(clientId, sessionId, exception.ToString()); + SessionReceivePumpSessionRenewLockException(clientId, sessionId, exception.ToString()); } } [Event(87, Level = EventLevel.Error, Message = "{0}: Exception while renewing session lock: SessionId: {1}, Exception: {2}")] void SessionReceivePumpSessionRenewLockException(string clientId, string sessionId, string exception) { - this.WriteEvent(87, clientId, sessionId, exception); + WriteEvent(87, clientId, sessionId, exception); } [NonEvent] public void AmqpSessionClientAcceptMessageSessionStart(string clientId, string entityPath, ReceiveMode receiveMode, int prefetchCount, string sessionId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpSessionClientAcceptMessageSessionStart(clientId, entityPath, receiveMode.ToString(), prefetchCount, sessionId ?? string.Empty); + AmqpSessionClientAcceptMessageSessionStart(clientId, entityPath, receiveMode.ToString(), prefetchCount, sessionId ?? string.Empty); } } [Event(88, Level = EventLevel.Informational, Message = "{0}: AcceptMessageSession start: EntityPath: {1}, ReceiveMode: {2}, PrefetchCount: {3}, SessionId: {4}")] void AmqpSessionClientAcceptMessageSessionStart(string clientId, string entityPath, string receiveMode, int prefetchCount, string sessionId) { - this.WriteEvent(88, clientId, entityPath, receiveMode, prefetchCount, sessionId); + WriteEvent(88, clientId, entityPath, receiveMode, prefetchCount, sessionId); } [Event(89, Level = EventLevel.Informational, Message = "{0}: AcceptMessageSession done: EntityPath: {1}, SessionId: {2}")] public void AmqpSessionClientAcceptMessageSessionStop(string clientId, string entityPath, string sessionId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(89, clientId, entityPath, sessionId); + WriteEvent(89, clientId, entityPath, sessionId); } } [NonEvent] public void AmqpSessionClientAcceptMessageSessionException(string clientId, string entityPath, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpSessionClientAcceptMessageSessionException(clientId, entityPath, exception.ToString()); + AmqpSessionClientAcceptMessageSessionException(clientId, entityPath, exception.ToString()); } } [Event(90, Level = EventLevel.Error, Message = "{0}: AcceptMessageSession Exception: EntityPath: {1}, Exception: {2}")] void AmqpSessionClientAcceptMessageSessionException(string clientId, string entityPath, string exception) { - this.WriteEvent(90, clientId, entityPath, exception); + WriteEvent(90, clientId, entityPath, exception); } [NonEvent] public void AmqpLinkCreationException(string entityPath, AmqpSession session, AmqpConnection connection, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpLinkCreationException(entityPath, session.ToString(), session.State.ToString(), session.GetInnerException()?.ToString() ?? string.Empty, connection.ToString(), connection.State.ToString(), exception.ToString()); + AmqpLinkCreationException(entityPath, session.ToString(), session.State.ToString(), session.GetInnerException()?.ToString() ?? string.Empty, connection.ToString(), connection.State.ToString(), exception.ToString()); } } [Event(91, Level = EventLevel.Error, Message = "AmqpLinkCreatorException Exception: EntityPath: {0}, SessionString: {1}, SessionState: {2}, TerminalException: {3}, ConnectionInfo: {4}, ConnectionState: {5}, Exception: {6}")] void AmqpLinkCreationException(string entityPath, string session, string sessionState, string terminalException, string connectionInfo, string connectionState, string exception) { - this.WriteEvent(91, entityPath, session, sessionState, terminalException, connectionInfo, connectionState, exception); + WriteEvent(91, entityPath, session, sessionState, terminalException, connectionInfo, connectionState, exception); } [NonEvent] public void AmqpConnectionCreated(string hostName, AmqpConnection connection) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpConnectionCreated(hostName, connection.ToString(), connection.State.ToString()); + AmqpConnectionCreated(hostName, connection.ToString(), connection.State.ToString()); } } [Event(92, Level = EventLevel.Verbose, Message = "AmqpConnectionCreated: HostName: {0}, ConnectionInfo: {1}, ConnectionState: {2}")] void AmqpConnectionCreated(string hostName, string connectionInfo, string connectionState) { - this.WriteEvent(92, hostName, connectionInfo, connectionState); + WriteEvent(92, hostName, connectionInfo, connectionState); } [NonEvent] public void AmqpConnectionClosed(AmqpConnection connection) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpConnectionClosed(connection.RemoteEndpoint, connection.ToString(), connection.State.ToString()); + AmqpConnectionClosed(connection.RemoteEndpoint, connection.ToString(), connection.State.ToString()); } } [Event(93, Level = EventLevel.Verbose, Message = "AmqpConnectionClosed: HostName: {0}, ConnectionInfo: {1}, ConnectionState: {2}")] public void AmqpConnectionClosed(string hostName, string connectionInfo, string connectionState) { - this.WriteEvent(93, hostName, connectionInfo, connectionState); + WriteEvent(93, hostName, connectionInfo, connectionState); } [NonEvent] public void AmqpSessionCreationException(string entityPath, AmqpConnection connection, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpSessionCreationException(entityPath, connection.ToString(), connection.State.ToString(), exception.ToString()); + AmqpSessionCreationException(entityPath, connection.ToString(), connection.State.ToString(), exception.ToString()); } } [Event(94, Level = EventLevel.Error, Message = "AmqpSessionCreationException Exception: EntityPath: {0}, ConnectionInfo: {1}, ConnectionState: {2}, Exception: {3}")] void AmqpSessionCreationException(string entityPath, string connectionInfo, string connectionState, string exception) { - this.WriteEvent(94, entityPath, connectionInfo, connectionState, exception); + WriteEvent(94, entityPath, connectionInfo, connectionState, exception); } [Event(95, Level = EventLevel.Verbose, Message = "User plugin {0} called on message {1}")] public void PluginCallStarted(string pluginName, string messageId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(95, pluginName, messageId); + WriteEvent(95, pluginName, messageId); } } [Event(96, Level = EventLevel.Verbose, Message = "User plugin {0} completed on message {1}")] public void PluginCallCompleted(string pluginName, string messageId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(96, pluginName, messageId); + WriteEvent(96, pluginName, messageId); } } [NonEvent] public void PluginCallFailed(string pluginName, string messageId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.PluginCallFailed(pluginName, messageId, exception.ToString()); + PluginCallFailed(pluginName, messageId, exception.ToString()); } } [Event(97, Level = EventLevel.Error, Message = "Exception during {0} plugin execution. MessageId: {1}, Exception {2}")] void PluginCallFailed(string pluginName, string messageId, string exception) { - this.WriteEvent(97, pluginName, messageId, exception); + WriteEvent(97, pluginName, messageId, exception); } [NonEvent] public void ScheduleTaskFailed(Func task, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.ScheduleTaskFailed(task.Target.GetType().FullName, task.GetMethodInfo().Name, exception.ToString()); + ScheduleTaskFailed(task.Target.GetType().FullName, task.GetMethodInfo().Name, exception.ToString()); } } @@ -1141,9 +1141,9 @@ void ScheduleTaskFailed(string funcTargetName, string methodInfoName, string exc [NonEvent] public void ExceptionReceivedHandlerThrewException(Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.ExceptionReceivedHandlerThrewException(exception.ToString()); + ExceptionReceivedHandlerThrewException(exception.ToString()); } } @@ -1156,9 +1156,9 @@ void ExceptionReceivedHandlerThrewException(string exception) [NonEvent] public void LinkStateLost(string clientId, string receiveLinkName, AmqpObjectState receiveLinkState, bool isSessionReceiver, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.LinkStateLost(clientId, receiveLinkName, receiveLinkState.ToString(), isSessionReceiver, exception.ToString()); + LinkStateLost(clientId, receiveLinkName, receiveLinkState.ToString(), isSessionReceiver, exception.ToString()); } } @@ -1171,7 +1171,7 @@ void LinkStateLost(string clientId, string receiveLinkName, string receiveLinkSt [Event(101, Level = EventLevel.Informational, Message = "Updating client id. OldClientId: {0}, NewClientId: {1}")] public void UpdateClientId(string oldClientId, string newClientId) { - if (this.IsEnabled()) + if (IsEnabled()) { WriteEvent(101, oldClientId, newClientId); } @@ -1180,42 +1180,42 @@ public void UpdateClientId(string oldClientId, string newClientId) [Event(102, Level = EventLevel.Informational, Message = "{0}: GetRulesException start.")] public void GetRulesStart(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(102, clientId); + WriteEvent(102, clientId); } } [Event(103, Level = EventLevel.Informational, Message = "{0}: GetRulesException done.")] public void GetRulesStop(string clientId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(103, clientId); + WriteEvent(103, clientId); } } [NonEvent] public void GetRulesException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.GetRulesException(clientId, exception.ToString()); + GetRulesException(clientId, exception.ToString()); } } [Event(104, Level = EventLevel.Error, Message = "{0}: GetRulesException Exception: {1}.")] void GetRulesException(string clientId, string exception) { - this.WriteEvent(104, clientId, exception); + WriteEvent(104, clientId, exception); } [NonEvent] public void CreatingNewLink(string clientId, bool isSessionReceiver, string sessionId, bool isRequestResponseLink, Exception linkException) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.CreatingNewLink(clientId, isSessionReceiver, sessionId ?? string.Empty, isRequestResponseLink, linkException?.ToString() ?? string.Empty); + CreatingNewLink(clientId, isSessionReceiver, sessionId ?? string.Empty, isRequestResponseLink, linkException?.ToString() ?? string.Empty); } } @@ -1228,9 +1228,9 @@ void CreatingNewLink(string clientId, bool isSessionReceiver, string sessionId, [NonEvent] public void SessionReceiverLinkClosed(string clientId, string sessionId, Exception linkException) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.SessionReceiverLinkClosed(clientId, sessionId ?? string.Empty, linkException?.ToString() ?? string.Empty); + SessionReceiverLinkClosed(clientId, sessionId ?? string.Empty, linkException?.ToString() ?? string.Empty); } } @@ -1243,141 +1243,141 @@ void SessionReceiverLinkClosed(string clientId, string sessionId, string linkExc [NonEvent] public void AmqpSendAuthenticationTokenException(string clientId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpSendAuthenticationTokenException(clientId, exception.ToString()); + AmqpSendAuthenticationTokenException(clientId, exception.ToString()); } } [Event(107, Level = EventLevel.Error, Message = "{0}: AmqpSendAuthenticationTokenException Exception: {1}.")] void AmqpSendAuthenticationTokenException(string clientId, string exception) { - this.WriteEvent(107, clientId, exception); + WriteEvent(107, clientId, exception); } [NonEvent] public void AmqpTransactionInitializeException(string transactionId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpTransactionInitializeException(transactionId, exception.ToString()); + AmqpTransactionInitializeException(transactionId, exception.ToString()); } } [Event(108, Level = EventLevel.Error, Message = "AmqpTransactionInitializeException for TransactionId: {0} Exception: {1}.")] void AmqpTransactionInitializeException(string transactionId, string exception) { - this.WriteEvent(108, transactionId, exception); + WriteEvent(108, transactionId, exception); } [NonEvent] public void AmqpTransactionDeclared(string localTransactionId, ArraySegment amqpTransactionId) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpTransactionDeclared(localTransactionId, amqpTransactionId.GetAsciiString()); + AmqpTransactionDeclared(localTransactionId, amqpTransactionId.GetAsciiString()); } } [Event(109, Level = EventLevel.Informational, Message = "AmqpTransactionDeclared for LocalTransactionId: {0} AmqpTransactionId: {1}.")] void AmqpTransactionDeclared(string transactionId, string amqpTransactionId) { - this.WriteEvent(109, transactionId, amqpTransactionId); + WriteEvent(109, transactionId, amqpTransactionId); } [NonEvent] public void AmqpTransactionDischarged(string localTransactionId, ArraySegment amqpTransactionId, bool rollback) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpTransactionDischarged(localTransactionId, amqpTransactionId.GetAsciiString(), rollback); + AmqpTransactionDischarged(localTransactionId, amqpTransactionId.GetAsciiString(), rollback); } } [Event(110, Level = EventLevel.Informational, Message = "AmqpTransactionDischarged for LocalTransactionId: {0} AmqpTransactionId: {1} Rollback: {2}.")] void AmqpTransactionDischarged(string transactionId, string amqpTransactionId, bool rollback) { - this.WriteEvent(110, transactionId, amqpTransactionId, rollback); + WriteEvent(110, transactionId, amqpTransactionId, rollback); } [NonEvent] public void AmqpTransactionDischargeException(string transactionId, ArraySegment amqpTransactionId, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpTransactionDischargeException(transactionId, amqpTransactionId.GetAsciiString(), exception.ToString()); + AmqpTransactionDischargeException(transactionId, amqpTransactionId.GetAsciiString(), exception.ToString()); } } [Event(111, Level = EventLevel.Error, Message = "AmqpTransactionDischargeException for TransactionId: {0} AmqpTransactionId: {1} Exception: {2}.")] void AmqpTransactionDischargeException(string transactionId, string amqpTransactionId, string exception) { - this.WriteEvent(111, transactionId, amqpTransactionId, exception); + WriteEvent(111, transactionId, amqpTransactionId, exception); } [NonEvent] public void AmqpCreateControllerException(string connectionManager, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.AmqpCreateControllerException(connectionManager, exception.ToString()); + AmqpCreateControllerException(connectionManager, exception.ToString()); } } [Event(112, Level = EventLevel.Error, Message = "AmqpCreateControllerException for ConnectionManager: {0} Exception: {1}.")] void AmqpCreateControllerException(string connectionManager, string exception) { - this.WriteEvent(112, connectionManager, exception); + WriteEvent(112, connectionManager, exception); } [Event(113, Level = EventLevel.Informational, Message = "{0}: Management operation '{1}' for '{2}' started.")] public void ManagementOperationStart(string clientId, string operationName, string details = "") { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(113, clientId, operationName, details); + WriteEvent(113, clientId, operationName, details); } } [Event(114, Level = EventLevel.Informational, Message = "{0}: Management operation '{1}' for '{2}' finished.")] public void ManagementOperationEnd(string clientId, string operationName, string details = "") { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(114, clientId, operationName, details); + WriteEvent(114, clientId, operationName, details); } } [NonEvent] public void ManagementOperationException(string clientId, string operationName, Exception exception) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.ManagementOperationException(clientId, operationName, exception.ToString()); + ManagementOperationException(clientId, operationName, exception.ToString()); } } [Event(115, Level = EventLevel.Error, Message = "{0}: Management operation '{1}' encountered exception: '{2}'.")] void ManagementOperationException(string clientId, string operationName, string exception) { - this.WriteEvent(115, clientId, operationName, exception); + WriteEvent(115, clientId, operationName, exception); } [Event(116, Level = EventLevel.Informational, Message = "{0}: Management client created with operationTimeout:{1}, tokenProvider:{2}.")] public void ManagementClientCreated(string clientId, double operationTimeout, string tokenProvider) { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(116, clientId, operationTimeout, tokenProvider); + WriteEvent(116, clientId, operationTimeout, tokenProvider); } } [Event(117, Level = EventLevel.Warning, Message = "[De]Serialization failed for object:{0}; Details:{1}")] public void ManagementSerializationException(string objectName, string details = "") { - if (this.IsEnabled()) + if (IsEnabled()) { - this.WriteEvent(117, objectName, details); + WriteEvent(117, objectName, details); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs index b94a7c746eb0..56c950dd9bd0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs @@ -19,9 +19,9 @@ public class AzureActiveDirectoryTokenProvider : TokenProvider public AzureActiveDirectoryTokenProvider(AuthenticationCallback authenticationCallback, string authority, object state) { - this.AuthCallback = authenticationCallback ?? throw Fx.Exception.ArgumentNull(nameof(authenticationCallback)); + AuthCallback = authenticationCallback ?? throw Fx.Exception.ArgumentNull(nameof(authenticationCallback)); this.authority = authority ?? throw Fx.Exception.ArgumentNull(nameof(authority)); - this.authCallbackState = state; + authCallbackState = state; } /// @@ -32,7 +32,7 @@ public AzureActiveDirectoryTokenProvider(AuthenticationCallback authenticationCa /// public override async Task GetTokenAsync(string appliesTo, TimeSpan timeout) { - var tokenString = await this.AuthCallback(Constants.AadServiceBusAudience, this.authority, this.authCallbackState).ConfigureAwait(false); + var tokenString = await AuthCallback(Constants.AadServiceBusAudience, authority, authCallbackState).ConfigureAwait(false); return new JsonSecurityToken(tokenString, appliesTo); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs index 16da8f9c4607..732af30e8d47 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs @@ -21,39 +21,39 @@ sealed class ConcurrentExpiringSet public ConcurrentExpiringSet() { - this.dictionary = new ConcurrentDictionary(); - this.dictionaryAsCollection = dictionary; + dictionary = new ConcurrentDictionary(); + dictionaryAsCollection = dictionary; _ = CollectExpiredEntriesAsync(tokenSource.Token); } public void AddOrUpdate(TKey key, DateTime expiration) { - this.ThrowIfClosed(); + ThrowIfClosed(); - this.dictionary[key] = expiration; - this.cleanupTaskCompletionSource.TrySetResult(true); + dictionary[key] = expiration; + cleanupTaskCompletionSource.TrySetResult(true); } public bool Contains(TKey key) { - this.ThrowIfClosed(); + ThrowIfClosed(); - return this.dictionary.TryGetValue(key, out var expiration) && expiration > DateTime.UtcNow; + return dictionary.TryGetValue(key, out var expiration) && expiration > DateTime.UtcNow; } public void Close() { - if (Interlocked.Exchange(ref this.closeSignaled, 1) != 0) + if (Interlocked.Exchange(ref closeSignaled, 1) != 0) { return; } - this.closed = true; + closed = true; - this.tokenSource.Cancel(); - this.cleanupTaskCompletionSource.TrySetCanceled(); - this.dictionary.Clear(); - this.tokenSource.Dispose(); + tokenSource.Cancel(); + cleanupTaskCompletionSource.TrySetCanceled(); + dictionary.Clear(); + tokenSource.Dispose(); } async Task CollectExpiredEntriesAsync(CancellationToken token) @@ -62,7 +62,7 @@ async Task CollectExpiredEntriesAsync(CancellationToken token) { try { - await this.cleanupTaskCompletionSource.Task.ConfigureAwait(false); + await cleanupTaskCompletionSource.Task.ConfigureAwait(false); await Task.Delay(delayBetweenCleanups, token).ConfigureAwait(false); } catch (OperationCanceledException) @@ -72,19 +72,19 @@ async Task CollectExpiredEntriesAsync(CancellationToken token) var isEmpty = true; var utcNow = DateTime.UtcNow; - foreach (var kvp in this.dictionary) + foreach (var kvp in dictionary) { isEmpty = false; var expiration = kvp.Value; if (utcNow > expiration) { - this.dictionaryAsCollection.Remove(kvp); + dictionaryAsCollection.Remove(kvp); } } if (isEmpty) { - this.cleanupTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + cleanupTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ExceptionUtility.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ExceptionUtility.cs index 515f090432d9..8a84ce07f6f9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ExceptionUtility.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ExceptionUtility.cs @@ -19,7 +19,7 @@ public Exception ArgumentNull(string paramName) public ArgumentException ArgumentNullOrWhiteSpace(string paramName) { - return this.Argument(paramName, Resources.ArgumentNullOrWhiteSpace.FormatForUser(paramName)); + return Argument(paramName, Resources.ArgumentNullOrWhiteSpace.FormatForUser(paramName)); } public ArgumentOutOfRangeException ArgumentOutOfRange(string paramName, object actualValue, string message) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs index 69a54c2b5156..f3b359168889 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs @@ -112,9 +112,9 @@ public ExternalResourceAttribute(Location location, string description) this.description = description; } - public Location Location => this.location; + public Location Location => location; - public string Description => this.description; + public string Description => description; } [AttributeUsage(AttributeTargets.Field)] @@ -126,22 +126,22 @@ public sealed class CacheAttribute : Attribute public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) { - this.Scope = Strings.DeclaringInstance; - this.SizeLimit = Strings.Unbounded; - this.Timeout = Strings.Infinite; + Scope = Strings.DeclaringInstance; + SizeLimit = Strings.Unbounded; + Timeout = Strings.Infinite; if (elementType == null) { - throw Fx.Exception.ArgumentNull(nameof(elementType)); + throw Exception.ArgumentNull(nameof(elementType)); } this.elementType = elementType; this.cacheAttrition = cacheAttrition; } - public Type ElementType => this.elementType; + public Type ElementType => elementType; - public CacheAttrition CacheAttrition => this.cacheAttrition; + public CacheAttrition CacheAttrition => cacheAttrition; public string Scope { get; set; } @@ -158,18 +158,18 @@ public sealed class QueueAttribute : Attribute public QueueAttribute(Type elementType) { - this.Scope = Strings.DeclaringInstance; - this.SizeLimit = Strings.Unbounded; + Scope = Strings.DeclaringInstance; + SizeLimit = Strings.Unbounded; if (elementType == null) { - throw Fx.Exception.ArgumentNull(nameof(elementType)); + throw Exception.ArgumentNull(nameof(elementType)); } this.elementType = elementType; } - public Type ElementType => this.elementType; + public Type ElementType => elementType; public string Scope { get; set; } @@ -188,9 +188,9 @@ public sealed class SynchronizationObjectAttribute : Attribute { public SynchronizationObjectAttribute() { - this.Blocking = true; - this.Scope = Strings.DeclaringInstance; - this.Kind = SynchronizationKind.FromFieldType; + Blocking = true; + Scope = Strings.DeclaringInstance; + Kind = SynchronizationKind.FromFieldType; } public bool Blocking { get; set; } @@ -211,7 +211,7 @@ public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing) this.blocksUsing = blocksUsing; } - public BlocksUsing BlocksUsing => this.blocksUsing; + public BlocksUsing BlocksUsing => blocksUsing; public bool SupportsAsync { get; set; } @@ -259,7 +259,7 @@ public ThrowsAttribute(Type exceptionType, string diagnosis) { if (exceptionType == null) { - throw Fx.Exception.ArgumentNull(nameof(exceptionType)); + throw Exception.ArgumentNull(nameof(exceptionType)); } if (string.IsNullOrEmpty(diagnosis)) { @@ -271,9 +271,9 @@ public ThrowsAttribute(Type exceptionType, string diagnosis) this.diagnosis = diagnosis; } - public Type ExceptionType => this.exceptionType; + public Type ExceptionType => exceptionType; - public string Diagnosis => this.diagnosis; + public string Diagnosis => diagnosis; } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs index e6aecfbb0d28..8dc906c747d2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Primitives { using System; using System.Threading.Tasks; - using Azure.Services.AppAuthentication; + using Services.AppAuthentication; /// /// Represents the Azure Active Directory token provider for Azure Managed Identity integration. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs index f2371c41f766..696991cf3e28 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs @@ -6,7 +6,7 @@ namespace Microsoft.Azure.ServiceBus.Primitives using System; using System.Collections; using System.Collections.Generic; - using Microsoft.Azure.ServiceBus.Amqp; + using Amqp; sealed class PropertyDictionary : IDictionary { @@ -14,91 +14,91 @@ sealed class PropertyDictionary : IDictionary public PropertyDictionary() { - this.inner = new Dictionary(StringComparer.OrdinalIgnoreCase); + inner = new Dictionary(StringComparer.OrdinalIgnoreCase); } public PropertyDictionary(IDictionary container) { - this.inner = container; + inner = container; } - public ICollection Keys => this.inner.Keys; + public ICollection Keys => inner.Keys; - public ICollection Values => this.inner.Values; + public ICollection Values => inner.Values; - public int Count => this.inner.Count; + public int Count => inner.Count; - public bool IsReadOnly => this.inner.IsReadOnly; + public bool IsReadOnly => inner.IsReadOnly; public object this[string key] { - get => this.inner[key]; + get => inner[key]; set { - if (this.IsSupportedObject(value)) + if (IsSupportedObject(value)) { - this.inner[key] = value; + inner[key] = value; } } } public void Add(string key, object value) { - if (this.IsSupportedObject(value)) + if (IsSupportedObject(value)) { - this.inner.Add(key, value); + inner.Add(key, value); } } public bool ContainsKey(string key) { - return this.inner.ContainsKey(key); + return inner.ContainsKey(key); } public bool Remove(string key) { - return this.inner.Remove(key); + return inner.Remove(key); } public bool TryGetValue(string key, out object value) { - return this.inner.TryGetValue(key, out value); + return inner.TryGetValue(key, out value); } public void Add(KeyValuePair item) { - this.inner.Add(item); + inner.Add(item); } public void Clear() { - this.inner.Clear(); + inner.Clear(); } public bool Contains(KeyValuePair item) { - return this.inner.Contains(item); + return inner.Contains(item); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { - this.inner.CopyTo(array, arrayIndex); + inner.CopyTo(array, arrayIndex); } public bool Remove(KeyValuePair item) { - return this.inner.Remove(item); + return inner.Remove(item); } public IEnumerator> GetEnumerator() { - return this.inner.GetEnumerator(); + return inner.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return this.inner.GetEnumerator(); + return inner.GetEnumerator(); } bool IsSupportedObject(object value) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs index ade1c588341c..6cc177317178 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs @@ -49,7 +49,7 @@ public SecurityToken(string tokenString, DateTime expiresAtUtc, string audience, throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(audience)); } - this.token = tokenString; + token = tokenString; this.expiresAtUtc = expiresAtUtc; this.audience = audience; this.tokenType = tokenType; @@ -58,21 +58,21 @@ public SecurityToken(string tokenString, DateTime expiresAtUtc, string audience, /// /// Gets the audience of this token. /// - public string Audience => this.audience; + public string Audience => audience; /// /// Gets the expiration time of this token. /// - public DateTime ExpiresAtUtc => this.expiresAtUtc; + public DateTime ExpiresAtUtc => expiresAtUtc; /// /// Gets the actual token. /// - public virtual string TokenValue => this.token; + public virtual string TokenValue => token; /// /// Gets the token type. /// - public virtual string TokenType => this.tokenType; + public virtual string TokenType => tokenType; } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs index 7a4af3b5ccec..888478119068 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs @@ -78,7 +78,7 @@ protected SharedAccessSignatureTokenProvider(string keyName, string sharedAccess this.keyName = keyName; this.tokenTimeToLive = tokenTimeToLive; - this.encodedSharedAccessKey = customKeyEncoder != null ? + encodedSharedAccessKey = customKeyEncoder != null ? customKeyEncoder(sharedAccessKey) : MessagingTokenProviderKeyEncoder(sharedAccessKey); this.tokenScope = tokenScope; @@ -98,7 +98,7 @@ public override Task GetTokenAsync(string appliesTo, TimeSpan tim { TimeoutHelper.ThrowIfNegativeArgument(timeout); appliesTo = NormalizeAppliesTo(appliesTo); - string tokenString = this.BuildSignature(appliesTo); + string tokenString = BuildSignature(appliesTo); var securityToken = new SharedAccessSignatureToken(tokenString); return Task.FromResult(securityToken); } @@ -108,18 +108,18 @@ public override Task GetTokenAsync(string appliesTo, TimeSpan tim /// protected virtual string BuildSignature(string targetUri) { - return string.IsNullOrWhiteSpace(this.sharedAccessSignature) + return string.IsNullOrWhiteSpace(sharedAccessSignature) ? SharedAccessSignatureBuilder.BuildSignature( - this.keyName, - this.encodedSharedAccessKey, + keyName, + encodedSharedAccessKey, targetUri, - this.tokenTimeToLive) - : this.sharedAccessSignature; + tokenTimeToLive) + : sharedAccessSignature; } string NormalizeAppliesTo(string appliesTo) { - return ServiceBusUriHelper.NormalizeUri(appliesTo, "https", true, stripPath: this.tokenScope == TokenScope.Namespace, ensureTrailingSlash: true); + return ServiceBusUriHelper.NormalizeUri(appliesTo, "https", true, stripPath: tokenScope == TokenScope.Namespace, ensureTrailingSlash: true); } static class SharedAccessSignatureBuilder diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs index 367641a8d583..7e9e78bea61f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs @@ -17,13 +17,13 @@ public TimeoutHelper(TimeSpan timeout, bool startTimeout) { Debug.Assert(timeout >= TimeSpan.Zero, "timeout must be non-negative"); - this.originalTimeout = timeout; - this.deadline = DateTime.MaxValue; - this.deadlineSet = (timeout == TimeSpan.MaxValue); + originalTimeout = timeout; + deadline = DateTime.MaxValue; + deadlineSet = (timeout == TimeSpan.MaxValue); - if (startTimeout && !this.deadlineSet) + if (startTimeout && !deadlineSet) { - this.SetDeadline(); + SetDeadline(); } } @@ -103,18 +103,18 @@ public static void ThrowIfNonPositiveArgument(TimeSpan timeout, string argumentN public TimeSpan RemainingTime() { - if (!this.deadlineSet) + if (!deadlineSet) { - this.SetDeadline(); - return this.originalTimeout; + SetDeadline(); + return originalTimeout; } - if (this.deadline == DateTime.MaxValue) + if (deadline == DateTime.MaxValue) { return TimeSpan.MaxValue; } - var remaining = this.deadline - DateTime.UtcNow; + var remaining = deadline - DateTime.UtcNow; if (remaining <= TimeSpan.Zero) { return TimeSpan.Zero; @@ -125,14 +125,14 @@ public TimeSpan RemainingTime() public TimeSpan ElapsedTime() { - return this.originalTimeout - this.RemainingTime(); + return originalTimeout - RemainingTime(); } void SetDeadline() { - Debug.Assert(!this.deadlineSet, "TimeoutHelper deadline set twice."); - this.deadline = DateTime.UtcNow + this.originalTimeout; - this.deadlineSet = true; + Debug.Assert(!deadlineSet, "TimeoutHelper deadline set twice."); + deadline = DateTime.UtcNow + originalTimeout; + deadlineSet = true; } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs index ed35e15d9310..6d3b7401911d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs @@ -27,7 +27,7 @@ public TokenProviderAdapter(ITokenProvider tokenProvider, TimeSpan operationTime public async Task GetTokenAsync(Uri namespaceAddress, string appliesTo, string[] requiredClaims) { var claim = requiredClaims?.FirstOrDefault(); - var securityToken = await this.tokenProvider.GetTokenAsync(appliesTo, this.operationTimeout).ConfigureAwait(false); + var securityToken = await tokenProvider.GetTokenAsync(appliesTo, operationTimeout).ConfigureAwait(false); return new CbsToken(securityToken.TokenValue, CbsConstants.ServiceBusSasTokenType, securityToken.ExpiresAtUtc); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs index 554ac1c9544d..509cd2e15e52 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs @@ -8,8 +8,8 @@ namespace Microsoft.Azure.ServiceBus using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Amqp; - using Microsoft.Azure.ServiceBus.Core; - using Microsoft.Azure.ServiceBus.Primitives; + using Core; + using Primitives; /// /// QueueClient can be used for all basic interactions with a Service Bus Queue. @@ -90,7 +90,7 @@ public QueueClient(string connectionString, string entityPath, ReceiveMode recei throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(connectionString)); } - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -112,7 +112,7 @@ public QueueClient( RetryPolicy retryPolicy = null) : this(new ServiceBusConnection(endpoint, transportType, retryPolicy) {TokenProvider = tokenProvider}, entityPath, receiveMode, retryPolicy) { - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -132,23 +132,23 @@ public QueueClient(ServiceBusConnection serviceBusConnection, string entityPath, throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(entityPath)); } - this.ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); - this.syncLock = new object(); - this.QueueName = entityPath; - this.ReceiveMode = receiveMode; - this.OwnsConnection = false; - this.ServiceBusConnection.ThrowIfClosed(); + ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); + syncLock = new object(); + QueueName = entityPath; + ReceiveMode = receiveMode; + OwnsConnection = false; + ServiceBusConnection.ThrowIfClosed(); - if (this.ServiceBusConnection.TokenProvider != null) + if (ServiceBusConnection.TokenProvider != null) { - this.CbsTokenProvider = new TokenProviderAdapter(this.ServiceBusConnection.TokenProvider, this.ServiceBusConnection.OperationTimeout); + CbsTokenProvider = new TokenProviderAdapter(ServiceBusConnection.TokenProvider, ServiceBusConnection.OperationTimeout); } else { throw new ArgumentNullException($"{nameof(ServiceBusConnection)} doesn't have a valid token provider"); } - MessagingEventSource.Log.QueueClientCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, this.ClientId); + MessagingEventSource.Log.QueueClientCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, ClientId); } /// @@ -166,14 +166,14 @@ public QueueClient(ServiceBusConnection serviceBusConnection, string entityPath, /// public override TimeSpan OperationTimeout { - get => this.ServiceBusConnection.OperationTimeout; - set => this.ServiceBusConnection.OperationTimeout = value; + get => ServiceBusConnection.OperationTimeout; + set => ServiceBusConnection.OperationTimeout = value; } /// /// Gets the name of the queue. /// - public override string Path => this.QueueName; + public override string Path => QueueName; /// /// Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when and before the application asks for one using Receive. @@ -196,21 +196,21 @@ public override TimeSpan OperationTimeout /// public int PrefetchCount { - get => this.prefetchCount; + get => prefetchCount; set { if (value < 0) { - throw Fx.Exception.ArgumentOutOfRange(nameof(this.PrefetchCount), value, "Value cannot be less than 0."); + throw Fx.Exception.ArgumentOutOfRange(nameof(PrefetchCount), value, "Value cannot be less than 0."); } - this.prefetchCount = value; - if (this.innerReceiver != null) + prefetchCount = value; + if (innerReceiver != null) { - this.innerReceiver.PrefetchCount = value; + innerReceiver.PrefetchCount = value; } - if (this.sessionClient != null) + if (sessionClient != null) { - this.sessionClient.PrefetchCount = value; + sessionClient.PrefetchCount = value; } } } @@ -218,7 +218,7 @@ public int PrefetchCount /// /// Gets a list of currently registered plugins for this QueueClient. /// - public override IList RegisteredPlugins => this.InnerSender.RegisteredPlugins; + public override IList RegisteredPlugins => InnerSender.RegisteredPlugins; /// /// Connection object to the service bus namespace. @@ -229,24 +229,24 @@ internal MessageSender InnerSender { get { - if (this.innerSender == null) + if (innerSender == null) { - lock (this.syncLock) + lock (syncLock) { - if (this.innerSender == null) + if (innerSender == null) { - this.innerSender = new MessageSender( - this.QueueName, + innerSender = new MessageSender( + QueueName, null, MessagingEntityType.Queue, - this.ServiceBusConnection, - this.CbsTokenProvider, - this.RetryPolicy); + ServiceBusConnection, + CbsTokenProvider, + RetryPolicy); } } } - return this.innerSender; + return innerSender; } } @@ -254,25 +254,25 @@ internal MessageReceiver InnerReceiver { get { - if (this.innerReceiver == null) + if (innerReceiver == null) { - lock (this.syncLock) + lock (syncLock) { - if (this.innerReceiver == null) + if (innerReceiver == null) { - this.innerReceiver = new MessageReceiver( - this.QueueName, + innerReceiver = new MessageReceiver( + QueueName, MessagingEntityType.Queue, - this.ReceiveMode, - this.ServiceBusConnection, - this.CbsTokenProvider, - this.RetryPolicy, - this.PrefetchCount); + ReceiveMode, + ServiceBusConnection, + CbsTokenProvider, + RetryPolicy, + PrefetchCount); } } } - return this.innerReceiver; + return innerReceiver; } } @@ -280,29 +280,29 @@ internal SessionClient SessionClient { get { - if (this.sessionClient == null) + if (sessionClient == null) { - lock (this.syncLock) + lock (syncLock) { - if (this.sessionClient == null) + if (sessionClient == null) { - this.sessionClient = new SessionClient( - this.ClientId, - this.Path, + sessionClient = new SessionClient( + ClientId, + Path, MessagingEntityType.Queue, - this.ReceiveMode, - this.PrefetchCount, - this.ServiceBusConnection, - this.CbsTokenProvider, - this.RetryPolicy, - this.RegisteredPlugins); + ReceiveMode, + PrefetchCount, + ServiceBusConnection, + CbsTokenProvider, + RetryPolicy, + RegisteredPlugins); } } } - return this.sessionClient; + return sessionClient; } } @@ -310,22 +310,22 @@ internal SessionPumpHost SessionPumpHost { get { - if (this.sessionPumpHost == null) + if (sessionPumpHost == null) { - lock (this.syncLock) + lock (syncLock) { - if (this.sessionPumpHost == null) + if (sessionPumpHost == null) { - this.sessionPumpHost = new SessionPumpHost( - this.ClientId, - this.ReceiveMode, - this.SessionClient, - this.ServiceBusConnection.Endpoint); + sessionPumpHost = new SessionPumpHost( + ClientId, + ReceiveMode, + SessionClient, + ServiceBusConnection.Endpoint); } } } - return this.sessionPumpHost; + return sessionPumpHost; } } @@ -336,7 +336,7 @@ internal SessionPumpHost SessionPumpHost /// public Task SendAsync(Message message) { - return this.SendAsync(new[] { message }); + return SendAsync(new[] { message }); } /// @@ -345,9 +345,9 @@ public Task SendAsync(Message message) /// public Task SendAsync(IList messageList) { - this.ThrowIfClosed(); + ThrowIfClosed(); - return this.InnerSender.SendAsync(messageList); + return InnerSender.SendAsync(messageList); } /// @@ -361,8 +361,8 @@ public Task SendAsync(IList messageList) /// public Task CompleteAsync(string lockToken) { - this.ThrowIfClosed(); - return this.InnerReceiver.CompleteAsync(lockToken); + ThrowIfClosed(); + return InnerReceiver.CompleteAsync(lockToken); } /// @@ -378,8 +378,8 @@ public Task CompleteAsync(string lockToken) /// This operation can only be performed on messages that were received by this client. public Task AbandonAsync(string lockToken, IDictionary propertiesToModify = null) { - this.ThrowIfClosed(); - return this.InnerReceiver.AbandonAsync(lockToken, propertiesToModify); + ThrowIfClosed(); + return InnerReceiver.AbandonAsync(lockToken, propertiesToModify); } /// @@ -396,8 +396,8 @@ public Task AbandonAsync(string lockToken, IDictionary propertie /// public Task DeadLetterAsync(string lockToken, IDictionary propertiesToModify = null) { - this.ThrowIfClosed(); - return this.InnerReceiver.DeadLetterAsync(lockToken, propertiesToModify); + ThrowIfClosed(); + return InnerReceiver.DeadLetterAsync(lockToken, propertiesToModify); } /// @@ -415,8 +415,8 @@ public Task DeadLetterAsync(string lockToken, IDictionary proper /// public Task DeadLetterAsync(string lockToken, string deadLetterReason, string deadLetterErrorDescription = null) { - this.ThrowIfClosed(); - return this.InnerReceiver.DeadLetterAsync(lockToken, deadLetterReason, deadLetterErrorDescription); + ThrowIfClosed(); + return InnerReceiver.DeadLetterAsync(lockToken, deadLetterReason, deadLetterErrorDescription); } /// @@ -430,7 +430,7 @@ public Task DeadLetterAsync(string lockToken, string deadLetterReason, string de /// Use to configure the settings of the pump. public void RegisterMessageHandler(Func handler, Func exceptionReceivedHandler) { - this.RegisterMessageHandler(handler, new MessageHandlerOptions(exceptionReceivedHandler)); + RegisterMessageHandler(handler, new MessageHandlerOptions(exceptionReceivedHandler)); } /// @@ -442,8 +442,8 @@ public void RegisterMessageHandler(Func handle /// Enable prefetch to speed up the receive rate. public void RegisterMessageHandler(Func handler, MessageHandlerOptions messageHandlerOptions) { - this.ThrowIfClosed(); - this.InnerReceiver.RegisterMessageHandler(handler, messageHandlerOptions); + ThrowIfClosed(); + InnerReceiver.RegisterMessageHandler(handler, messageHandlerOptions); } /// @@ -459,7 +459,7 @@ public void RegisterMessageHandler(Func handle public void RegisterSessionHandler(Func handler, Func exceptionReceivedHandler) { var sessionHandlerOptions = new SessionHandlerOptions(exceptionReceivedHandler); - this.RegisterSessionHandler(handler, sessionHandlerOptions); + RegisterSessionHandler(handler, sessionHandlerOptions); } /// @@ -472,8 +472,8 @@ public void RegisterSessionHandler(FuncEnable prefetch to speed up the receive rate. public void RegisterSessionHandler(Func handler, SessionHandlerOptions sessionHandlerOptions) { - this.ThrowIfClosed(); - this.SessionPumpHost.OnSessionHandler(handler, sessionHandlerOptions); + ThrowIfClosed(); + SessionPumpHost.OnSessionHandler(handler, sessionHandlerOptions); } /// @@ -483,8 +483,8 @@ public void RegisterSessionHandler(FuncThe sequence number of the message that was scheduled. public Task ScheduleMessageAsync(Message message, DateTimeOffset scheduleEnqueueTimeUtc) { - this.ThrowIfClosed(); - return this.InnerSender.ScheduleMessageAsync(message, scheduleEnqueueTimeUtc); + ThrowIfClosed(); + return InnerSender.ScheduleMessageAsync(message, scheduleEnqueueTimeUtc); } /// @@ -493,8 +493,8 @@ public Task ScheduleMessageAsync(Message message, DateTimeOffset scheduleE /// The of the message to be cancelled. public Task CancelScheduledMessageAsync(long sequenceNumber) { - this.ThrowIfClosed(); - return this.InnerSender.CancelScheduledMessageAsync(sequenceNumber); + ThrowIfClosed(); + return InnerSender.CancelScheduledMessageAsync(sequenceNumber); } /// @@ -502,9 +502,9 @@ public Task CancelScheduledMessageAsync(long sequenceNumber) /// public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) { - this.ThrowIfClosed(); - this.InnerSender.RegisterPlugin(serviceBusPlugin); - this.InnerReceiver.RegisterPlugin(serviceBusPlugin); + ThrowIfClosed(); + InnerSender.RegisterPlugin(serviceBusPlugin); + InnerReceiver.RegisterPlugin(serviceBusPlugin); } /// @@ -513,28 +513,28 @@ public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) /// The name to be unregistered public override void UnregisterPlugin(string serviceBusPluginName) { - this.ThrowIfClosed(); - this.InnerSender.UnregisterPlugin(serviceBusPluginName); - this.InnerReceiver.UnregisterPlugin(serviceBusPluginName); + ThrowIfClosed(); + InnerSender.UnregisterPlugin(serviceBusPluginName); + InnerReceiver.UnregisterPlugin(serviceBusPluginName); } protected override async Task OnClosingAsync() { - if (this.innerSender != null) + if (innerSender != null) { - await this.innerSender.CloseAsync().ConfigureAwait(false); + await innerSender.CloseAsync().ConfigureAwait(false); } - if (this.innerReceiver != null) + if (innerReceiver != null) { - await this.innerReceiver.CloseAsync().ConfigureAwait(false); + await innerReceiver.CloseAsync().ConfigureAwait(false); } - this.sessionPumpHost?.Close(); + sessionPumpHost?.Close(); - if (this.sessionClient != null) + if (sessionClient != null) { - await this.sessionClient.CloseAsync().ConfigureAwait(false); + await sessionClient.CloseAsync().ConfigureAwait(false); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryExponential.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryExponential.cs index 8107060bf5ab..34f22db9b25a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryExponential.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryExponential.cs @@ -41,10 +41,10 @@ internal RetryExponential(TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan del throw new ArgumentException(Resources.ExponentialRetryBackoffRange.FormatForUser(minBackoff, maxBackoff)); } - this.MinimalBackoff = minBackoff; - this.MaximumBackoff = maxBackoff; - this.DeltaBackoff = deltaBackoff; - this.MaxRetryCount = maxRetryCount; + MinimalBackoff = minBackoff; + MaximumBackoff = maxBackoff; + DeltaBackoff = deltaBackoff; + MaxRetryCount = maxRetryCount; } /// @@ -79,7 +79,7 @@ internal RetryExponential(TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan del /// The amount of time to delay before retry. protected override bool OnShouldRetry(TimeSpan remainingTime, int currentRetryCount, out TimeSpan retryInterval) { - if (currentRetryCount > this.MaxRetryCount) + if (currentRetryCount > MaxRetryCount) { retryInterval = TimeSpan.Zero; return false; @@ -88,9 +88,9 @@ protected override bool OnShouldRetry(TimeSpan remainingTime, int currentRetryCo // Logic: - first use currentRetryCount to calculate the size of the interval. // - then get the interval in terms of sleep time (between min and max sleep time) // - if interval to large to fit inside remainingTime, we quit. - var randomizedInterval = ConcurrentRandom.Next((int)(this.DeltaBackoff.TotalMilliseconds * 0.8), (int)(this.DeltaBackoff.TotalMilliseconds * 1.2)); + var randomizedInterval = ConcurrentRandom.Next((int)(DeltaBackoff.TotalMilliseconds * 0.8), (int)(DeltaBackoff.TotalMilliseconds * 1.2)); double increment = (Math.Pow(2, currentRetryCount) - 1) * randomizedInterval; - double timeToSleepMsec = Math.Min(this.MinimalBackoff.TotalMilliseconds + increment, this.MaximumBackoff.TotalMilliseconds); + double timeToSleepMsec = Math.Min(MinimalBackoff.TotalMilliseconds + increment, MaximumBackoff.TotalMilliseconds); retryInterval = TimeSpan.FromMilliseconds(timeToSleepMsec); return true; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs index e8e41231b781..34e8fb0519f1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs @@ -62,19 +62,19 @@ public async Task RunOperation(Func operation, TimeSpan operationTimeout) List exceptions = null; var timeoutHelper = new TimeoutHelper(operationTimeout, true); - if (this.IsServerBusy && timeoutHelper.RemainingTime() < RetryPolicy.ServerBusyBaseSleepTime) + if (IsServerBusy && timeoutHelper.RemainingTime() < ServerBusyBaseSleepTime) { // We are in a server busy state before we start processing. // Since ServerBusyBaseSleepTime > remaining time for the operation, we don't wait for the entire Sleep time. await Task.Delay(timeoutHelper.RemainingTime()).ConfigureAwait(false); - throw new ServerBusyException(this.ServerBusyExceptionMessage); + throw new ServerBusyException(ServerBusyExceptionMessage); } while (true) { - if (this.IsServerBusy) + if (IsServerBusy) { - await Task.Delay(RetryPolicy.ServerBusyBaseSleepTime).ConfigureAwait(false); + await Task.Delay(ServerBusyBaseSleepTime).ConfigureAwait(false); } try @@ -82,7 +82,7 @@ public async Task RunOperation(Func operation, TimeSpan operationTimeout) await operation().ConfigureAwait(false); // Its a successful operation. Preemptively reset ServerBusy status. - this.ResetServerBusy(); + ResetServerBusy(); break; } catch (Exception exception) @@ -94,7 +94,7 @@ public async Task RunOperation(Func operation, TimeSpan operationTimeout) } exceptions.Add(exception); - if (this.ShouldRetry( + if (ShouldRetry( timeoutHelper.RemainingTime(), currentRetryCount, exception, out var retryInterval) && retryInterval < timeoutHelper.RemainingTime()) { @@ -135,12 +135,12 @@ internal bool ShouldRetry(TimeSpan remainingTime, int currentRetryCount, Excepti if (lastException is ServerBusyException) { - this.SetServerBusy(lastException.Message); + SetServerBusy(lastException.Message); } - if (this.IsRetryableException(lastException)) + if (IsRetryableException(lastException)) { - return this.OnShouldRetry(remainingTime, currentRetryCount, out retryInterval); + return OnShouldRetry(remainingTime, currentRetryCount, out retryInterval); } retryInterval = TimeSpan.Zero; @@ -150,19 +150,19 @@ internal bool ShouldRetry(TimeSpan remainingTime, int currentRetryCount, Excepti internal void SetServerBusy(string exceptionMessage) { // multiple call to this method will not prolong the timer. - if (this.encounteredServerBusy) + if (encounteredServerBusy) { return; } - lock (this.serverBusyLock) + lock (serverBusyLock) { - if (!this.encounteredServerBusy) + if (!encounteredServerBusy) { - this.encounteredServerBusy = true; - this.ServerBusyExceptionMessage = string.IsNullOrWhiteSpace(exceptionMessage) ? + encounteredServerBusy = true; + ServerBusyExceptionMessage = string.IsNullOrWhiteSpace(exceptionMessage) ? Resources.DefaultServerBusyException : exceptionMessage; - this.IsServerBusy = true; + IsServerBusy = true; TaskExtensionHelper.Schedule(ScheduleResetServerBusy); } } @@ -170,18 +170,18 @@ internal void SetServerBusy(string exceptionMessage) internal void ResetServerBusy() { - if (!this.encounteredServerBusy) + if (!encounteredServerBusy) { return; } - lock (this.serverBusyLock) + lock (serverBusyLock) { - if (this.encounteredServerBusy) + if (encounteredServerBusy) { - this.encounteredServerBusy = false; - this.ServerBusyExceptionMessage = Resources.DefaultServerBusyException; - this.IsServerBusy = false; + encounteredServerBusy = false; + ServerBusyExceptionMessage = Resources.DefaultServerBusyException; + IsServerBusy = false; } } } @@ -190,7 +190,7 @@ internal void ResetServerBusy() private async Task ScheduleResetServerBusy() { - await Task.Delay(RetryPolicy.ServerBusyBaseSleepTime).ConfigureAwait(false); + await Task.Delay(ServerBusyBaseSleepTime).ConfigureAwait(false); ResetServerBusy(); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs index 4d4454e1c78b..c2dcf1e842d4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs @@ -10,8 +10,8 @@ namespace Microsoft.Azure.ServiceBus using Microsoft.Azure.Amqp.Framing; using Microsoft.Azure.Amqp.Transaction; using Microsoft.Azure.Amqp.Transport; - using Microsoft.Azure.ServiceBus.Amqp; - using Microsoft.Azure.ServiceBus.Primitives; + using Amqp; + using Primitives; /// /// Connection object to service bus namespace @@ -62,7 +62,7 @@ public ServiceBusConnection(string namespaceConnectionString, RetryPolicy retryP throw Fx.Exception.Argument(nameof(namespaceConnectionString), "NamespaceConnectionString should not contain EntityPath."); } - this.InitializeConnection(serviceBusConnectionStringBuilder); + InitializeConnection(serviceBusConnectionStringBuilder); } /// @@ -87,9 +87,9 @@ public ServiceBusConnection(string namespaceConnectionString, TimeSpan operation throw Fx.Exception.Argument(nameof(namespaceConnectionString), "NamespaceConnectionString should not contain EntityPath."); } - this.InitializeConnection(serviceBusConnectionStringBuilder); + InitializeConnection(serviceBusConnectionStringBuilder); // operationTimeout argument explicitly provided by caller should take precedence over OperationTimeout found in the connection string. - this.OperationTimeout = operationTimeout; + OperationTimeout = operationTimeout; } /// @@ -112,13 +112,13 @@ public ServiceBusConnection(string endpoint, TransportType transportType, RetryP TransportType = transportType }; - this.InitializeConnection(serviceBusConnectionStringBuilder); + InitializeConnection(serviceBusConnectionStringBuilder); } internal ServiceBusConnection(RetryPolicy retryPolicy = null) { - this.RetryPolicy = retryPolicy ?? RetryPolicy.Default; - this.syncLock = new object(); + RetryPolicy = retryPolicy ?? RetryPolicy.Default; + syncLock = new object(); } /// @@ -179,7 +179,7 @@ internal set /// internal virtual void ThrowIfClosed() { - if (this.IsClosedOrClosing) + if (IsClosedOrClosing) { throw new ObjectDisposedException($"{nameof(ServiceBusConnection)} has already been closed. Please create a new instance"); } @@ -191,42 +191,42 @@ internal virtual void ThrowIfClosed() public async Task CloseAsync() { var callClose = false; - lock (this.syncLock) + lock (syncLock) { - if (!this.IsClosedOrClosing) + if (!IsClosedOrClosing) { - this.IsClosedOrClosing = true; + IsClosedOrClosing = true; callClose = true; } } if (callClose) { - await this.ConnectionManager.CloseAsync().ConfigureAwait(false); + await ConnectionManager.CloseAsync().ConfigureAwait(false); } } void InitializeConnection(ServiceBusConnectionStringBuilder builder) { - this.Endpoint = new Uri(builder.Endpoint); + Endpoint = new Uri(builder.Endpoint); if (builder.SasToken != null) { - this.TokenProvider = new SharedAccessSignatureTokenProvider(builder.SasToken); + TokenProvider = new SharedAccessSignatureTokenProvider(builder.SasToken); } else if (builder.SasKeyName != null || builder.SasKey != null) { - this.TokenProvider = new SharedAccessSignatureTokenProvider(builder.SasKeyName, builder.SasKey); + TokenProvider = new SharedAccessSignatureTokenProvider(builder.SasKeyName, builder.SasKey); } else if (builder.Authentication.Equals(ServiceBusConnectionStringBuilder.AuthenticationType.ManagedIdentity)) { - this.TokenProvider = new ManagedIdentityTokenProvider(); + TokenProvider = new ManagedIdentityTokenProvider(); } - this.OperationTimeout = builder.OperationTimeout; - this.TransportType = builder.TransportType; - this.ConnectionManager = new FaultTolerantAmqpObject(this.CreateConnectionAsync, CloseConnection); - this.TransactionController = new FaultTolerantAmqpObject(this.CreateControllerAsync, CloseController); + OperationTimeout = builder.OperationTimeout; + TransportType = builder.TransportType; + ConnectionManager = new FaultTolerantAmqpObject(CreateConnectionAsync, CloseConnection); + TransactionController = new FaultTolerantAmqpObject(CreateControllerAsync, CloseController); } static void CloseConnection(AmqpConnection connection) @@ -242,7 +242,7 @@ static void CloseController(Controller controller) async Task CreateConnectionAsync(TimeSpan timeout) { - var hostName = this.Endpoint.Host; + var hostName = Endpoint.Host; var timeoutHelper = new TimeoutHelper(timeout, true); var amqpSettings = AmqpConnectionHelper.CreateAmqpSettings( @@ -275,7 +275,7 @@ async Task CreateConnectionAsync(TimeSpan timeout) async Task CreateControllerAsync(TimeSpan timeout) { var timeoutHelper = new TimeoutHelper(timeout, true); - var connection = await this.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); + var connection = await ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; AmqpSession amqpSession = null; @@ -296,7 +296,7 @@ async Task CreateControllerAsync(TimeSpan timeout) await amqpSession.CloseAsync(timeout).ConfigureAwait(false); } - MessagingEventSource.Log.AmqpCreateControllerException(this.ConnectionManager.ToString(), exception); + MessagingEventSource.Log.AmqpCreateControllerException(ConnectionManager.ToString(), exception); throw; } @@ -305,9 +305,9 @@ async Task CreateControllerAsync(TimeSpan timeout) TransportSettings CreateTransportSettings() { - var hostName = this.Endpoint.Host; - var networkHost = this.Endpoint.Host; - var port = this.Endpoint.Port; + var hostName = Endpoint.Host; + var networkHost = Endpoint.Host; + var port = Endpoint.Port; if (TransportType == TransportType.AmqpWebSockets) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs index 6583f278e086..ae6481fa9959 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs @@ -52,7 +52,7 @@ public ServiceBusConnectionStringBuilder(string connectionString) { if (!string.IsNullOrWhiteSpace(connectionString)) { - this.ParseConnectionString(connectionString); + ParseConnectionString(connectionString); } } @@ -81,10 +81,10 @@ public ServiceBusConnectionStringBuilder(string endpoint, string entityPath, str throw Fx.Exception.ArgumentNullOrWhiteSpace(string.IsNullOrWhiteSpace(sharedAccessKeyName) ? nameof(sharedAccessKeyName) : nameof(sharedAccessKey)); } - this.Endpoint = endpoint; - this.EntityPath = entityPath; - this.SasKeyName = sharedAccessKeyName; - this.SasKey = sharedAccessKey; + Endpoint = endpoint; + EntityPath = entityPath; + SasKeyName = sharedAccessKeyName; + SasKey = sharedAccessKey; } /// @@ -111,9 +111,9 @@ public ServiceBusConnectionStringBuilder(string endpoint, string entityPath, str throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(sharedAccessSignature)); } - this.Endpoint = endpoint; - this.EntityPath = entityPath; - this.SasToken = sharedAccessSignature; + Endpoint = endpoint; + EntityPath = entityPath; + SasToken = sharedAccessSignature; } /// @@ -134,7 +134,7 @@ public ServiceBusConnectionStringBuilder(string endpoint, string entityPath, str public ServiceBusConnectionStringBuilder(string endpoint, string entityPath, string sharedAccessKeyName, string sharedAccessKey, TransportType transportType) : this(endpoint, entityPath, sharedAccessKeyName, sharedAccessKey) { - this.TransportType = transportType; + TransportType = transportType; } /// @@ -154,7 +154,7 @@ public ServiceBusConnectionStringBuilder(string endpoint, string entityPath, str public ServiceBusConnectionStringBuilder(string endpoint, string entityPath, string sharedAccessSignature, TransportType transportType) :this(endpoint, entityPath, sharedAccessSignature) { - this.TransportType = transportType; + TransportType = transportType; } /// @@ -167,7 +167,7 @@ public ServiceBusConnectionStringBuilder(string endpoint, string entityPath, str /// Throws when the hostname cannot be parsed public string Endpoint { - get => this.endpoint; + get => endpoint; set { if (!value.Contains(".")) @@ -176,7 +176,7 @@ public string Endpoint } var uriBuilder = new UriBuilder(value.Trim()); - this.endpoint = (value.Contains("://") ? uriBuilder.Scheme : EndpointScheme) + "://" + uriBuilder.Host; + endpoint = (value.Contains("://") ? uriBuilder.Scheme : EndpointScheme) + "://" + uriBuilder.Host; } } @@ -185,8 +185,8 @@ public string Endpoint /// public string EntityPath { - get => this.entityPath; - set => this.entityPath = value.Trim(); + get => entityPath; + set => entityPath = value.Trim(); } /// @@ -194,14 +194,14 @@ public string EntityPath /// public string SasKeyName { - get => this.sasKeyName; + get => sasKeyName; set { - if (this.Authentication != AuthenticationType.Other) + if (Authentication != AuthenticationType.Other) { throw Fx.Exception.Argument("Authentication, SasKeyName", Resources.ArgumentInvalidCombination.FormatForUser("Authentication, SasKeyName")); } - this.sasKeyName = value.Trim(); + sasKeyName = value.Trim(); } } @@ -211,8 +211,8 @@ public string SasKeyName /// Shared Access Signature key public string SasKey { - get => this.sasKey; - set => this.sasKey = value.Trim(); + get => sasKey; + set => sasKey = value.Trim(); } /// @@ -221,14 +221,14 @@ public string SasKey /// Shared Access Signature token public string SasToken { - get => this.sasToken; + get => sasToken; set { - if (this.Authentication != AuthenticationType.Other) + if (Authentication != AuthenticationType.Other) { throw Fx.Exception.Argument("Authentication, SasToken", Resources.ArgumentInvalidCombination.FormatForUser("Authentication, SasToken")); } - this.sasToken = value.Trim(); + sasToken = value.Trim(); } } @@ -248,21 +248,21 @@ public string SasToken /// public AuthenticationType Authentication { - get => this.authType; + get => authType; set { - if (!string.IsNullOrWhiteSpace(this.SasKeyName)) + if (!string.IsNullOrWhiteSpace(SasKeyName)) { throw Fx.Exception.Argument(nameof(AuthenticationConfigName) + ", " + nameof(SharedAccessKeyConfigName), Resources.ArgumentInvalidCombination.FormatForUser(nameof(AuthenticationConfigName) + ", " + nameof(SharedAccessKeyConfigName))); } - if (!string.IsNullOrWhiteSpace(this.SasToken)) + if (!string.IsNullOrWhiteSpace(SasToken)) { throw Fx.Exception.Argument(nameof(AuthenticationConfigName) + ", " + nameof(SharedAccessKeyConfigName), Resources.ArgumentInvalidCombination.FormatForUser(nameof(AuthenticationConfigName) + ", " + nameof(SharedAccessKeyConfigName))); } - this.authType = value; + authType = value; } } @@ -275,37 +275,37 @@ public AuthenticationType Authentication public string GetNamespaceConnectionString() { var connectionStringBuilder = new StringBuilder(); - if (this.Endpoint != null) + if (Endpoint != null) { - connectionStringBuilder.Append(EndpointConfigName).Append(KeyValueSeparator).Append(this.Endpoint).Append(KeyValuePairDelimiter); + connectionStringBuilder.Append(EndpointConfigName).Append(KeyValueSeparator).Append(Endpoint).Append(KeyValuePairDelimiter); } - if (!string.IsNullOrWhiteSpace(this.SasKeyName)) + if (!string.IsNullOrWhiteSpace(SasKeyName)) { - connectionStringBuilder.Append(SharedAccessKeyNameConfigName).Append(KeyValueSeparator).Append(this.SasKeyName).Append(KeyValuePairDelimiter); + connectionStringBuilder.Append(SharedAccessKeyNameConfigName).Append(KeyValueSeparator).Append(SasKeyName).Append(KeyValuePairDelimiter); } - if (!string.IsNullOrWhiteSpace(this.SasKey)) + if (!string.IsNullOrWhiteSpace(SasKey)) { - connectionStringBuilder.Append(SharedAccessKeyConfigName).Append(KeyValueSeparator).Append(this.SasKey).Append(KeyValuePairDelimiter); + connectionStringBuilder.Append(SharedAccessKeyConfigName).Append(KeyValueSeparator).Append(SasKey).Append(KeyValuePairDelimiter); } - if (!string.IsNullOrWhiteSpace(this.SasToken)) + if (!string.IsNullOrWhiteSpace(SasToken)) { - connectionStringBuilder.Append(SharedAccessSignatureConfigName).Append(KeyValueSeparator).Append(this.SasToken).Append(KeyValuePairDelimiter); + connectionStringBuilder.Append(SharedAccessSignatureConfigName).Append(KeyValueSeparator).Append(SasToken).Append(KeyValuePairDelimiter); } - if (this.TransportType != TransportType.Amqp) + if (TransportType != TransportType.Amqp) { - connectionStringBuilder.Append(TransportTypeConfigName).Append(KeyValueSeparator).Append(this.TransportType).Append(KeyValuePairDelimiter); + connectionStringBuilder.Append(TransportTypeConfigName).Append(KeyValueSeparator).Append(TransportType).Append(KeyValuePairDelimiter); } - if (this.OperationTimeout != Constants.DefaultOperationTimeout) + if (OperationTimeout != Constants.DefaultOperationTimeout) { - connectionStringBuilder.Append(OperationTimeoutConfigName).Append(KeyValueSeparator).Append(this.OperationTimeout).Append(KeyValuePairDelimiter); + connectionStringBuilder.Append(OperationTimeoutConfigName).Append(KeyValueSeparator).Append(OperationTimeout).Append(KeyValuePairDelimiter); } - if (this.Authentication == AuthenticationType.ManagedIdentity) + if (Authentication == AuthenticationType.ManagedIdentity) { connectionStringBuilder.Append(AuthenticationConfigName).Append(KeyValueSeparator).Append("Managed Identity").Append(KeyValuePairDelimiter); } @@ -319,12 +319,12 @@ public string GetNamespaceConnectionString() /// Entity connection string public string GetEntityConnectionString() { - if (string.IsNullOrWhiteSpace(this.EntityPath)) + if (string.IsNullOrWhiteSpace(EntityPath)) { - throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(this.EntityPath)); + throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(EntityPath)); } - return $"{this.GetNamespaceConnectionString()}{KeyValuePairDelimiter}{EntityPathConfigName}{KeyValueSeparator}{this.EntityPath}"; + return $"{GetNamespaceConnectionString()}{KeyValuePairDelimiter}{EntityPathConfigName}{KeyValueSeparator}{EntityPath}"; } /// @@ -333,12 +333,12 @@ public string GetEntityConnectionString() /// The connection string public override string ToString() { - if (string.IsNullOrWhiteSpace(this.EntityPath)) + if (string.IsNullOrWhiteSpace(EntityPath)) { - return this.GetNamespaceConnectionString(); + return GetNamespaceConnectionString(); } - return this.GetEntityConnectionString(); + return GetEntityConnectionString(); } void ParseConnectionString(string connectionString) @@ -358,52 +358,52 @@ void ParseConnectionString(string connectionString) var value = keyAndValue[1].Trim(); if (key.Equals(EndpointConfigName, StringComparison.OrdinalIgnoreCase)) { - this.Endpoint = value; + Endpoint = value; } else if (key.Equals(SharedAccessKeyNameConfigName, StringComparison.OrdinalIgnoreCase)) { - this.SasKeyName = value; + SasKeyName = value; } else if (key.Equals(EntityPathConfigName, StringComparison.OrdinalIgnoreCase)) { - this.EntityPath = value; + EntityPath = value; } else if (key.Equals(SharedAccessKeyConfigName, StringComparison.OrdinalIgnoreCase)) { - this.SasKey = value; + SasKey = value; } else if (key.Equals(SharedAccessSignatureConfigName, StringComparison.OrdinalIgnoreCase)) { - this.SasToken = value; + SasToken = value; } else if (key.Equals(TransportTypeConfigName, StringComparison.OrdinalIgnoreCase)) { if (Enum.TryParse(value, true, out TransportType transportType)) { - this.TransportType = transportType; + TransportType = transportType; } } else if (key.Equals(OperationTimeoutConfigName, StringComparison.OrdinalIgnoreCase)) { if (int.TryParse(value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out var timeoutInSeconds)) { - this.OperationTimeout = TimeSpan.FromSeconds(timeoutInSeconds); + OperationTimeout = TimeSpan.FromSeconds(timeoutInSeconds); } else if (TimeSpan.TryParse(value, NumberFormatInfo.InvariantInfo, out var operationTimeout)) { - this.OperationTimeout = operationTimeout; + OperationTimeout = operationTimeout; } else { throw Fx.Exception.Argument(nameof(connectionString), $"The {OperationTimeoutConfigName} ({value}) format is invalid. It must be an integer representing a number of seconds."); } - if (this.OperationTimeout.TotalMilliseconds <= 0) + if (OperationTimeout.TotalMilliseconds <= 0) { throw Fx.Exception.Argument(nameof(connectionString), $"The {OperationTimeoutConfigName} ({value}) must be greater than zero."); } - if (this.OperationTimeout.TotalHours >= 1) + if (OperationTimeout.TotalHours >= 1) { throw Fx.Exception.Argument(nameof(connectionString), $"The {OperationTimeoutConfigName} ({value}) must be smaller than one hour."); } @@ -411,9 +411,9 @@ void ParseConnectionString(string connectionString) else if (key.Equals(AuthenticationConfigName, StringComparison.OrdinalIgnoreCase) && !int.TryParse(value, out _)) { value = value.Replace(" ", string.Empty); - if (!Enum.TryParse(value, true, out this.authType)) + if (!Enum.TryParse(value, true, out authType)) { - this.authType = AuthenticationType.Other; + authType = AuthenticationType.Other; } } else diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs index 2b1e5c8c5d77..cf4c90a26340 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs @@ -9,7 +9,7 @@ namespace Microsoft.Azure.ServiceBus using System.Linq; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Diagnostics; + using Diagnostics; internal class ServiceBusDiagnosticSource { @@ -48,8 +48,8 @@ internal Activity SendStart(IList messageList) Activity activity = Start("Send", () => new { Messages = messageList, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, a => SetTags(a, messageList) ); @@ -66,8 +66,8 @@ internal void SendStop(Activity activity, IList messageList, TaskStatus DiagnosticListener.StopActivity(activity, new { Messages = messageList, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -83,8 +83,8 @@ internal Activity ProcessStart(Message message) return ProcessStart("Process", message, () => new { Message = message, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, a => SetTags(a, message)); } @@ -96,8 +96,8 @@ internal void ProcessStop(Activity activity, Message message, TaskStatus? status DiagnosticListener.StopActivity(activity, new { Message = message, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -114,8 +114,8 @@ internal Activity ProcessSessionStart(IMessageSession session, Message message) { Session = session, Message = message, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, a => SetTags(a, message)); } @@ -128,8 +128,8 @@ internal void ProcessSessionStop(Activity activity, IMessageSession session, Mes { Session = session, Message = message, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -146,8 +146,8 @@ internal Activity ScheduleStart(Message message, DateTimeOffset scheduleEnqueueT { Message = message, ScheduleEnqueueTimeUtc = scheduleEnqueueTimeUtc, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, a => SetTags(a, message)); @@ -164,8 +164,8 @@ internal void ScheduleStop(Activity activity, Message message, DateTimeOffset sc { Message = message, ScheduleEnqueueTimeUtc = scheduleEnqueueTimeUtc, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, SequenceNumber = sequenceNumber, Status = status ?? TaskStatus.Faulted }); @@ -182,8 +182,8 @@ internal Activity CancelStart(long sequenceNumber) return Start("Cancel", () => new { SequenceNumber = sequenceNumber, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, null); } @@ -195,8 +195,8 @@ internal void CancelStop(Activity activity, long sequenceNumber, TaskStatus? sta DiagnosticListener.StopActivity(activity, new { SequenceNumber = sequenceNumber, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -212,8 +212,8 @@ internal Activity ReceiveStart(int messageCount) return Start("Receive", () => new { RequestedMessageCount = messageCount, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, null); } @@ -227,8 +227,8 @@ internal void ReceiveStop(Activity activity, int messageCount, TaskStatus? statu DiagnosticListener.StopActivity(activity, new { RequestedMessageCount = messageCount, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted, Messages = messageList }); @@ -246,8 +246,8 @@ internal Activity PeekStart(long fromSequenceNumber, int messageCount) { FromSequenceNumber = fromSequenceNumber, RequestedMessageCount = messageCount, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, null); } @@ -263,8 +263,8 @@ internal void PeekStop(Activity activity, long fromSequenceNumber, int messageCo { FromSequenceNumber = fromSequenceNumber, RequestedMessageCount = messageCount, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted, Messages = messageList }); @@ -281,8 +281,8 @@ internal Activity ReceiveDeferredStart(IEnumerable sequenceNumbers) return Start("ReceiveDeferred", () => new { SequenceNumbers = sequenceNumbers, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, null); } @@ -297,8 +297,8 @@ internal void ReceiveDeferredStop(Activity activity, IEnumerable sequenceN DiagnosticListener.StopActivity(activity, new { SequenceNumbers = sequenceNumbers, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Messages = messageList, Status = status ?? TaskStatus.Faulted }); @@ -315,8 +315,8 @@ internal Activity CompleteStart(IList lockTokens) return Start("Complete", () => new { LockTokens = lockTokens, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, null); } @@ -328,8 +328,8 @@ internal void CompleteStop(Activity activity, IList lockTokens, TaskStat DiagnosticListener.StopActivity(activity, new { LockTokens = lockTokens, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -345,8 +345,8 @@ internal Activity DisposeStart(string operationName, string lockToken) return Start(operationName, () => new { LockToken = lockToken, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, null); } @@ -358,8 +358,8 @@ internal void DisposeStop(Activity activity, string lockToken, TaskStatus? statu DiagnosticListener.StopActivity(activity, new { LockToken = lockToken, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -375,8 +375,8 @@ internal Activity RenewLockStart(string lockToken) return Start("RenewLock", () => new { LockToken = lockToken, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, null); } @@ -388,8 +388,8 @@ internal void RenewLockStop(Activity activity, string lockToken, TaskStatus? sta DiagnosticListener.StopActivity(activity, new { LockToken = lockToken, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted, LockedUntilUtc = lockedUntilUtc }); @@ -406,8 +406,8 @@ internal Activity AddRuleStart(RuleDescription description) return Start("AddRule", () => new { Rule = description, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, null); } @@ -419,8 +419,8 @@ internal void AddRuleStop(Activity activity, RuleDescription description, TaskSt DiagnosticListener.StopActivity(activity, new { Rule = description, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -436,8 +436,8 @@ internal Activity RemoveRuleStart(string ruleName) return Start("RemoveRule", () => new { RuleName = ruleName, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, null); } @@ -449,8 +449,8 @@ internal void RemoveRuleStop(Activity activity, string ruleName, TaskStatus? sta DiagnosticListener.StopActivity(activity, new { RuleName = ruleName, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -465,8 +465,8 @@ internal Activity GetRulesStart() { return Start("GetRules", () => new { - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, null); } @@ -478,8 +478,8 @@ internal void GetRulesStop(Activity activity, IEnumerable rules DiagnosticListener.StopActivity(activity, new { Rules = rules, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -495,8 +495,8 @@ internal Activity AcceptMessageSessionStart(string sessionId) return Start("AcceptMessageSession", () => new { SessionId = sessionId, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, a => SetSessionTag(a, sessionId) ); @@ -509,8 +509,8 @@ internal void AcceptMessageSessionStop(Activity activity, string sessionId, Task DiagnosticListener.StopActivity(activity, new { SessionId = sessionId, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -526,8 +526,8 @@ internal Activity GetSessionStateStart(string sessionId) return Start("GetSessionState", () => new { SessionId = sessionId, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, a => SetSessionTag(a, sessionId)); } @@ -539,8 +539,8 @@ internal void GetSessionStateStop(Activity activity, string sessionId, byte[] st DiagnosticListener.StopActivity(activity, new { SessionId = sessionId, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted, State = state }); @@ -558,8 +558,8 @@ internal Activity SetSessionStateStart(string sessionId, byte[] state) { State = state, SessionId = sessionId, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, a => SetSessionTag(a, sessionId)); } @@ -572,8 +572,8 @@ internal void SetSessionStateStop(Activity activity, byte[] state, string sessio { State = state, SessionId = sessionId, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -589,8 +589,8 @@ internal Activity RenewSessionLockStart(string sessionId) return Start("RenewSessionLock", () => new { SessionId = sessionId, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }, a => SetSessionTag(a, sessionId)); } @@ -602,8 +602,8 @@ internal void RenewSessionLockStop(Activity activity, string sessionId, TaskStat DiagnosticListener.StopActivity(activity, new { SessionId = sessionId, - Entity = this.entityPath, - Endpoint = this.endpoint, + Entity = entityPath, + Endpoint = endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -619,8 +619,8 @@ internal void ReportException(Exception ex) new { Exception = ex, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = entityPath, + Endpoint = endpoint }); } } @@ -629,7 +629,7 @@ private Activity Start(string operationName, Func getPayload, ActionSpecifies whether or not the exception is transient. public ServiceBusException(bool isTransient) { - this.IsTransient = isTransient; + IsTransient = isTransient; } /// @@ -28,7 +28,7 @@ public ServiceBusException(bool isTransient) public ServiceBusException(bool isTransient, string message) : base(message) { - this.IsTransient = isTransient; + IsTransient = isTransient; } /// @@ -38,7 +38,7 @@ public ServiceBusException(bool isTransient, string message) public ServiceBusException(bool isTransient, Exception innerException) : base(innerException.Message, innerException) { - this.IsTransient = isTransient; + IsTransient = isTransient; } /// @@ -49,7 +49,7 @@ public ServiceBusException(bool isTransient, Exception innerException) public ServiceBusException(bool isTransient, string message, Exception innerException) : base(message, innerException) { - this.IsTransient = isTransient; + IsTransient = isTransient; } /// @@ -60,12 +60,12 @@ public override string Message get { var baseMessage = base.Message; - if (string.IsNullOrEmpty(this.ServiceBusNamespace)) + if (string.IsNullOrEmpty(ServiceBusNamespace)) { return baseMessage; } - return "{0}, ({1})".FormatInvariant(baseMessage, this.ServiceBusNamespace); + return "{0}, ({1})".FormatInvariant(baseMessage, ServiceBusNamespace); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs index 71caabc78b1c..02af8274e181 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs @@ -96,7 +96,7 @@ public SessionClient( throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -129,7 +129,7 @@ public SessionClient( retryPolicy, null) { - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -157,7 +157,7 @@ public SessionClient( retryPolicy, null) { - this.OwnsConnection = false; + OwnsConnection = false; } internal SessionClient( @@ -177,34 +177,34 @@ internal SessionClient( throw Fx.Exception.ArgumentNullOrWhiteSpace(entityPath); } - this.ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); - this.EntityPath = entityPath; - this.EntityType = entityType; - this.ReceiveMode = receiveMode; - this.PrefetchCount = prefetchCount; - this.ServiceBusConnection.ThrowIfClosed(); + ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); + EntityPath = entityPath; + EntityType = entityType; + ReceiveMode = receiveMode; + PrefetchCount = prefetchCount; + ServiceBusConnection.ThrowIfClosed(); if (cbsTokenProvider != null) { - this.CbsTokenProvider = cbsTokenProvider; + CbsTokenProvider = cbsTokenProvider; } - else if (this.ServiceBusConnection.TokenProvider != null) + else if (ServiceBusConnection.TokenProvider != null) { - this.CbsTokenProvider = new TokenProviderAdapter(this.ServiceBusConnection.TokenProvider, this.ServiceBusConnection.OperationTimeout); + CbsTokenProvider = new TokenProviderAdapter(ServiceBusConnection.TokenProvider, ServiceBusConnection.OperationTimeout); } else { throw new ArgumentNullException($"{nameof(ServiceBusConnection)} doesn't have a valid token provider"); } - this.diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); + diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); // Register plugins on the message session. if (registeredPlugins != null) { foreach (var serviceBusPlugin in registeredPlugins) { - this.RegisterPlugin(serviceBusPlugin); + RegisterPlugin(serviceBusPlugin); } } } @@ -219,15 +219,15 @@ internal SessionClient( /// /// Gets the path of the entity. This is either the name of the queue, or the full path of the subscription. /// - public override string Path => this.EntityPath; + public override string Path => EntityPath; /// /// Duration after which individual operations will timeout. /// public override TimeSpan OperationTimeout { - get => this.ServiceBusConnection.OperationTimeout; - set => this.ServiceBusConnection.OperationTimeout = value; + get => ServiceBusConnection.OperationTimeout; + set => ServiceBusConnection.OperationTimeout = value; } /// @@ -253,7 +253,7 @@ public override TimeSpan OperationTimeout /// Individual sessions can further register additional plugins. public Task AcceptMessageSessionAsync() { - return this.AcceptMessageSessionAsync(this.ServiceBusConnection.OperationTimeout); + return AcceptMessageSessionAsync(ServiceBusConnection.OperationTimeout); } /// @@ -264,7 +264,7 @@ public Task AcceptMessageSessionAsync() /// Individual sessions can further register additional plugins. public Task AcceptMessageSessionAsync(TimeSpan operationTimeout) { - return this.AcceptMessageSessionAsync(null, operationTimeout); + return AcceptMessageSessionAsync(null, operationTimeout); } /// @@ -275,7 +275,7 @@ public Task AcceptMessageSessionAsync(TimeSpan operationTimeout /// Individual sessions can further register additional plugins. public Task AcceptMessageSessionAsync(string sessionId) { - return this.AcceptMessageSessionAsync(sessionId, this.ServiceBusConnection.OperationTimeout); + return AcceptMessageSessionAsync(sessionId, ServiceBusConnection.OperationTimeout); } /// @@ -287,33 +287,33 @@ public Task AcceptMessageSessionAsync(string sessionId) /// Individual sessions can further register additional plugins. public async Task AcceptMessageSessionAsync(string sessionId, TimeSpan operationTimeout) { - this.ThrowIfClosed(); + ThrowIfClosed(); MessagingEventSource.Log.AmqpSessionClientAcceptMessageSessionStart( - this.ClientId, - this.EntityPath, - this.ReceiveMode, - this.PrefetchCount, + ClientId, + EntityPath, + ReceiveMode, + PrefetchCount, sessionId); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.AcceptMessageSessionStart(sessionId) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.AcceptMessageSessionStart(sessionId) : null; Task acceptMessageSessionTask = null; var session = new MessageSession( - this.EntityPath, - this.EntityType, - this.ReceiveMode, - this.ServiceBusConnection, - this.CbsTokenProvider, - this.RetryPolicy, - this.PrefetchCount, + EntityPath, + EntityType, + ReceiveMode, + ServiceBusConnection, + CbsTokenProvider, + RetryPolicy, + PrefetchCount, sessionId, true); try { - acceptMessageSessionTask = this.RetryPolicy.RunOperation( + acceptMessageSessionTask = RetryPolicy.RunOperation( () => session.GetSessionReceiverLinkAsync(operationTimeout), operationTimeout); await acceptMessageSessionTask.ConfigureAwait(false); @@ -322,12 +322,12 @@ public async Task AcceptMessageSessionAsync(string sessionId, T { if (isDiagnosticSourceEnabled && !(exception is ServiceBusTimeoutException)) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } MessagingEventSource.Log.AmqpSessionClientAcceptMessageSessionException( - this.ClientId, - this.EntityPath, + ClientId, + EntityPath, exception); await session.CloseAsync().ConfigureAwait(false); @@ -335,17 +335,17 @@ public async Task AcceptMessageSessionAsync(string sessionId, T } finally { - this.diagnosticSource.AcceptMessageSessionStop(activity, session.SessionId, acceptMessageSessionTask?.Status); + diagnosticSource.AcceptMessageSessionStop(activity, session.SessionId, acceptMessageSessionTask?.Status); } MessagingEventSource.Log.AmqpSessionClientAcceptMessageSessionStop( - this.ClientId, - this.EntityPath, + ClientId, + EntityPath, session.SessionIdInternal); - session.UpdateClientId(ClientEntity.GenerateClientId(nameof(MessageSession), $"{this.EntityPath}_{session.SessionId}")); + session.UpdateClientId(GenerateClientId(nameof(MessageSession), $"{EntityPath}_{session.SessionId}")); // Register plugins on the message session. - foreach (var serviceBusPlugin in this.RegisteredPlugins) + foreach (var serviceBusPlugin in RegisteredPlugins) { session.RegisterPlugin(serviceBusPlugin); } @@ -359,17 +359,17 @@ public async Task AcceptMessageSessionAsync(string sessionId, T /// The to register. public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) { - this.ThrowIfClosed(); + ThrowIfClosed(); if (serviceBusPlugin == null) { throw new ArgumentNullException(nameof(serviceBusPlugin), Resources.ArgumentNullOrWhiteSpace.FormatForUser(nameof(serviceBusPlugin))); } - if (this.RegisteredPlugins.Any(p => p.Name == serviceBusPlugin.Name)) + if (RegisteredPlugins.Any(p => p.Name == serviceBusPlugin.Name)) { throw new ArgumentException(nameof(serviceBusPlugin), Resources.PluginAlreadyRegistered.FormatForUser(nameof(serviceBusPlugin))); } - this.RegisteredPlugins.Add(serviceBusPlugin); + RegisteredPlugins.Add(serviceBusPlugin); } /// @@ -378,9 +378,9 @@ public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) /// The of the plugin to be unregistered. public override void UnregisterPlugin(string serviceBusPluginName) { - this.ThrowIfClosed(); + ThrowIfClosed(); - if (this.RegisteredPlugins == null) + if (RegisteredPlugins == null) { return; } @@ -388,10 +388,10 @@ public override void UnregisterPlugin(string serviceBusPluginName) { throw new ArgumentNullException(nameof(serviceBusPluginName), Resources.ArgumentNullOrWhiteSpace.FormatForUser(nameof(serviceBusPluginName))); } - if (this.RegisteredPlugins.Any(p => p.Name == serviceBusPluginName)) + if (RegisteredPlugins.Any(p => p.Name == serviceBusPluginName)) { - var plugin = this.RegisteredPlugins.First(p => p.Name == serviceBusPluginName); - this.RegisteredPlugins.Remove(plugin); + var plugin = RegisteredPlugins.First(p => p.Name == serviceBusPluginName); + RegisteredPlugins.Remove(plugin); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs index 185a24a9fe05..b8d9d5e90a7e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs @@ -29,11 +29,11 @@ public sealed class SessionHandlerOptions public SessionHandlerOptions(Func exceptionReceivedHandler) { // These are default values - this.AutoComplete = true; - this.MaxConcurrentSessions = 2000; - this.MessageWaitTimeout = TimeSpan.FromMinutes(1); - this.MaxAutoRenewDuration = Constants.ClientPumpRenewLockTimeout; - this.ExceptionReceivedHandler = exceptionReceivedHandler ?? throw new ArgumentNullException(nameof(exceptionReceivedHandler)); + AutoComplete = true; + MaxConcurrentSessions = 2000; + MessageWaitTimeout = TimeSpan.FromMinutes(1); + MaxAutoRenewDuration = Constants.ClientPumpRenewLockTimeout; + ExceptionReceivedHandler = exceptionReceivedHandler ?? throw new ArgumentNullException(nameof(exceptionReceivedHandler)); } /// Occurs when an exception is received. Enables you to be notified of any errors encountered by the session pump. @@ -44,12 +44,12 @@ public SessionHandlerOptions(Func exceptionRec /// The duration for which the session renew its state. public TimeSpan MaxAutoRenewDuration { - get => this.maxAutoRenewDuration; + get => maxAutoRenewDuration; set { TimeoutHelper.ThrowIfNegativeArgument(value, nameof(value)); - this.maxAutoRenewDuration = value; + maxAutoRenewDuration = value; } } @@ -57,12 +57,12 @@ public TimeSpan MaxAutoRenewDuration /// The time to wait for receiving the message. public TimeSpan MessageWaitTimeout { - get => this.messageWaitTimeout; + get => messageWaitTimeout; set { TimeoutHelper.ThrowIfNegativeArgument(value, nameof(value)); - this.messageWaitTimeout = value; + messageWaitTimeout = value; } } @@ -70,7 +70,7 @@ public TimeSpan MessageWaitTimeout /// The maximum number of sessions that the User wants to handle concurrently. public int MaxConcurrentSessions { - get => this.maxConcurrentSessions; + get => maxConcurrentSessions; set { @@ -79,8 +79,8 @@ public int MaxConcurrentSessions throw new ArgumentOutOfRangeException(Resources.MaxConcurrentCallsMustBeGreaterThanZero.FormatForUser(value)); } - this.maxConcurrentSessions = value; - this.MaxConcurrentAcceptSessionCalls = Math.Min(value, 2 * Environment.ProcessorCount); + maxConcurrentSessions = value; + MaxConcurrentAcceptSessionCalls = Math.Min(value, 2 * Environment.ProcessorCount); } } @@ -88,7 +88,7 @@ public int MaxConcurrentSessions /// true if the autocomplete option of the session handler is enabled; otherwise, false. public bool AutoComplete { get; set; } - internal bool AutoRenewLock => this.MaxAutoRenewDuration > TimeSpan.Zero; + internal bool AutoRenewLock => MaxAutoRenewDuration > TimeSpan.Zero; internal int MaxConcurrentAcceptSessionCalls { get; set; } @@ -96,7 +96,7 @@ internal async Task RaiseExceptionReceived(ExceptionReceivedEventArgs eventArgs) { try { - await this.ExceptionReceivedHandler(eventArgs).ConfigureAwait(false); + await ExceptionReceivedHandler(eventArgs).ConfigureAwait(false); } catch (Exception exception) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs index b3d6b8ab67c0..447a63538a1e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs @@ -16,10 +16,10 @@ internal sealed class SessionPumpHost public SessionPumpHost(string clientId, ReceiveMode receiveMode, ISessionClient sessionClient, Uri endpoint) { - this.syncLock = new object(); - this.ClientId = clientId; - this.ReceiveMode = receiveMode; - this.SessionClient = sessionClient; + syncLock = new object(); + ClientId = clientId; + ReceiveMode = receiveMode; + SessionClient = sessionClient; this.endpoint = endpoint; } @@ -31,11 +31,11 @@ public SessionPumpHost(string clientId, ReceiveMode receiveMode, ISessionClient public void Close() { - if (this.sessionReceivePump != null) + if (sessionReceivePump != null) { - this.sessionPumpCancellationTokenSource?.Cancel(); - this.sessionPumpCancellationTokenSource?.Dispose(); - this.sessionReceivePump = null; + sessionPumpCancellationTokenSource?.Cancel(); + sessionPumpCancellationTokenSource?.Dispose(); + sessionReceivePump = null; } } @@ -43,44 +43,44 @@ public void OnSessionHandler( Func callback, SessionHandlerOptions sessionHandlerOptions) { - MessagingEventSource.Log.RegisterOnSessionHandlerStart(this.ClientId, sessionHandlerOptions); + MessagingEventSource.Log.RegisterOnSessionHandlerStart(ClientId, sessionHandlerOptions); - lock (this.syncLock) + lock (syncLock) { - if (this.sessionReceivePump != null) + if (sessionReceivePump != null) { throw new InvalidOperationException(Resources.SessionHandlerAlreadyRegistered); } - this.sessionPumpCancellationTokenSource = new CancellationTokenSource(); - this.sessionReceivePump = new SessionReceivePump( - this.ClientId, - this.SessionClient, - this.ReceiveMode, + sessionPumpCancellationTokenSource = new CancellationTokenSource(); + sessionReceivePump = new SessionReceivePump( + ClientId, + SessionClient, + ReceiveMode, sessionHandlerOptions, callback, - this.endpoint, - this.sessionPumpCancellationTokenSource.Token); + endpoint, + sessionPumpCancellationTokenSource.Token); } try { - this.sessionReceivePump.StartPump(); + sessionReceivePump.StartPump(); } catch (Exception exception) { - MessagingEventSource.Log.RegisterOnSessionHandlerException(this.ClientId, exception); - if (this.sessionReceivePump != null) + MessagingEventSource.Log.RegisterOnSessionHandlerException(ClientId, exception); + if (sessionReceivePump != null) { - this.sessionPumpCancellationTokenSource.Cancel(); - this.sessionPumpCancellationTokenSource.Dispose(); - this.sessionReceivePump = null; + sessionPumpCancellationTokenSource.Cancel(); + sessionPumpCancellationTokenSource.Dispose(); + sessionReceivePump = null; } throw; } - MessagingEventSource.Log.RegisterOnSessionHandlerStop(this.ClientId); + MessagingEventSource.Log.RegisterOnSessionHandlerStop(ClientId); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs index 9a35b3d54d35..a234363b0473 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs @@ -32,15 +32,15 @@ public SessionReceivePump(string clientId, { this.client = client ?? throw new ArgumentException(nameof(client)); this.clientId = clientId; - this.ReceiveMode = receiveMode; + ReceiveMode = receiveMode; this.sessionHandlerOptions = sessionHandlerOptions; - this.userOnSessionCallback = callback; + userOnSessionCallback = callback; this.endpoint = endpoint.Authority; - this.entityPath = client.EntityPath; - this.pumpCancellationToken = token; - this.maxConcurrentSessionsSemaphoreSlim = new SemaphoreSlim(this.sessionHandlerOptions.MaxConcurrentSessions); - this.maxPendingAcceptSessionsSemaphoreSlim = new SemaphoreSlim(this.sessionHandlerOptions.MaxConcurrentAcceptSessionCalls); - this.diagnosticSource = new ServiceBusDiagnosticSource(client.EntityPath, endpoint); + entityPath = client.EntityPath; + pumpCancellationToken = token; + maxConcurrentSessionsSemaphoreSlim = new SemaphoreSlim(this.sessionHandlerOptions.MaxConcurrentSessions); + maxPendingAcceptSessionsSemaphoreSlim = new SemaphoreSlim(this.sessionHandlerOptions.MaxConcurrentAcceptSessionCalls); + diagnosticSource = new ServiceBusDiagnosticSource(client.EntityPath, endpoint); } ReceiveMode ReceiveMode { get; } @@ -48,9 +48,9 @@ public SessionReceivePump(string clientId, public void StartPump() { // Schedule Tasks for doing PendingAcceptSession calls - for (var i = 0; i < this.sessionHandlerOptions.MaxConcurrentAcceptSessionCalls; i++) + for (var i = 0; i < sessionHandlerOptions.MaxConcurrentAcceptSessionCalls; i++) { - TaskExtensionHelper.Schedule(this.SessionPumpTaskAsync); + TaskExtensionHelper.Schedule(SessionPumpTaskAsync); } } @@ -71,29 +71,29 @@ static void CancelAutoRenewLock(object state) bool ShouldRenewSessionLock() { return - this.ReceiveMode == ReceiveMode.PeekLock && - this.sessionHandlerOptions.AutoRenewLock; + ReceiveMode == ReceiveMode.PeekLock && + sessionHandlerOptions.AutoRenewLock; } Task RaiseExceptionReceived(Exception e, string action) { - var eventArgs = new ExceptionReceivedEventArgs(e, action, this.endpoint, this.entityPath, this.clientId); - return this.sessionHandlerOptions.RaiseExceptionReceived(eventArgs); + var eventArgs = new ExceptionReceivedEventArgs(e, action, endpoint, entityPath, clientId); + return sessionHandlerOptions.RaiseExceptionReceived(eventArgs); } async Task CompleteMessageIfNeededAsync(IMessageSession session, Message message) { try { - if (this.ReceiveMode == ReceiveMode.PeekLock && - this.sessionHandlerOptions.AutoComplete) + if (ReceiveMode == ReceiveMode.PeekLock && + sessionHandlerOptions.AutoComplete) { await session.CompleteAsync(new[] { message.SystemProperties.LockToken }).ConfigureAwait(false); } } catch (Exception exception) { - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Complete).ConfigureAwait(false); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Complete).ConfigureAwait(false); } } @@ -108,61 +108,61 @@ async Task AbandonMessageIfNeededAsync(IMessageSession session, Message message) } catch (Exception exception) { - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Abandon).ConfigureAwait(false); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Abandon).ConfigureAwait(false); } } async Task SessionPumpTaskAsync() { - while (!this.pumpCancellationToken.IsCancellationRequested) + while (!pumpCancellationToken.IsCancellationRequested) { var concurrentSessionSemaphoreAcquired = false; try { - await this.maxConcurrentSessionsSemaphoreSlim.WaitAsync(this.pumpCancellationToken).ConfigureAwait(false); + await maxConcurrentSessionsSemaphoreSlim.WaitAsync(pumpCancellationToken).ConfigureAwait(false); concurrentSessionSemaphoreAcquired = true; - await this.maxPendingAcceptSessionsSemaphoreSlim.WaitAsync(this.pumpCancellationToken).ConfigureAwait(false); - var session = await this.client.AcceptMessageSessionAsync().ConfigureAwait(false); + await maxPendingAcceptSessionsSemaphoreSlim.WaitAsync(pumpCancellationToken).ConfigureAwait(false); + var session = await client.AcceptMessageSessionAsync().ConfigureAwait(false); if (session == null) { - await Task.Delay(Constants.NoMessageBackoffTimeSpan, this.pumpCancellationToken).ConfigureAwait(false); + await Task.Delay(Constants.NoMessageBackoffTimeSpan, pumpCancellationToken).ConfigureAwait(false); continue; } // `session` needs to be copied to another local variable before passing to Schedule // because of the way variables are captured. (Refer 'Captured variables') var messageSession = session; - TaskExtensionHelper.Schedule(() => this.MessagePumpTaskAsync(messageSession)); + TaskExtensionHelper.Schedule(() => MessagePumpTaskAsync(messageSession)); } catch (Exception exception) { - MessagingEventSource.Log.SessionReceivePumpSessionReceiveException(this.clientId, exception); + MessagingEventSource.Log.SessionReceivePumpSessionReceiveException(clientId, exception); if (concurrentSessionSemaphoreAcquired) { - this.maxConcurrentSessionsSemaphoreSlim.Release(); + maxConcurrentSessionsSemaphoreSlim.Release(); } if (exception is ServiceBusTimeoutException) { - await Task.Delay(Constants.NoMessageBackoffTimeSpan, this.pumpCancellationToken).ConfigureAwait(false); + await Task.Delay(Constants.NoMessageBackoffTimeSpan, pumpCancellationToken).ConfigureAwait(false); } else { - if (!(exception is ObjectDisposedException && this.pumpCancellationToken.IsCancellationRequested)) + if (!(exception is ObjectDisposedException && pumpCancellationToken.IsCancellationRequested)) { - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.AcceptMessageSession).ConfigureAwait(false); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.AcceptMessageSession).ConfigureAwait(false); } if (!MessagingUtilities.ShouldRetry(exception)) { - await Task.Delay(Constants.NoMessageBackoffTimeSpan, this.pumpCancellationToken).ConfigureAwait(false); + await Task.Delay(Constants.NoMessageBackoffTimeSpan, pumpCancellationToken).ConfigureAwait(false); } } } finally { - this.maxPendingAcceptSessionsSemaphoreSlim.Release(); + maxPendingAcceptSessionsSemaphoreSlim.Release(); } } } @@ -175,9 +175,9 @@ async Task MessagePumpTaskAsync(IMessageSession session) } var renewLockCancellationTokenSource = new CancellationTokenSource(); - if (this.ShouldRenewSessionLock()) + if (ShouldRenewSessionLock()) { - TaskExtensionHelper.Schedule(() => this.RenewSessionLockTaskAsync(session, renewLockCancellationTokenSource.Token)); + TaskExtensionHelper.Schedule(() => RenewSessionLockTaskAsync(session, renewLockCancellationTokenSource.Token)); } var autoRenewLockCancellationTimer = new Timer( @@ -188,63 +188,63 @@ async Task MessagePumpTaskAsync(IMessageSession session) try { - while (!this.pumpCancellationToken.IsCancellationRequested && !session.IsClosedOrClosing) + while (!pumpCancellationToken.IsCancellationRequested && !session.IsClosedOrClosing) { Message message; try { - message = await session.ReceiveAsync(this.sessionHandlerOptions.MessageWaitTimeout).ConfigureAwait(false); + message = await session.ReceiveAsync(sessionHandlerOptions.MessageWaitTimeout).ConfigureAwait(false); } catch (Exception exception) { - MessagingEventSource.Log.MessageReceivePumpTaskException(this.clientId, session.SessionId, exception); + MessagingEventSource.Log.MessageReceivePumpTaskException(clientId, session.SessionId, exception); if (exception is ServiceBusTimeoutException) { // Timeout Exceptions are pretty common. Not alerting the User on this. continue; } - if (!(exception is ObjectDisposedException && this.pumpCancellationToken.IsCancellationRequested)) + if (!(exception is ObjectDisposedException && pumpCancellationToken.IsCancellationRequested)) { - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Receive).ConfigureAwait(false); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Receive).ConfigureAwait(false); } break; } if (message == null) { - MessagingEventSource.Log.SessionReceivePumpSessionEmpty(this.clientId, session.SessionId); + MessagingEventSource.Log.SessionReceivePumpSessionEmpty(clientId, session.SessionId); break; } bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.ProcessSessionStart(session, message) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.ProcessSessionStart(session, message) : null; Task processTask = null; try { // Set the timer - autoRenewLockCancellationTimer.Change(this.sessionHandlerOptions.MaxAutoRenewDuration, + autoRenewLockCancellationTimer.Change(sessionHandlerOptions.MaxAutoRenewDuration, TimeSpan.FromMilliseconds(-1)); var callbackExceptionOccurred = false; try { - processTask = this.userOnSessionCallback(session, message, this.pumpCancellationToken); + processTask = userOnSessionCallback(session, message, pumpCancellationToken); await processTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageReceivePumpTaskException(this.clientId, session.SessionId, exception); - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.UserCallback).ConfigureAwait(false); + MessagingEventSource.Log.MessageReceivePumpTaskException(clientId, session.SessionId, exception); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.UserCallback).ConfigureAwait(false); callbackExceptionOccurred = true; if (!(exception is MessageLockLostException || exception is SessionLockLostException)) { - await this.AbandonMessageIfNeededAsync(session, message).ConfigureAwait(false); + await AbandonMessageIfNeededAsync(session, message).ConfigureAwait(false); } } finally @@ -254,7 +254,7 @@ async Task MessagePumpTaskAsync(IMessageSession session) if (!callbackExceptionOccurred) { - await this.CompleteMessageIfNeededAsync(session, message).ConfigureAwait(false); + await CompleteMessageIfNeededAsync(session, message).ConfigureAwait(false); } else if (session.IsClosedOrClosing) { @@ -264,7 +264,7 @@ async Task MessagePumpTaskAsync(IMessageSession session) } finally { - this.diagnosticSource.ProcessSessionStop(activity, session, message, processTask?.Status); + diagnosticSource.ProcessSessionStop(activity, session, message, processTask?.Status); } } } @@ -274,8 +274,8 @@ async Task MessagePumpTaskAsync(IMessageSession session) renewLockCancellationTokenSource.Dispose(); autoRenewLockCancellationTimer.Dispose(); - await this.CloseSessionIfNeededAsync(session).ConfigureAwait(false); - this.maxConcurrentSessionsSemaphoreSlim.Release(); + await CloseSessionIfNeededAsync(session).ConfigureAwait(false); + maxConcurrentSessionsSemaphoreSlim.Release(); } } @@ -286,33 +286,33 @@ async Task CloseSessionIfNeededAsync(IMessageSession session) try { await session.CloseAsync().ConfigureAwait(false); - MessagingEventSource.Log.SessionReceivePumpSessionClosed(this.clientId, session.SessionId); + MessagingEventSource.Log.SessionReceivePumpSessionClosed(clientId, session.SessionId); } catch (Exception exception) { - MessagingEventSource.Log.SessionReceivePumpSessionCloseException(this.clientId, session.SessionId, exception); - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.CloseMessageSession).ConfigureAwait(false); + MessagingEventSource.Log.SessionReceivePumpSessionCloseException(clientId, session.SessionId, exception); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.CloseMessageSession).ConfigureAwait(false); } } } async Task RenewSessionLockTaskAsync(IMessageSession session, CancellationToken renewLockCancellationToken) { - while (!this.pumpCancellationToken.IsCancellationRequested && + while (!pumpCancellationToken.IsCancellationRequested && !renewLockCancellationToken.IsCancellationRequested) { try { var amount = MessagingUtilities.CalculateRenewAfterDuration(session.LockedUntilUtc); - MessagingEventSource.Log.SessionReceivePumpSessionRenewLockStart(this.clientId, session.SessionId, amount); + MessagingEventSource.Log.SessionReceivePumpSessionRenewLockStart(clientId, session.SessionId, amount); await Task.Delay(amount, renewLockCancellationToken).ConfigureAwait(false); - if (!this.pumpCancellationToken.IsCancellationRequested && + if (!pumpCancellationToken.IsCancellationRequested && !renewLockCancellationToken.IsCancellationRequested) { await session.RenewSessionLockAsync().ConfigureAwait(false); - MessagingEventSource.Log.SessionReceivePumpSessionRenewLockStop(this.clientId, session.SessionId); + MessagingEventSource.Log.SessionReceivePumpSessionRenewLockStop(clientId, session.SessionId); } else { @@ -321,14 +321,14 @@ async Task RenewSessionLockTaskAsync(IMessageSession session, CancellationToken } catch (Exception exception) { - MessagingEventSource.Log.SessionReceivePumpSessionRenewLockException(this.clientId, session.SessionId, exception); + MessagingEventSource.Log.SessionReceivePumpSessionRenewLockException(clientId, session.SessionId, exception); // TaskCanceled is expected here as renewTasks will be cancelled after the Complete call is made. // ObjectDisposedException should only happen here because the CancellationToken was disposed at which point // this renew exception is not relevant anymore. Lets not bother user with this exception. if (!(exception is TaskCanceledException) && !(exception is ObjectDisposedException)) { - await this.RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.RenewLock).ConfigureAwait(false); + await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.RenewLock).ConfigureAwait(false); } if (!MessagingUtilities.ShouldRetry(exception)) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs index c5d7ebeecfc1..7ffb31b64eb0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs @@ -9,9 +9,9 @@ namespace Microsoft.Azure.ServiceBus using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Amqp; - using Microsoft.Azure.ServiceBus.Amqp; - using Microsoft.Azure.ServiceBus.Core; - using Microsoft.Azure.ServiceBus.Primitives; + using Amqp; + using Core; + using Primitives; /// /// SubscriptionClient can be used for all basic interactions with a Service Bus Subscription. @@ -85,7 +85,7 @@ public SubscriptionClient(string connectionString, string topicPath, string subs throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -109,7 +109,7 @@ public SubscriptionClient( RetryPolicy retryPolicy = null) : this(new ServiceBusConnection(endpoint, transportType, retryPolicy) {TokenProvider = tokenProvider}, topicPath, subscriptionName, receiveMode, retryPolicy) { - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -134,26 +134,26 @@ public SubscriptionClient(ServiceBusConnection serviceBusConnection, string topi MessagingEventSource.Log.SubscriptionClientCreateStart(serviceBusConnection?.Endpoint.Authority, topicPath, subscriptionName, receiveMode.ToString()); - this.ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); - this.syncLock = new object(); - this.TopicPath = topicPath; - this.SubscriptionName = subscriptionName; - this.Path = EntityNameHelper.FormatSubscriptionPath(this.TopicPath, this.SubscriptionName); - this.ReceiveMode = receiveMode; - this.diagnosticSource = new ServiceBusDiagnosticSource(this.Path, serviceBusConnection.Endpoint); - this.OwnsConnection = false; - this.ServiceBusConnection.ThrowIfClosed(); - - if (this.ServiceBusConnection.TokenProvider != null) + ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); + syncLock = new object(); + TopicPath = topicPath; + SubscriptionName = subscriptionName; + Path = EntityNameHelper.FormatSubscriptionPath(TopicPath, SubscriptionName); + ReceiveMode = receiveMode; + diagnosticSource = new ServiceBusDiagnosticSource(Path, serviceBusConnection.Endpoint); + OwnsConnection = false; + ServiceBusConnection.ThrowIfClosed(); + + if (ServiceBusConnection.TokenProvider != null) { - this.CbsTokenProvider = new TokenProviderAdapter(this.ServiceBusConnection.TokenProvider, this.ServiceBusConnection.OperationTimeout); + CbsTokenProvider = new TokenProviderAdapter(ServiceBusConnection.TokenProvider, ServiceBusConnection.OperationTimeout); } else { throw new ArgumentNullException($"{nameof(ServiceBusConnection)} doesn't have a valid token provider"); } - MessagingEventSource.Log.SubscriptionClientCreateStop(serviceBusConnection.Endpoint.Authority, topicPath, subscriptionName, this.ClientId); + MessagingEventSource.Log.SubscriptionClientCreateStop(serviceBusConnection.Endpoint.Authority, topicPath, subscriptionName, ClientId); } /// @@ -182,8 +182,8 @@ public SubscriptionClient(ServiceBusConnection serviceBusConnection, string topi /// public override TimeSpan OperationTimeout { - get => this.ServiceBusConnection.OperationTimeout; - set => this.ServiceBusConnection.OperationTimeout = value; + get => ServiceBusConnection.OperationTimeout; + set => ServiceBusConnection.OperationTimeout = value; } /// @@ -207,21 +207,21 @@ public override TimeSpan OperationTimeout /// public int PrefetchCount { - get => this.prefetchCount; + get => prefetchCount; set { if (value < 0) { - throw Fx.Exception.ArgumentOutOfRange(nameof(this.PrefetchCount), value, "Value cannot be less than 0."); + throw Fx.Exception.ArgumentOutOfRange(nameof(PrefetchCount), value, "Value cannot be less than 0."); } - this.prefetchCount = value; - if (this.innerSubscriptionClient != null) + prefetchCount = value; + if (innerSubscriptionClient != null) { - this.innerSubscriptionClient.PrefetchCount = value; + innerSubscriptionClient.PrefetchCount = value; } - if (this.sessionClient != null) + if (sessionClient != null) { - this.sessionClient.PrefetchCount = value; + sessionClient.PrefetchCount = value; } } } @@ -235,21 +235,21 @@ internal IInnerSubscriptionClient InnerSubscriptionClient { get { - if (this.innerSubscriptionClient == null) + if (innerSubscriptionClient == null) { - lock (this.syncLock) + lock (syncLock) { - this.innerSubscriptionClient = new AmqpSubscriptionClient( - this.Path, - this.ServiceBusConnection, - this.RetryPolicy, - this.CbsTokenProvider, - this.PrefetchCount, - this.ReceiveMode); + innerSubscriptionClient = new AmqpSubscriptionClient( + Path, + ServiceBusConnection, + RetryPolicy, + CbsTokenProvider, + PrefetchCount, + ReceiveMode); } } - return this.innerSubscriptionClient; + return innerSubscriptionClient; } } @@ -257,27 +257,27 @@ internal SessionClient SessionClient { get { - if (this.sessionClient == null) + if (sessionClient == null) { - lock (this.syncLock) + lock (syncLock) { - if (this.sessionClient == null) + if (sessionClient == null) { - this.sessionClient = new SessionClient( - this.ClientId, - this.Path, + sessionClient = new SessionClient( + ClientId, + Path, MessagingEntityType.Subscriber, - this.ReceiveMode, - this.PrefetchCount, - this.ServiceBusConnection, - this.CbsTokenProvider, - this.RetryPolicy, - this.RegisteredPlugins); + ReceiveMode, + PrefetchCount, + ServiceBusConnection, + CbsTokenProvider, + RetryPolicy, + RegisteredPlugins); } } } - return this.sessionClient; + return sessionClient; } } @@ -285,22 +285,22 @@ internal SessionPumpHost SessionPumpHost { get { - if (this.sessionPumpHost == null) + if (sessionPumpHost == null) { - lock (this.syncLock) + lock (syncLock) { - if (this.sessionPumpHost == null) + if (sessionPumpHost == null) { - this.sessionPumpHost = new SessionPumpHost( - this.ClientId, - this.ReceiveMode, - this.SessionClient, - this.ServiceBusConnection.Endpoint); + sessionPumpHost = new SessionPumpHost( + ClientId, + ReceiveMode, + SessionClient, + ServiceBusConnection.Endpoint); } } } - return this.sessionPumpHost; + return sessionPumpHost; } } @@ -317,8 +317,8 @@ internal SessionPumpHost SessionPumpHost /// public Task CompleteAsync(string lockToken) { - this.ThrowIfClosed(); - return this.InnerSubscriptionClient.InnerReceiver.CompleteAsync(lockToken); + ThrowIfClosed(); + return InnerSubscriptionClient.InnerReceiver.CompleteAsync(lockToken); } /// @@ -333,8 +333,8 @@ public Task CompleteAsync(string lockToken) /// public Task AbandonAsync(string lockToken, IDictionary propertiesToModify = null) { - this.ThrowIfClosed(); - return this.InnerSubscriptionClient.InnerReceiver.AbandonAsync(lockToken, propertiesToModify); + ThrowIfClosed(); + return InnerSubscriptionClient.InnerReceiver.AbandonAsync(lockToken, propertiesToModify); } /// @@ -350,8 +350,8 @@ public Task AbandonAsync(string lockToken, IDictionary propertie /// public Task DeadLetterAsync(string lockToken) { - this.ThrowIfClosed(); - return this.InnerSubscriptionClient.InnerReceiver.DeadLetterAsync(lockToken); + ThrowIfClosed(); + return InnerSubscriptionClient.InnerReceiver.DeadLetterAsync(lockToken); } /// @@ -368,8 +368,8 @@ public Task DeadLetterAsync(string lockToken) /// public Task DeadLetterAsync(string lockToken, IDictionary propertiesToModify) { - this.ThrowIfClosed(); - return this.InnerSubscriptionClient.InnerReceiver.DeadLetterAsync(lockToken, propertiesToModify); + ThrowIfClosed(); + return InnerSubscriptionClient.InnerReceiver.DeadLetterAsync(lockToken, propertiesToModify); } /// @@ -387,8 +387,8 @@ public Task DeadLetterAsync(string lockToken, IDictionary proper /// public Task DeadLetterAsync(string lockToken, string deadLetterReason, string deadLetterErrorDescription = null) { - this.ThrowIfClosed(); - return this.InnerSubscriptionClient.InnerReceiver.DeadLetterAsync(lockToken, deadLetterReason, deadLetterErrorDescription); + ThrowIfClosed(); + return InnerSubscriptionClient.InnerReceiver.DeadLetterAsync(lockToken, deadLetterReason, deadLetterErrorDescription); } /// @@ -402,8 +402,8 @@ public Task DeadLetterAsync(string lockToken, string deadLetterReason, string de /// Use to configure the settings of the pump. public void RegisterMessageHandler(Func handler, Func exceptionReceivedHandler) { - this.ThrowIfClosed(); - this.InnerSubscriptionClient.InnerReceiver.RegisterMessageHandler(handler, exceptionReceivedHandler); + ThrowIfClosed(); + InnerSubscriptionClient.InnerReceiver.RegisterMessageHandler(handler, exceptionReceivedHandler); } /// @@ -415,8 +415,8 @@ public void RegisterMessageHandler(Func handle /// Enable prefetch to speed up the receive rate. public void RegisterMessageHandler(Func handler, MessageHandlerOptions messageHandlerOptions) { - this.ThrowIfClosed(); - this.InnerSubscriptionClient.InnerReceiver.RegisterMessageHandler(handler, messageHandlerOptions); + ThrowIfClosed(); + InnerSubscriptionClient.InnerReceiver.RegisterMessageHandler(handler, messageHandlerOptions); } /// @@ -432,7 +432,7 @@ public void RegisterMessageHandler(Func handle public void RegisterSessionHandler(Func handler, Func exceptionReceivedHandler) { var sessionHandlerOptions = new SessionHandlerOptions(exceptionReceivedHandler); - this.RegisterSessionHandler(handler, sessionHandlerOptions); + RegisterSessionHandler(handler, sessionHandlerOptions); } /// @@ -445,8 +445,8 @@ public void RegisterSessionHandler(FuncEnable prefetch to speed up the receive rate. public void RegisterSessionHandler(Func handler, SessionHandlerOptions sessionHandlerOptions) { - this.ThrowIfClosed(); - this.SessionPumpHost.OnSessionHandler(handler, sessionHandlerOptions); + ThrowIfClosed(); + SessionPumpHost.OnSessionHandler(handler, sessionHandlerOptions); } /// @@ -463,7 +463,7 @@ public void RegisterSessionHandler(Func public Task AddRuleAsync(string ruleName, Filter filter) { - return this.AddRuleAsync(new RuleDescription(name: ruleName, filter: filter)); + return AddRuleAsync(new RuleDescription(name: ruleName, filter: filter)); } /// @@ -479,7 +479,7 @@ public Task AddRuleAsync(string ruleName, Filter filter) /// public async Task AddRuleAsync(RuleDescription description) { - this.ThrowIfClosed(); + ThrowIfClosed(); if (description == null) { @@ -487,33 +487,33 @@ public async Task AddRuleAsync(RuleDescription description) } EntityNameHelper.CheckValidRuleName(description.Name); - MessagingEventSource.Log.AddRuleStart(this.ClientId, description.Name); + MessagingEventSource.Log.AddRuleStart(ClientId, description.Name); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.AddRuleStart(description) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.AddRuleStart(description) : null; Task addRuleTask = null; try { - addRuleTask = this.InnerSubscriptionClient.OnAddRuleAsync(description); + addRuleTask = InnerSubscriptionClient.OnAddRuleAsync(description); await addRuleTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.AddRuleException(this.ClientId, exception); + MessagingEventSource.Log.AddRuleException(ClientId, exception); throw; } finally { - this.diagnosticSource.AddRuleStop(activity, description, addRuleTask?.Status); + diagnosticSource.AddRuleStop(activity, description, addRuleTask?.Status); } - MessagingEventSource.Log.AddRuleStop(this.ClientId); + MessagingEventSource.Log.AddRuleStop(ClientId); } /// @@ -522,40 +522,40 @@ public async Task AddRuleAsync(RuleDescription description) /// A task instance that represents the asynchronous remove rule operation. public async Task RemoveRuleAsync(string ruleName) { - this.ThrowIfClosed(); + ThrowIfClosed(); if (string.IsNullOrWhiteSpace(ruleName)) { throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(ruleName)); } - MessagingEventSource.Log.RemoveRuleStart(this.ClientId, ruleName); + MessagingEventSource.Log.RemoveRuleStart(ClientId, ruleName); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.RemoveRuleStart(ruleName) : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.RemoveRuleStart(ruleName) : null; Task removeRuleTask = null; try { - removeRuleTask = this.InnerSubscriptionClient.OnRemoveRuleAsync(ruleName); + removeRuleTask = InnerSubscriptionClient.OnRemoveRuleAsync(ruleName); await removeRuleTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.RemoveRuleException(this.ClientId, exception); + MessagingEventSource.Log.RemoveRuleException(ClientId, exception); throw; } finally { - this.diagnosticSource.RemoveRuleStop(activity, ruleName, removeRuleTask?.Status); + diagnosticSource.RemoveRuleStop(activity, ruleName, removeRuleTask?.Status); } - MessagingEventSource.Log.RemoveRuleStop(this.ClientId); + MessagingEventSource.Log.RemoveRuleStop(ClientId); } /// @@ -563,11 +563,11 @@ public async Task RemoveRuleAsync(string ruleName) /// public async Task> GetRulesAsync() { - this.ThrowIfClosed(); + ThrowIfClosed(); - MessagingEventSource.Log.GetRulesStart(this.ClientId); + MessagingEventSource.Log.GetRulesStart(ClientId); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.GetRulesStart() : null; + Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.GetRulesStart() : null; Task> getRulesTask = null; var skip = 0; @@ -576,33 +576,33 @@ public async Task> GetRulesAsync() try { - getRulesTask = this.InnerSubscriptionClient.OnGetRulesAsync(top, skip); + getRulesTask = InnerSubscriptionClient.OnGetRulesAsync(top, skip); rules = await getRulesTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - this.diagnosticSource.ReportException(exception); + diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.GetRulesException(this.ClientId, exception); + MessagingEventSource.Log.GetRulesException(ClientId, exception); throw; } finally { - this.diagnosticSource.GetRulesStop(activity, rules, getRulesTask?.Status); + diagnosticSource.GetRulesStop(activity, rules, getRulesTask?.Status); } - MessagingEventSource.Log.GetRulesStop(this.ClientId); + MessagingEventSource.Log.GetRulesStop(ClientId); return rules; } /// /// Gets a list of currently registered plugins for this SubscriptionClient. /// - public override IList RegisteredPlugins => this.InnerSubscriptionClient.InnerReceiver.RegisteredPlugins; + public override IList RegisteredPlugins => InnerSubscriptionClient.InnerReceiver.RegisteredPlugins; /// /// Registers a to be used for receiving messages from Service Bus. @@ -610,8 +610,8 @@ public async Task> GetRulesAsync() /// The to register public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) { - this.ThrowIfClosed(); - this.InnerSubscriptionClient.InnerReceiver.RegisterPlugin(serviceBusPlugin); + ThrowIfClosed(); + InnerSubscriptionClient.InnerReceiver.RegisterPlugin(serviceBusPlugin); } /// @@ -620,22 +620,22 @@ public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) /// The name to be unregistered public override void UnregisterPlugin(string serviceBusPluginName) { - this.ThrowIfClosed(); - this.InnerSubscriptionClient.InnerReceiver.UnregisterPlugin(serviceBusPluginName); + ThrowIfClosed(); + InnerSubscriptionClient.InnerReceiver.UnregisterPlugin(serviceBusPluginName); } protected override async Task OnClosingAsync() { - if (this.innerSubscriptionClient != null) + if (innerSubscriptionClient != null) { - await this.innerSubscriptionClient.CloseAsync().ConfigureAwait(false); + await innerSubscriptionClient.CloseAsync().ConfigureAwait(false); } - this.sessionPumpHost?.Close(); + sessionPumpHost?.Close(); - if (this.sessionClient != null) + if (sessionClient != null) { - await this.sessionClient.CloseAsync().ConfigureAwait(false); + await sessionClient.CloseAsync().ConfigureAwait(false); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs index 6cc40090c1b9..d455d585ed41 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs @@ -7,8 +7,8 @@ namespace Microsoft.Azure.ServiceBus using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Azure.Amqp; - using Microsoft.Azure.ServiceBus.Core; - using Microsoft.Azure.ServiceBus.Primitives; + using Core; + using Primitives; /// /// TopicClient can be used for all basic interactions with a Service Bus topic. @@ -60,7 +60,7 @@ public TopicClient(string connectionString, string entityPath, RetryPolicy retry throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -80,7 +80,7 @@ public TopicClient( RetryPolicy retryPolicy = null) : this(new ServiceBusConnection(endpoint, transportType, retryPolicy) {TokenProvider = tokenProvider}, entityPath, retryPolicy) { - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -98,22 +98,22 @@ public TopicClient(ServiceBusConnection serviceBusConnection, string entityPath, { throw Fx.Exception.ArgumentNullOrWhiteSpace(entityPath); } - this.ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); - this.syncLock = new object(); - this.TopicName = entityPath; - this.OwnsConnection = false; - this.ServiceBusConnection.ThrowIfClosed(); + ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); + syncLock = new object(); + TopicName = entityPath; + OwnsConnection = false; + ServiceBusConnection.ThrowIfClosed(); - if (this.ServiceBusConnection.TokenProvider != null) + if (ServiceBusConnection.TokenProvider != null) { - this.CbsTokenProvider = new TokenProviderAdapter(this.ServiceBusConnection.TokenProvider, this.ServiceBusConnection.OperationTimeout); + CbsTokenProvider = new TokenProviderAdapter(ServiceBusConnection.TokenProvider, ServiceBusConnection.OperationTimeout); } else { throw new ArgumentNullException($"{nameof(ServiceBusConnection)} doesn't have a valid token provider"); } - MessagingEventSource.Log.TopicClientCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, this.ClientId); + MessagingEventSource.Log.TopicClientCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, ClientId); } /// @@ -126,14 +126,14 @@ public TopicClient(ServiceBusConnection serviceBusConnection, string entityPath, /// public override TimeSpan OperationTimeout { - get => this.ServiceBusConnection.OperationTimeout; - set => this.ServiceBusConnection.OperationTimeout = value; + get => ServiceBusConnection.OperationTimeout; + set => ServiceBusConnection.OperationTimeout = value; } /// /// Gets the name of the topic. /// - public override string Path => this.TopicName; + public override string Path => TopicName; /// /// Connection object to the service bus namespace. @@ -144,24 +144,24 @@ internal MessageSender InnerSender { get { - if (this.innerSender == null) + if (innerSender == null) { - lock (this.syncLock) + lock (syncLock) { - if (this.innerSender == null) + if (innerSender == null) { - this.innerSender = new MessageSender( - this.TopicName, + innerSender = new MessageSender( + TopicName, null, MessagingEntityType.Topic, - this.ServiceBusConnection, - this.CbsTokenProvider, - this.RetryPolicy); + ServiceBusConnection, + CbsTokenProvider, + RetryPolicy); } } } - return this.innerSender; + return innerSender; } } @@ -172,7 +172,7 @@ internal MessageSender InnerSender /// public Task SendAsync(Message message) { - return this.SendAsync(new[] { message }); + return SendAsync(new[] { message }); } /// @@ -181,8 +181,8 @@ public Task SendAsync(Message message) /// public Task SendAsync(IList messageList) { - this.ThrowIfClosed(); - return this.InnerSender.SendAsync(messageList); + ThrowIfClosed(); + return InnerSender.SendAsync(messageList); } /// @@ -193,8 +193,8 @@ public Task SendAsync(IList messageList) /// The sequence number of the message that was scheduled. public Task ScheduleMessageAsync(Message message, DateTimeOffset scheduleEnqueueTimeUtc) { - this.ThrowIfClosed(); - return this.InnerSender.ScheduleMessageAsync(message, scheduleEnqueueTimeUtc); + ThrowIfClosed(); + return InnerSender.ScheduleMessageAsync(message, scheduleEnqueueTimeUtc); } /// @@ -203,22 +203,22 @@ public Task ScheduleMessageAsync(Message message, DateTimeOffset scheduleE /// The of the message to be cancelled. public Task CancelScheduledMessageAsync(long sequenceNumber) { - this.ThrowIfClosed(); - return this.InnerSender.CancelScheduledMessageAsync(sequenceNumber); + ThrowIfClosed(); + return InnerSender.CancelScheduledMessageAsync(sequenceNumber); } /// /// Gets a list of currently registered plugins for this TopicClient. /// - public override IList RegisteredPlugins => this.InnerSender.RegisteredPlugins; + public override IList RegisteredPlugins => InnerSender.RegisteredPlugins; /// /// Registers a to be used with this topic client. /// public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) { - this.ThrowIfClosed(); - this.InnerSender.RegisterPlugin(serviceBusPlugin); + ThrowIfClosed(); + InnerSender.RegisterPlugin(serviceBusPlugin); } /// @@ -227,15 +227,15 @@ public override void RegisterPlugin(ServiceBusPlugin serviceBusPlugin) /// The name to be unregistered public override void UnregisterPlugin(string serviceBusPluginName) { - this.ThrowIfClosed(); - this.InnerSender.UnregisterPlugin(serviceBusPluginName); + ThrowIfClosed(); + InnerSender.UnregisterPlugin(serviceBusPluginName); } protected override async Task OnClosingAsync() { - if (this.innerSender != null) + if (innerSender != null) { - await this.innerSender.CloseAsync().ConfigureAwait(false); + await innerSender.CloseAsync().ConfigureAwait(false); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs index f6579f86657d..0ea6b1aaed2b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs @@ -7,7 +7,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests using System.Text; using Azure.Amqp.Framing; using Microsoft.Azure.Amqp; - using Microsoft.Azure.ServiceBus.Amqp; + using Amqp; using InteropExtensions; using Xunit; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs index 904a83616b4f..ba569fedeb47 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs @@ -33,7 +33,7 @@ protected FakeDiagnosticListener CreateEventListener(string entityName, Concurre // If an entity name was provided, log those payloads where the target is explicitly not associated with the entity. if (!String.IsNullOrEmpty(entityName)) { - var targetEntity = this.GetPropertyValueFromAnonymousTypeInstance(kvp.Value, "Entity", true); + var targetEntity = GetPropertyValueFromAnonymousTypeInstance(kvp.Value, "Entity", true); if (String.IsNullOrEmpty(targetEntity) || !String.Equals(targetEntity, entityName, StringComparison.InvariantCultureIgnoreCase)) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs index 09072d025927..b437dcf3e847 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs @@ -29,7 +29,7 @@ public void OnError(Exception error) public void OnNext(KeyValuePair value) { - this.writeCallback(value); + writeCallback(value); } } @@ -54,13 +54,13 @@ public void OnNext(DiagnosticListener value) { if (value.Name.Equals("Microsoft.Azure.ServiceBus")) { - this.subscription = value.Subscribe(new FakeDiagnosticSourceWriteObserver(this.writeCallback), this.IsEnabled); + subscription = value.Subscribe(new FakeDiagnosticSourceWriteObserver(writeCallback), IsEnabled); } } public void Enable() { - this.writeObserverEnabled = (name, arg1, arg2) => true; + writeObserverEnabled = (name, arg1, arg2) => true; } public void Enable(Func writeObserverEnabled) @@ -75,16 +75,16 @@ public void Enable(Func writeObserverEnabled) public void Disable() { - this.writeObserverEnabled = (name, arg1, arg2) => false; + writeObserverEnabled = (name, arg1, arg2) => false; } private bool IsEnabled(string s, object arg1, object arg2) => - this.writeObserverEnabled(s, arg1, arg2); + writeObserverEnabled(s, arg1, arg2); public void Dispose() { - this.Disable(); - this.subscription?.Dispose(); + Disable(); + subscription?.Dispose(); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs index 616065e577e3..b65438c77afd 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs @@ -20,12 +20,12 @@ public async Task SendAndHandlerFireEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Enable((name, queue, arg) => !name.Contains("Receive") && !name.Contains("Exception")); @@ -101,12 +101,12 @@ public async Task SendAndHandlerFireExceptionEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); listener.Enable((name, queue, arg) => !name.EndsWith(".Start") && !name.Contains("Receive") ); @@ -187,12 +187,12 @@ public async Task AbandonCompleteFireEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); @@ -234,12 +234,12 @@ public async Task ReceiveNoMessageFireEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Enable((name, queue, arg) => name.Contains("Send") || name.Contains("Receive")); var messages = await queueClient.InnerReceiver.ReceiveAsync(2, TimeSpan.FromSeconds(5)); @@ -273,12 +273,12 @@ public async Task BatchSendReceiveFireEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Enable( (name, queue, arg) => name.Contains("Send") || name.Contains("Receive") ); await TestUtility.SendMessagesAsync(queueClient.InnerSender, 2); @@ -333,12 +333,12 @@ public async Task PeekFireEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Enable((name, queuName, arg) => name.Contains("Send") || name.Contains("Peek")); @@ -380,12 +380,12 @@ private async Task DeadLetterFireEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); @@ -429,12 +429,12 @@ public async Task RenewLockFireEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); @@ -469,12 +469,12 @@ public async Task DeferReceiveDeferredFireEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Enable((name, queue, arg) => name.Contains("Send") || name.Contains("Defer") || name.Contains("Receive")); @@ -522,12 +522,12 @@ public async Task ScheduleAndCancelFireEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { Activity parentActivity = new Activity("test"); listener.Enable((name, queue, arg) => name.Contains("Schedule") || name.Contains("Cancel")); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs index 135f0385096f..cc20c92e26c4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs @@ -7,7 +7,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.Diagnostics using System.Diagnostics; using System.Linq; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Xunit; [Collection(nameof(DiagnosticsTests))] @@ -23,12 +23,12 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, var messageSender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); var messageSession = default(IMessageSession); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Enable(); @@ -104,7 +104,7 @@ public async Task SessionHandlerFireEvents() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, async queueName => { var timeout = TimeSpan.FromSeconds(5); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete, new NoRetry()) { @@ -113,8 +113,8 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { queueClient.ServiceBusConnection.OperationTimeout = timeout; queueClient.SessionClient.OperationTimeout = timeout; @@ -192,9 +192,9 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, protected void AssertAcceptMessageSessionStart(string entityName, string eventName, object payload, Activity activity) { Assert.Equal("Microsoft.Azure.ServiceBus.AcceptMessageSession.Start", eventName); - this.AssertCommonPayloadProperties(entityName, payload); + AssertCommonPayloadProperties(entityName, payload); - var sessionId = this.GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); + var sessionId = GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); Assert.NotNull(activity); Assert.Null(activity.Parent); @@ -204,8 +204,8 @@ protected void AssertAcceptMessageSessionStart(string entityName, string eventNa protected void AssertAcceptMessageSessionStop(string entityName, string eventName, object payload, Activity activity, Activity acceptActivity) { Assert.Equal("Microsoft.Azure.ServiceBus.AcceptMessageSession.Stop", eventName); - this.AssertCommonStopPayloadProperties(entityName, payload); - this.GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); + AssertCommonStopPayloadProperties(entityName, payload); + GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); if (acceptActivity != null) { @@ -216,9 +216,9 @@ protected void AssertAcceptMessageSessionStop(string entityName, string eventNam protected void AssertGetSessionStateStart(string entityName, string eventName, object payload, Activity activity) { Assert.Equal("Microsoft.Azure.ServiceBus.GetSessionState.Start", eventName); - this.AssertCommonPayloadProperties(entityName, payload); + AssertCommonPayloadProperties(entityName, payload); - var sessionId = this.GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); + var sessionId = GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); Assert.NotNull(activity); Assert.Null(activity.Parent); @@ -228,9 +228,9 @@ protected void AssertGetSessionStateStart(string entityName, string eventName, o protected void AssertGetSessionStateStop(string entityName, string eventName, object payload, Activity activity, Activity getStateActivity) { Assert.Equal("Microsoft.Azure.ServiceBus.GetSessionState.Stop", eventName); - this.AssertCommonStopPayloadProperties(entityName, payload); - this.GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); - this.GetPropertyValueFromAnonymousTypeInstance(payload, "State"); + AssertCommonStopPayloadProperties(entityName, payload); + GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); + GetPropertyValueFromAnonymousTypeInstance(payload, "State"); if (getStateActivity != null) { @@ -241,9 +241,9 @@ protected void AssertGetSessionStateStop(string entityName, string eventName, ob protected void AssertSetSessionStateStart(string entityName, string eventName, object payload, Activity activity) { Assert.Equal("Microsoft.Azure.ServiceBus.SetSessionState.Start", eventName); - this.AssertCommonPayloadProperties(entityName, payload); - var sessionId = this.GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); - this.GetPropertyValueFromAnonymousTypeInstance(payload, "State"); + AssertCommonPayloadProperties(entityName, payload); + var sessionId = GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); + GetPropertyValueFromAnonymousTypeInstance(payload, "State"); Assert.NotNull(activity); Assert.Null(activity.Parent); @@ -254,9 +254,9 @@ protected void AssertSetSessionStateStop(string entityName, string eventName, ob { Assert.Equal("Microsoft.Azure.ServiceBus.SetSessionState.Stop", eventName); - this.AssertCommonStopPayloadProperties(entityName, payload); - this.GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); - this.GetPropertyValueFromAnonymousTypeInstance(payload, "State"); + AssertCommonStopPayloadProperties(entityName, payload); + GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); + GetPropertyValueFromAnonymousTypeInstance(payload, "State"); if (setStateActivity != null) { @@ -267,8 +267,8 @@ protected void AssertSetSessionStateStop(string entityName, string eventName, ob protected void AssertRenewSessionLockStart(string entityName, string eventName, object payload, Activity activity, Activity parentActivity) { Assert.Equal("Microsoft.Azure.ServiceBus.RenewSessionLock.Start", eventName); - this.AssertCommonPayloadProperties(entityName, payload); - var sessionId= this.GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); + AssertCommonPayloadProperties(entityName, payload); + var sessionId= GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); Assert.NotNull(activity); Assert.Null(activity.Parent); @@ -279,8 +279,8 @@ protected void AssertRenewSessionLockStop(string entityName, string eventName, o { Assert.Equal("Microsoft.Azure.ServiceBus.RenewSessionLock.Stop", eventName); - this.AssertCommonStopPayloadProperties(entityName, payload); - this.GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); + AssertCommonStopPayloadProperties(entityName, payload); + GetPropertyValueFromAnonymousTypeInstance(payload, "SessionId"); if (renewActivity != null) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs index deb6fb589f3e..730fb7530386 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs @@ -20,13 +20,13 @@ public async Task AddRemoveGetFireEvents() await ServiceBusScope.UsingTopicAsync(partitioned: false, sessionEnabled: false, async (topicName, subscriptionName) => { var subscriptionClient = new SubscriptionClient(TestUtility.NamespaceConnectionString, topicName, subscriptionName, ReceiveMode.ReceiveAndDelete); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); var entityName = $"{topicName}/Subscriptions/{subscriptionName}"; try { - using (var listener = this.CreateEventListener(entityName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(entityName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Enable((name, queue, id) => name.Contains("Rule")); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs index 220b6e7af1cc..9dfcd3edbe22 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs @@ -6,7 +6,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests using System; using System.Text; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Xunit; public class ExpectedMessagingExceptionTests diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs index c97db0086372..04955629b7db 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.Diagnostics { using System; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Xunit; [Collection(nameof(DiagnosticsTests))] @@ -19,13 +19,13 @@ public async Task SubscriptionsEventsAreNotCapturedWhenDiagnosticsIsDisabled() await ServiceBusScope.UsingTopicAsync(partitioned: false, sessionEnabled: false, async (topicName, subscriptionName) => { var subscriptionClient = new SubscriptionClient(TestUtility.NamespaceConnectionString, topicName, subscriptionName, ReceiveMode.ReceiveAndDelete); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); var entityName = $"{topicName}/Subscriptions/{subscriptionName}"; try { - using (var listener = this.CreateEventListener(entityName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(entityName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Disable(); @@ -52,12 +52,12 @@ public async Task QueueEventsAreNotCapturedWhenDiagnosticsIsDisabled() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Disable(); @@ -95,12 +95,12 @@ public async Task QueueEventsAreNotCapturedWhenDiagnosticsWhenEntityIsExplicitly await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Enable((name, queue, arg) => queue?.ToString() != queueName); @@ -141,12 +141,12 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, var messageSender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); var messageSession = default(IMessageSession); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Disable(); @@ -185,12 +185,12 @@ public async Task QueueHandlerEventsCanBeFiltered() await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); - var eventQueue = this.CreateEventQueue(); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (var subscription = SubscribeToEvents(listener)) { listener.Enable((name, queue, arg) => !name.Contains("Send") && !name.Contains("Process") && !name.Contains("Receive") && !name.Contains("Exception")); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/DisplayTestMethodNameAttribute.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/DisplayTestMethodNameAttribute.cs index 68d20fe1356a..8aa14b916deb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/DisplayTestMethodNameAttribute.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/DisplayTestMethodNameAttribute.cs @@ -4,7 +4,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests { using System.Reflection; - using Microsoft.Extensions.PlatformAbstractions; + using Extensions.PlatformAbstractions; using Xunit.Sdk; public class DisplayTestMethodNameAttribute : BeforeAfterTestAttribute diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs index c00570ac93b1..fd4d8c9ca7e0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs @@ -8,7 +8,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.Management using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Microsoft.Azure.ServiceBus.Management; using Xunit; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/TestBook.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/TestBook.cs index 5294e5fdda2c..4346fed4b212 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/TestBook.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/TestBook.cs @@ -11,9 +11,9 @@ public TestBook() { } public TestBook(string name, int id, int count) { - this.Name = name; - this.Count = count; - this.Id = id; + Name = name; + Count = count; + Id = id; } public override bool Equals(object obj) @@ -26,9 +26,9 @@ public override bool Equals(object obj) var testBook = (TestBook)obj; return - this.Name.Equals(testBook.Name, StringComparison.OrdinalIgnoreCase) && - this.Count == testBook.Count && - this.Id == testBook.Id; + Name.Equals(testBook.Name, StringComparison.OrdinalIgnoreCase) && + Count == testBook.Count && + Id == testBook.Id; } public override int GetHashCode() diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs index 1b79ea90b71b..ac65cf839635 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs @@ -8,7 +8,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests using System.Linq; using System.Text; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Xunit; public class MessageTests diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs index ede0b52db34b..909953d16cd9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs @@ -26,7 +26,7 @@ public class OnMessageQueueTests : SenderReceiverClientTestBase [DisplayTestMethodName] public Task OnMessagePeekLockWithAutoCompleteTrue(bool partitioned, bool sessionEnabled, int maxConcurrentCalls) { - return this.OnMessageTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, true); + return OnMessageTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, true); } [Theory] @@ -35,7 +35,7 @@ public Task OnMessagePeekLockWithAutoCompleteTrue(bool partitioned, bool session [DisplayTestMethodName] public Task OnMessagePeekLockWithAutoCompleteFalse(bool partitioned, bool sessionEnabled, int maxConcurrentCalls) { - return this.OnMessageTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, false); + return OnMessageTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, false); } [Theory] @@ -44,7 +44,7 @@ public Task OnMessagePeekLockWithAutoCompleteFalse(bool partitioned, bool sessio [DisplayTestMethodName] public Task OnMessageReceiveDelete(bool partitioned, bool sessionEnabled, int maxConcurrentCalls) { - return this.OnMessageTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.ReceiveAndDelete, false); + return OnMessageTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.ReceiveAndDelete, false); } [Theory] @@ -58,7 +58,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); try { - await this.OnMessageRegistrationWithoutPendingMessagesTestCase(queueClient.InnerSender, queueClient.InnerReceiver, maxConcurrentCalls, true); + await OnMessageRegistrationWithoutPendingMessagesTestCase(queueClient.InnerSender, queueClient.InnerReceiver, maxConcurrentCalls, true); } finally { @@ -120,7 +120,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, mode); try { - await this.OnMessageAsyncTestCase( + await OnMessageAsyncTestCase( queueClient.InnerSender, queueClient.InnerReceiver, maxConcurrentCalls, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs index 251778bec6b5..87e27ea561ef 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs @@ -22,7 +22,7 @@ public class OnMessageTopicSubscriptionTests : SenderReceiverClientTestBase [DisplayTestMethodName] public Task OnMessagePeekLockWithAutoCompleteTrue(bool partitioned, bool sessionEnabled, int maxConcurrentCalls) { - return this.OnMessageTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, true); + return OnMessageTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, true); } [Theory] @@ -31,7 +31,7 @@ public Task OnMessagePeekLockWithAutoCompleteTrue(bool partitioned, bool session [DisplayTestMethodName] public Task OnMessageReceiveDelete(bool partitioned, bool sessionEnabled, int maxConcurrentCalls) { - return this.OnMessageTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.ReceiveAndDelete, false); + return OnMessageTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.ReceiveAndDelete, false); } private async Task OnMessageTestAsync(bool partitioned, bool sessionEnabled, int maxConcurrentCalls, ReceiveMode mode, bool autoComplete) @@ -49,7 +49,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { - await this.OnMessageAsyncTestCase( + await OnMessageAsyncTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, maxConcurrentCalls, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs index 42da0e7ce4c4..1e9f87906f30 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs @@ -33,7 +33,7 @@ public class OnSessionQueueTests [DisplayTestMethodName] public Task OnSessionPeekLockWithAutoCompleteTrue(bool partitioned, bool sessionEnabled, int maxConcurrentCalls) { - return this.OnSessionTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, true); + return OnSessionTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, true); } [Theory] @@ -42,7 +42,7 @@ public Task OnSessionPeekLockWithAutoCompleteTrue(bool partitioned, bool session [DisplayTestMethodName] public Task OnSessionPeekLockWithAutoCompleteFalse(bool partitioned, bool sessionEnabled, int maxConcurrentCalls) { - return this.OnSessionTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, false); + return OnSessionTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, false); } [Theory] @@ -51,7 +51,7 @@ public Task OnSessionPeekLockWithAutoCompleteFalse(bool partitioned, bool sessio [DisplayTestMethodName] public Task OnSessionReceiveDelete(bool partitioned, bool sessionEnabled, int maxConcurrentCalls) { - return this.OnSessionTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.ReceiveAndDelete, false); + return OnSessionTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.ReceiveAndDelete, false); } [Fact] diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs index 161836250b28..cbc42f7a5b61 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs @@ -26,7 +26,7 @@ public class OnSessionTopicSubscriptionTests [DisplayTestMethodName] public Task OnSessionPeekLockWithAutoCompleteTrue(bool partitioned, bool sessionEnabled, int maxConcurrentCalls) { - return this.OnSessionTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, true); + return OnSessionTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, true); } [Theory] @@ -35,7 +35,7 @@ public Task OnSessionPeekLockWithAutoCompleteTrue(bool partitioned, bool session [DisplayTestMethodName] public Task OnSessionPeekLockWithAutoCompleteFalse(bool partitioned, bool sessionEnabled, int maxConcurrentCalls) { - return this.OnSessionTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, false); + return OnSessionTestAsync(partitioned, sessionEnabled, maxConcurrentCalls, ReceiveMode.PeekLock, false); } [Fact] diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index c83252486c50..d9c22fb38059 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -3,8 +3,8 @@ namespace Microsoft.Azure.ServiceBus.Performance { - using Microsoft.Azure.ServiceBus; - using Microsoft.Azure.ServiceBus.Core; + using ServiceBus; + using Core; using System; using System.Diagnostics; using System.Threading; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/PluginTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/PluginTests.cs index 0d72210690e7..3d37a93c44cb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/PluginTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/PluginTests.cs @@ -8,7 +8,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests using System.Linq; using System.Text; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Xunit; public class PluginTests @@ -295,7 +295,7 @@ internal class SendReceivePlugin : ServiceBusPlugin public override Task BeforeMessageSend(Message message) { - this.MessageBodies.Add(message.MessageId, message.Body); + MessageBodies.Add(message.MessageId, message.Body); var clonedMessage = message.Clone(); clonedMessage.Body = null; return Task.FromResult(clonedMessage); @@ -304,7 +304,7 @@ public override Task BeforeMessageSend(Message message) public override Task AfterMessageReceive(Message message) { Assert.Null(message.Body); - message.Body = this.MessageBodies[message.MessageId]; + message.Body = MessageBodies[message.MessageId]; return Task.FromResult(message); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs index 9d3e3159b52f..7a539892e17c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs @@ -28,7 +28,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); try { - await this.PeekLockTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); + await PeekLockTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); } finally { @@ -102,7 +102,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); try { - await this.ReceiveDeleteTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); + await ReceiveDeleteTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); } finally { @@ -122,7 +122,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); try { - await this.PeekLockWithAbandonTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); + await PeekLockWithAbandonTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); } finally { @@ -147,7 +147,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { await - this.PeekLockWithDeadLetterTestCase( + PeekLockWithDeadLetterTestCase( queueClient.InnerSender, queueClient.InnerReceiver, deadLetterQueueClient.InnerReceiver, @@ -172,7 +172,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); try { - await this.RenewLockTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); + await RenewLockTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); } finally { @@ -192,7 +192,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); try { - await this.ScheduleMessagesAppearAfterScheduledTimeAsyncTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); + await ScheduleMessagesAppearAfterScheduledTimeAsyncTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); } finally { @@ -212,7 +212,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); try { - await this.CancelScheduledMessagesAsyncTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); + await CancelScheduledMessagesAsyncTestCase(queueClient.InnerSender, queueClient.InnerReceiver, messageCount); } finally { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs index 002172f78671..e04673272a9c 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs @@ -162,10 +162,10 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa TestUtility.Log($"Sent Message: {messageId2} to Session: {sessionId2}"); // Peek Message, Receive and Delete with SessionId - sessionId 1 - await this.PeekAndDeleteMessageAsync(sessionClient, sessionId1, messageId1); + await PeekAndDeleteMessageAsync(sessionClient, sessionId1, messageId1); // Peek Message, Receive and Delete with SessionId - sessionId 2 - await this.PeekAndDeleteMessageAsync(sessionClient, sessionId2, messageId2); + await PeekAndDeleteMessageAsync(sessionClient, sessionId2, messageId2); } finally { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs index 3ead6d7056f5..f48fcb32c3c9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs @@ -200,9 +200,9 @@ private sealed class ExceptionRetryData public ExceptionRetryData(Exception exception, int retryCount, bool shouldRetry) { - this.Exception = exception; - this.RetryCount = retryCount; - this.ShouldRetry = shouldRetry; + Exception = exception; + RetryCount = retryCount; + ShouldRetry = shouldRetry; } public override string ToString() => $"{ Exception }/{ RetryCount }"; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs index fe69daeb0886..5c9e734b4959 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs @@ -35,7 +35,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - await this.PeekLockTestCase(sender, receiver, messageCount); + await PeekLockTestCase(sender, receiver, messageCount); } finally { @@ -59,7 +59,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { await - this.PeekLockDeferTestCase(sender, receiver, messageCount); + PeekLockDeferTestCase(sender, receiver, messageCount); } finally { @@ -82,7 +82,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - await this.PeekAsyncTestCase(sender, receiver, messageCount); + await PeekAsyncTestCase(sender, receiver, messageCount); } finally { @@ -105,7 +105,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - await this.ReceiveShouldReturnNoLaterThanServerWaitTimeTestCase(sender, receiver, messageCount); + await ReceiveShouldReturnNoLaterThanServerWaitTimeTestCase(sender, receiver, messageCount); } finally { @@ -127,7 +127,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - await this.ReceiveShouldThrowForServerTimeoutZero(receiver); + await ReceiveShouldThrowForServerTimeoutZero(receiver); } finally { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs index 4d0eaf130d79..6566b15b04cf 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs @@ -6,7 +6,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests using System; using System.Collections.Generic; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Microsoft.Azure.ServiceBus.Management; using Microsoft.Azure.ServiceBus.Primitives; using Xunit; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs index 99b76a09c8d2..123d604154fe 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs @@ -34,17 +34,17 @@ public TestSessionHandler( this.sessionHandlerOptions = sessionHandlerOptions; this.sender = sender; this.sessionPumpHost = sessionPumpHost; - this.sessionMessageMap = new ConcurrentDictionary(); + sessionMessageMap = new ConcurrentDictionary(); } public void RegisterSessionHandler(SessionHandlerOptions handlerOptions) { - this.sessionPumpHost.OnSessionHandler(this.OnSessionHandler, this.sessionHandlerOptions); + sessionPumpHost.OnSessionHandler(OnSessionHandler, sessionHandlerOptions); } public async Task SendSessionMessages() { - await TestUtility.SendSessionMessagesAsync(this.sender, NumberOfSessions, MessagesPerSession); + await TestUtility.SendSessionMessagesAsync(sender, NumberOfSessions, MessagesPerSession); } public async Task OnSessionHandler(IMessageSession session, Message message, CancellationToken token) @@ -52,15 +52,15 @@ public async Task OnSessionHandler(IMessageSession session, Message message, Can Assert.NotNull(session); Assert.NotNull(message); - Interlocked.Increment(ref this.totalMessageCount); + Interlocked.Increment(ref totalMessageCount); TestUtility.Log($"Received Session: {session.SessionId} message: SequenceNumber: {message.SystemProperties.SequenceNumber}"); - if (this.receiveMode == ReceiveMode.PeekLock && !this.sessionHandlerOptions.AutoComplete) + if (receiveMode == ReceiveMode.PeekLock && !sessionHandlerOptions.AutoComplete) { await session.CompleteAsync(message.SystemProperties.LockToken); } - this.sessionMessageMap.AddOrUpdate(session.SessionId, 1, (_, current) => current + 1); + sessionMessageMap.AddOrUpdate(session.SessionId, 1, (_, current) => current + 1); } public async Task VerifyRun() @@ -69,27 +69,27 @@ public async Task VerifyRun() var stopwatch = Stopwatch.StartNew(); while (stopwatch.Elapsed.TotalSeconds <= 180) { - if (this.totalMessageCount == MessagesPerSession * NumberOfSessions) + if (totalMessageCount == MessagesPerSession * NumberOfSessions) { - TestUtility.Log($"All '{this.totalMessageCount}' messages Received."); + TestUtility.Log($"All '{totalMessageCount}' messages Received."); break; } await Task.Delay(TimeSpan.FromSeconds(5)); } - foreach (KeyValuePair keyValuePair in this.sessionMessageMap) + foreach (KeyValuePair keyValuePair in sessionMessageMap) { TestUtility.Log($"Session: {keyValuePair.Key}, Messages Received in this Session: {keyValuePair.Value}"); } - Assert.True(this.sessionMessageMap.Keys.Count == NumberOfSessions); - Assert.True(this.totalMessageCount == MessagesPerSession * NumberOfSessions); + Assert.True(sessionMessageMap.Keys.Count == NumberOfSessions); + Assert.True(totalMessageCount == MessagesPerSession * NumberOfSessions); } public void ClearData() { - this.totalMessageCount = 0; - this.sessionMessageMap = new ConcurrentDictionary(); + totalMessageCount = 0; + sessionMessageMap = new ConcurrentDictionary(); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs index e98ac8b54e2a..37d101438d84 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests { using System; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Microsoft.Azure.ServiceBus.Primitives; using Xunit; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs index 5326ab039aea..1d907fdad238 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs @@ -32,7 +32,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { - await this.PeekLockTestCase( + await PeekLockTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); @@ -62,7 +62,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { await - this.ReceiveDeleteTestCase( + ReceiveDeleteTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); @@ -91,7 +91,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { await - this.PeekLockWithAbandonTestCase( + PeekLockWithAbandonTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); @@ -128,7 +128,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { await - this.PeekLockWithDeadLetterTestCase( + PeekLockWithDeadLetterTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, deadLetterSubscriptionClient.InnerSubscriptionClient.InnerReceiver, @@ -158,7 +158,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN subscriptionName); try { - await this.RenewLockTestCase( + await RenewLockTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); @@ -188,7 +188,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { await - this.ScheduleMessagesAppearAfterScheduledTimeAsyncTestCase( + ScheduleMessagesAppearAfterScheduledTimeAsyncTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); @@ -218,7 +218,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { await - this.CancelScheduledMessagesAsyncTestCase( + CancelScheduledMessagesAsyncTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); From 52cb4101a1233c7aa65527e80b6e17c5b4fe0be9 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:06:18 -0400 Subject: [PATCH 02/82] Removed redundant type specifications --- .../src/Core/MessageReceiver.cs | 8 ++++---- .../Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs | 8 ++++---- .../tests/MessageInterop/MessageInteropEnd2EndTests.cs | 2 +- .../tests/OnMessageQueueTests.cs | 2 +- .../tests/OnMessageTopicSubscriptionTests.cs | 2 +- .../tests/OnSessionQueueTests.cs | 4 ++-- .../tests/OnSessionTopicSubscriptionTests.cs | 2 +- .../Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs | 2 +- .../Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs | 2 +- .../tests/SenderReceiverTests.cs | 2 +- .../tests/SubscriptionClientTests.cs | 2 +- .../Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs | 2 +- .../Microsoft.Azure.ServiceBus/tests/TransactionTests.cs | 4 ++-- 13 files changed, 21 insertions(+), 21 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index 58c2ae72e917..da1b8327a7df 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -1527,7 +1527,7 @@ async Task CreateLinkAsync(TimeSpan timeout) Path, ServiceBusConnection, endpointUri, - new string[] { endpointUri.AbsoluteUri }, + new[] { endpointUri.AbsoluteUri }, claims, CbsTokenProvider, amqpLinkSettings, @@ -1539,7 +1539,7 @@ async Task CreateLinkAsync(TimeSpan timeout) var activeSendReceiveClientLink = new ActiveSendReceiveClientLink( receivingAmqpLink, endpointUri, - new string[] { endpointUri.AbsoluteUri }, + new[] { endpointUri.AbsoluteUri }, claims, linkDetails.Item2); @@ -1565,7 +1565,7 @@ async Task CreateRequestResponseLinkAsync(TimeSpan time entityPath, ServiceBusConnection, endpointUri, - new string[] { endpointUri.AbsoluteUri }, + new[] { endpointUri.AbsoluteUri }, claims, CbsTokenProvider, amqpLinkSettings, @@ -1577,7 +1577,7 @@ async Task CreateRequestResponseLinkAsync(TimeSpan time var activeRequestResponseClientLink = new ActiveRequestResponseLink( requestResponseAmqpLink, endpointUri, - new string[] { endpointUri.AbsoluteUri }, + new[] { endpointUri.AbsoluteUri }, claims, linkDetails.Item2); clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs index 2fe3316cf66c..e53b681e8a58 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs @@ -701,12 +701,12 @@ async Task CreateLinkAsync(TimeSpan timeout) if (isViaSender) { var transferDestinationEndpointUri = new Uri(ServiceBusConnection.Endpoint, TransferDestinationPath); - audience = new string[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; + audience = new[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; amqpLinkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, TransferDestinationPath); } else { - audience = new string[] { endpointUri.AbsoluteUri }; + audience = new[] { endpointUri.AbsoluteUri }; } string[] claims = {ClaimConstants.Send}; @@ -739,12 +739,12 @@ async Task CreateRequestResponseLinkAsync(TimeSpan time if (isViaSender) { var transferDestinationEndpointUri = new Uri(ServiceBusConnection.Endpoint, TransferDestinationPath); - audience = new string[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; + audience = new[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; amqpLinkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, TransferDestinationPath); } else { - audience = new string[] { endpointUri.AbsoluteUri }; + audience = new[] { endpointUri.AbsoluteUri }; } string[] claims = { ClaimConstants.Manage, ClaimConstants.Send }; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs index 182111f0d4ac..b4dd5dc03995 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs @@ -14,7 +14,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.MessageInterop public class MessageInteropEnd2EndTests { - public static IEnumerable TestEnd2EndEntityPermutations => new object[][] + public static IEnumerable TestEnd2EndEntityPermutations => new[] { new object[] { TransportType.NetMessaging, MessageInteropEnd2EndTests.GetSbConnectionString(TransportType.NetMessaging) }, new object[] { TransportType.Amqp, MessageInteropEnd2EndTests.GetSbConnectionString(TransportType.Amqp) } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs index 909953d16cd9..c55f760a25b1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs @@ -11,7 +11,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class OnMessageQueueTests : SenderReceiverClientTestBase { - public static IEnumerable TestPermutations => new object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedQueue, useSessionQueue, maxCurrentCalls } new object[] { false, false, 1 }, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs index 87e27ea561ef..6dfd8e852fed 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs @@ -9,7 +9,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class OnMessageTopicSubscriptionTests : SenderReceiverClientTestBase { - public static IEnumerable TestPermutations => new object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedTopic, useSessionTopic, maxCurrentCalls } new object[] { false, false, 5 }, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs index 1e9f87906f30..391668caff3e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs @@ -11,7 +11,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class OnSessionQueueTests { - public static IEnumerable TestPermutations => new object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedQueue, useSessionQueue, maxCurrentCalls } new object[] { false, true, 1 }, @@ -20,7 +20,7 @@ public class OnSessionQueueTests new object[] { true, true, 5 }, }; - public static IEnumerable PartitionedNonPartitionedTestPermutations => new object[][] + public static IEnumerable PartitionedNonPartitionedTestPermutations => new[] { // Expected structure: { usePartitionedQueue, useSessionQueue, maxCurrentCalls } new object[] { false, true, 5 }, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs index cbc42f7a5b61..e1091cc0e8f0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs @@ -11,7 +11,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class OnSessionTopicSubscriptionTests { - public static IEnumerable TestPermutations => new object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedTopic, useSessionTopic, maxCurrentCalls } new object[] { false, true, 1 }, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs index 7a539892e17c..0983b8a1e788 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs @@ -10,7 +10,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public sealed class QueueClientTests : SenderReceiverClientTestBase { - public static IEnumerable TestPermutations => new object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedQueue, useSessionQueue } new object[] { false, false }, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs index e04673272a9c..b19c07ba238a 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs @@ -12,7 +12,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public sealed class QueueSessionTests { - public static IEnumerable TestPermutations => new object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedQueue, useSessionQueue } new object[] { false, true }, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs index 5c9e734b4959..8ff7778c7293 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs @@ -15,7 +15,7 @@ public class SenderReceiverTests : SenderReceiverClientTestBase { private static TimeSpan TwoSeconds = TimeSpan.FromSeconds(2); - public static IEnumerable TestPermutations => new object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedQueue, useSessionQueue } new object[] { false, false }, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SubscriptionClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SubscriptionClientTests.cs index 1baf29cdae42..2e9c748fee54 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SubscriptionClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SubscriptionClientTests.cs @@ -11,7 +11,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public sealed class SubscriptionClientTests : SenderReceiverClientTestBase { - public static IEnumerable TestPermutations => new object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedTopic, useSessionTopic } new object[] { false, false }, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs index 1d907fdad238..a0a222286fb9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs @@ -9,7 +9,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public sealed class TopicClientTests : SenderReceiverClientTestBase { - public static IEnumerable TestPermutations => new object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedTopic, useSessionTopic } new object[] { false, false }, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs index dfa87e34e344..8f493c6660ae 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs @@ -16,14 +16,14 @@ public class TransactionTests static readonly string ConnectionString = TestUtility.NamespaceConnectionString; static readonly TimeSpan ReceiveTimeout = TimeSpan.FromSeconds(5); - public static IEnumerable TestPermutations => new object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedQueue, useSessionQueue } new object[] { false, false }, new object[] { true, false } }; - public static IEnumerable SessionTestPermutations => new object[][] + public static IEnumerable SessionTestPermutations => new[] { // Expected structure: { usePartitionedQueue, useSessionQueue } new object[] { false, true }, From 505722dc8c093cb1fdcee3bd1fb3a009c0efe2b6 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:09:38 -0400 Subject: [PATCH 03/82] Adjusted namespaces to match folder structure --- .../src/Amqp/AmqpMessageConverter.cs | 2 + .../src/Amqp/AmqpSubscriptionClient.cs | 2 + .../src/Core/IInnerSubscriptionClient.cs | 2 + .../DataContractBinarySerializer.cs | 14 +- .../MessageDiagnosticsExtensions.cs | 12 +- .../Extensions/MessageInterOpExtensions.cs | 12 +- .../src/Filters/CorrelationFilter.cs | 14 +- .../Filters/CorrelationFilterExtensions.cs | 11 +- .../src/Filters/FalseFilter.cs | 2 +- .../src/Filters/Filter.cs | 8 +- .../src/Filters/FilterExtensions.cs | 12 +- .../src/Filters/RuleAction.cs | 8 +- .../src/Filters/RuleActionExtensions.cs | 13 +- .../src/Filters/RuleDescription.cs | 11 +- .../src/Filters/RuleDescriptionExtensions.cs | 16 +- .../src/Filters/SqlFilter.cs | 14 +- .../src/Filters/SqlFilterExtensions.cs | 11 +- .../src/Filters/SqlRuleAction.cs | 14 +- .../src/Filters/TrueFilter.cs | 2 +- .../src/ISubscriptionClient.cs | 2 + .../src/Management/ManagementClient.cs | 2 + .../src/Management/SubscriptionDescription.cs | 2 + .../SubscriptionDescriptionExtensions.cs | 2 + .../src/ServiceBusDiagnosticsSource.cs | 5 +- .../src/SubscriptionClient.cs | 2 + .../tests/AmqpConverterTests.cs | 4 +- .../tests/Diagnostics/DiagnosticsTests.cs | 2 + .../tests/Diagnostics/ExtractActivityTests.cs | 4 +- .../QueueClientDiagnosticsTests.cs | 2 + .../Diagnostics/SessionDiagnosticsTests.cs | 2 + .../SubscriptionClientDiagnosticsTests.cs | 3 + .../tests/ExpectedMessagingExceptionTests.cs | 2 + .../FakeDiagnosticsListenerTests.cs | 16 +- .../TaskExtensionTests.cs | 3 +- .../DisplayTestMethodNameAttribute.cs | 12 +- .../tests/Infrastructure/LiveTestAttribute.cs | 10 +- .../tests/Infrastructure/ServiceBusScope.cs | 18 +-- .../tests/Infrastructure/TaskExtensions.cs | 2 +- .../tests/Infrastructure/TestConstants.cs | 8 +- .../tests/Infrastructure/TestUtility.cs | 23 ++- .../tests/Management/ManagementClientTests.cs | 3 + .../tests/Management/QueueDescriptionTests.cs | 153 +++++++++--------- .../SubscriptionDescriptionTests.cs | 105 ++++++------ .../MessageInterop/MessageInterOpTests.cs | 4 +- .../MessageInteropEnd2EndTests.cs | 4 +- .../tests/MessageSenderTests.cs | 2 + .../tests/MessageTests.cs | 2 + .../tests/OnMessageQueueTests.cs | 2 + .../tests/OnMessageTopicSubscriptionTests.cs | 2 + .../tests/OnSessionQueueTests.cs | 2 + .../tests/OnSessionTopicSubscriptionTests.cs | 2 + .../tests/PluginTests.cs | 2 + .../tests/QueueClientTests.cs | 2 + .../tests/QueueSessionTests.cs | 2 + .../tests/RetryPolicyTests.cs | 4 +- .../tests/RetryTests.cs | 2 + .../tests/SenderReceiverClientTestBase.cs | 2 + .../tests/SenderReceiverTests.cs | 2 + .../ServiceBusConnectionStringBuilderTests.cs | 2 + .../tests/SubscriptionClientTests.cs | 3 + .../tests/TestSessionHandler.cs | 2 + .../tests/TokenProviderTests.cs | 2 + .../tests/TopicClientTests.cs | 2 + .../tests/TransactionTests.cs | 2 + .../tests/WebSocketsEnd2EndTests.cs | 2 + 65 files changed, 350 insertions(+), 268 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index bd879bad88ae..c52ffb6d5545 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; + namespace Microsoft.Azure.ServiceBus.Amqp { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs index 6d53599e874d..f6475f9e5cb1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; + namespace Microsoft.Azure.ServiceBus.Amqp { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/IInnerSubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/IInnerSubscriptionClient.cs index 0dc3e0d3be6e..662d13c23b01 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/IInnerSubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/IInnerSubscriptionClient.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; + namespace Microsoft.Azure.ServiceBus.Core { using System.Collections.Generic; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs index f8eb32c098d6..18528debf976 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs @@ -1,14 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus.InteropExtensions -{ - using System; - using System.IO; - using System.Runtime.Serialization; - using System.Xml; +using System; +using System.IO; +using System.Runtime.Serialization; +using System.Xml; - /// +namespace Microsoft.Azure.ServiceBus.Extensions +{ + /// /// This class describes a serializer class used to serialize and deserialize an Object. /// This class is almost identical to DataContractSerializer; only difference is that /// ReadObject(Stream) and WriteObject(Stream, object) pick Binary Xml Reader/Writer diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageDiagnosticsExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageDiagnosticsExtensions.cs index a7547c2641f0..951fd8c2247e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageDiagnosticsExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageDiagnosticsExtensions.cs @@ -1,13 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus.Diagnostics -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; +using System; +using System.Collections.Generic; +using System.Diagnostics; - public static class MessageExtensions +namespace Microsoft.Azure.ServiceBus.Extensions +{ + public static class MessageExtensions { /// /// Creates based on the tracing context stored in the diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageInterOpExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageInterOpExtensions.cs index d2f2de2d3b9b..dd89af7d8a02 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageInterOpExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageInterOpExtensions.cs @@ -1,13 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus.InteropExtensions -{ - using System; - using System.IO; - using System.Runtime.Serialization; +using System; +using System.IO; +using System.Runtime.Serialization; - /// +namespace Microsoft.Azure.ServiceBus.Extensions +{ + /// /// A Message Extension Class that provides extension methods to deserialize /// the body of a message that was serialized and sent to ServiceBus Queue/Topic /// using the WindowsAzure.Messaging client library. The WindowsAzure.Messaging diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs index 00a50bf25143..9c078a17c01d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs @@ -1,14 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System; - using System.Collections.Generic; - using System.Text; - using Primitives; +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.Azure.ServiceBus.Primitives; - /// +namespace Microsoft.Azure.ServiceBus.Filters +{ + /// /// Represents the correlation filter expression. /// /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs index dc68e3d98302..cf922fe8f0eb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs @@ -1,13 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System.Xml.Linq; - using Filters; - using Management; +using System.Xml.Linq; +using Microsoft.Azure.ServiceBus.Management; - internal static class CorrelationFilterExtensions +namespace Microsoft.Azure.ServiceBus.Filters +{ + internal static class CorrelationFilterExtensions { public static Filter ParseFromXElement(XElement xElement) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FalseFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FalseFilter.cs index 5ef3c5bf7e82..d4b01b6a9742 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FalseFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FalseFilter.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus +namespace Microsoft.Azure.ServiceBus.Filters { /// /// Matches none the messages arriving to be selected for the subscription. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/Filter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/Filter.cs index 2fdbd33657bc..a3863d5238ca 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/Filter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/Filter.cs @@ -1,11 +1,11 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System; +using System; - /// +namespace Microsoft.Azure.ServiceBus.Filters +{ + /// /// Describes a filter expression that is evaluated against a Message. /// /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FilterExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FilterExtensions.cs index c3de4a7792e9..c79bf7c145b0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FilterExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/FilterExtensions.cs @@ -1,13 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System; - using System.Xml.Linq; - using Management; +using System; +using System.Xml.Linq; +using Microsoft.Azure.ServiceBus.Management; - internal static class FilterExtensions +namespace Microsoft.Azure.ServiceBus.Filters +{ + internal static class FilterExtensions { public static Filter ParseFromXElement(XElement xElement) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleAction.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleAction.cs index a3bcdf265cc6..852fd9aa9af1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleAction.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleAction.cs @@ -1,11 +1,11 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System; +using System; - /// +namespace Microsoft.Azure.ServiceBus.Filters +{ + /// /// Represents the filter actions which are allowed for the transformation /// of a message that have been matched by a filter expression. /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs index edf81f615d5e..04a2d859caed 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs @@ -1,14 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System; - using System.Xml.Linq; - using Filters; - using Management; +using System; +using System.Xml.Linq; +using Microsoft.Azure.ServiceBus.Management; - internal static class RuleActionExtensions +namespace Microsoft.Azure.ServiceBus.Filters +{ + internal static class RuleActionExtensions { internal static RuleAction ParseFromXElement(XElement xElement) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs index 007dd977fcb2..112182d7c071 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs @@ -1,13 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System; - using Management; - using Primitives; +using System; +using Microsoft.Azure.ServiceBus.Primitives; - /// +namespace Microsoft.Azure.ServiceBus.Filters +{ + /// /// Represents a description of a rule. /// public sealed class RuleDescription : IEquatable diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs index bf926084f17b..b3100633cdca 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs @@ -1,15 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System; - using System.Collections.Generic; - using System.Xml.Linq; - using Management; - using Primitives; +using System; +using System.Collections.Generic; +using System.Xml.Linq; +using Microsoft.Azure.ServiceBus.Management; +using Microsoft.Azure.ServiceBus.Primitives; - internal static class RuleDescriptionExtensions +namespace Microsoft.Azure.ServiceBus.Filters +{ + internal static class RuleDescriptionExtensions { public static void ValidateDescriptionName(this RuleDescription description) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs index 8d995e89e131..52d34031fb37 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs @@ -1,14 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System; - using System.Collections.Generic; - using System.Globalization; - using Primitives; +using System; +using System.Collections.Generic; +using System.Globalization; +using Microsoft.Azure.ServiceBus.Primitives; - /// +namespace Microsoft.Azure.ServiceBus.Filters +{ + /// /// Represents a filter which is a composition of an expression and an action that is executed in the pub/sub pipeline. /// /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs index 061b0ec424e1..7ed688c65e03 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs @@ -1,13 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System.Xml.Linq; - using Filters; - using Management; +using System.Xml.Linq; +using Microsoft.Azure.ServiceBus.Management; - internal static class SqlFilterExtensions +namespace Microsoft.Azure.ServiceBus.Filters +{ + internal static class SqlFilterExtensions { public static Filter ParseFromXElement(XElement xElement) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs index 88aadf5ef3ea..0e5d349f6eb1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs @@ -1,14 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus -{ - using System; - using System.Collections.Generic; - using System.Globalization; - using Primitives; +using System; +using System.Collections.Generic; +using System.Globalization; +using Microsoft.Azure.ServiceBus.Primitives; - /// +namespace Microsoft.Azure.ServiceBus.Filters +{ + /// /// Represents set of actions written in SQL language-based syntax that is performed against a . /// public sealed class SqlRuleAction : RuleAction diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/TrueFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/TrueFilter.cs index 6ed5c1b3ae62..ad1287ed5151 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/TrueFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/TrueFilter.cs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus +namespace Microsoft.Azure.ServiceBus.Filters { /// /// Matches all the messages arriving to be selected for the subscription. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ISubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ISubscriptionClient.cs index 0e12e751e958..f6134b8526bf 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ISubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ISubscriptionClient.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; + namespace Microsoft.Azure.ServiceBus { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs index dab05a16af2f..fc8e09e3d3b0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; + namespace Microsoft.Azure.ServiceBus.Management { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs index 77dc77bd0b21..bb74cae986c9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; + namespace Microsoft.Azure.ServiceBus.Management { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescriptionExtensions.cs index 40ac2ad514cc..6ae39b63a05b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescriptionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescriptionExtensions.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; + namespace Microsoft.Azure.ServiceBus.Management { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs index cf4c90a26340..9154f6912c48 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Extensions; +using Microsoft.Azure.ServiceBus.Filters; + namespace Microsoft.Azure.ServiceBus { using System; @@ -9,8 +12,6 @@ namespace Microsoft.Azure.ServiceBus using System.Linq; using System.Threading.Tasks; - using Diagnostics; - internal class ServiceBusDiagnosticSource { public const string DiagnosticListenerName = "Microsoft.Azure.ServiceBus"; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs index 7ffb31b64eb0..92405c2272e0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; + namespace Microsoft.Azure.ServiceBus { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs index 0ea6b1aaed2b..c2be374b8913 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Extensions; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; @@ -8,7 +11,6 @@ namespace Microsoft.Azure.ServiceBus.UnitTests using Azure.Amqp.Framing; using Microsoft.Azure.Amqp; using Amqp; - using InteropExtensions; using Xunit; public class AmqpConverterTests diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs index ba569fedeb47..938ef63d67d8 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests.Diagnostics { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs index 931346e02833..2ac749273eab 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs @@ -1,10 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Extensions; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests.Diagnostics { using System.Linq; - using Microsoft.Azure.ServiceBus.Diagnostics; using Xunit; public class ExtractActivityTests diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs index b65438c77afd..f802fd9b7527 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests.Diagnostics { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs index cc20c92e26c4..a9dcebfe65f5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests.Diagnostics { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs index 730fb7530386..34cdac8a4491 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests.Diagnostics { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs index 9dfcd3edbe22..83c77bd9b78b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs index 04955629b7db..b10e0e2e9aa6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs @@ -1,14 +1,16 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus.UnitTests.Diagnostics +using System; +using System.Threading.Tasks; +using Microsoft.Azure.ServiceBus.Core; +using Microsoft.Azure.ServiceBus.Filters; +using Microsoft.Azure.ServiceBus.UnitTests.Diagnostics; +using Xunit; + +namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure.Tests { - using System; - using System.Threading.Tasks; - using Core; - using Xunit; - - [Collection(nameof(DiagnosticsTests))] + [Collection(nameof(DiagnosticsTests))] public class FakeDiagnosticsListenerTests : DiagnosticsTests { [Fact] diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/TaskExtensionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/TaskExtensionTests.cs index 86fb0d0e0145..bda95c1b4b96 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/TaskExtensionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/TaskExtensionTests.cs @@ -1,10 +1,9 @@ using System; -using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Xunit; -namespace Microsoft.Azure.ServiceBus.UnitTests +namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure.Tests { public class TaskExtensionsTests { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/DisplayTestMethodNameAttribute.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/DisplayTestMethodNameAttribute.cs index 8aa14b916deb..faf15badc4c1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/DisplayTestMethodNameAttribute.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/DisplayTestMethodNameAttribute.cs @@ -1,13 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus.UnitTests -{ - using System.Reflection; - using Extensions.PlatformAbstractions; - using Xunit.Sdk; +using System.Reflection; +using Microsoft.Extensions.PlatformAbstractions; +using Xunit.Sdk; - public class DisplayTestMethodNameAttribute : BeforeAfterTestAttribute +namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure +{ + public class DisplayTestMethodNameAttribute : BeforeAfterTestAttribute { public override void Before(MethodInfo methodUnderTest) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs index 5a9d00baa921..4f4051ee972d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs @@ -1,12 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information -namespace Microsoft.Azure.ServiceBus.UnitTests -{ - using System; - using Xunit.Sdk; +using System; +using Xunit.Sdk; - [TraitDiscoverer("Xunit.Sdk.TraitDiscoverer", "xunit.core")] +namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure +{ + [TraitDiscoverer("Xunit.Sdk.TraitDiscoverer", "xunit.core")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] public class LiveTestAttribute : Attribute, ITraitAttribute { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs index 5811a54e30b7..45de9abb0fd5 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs @@ -1,16 +1,16 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus.UnitTests +using System; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Azure.ServiceBus.Management; +using Polly; + +namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure { - using System; - using System.Runtime.CompilerServices; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Management; - using Polly; - - internal static class ServiceBusScope + internal static class ServiceBusScope { private static int randomSeed = Environment.TickCount; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TaskExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TaskExtensions.cs index cc1a59af184f..439369e59284 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TaskExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TaskExtensions.cs @@ -3,7 +3,7 @@ using System.Threading; using System.Threading.Tasks; -namespace Microsoft.Azure.ServiceBus.UnitTests +namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure { /// /// The set of extension methods for the class. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestConstants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestConstants.cs index 53bffb28ac92..250c4dfee52b 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestConstants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestConstants.cs @@ -1,11 +1,11 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus.UnitTests -{ - using System; +using System; - static class TestConstants +namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure +{ + static class TestConstants { // Enviornment Variables internal const string ConnectionStringEnvironmentVariable = "SERVICE_BUS_CONNECTION_STRING"; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestUtility.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestUtility.cs index fe7f2a41231d..a9b98649931c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestUtility.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestUtility.cs @@ -1,19 +1,18 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus.UnitTests +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Azure.ServiceBus.Core; + +namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Linq; - using System.Text; - using System.Threading; - using System.Threading.Tasks; - using Core; - using Polly; - - static class TestUtility + static class TestUtility { private static readonly Lazy NamespaceConnectionStringInstance = new Lazy( () => new ServiceBusConnectionStringBuilder(ReadEnvironmentConnectionString()).ToString(), LazyThreadSafetyMode.PublicationOnly); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs index fd4d8c9ca7e0..7676b58e33ba 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests.Management { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/QueueDescriptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/QueueDescriptionTests.cs index 730b3a9910e7..e84a521a0384 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/QueueDescriptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/QueueDescriptionTests.cs @@ -1,92 +1,95 @@ using System; using System.Linq; using Microsoft.Azure.ServiceBus.Management; -using Microsoft.Azure.ServiceBus.UnitTests; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; using Xunit; -public class QueueDescriptionTests -{ - [Theory] - [InlineData("sb://fakepath/", 261)] - [InlineData("", 261)] - [DisplayTestMethodName] - public void ForwardToThrowsArgumentOutOfRangeException(string baseUrl, int lengthOfName) - { - var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); - var sub = new QueueDescription("Fake SubscriptionName"); +namespace Microsoft.Azure.ServiceBus.UnitTests.Management +{ + public class QueueDescriptionTests + { + [Theory] + [InlineData("sb://fakepath/", 261)] + [InlineData("", 261)] + [DisplayTestMethodName] + public void ForwardToThrowsArgumentOutOfRangeException(string baseUrl, int lengthOfName) + { + var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); + var sub = new QueueDescription("Fake SubscriptionName"); - var ex = Assert.Throws(() => sub.ForwardTo = $"{baseUrl}{longName}"); + var ex = Assert.Throws(() => sub.ForwardTo = $"{baseUrl}{longName}"); - Assert.StartsWith($"Entity path '{longName}' exceeds the '260' character limit.", ex.Message); - Assert.Equal($"ForwardTo", ex.ParamName); - } + Assert.StartsWith($"Entity path '{longName}' exceeds the '260' character limit.", ex.Message); + Assert.Equal($"ForwardTo", ex.ParamName); + } - [Theory] - [InlineData("sb://fakepath/", 261)] - [InlineData("", 261)] - [DisplayTestMethodName] - public void ForwardDeadLetteredMessagesToThrowsArgumentOutOfRangeException(string baseUrl, int lengthOfName) - { - var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); - var sub = new QueueDescription("Fake SubscriptionName"); + [Theory] + [InlineData("sb://fakepath/", 261)] + [InlineData("", 261)] + [DisplayTestMethodName] + public void ForwardDeadLetteredMessagesToThrowsArgumentOutOfRangeException(string baseUrl, int lengthOfName) + { + var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); + var sub = new QueueDescription("Fake SubscriptionName"); - var ex = Assert.Throws(() => sub.ForwardDeadLetteredMessagesTo = $"{baseUrl}{longName}"); + var ex = Assert.Throws(() => sub.ForwardDeadLetteredMessagesTo = $"{baseUrl}{longName}"); - Assert.StartsWith($"Entity path '{longName}' exceeds the '260' character limit.", ex.Message); - Assert.Equal($"ForwardDeadLetteredMessagesTo", ex.ParamName); - } + Assert.StartsWith($"Entity path '{longName}' exceeds the '260' character limit.", ex.Message); + Assert.Equal($"ForwardDeadLetteredMessagesTo", ex.ParamName); + } - [Theory] - [InlineData("sb://fakepath/", 261)] - [InlineData("", 261)] - [DisplayTestMethodName] - public void PathToThrowsArgumentOutOfRangeException(string baseUrl, int lengthOfName) - { - var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); - var sub = new QueueDescription("Fake SubscriptionName"); + [Theory] + [InlineData("sb://fakepath/", 261)] + [InlineData("", 261)] + [DisplayTestMethodName] + public void PathToThrowsArgumentOutOfRangeException(string baseUrl, int lengthOfName) + { + var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); + var sub = new QueueDescription("Fake SubscriptionName"); - var ex = Assert.Throws(() => sub.Path = $"{baseUrl}{longName}"); + var ex = Assert.Throws(() => sub.Path = $"{baseUrl}{longName}"); - Assert.StartsWith($"Entity path '{longName}' exceeds the '260' character limit.", ex.Message); - Assert.Equal($"Path", ex.ParamName); - } + Assert.StartsWith($"Entity path '{longName}' exceeds the '260' character limit.", ex.Message); + Assert.Equal($"Path", ex.ParamName); + } - [Theory] - [InlineData("sb://fakepath/", 260)] - [InlineData("sb://fakepath//", 260)] - [InlineData("", 260)] - [DisplayTestMethodName] - public void ForwardToAllowsMaxLengthMinusBaseUrl(string baseUrl, int lengthOfName) - { - var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); - var sub = new QueueDescription("Fake SubscriptionName"); - sub.ForwardTo = $"{baseUrl}{longName}"; - Assert.Equal($"{baseUrl}{longName}", sub.ForwardTo); - } + [Theory] + [InlineData("sb://fakepath/", 260)] + [InlineData("sb://fakepath//", 260)] + [InlineData("", 260)] + [DisplayTestMethodName] + public void ForwardToAllowsMaxLengthMinusBaseUrl(string baseUrl, int lengthOfName) + { + var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); + var sub = new QueueDescription("Fake SubscriptionName"); + sub.ForwardTo = $"{baseUrl}{longName}"; + Assert.Equal($"{baseUrl}{longName}", sub.ForwardTo); + } - [Theory] - [InlineData("sb://fakepath/", 260)] - [InlineData("sb://fakepath//", 260)] - [InlineData("", 260)] - [DisplayTestMethodName] - public void ForwardDeadLetteredMessagesToAllowsMaxLengthMinusBaseUrl(string baseUrl, int lengthOfName) - { - var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); - var sub = new QueueDescription("Fake SubscriptionName"); - sub.ForwardDeadLetteredMessagesTo = $"{baseUrl}{longName}"; - Assert.Equal($"{baseUrl}{longName}", sub.ForwardDeadLetteredMessagesTo); - } + [Theory] + [InlineData("sb://fakepath/", 260)] + [InlineData("sb://fakepath//", 260)] + [InlineData("", 260)] + [DisplayTestMethodName] + public void ForwardDeadLetteredMessagesToAllowsMaxLengthMinusBaseUrl(string baseUrl, int lengthOfName) + { + var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); + var sub = new QueueDescription("Fake SubscriptionName"); + sub.ForwardDeadLetteredMessagesTo = $"{baseUrl}{longName}"; + Assert.Equal($"{baseUrl}{longName}", sub.ForwardDeadLetteredMessagesTo); + } - [Theory] - [InlineData("sb://fakepath/", 260)] - [InlineData("sb://fakepath//", 260)] - [InlineData("", 260)] - [DisplayTestMethodName] - public void PathAllowsMaxLengthMinusBaseUrl(string baseUrl, int lengthOfName) - { - var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); - var sub = new QueueDescription("Fake SubscriptionName"); - sub.Path = $"{baseUrl}{longName}"; - Assert.Equal($"{baseUrl}{longName}", sub.Path); - } + [Theory] + [InlineData("sb://fakepath/", 260)] + [InlineData("sb://fakepath//", 260)] + [InlineData("", 260)] + [DisplayTestMethodName] + public void PathAllowsMaxLengthMinusBaseUrl(string baseUrl, int lengthOfName) + { + var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); + var sub = new QueueDescription("Fake SubscriptionName"); + sub.Path = $"{baseUrl}{longName}"; + Assert.Equal($"{baseUrl}{longName}", sub.Path); + } + } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/SubscriptionDescriptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/SubscriptionDescriptionTests.cs index 1fc920420ad2..dff81b415c0a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/SubscriptionDescriptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/SubscriptionDescriptionTests.cs @@ -1,64 +1,67 @@ using System; using System.Linq; using Microsoft.Azure.ServiceBus.Management; -using Microsoft.Azure.ServiceBus.UnitTests; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; using Xunit; -public class SubscriptionDescriptionTests -{ - [Theory] - [InlineData("sb://fakepath/", 261)] - [InlineData("", 261)] - [DisplayTestMethodName] - public void ForwardToThrowsArgumentOutOfRangeException(string baseUrl, int lengthOfName) - { - var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); - var sub = new SubscriptionDescription("sb://fakeservicebus", "Fake SubscriptionName"); +namespace Microsoft.Azure.ServiceBus.UnitTests.Management +{ + public class SubscriptionDescriptionTests + { + [Theory] + [InlineData("sb://fakepath/", 261)] + [InlineData("", 261)] + [DisplayTestMethodName] + public void ForwardToThrowsArgumentOutOfRangeException(string baseUrl, int lengthOfName) + { + var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); + var sub = new SubscriptionDescription("sb://fakeservicebus", "Fake SubscriptionName"); - var ex = Assert.Throws(() => sub.ForwardTo = $"{baseUrl}{longName}"); + var ex = Assert.Throws(() => sub.ForwardTo = $"{baseUrl}{longName}"); - Assert.StartsWith($"Entity path '{longName}' exceeds the '260' character limit.", ex.Message); - Assert.Equal($"ForwardTo", ex.ParamName); - } + Assert.StartsWith($"Entity path '{longName}' exceeds the '260' character limit.", ex.Message); + Assert.Equal($"ForwardTo", ex.ParamName); + } - [Theory] - [InlineData("sb://fakepath/", 261)] - [InlineData("", 261)] - [DisplayTestMethodName] - public void ForwardDeadLetteredMessagesToThrowsArgumentOutOfRangeException(string baseUrl, int lengthOfName) - { - var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); - var sub = new SubscriptionDescription("sb://fakeservicebus", "Fake SubscriptionName"); + [Theory] + [InlineData("sb://fakepath/", 261)] + [InlineData("", 261)] + [DisplayTestMethodName] + public void ForwardDeadLetteredMessagesToThrowsArgumentOutOfRangeException(string baseUrl, int lengthOfName) + { + var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); + var sub = new SubscriptionDescription("sb://fakeservicebus", "Fake SubscriptionName"); - var ex = Assert.Throws(() => sub.ForwardDeadLetteredMessagesTo = $"{baseUrl}{longName}"); + var ex = Assert.Throws(() => sub.ForwardDeadLetteredMessagesTo = $"{baseUrl}{longName}"); - Assert.StartsWith($"Entity path '{longName}' exceeds the '260' character limit.", ex.Message); - Assert.Equal($"ForwardDeadLetteredMessagesTo", ex.ParamName); - } + Assert.StartsWith($"Entity path '{longName}' exceeds the '260' character limit.", ex.Message); + Assert.Equal($"ForwardDeadLetteredMessagesTo", ex.ParamName); + } - [Theory] - [InlineData("sb://fakepath/", 260)] - [InlineData("sb://fakepath//", 260)] - [InlineData("", 260)] - [DisplayTestMethodName] - public void ForwardToAllowsMaxLengthMinusBaseUrl(string baseUrl, int lengthOfName) - { - var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); - var sub = new SubscriptionDescription("sb://fakeservicebus", "Fake SubscriptionName"); - sub.ForwardTo = $"{baseUrl}{longName}"; - Assert.Equal($"{baseUrl}{longName}", sub.ForwardTo); - } + [Theory] + [InlineData("sb://fakepath/", 260)] + [InlineData("sb://fakepath//", 260)] + [InlineData("", 260)] + [DisplayTestMethodName] + public void ForwardToAllowsMaxLengthMinusBaseUrl(string baseUrl, int lengthOfName) + { + var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); + var sub = new SubscriptionDescription("sb://fakeservicebus", "Fake SubscriptionName"); + sub.ForwardTo = $"{baseUrl}{longName}"; + Assert.Equal($"{baseUrl}{longName}", sub.ForwardTo); + } - [Theory] - [InlineData("sb://fakepath/", 260)] - [InlineData("sb://fakepath//", 260)] - [InlineData("", 260)] - [DisplayTestMethodName] - public void ForwardDeadLetteredMessagesToAllowsMaxLengthMinusBaseUrl(string baseUrl, int lengthOfName) - { - var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); - var sub = new SubscriptionDescription("sb://fakeservicebus", "Fake SubscriptionName"); - sub.ForwardDeadLetteredMessagesTo = $"{baseUrl}{longName}"; - Assert.Equal($"{baseUrl}{longName}", sub.ForwardDeadLetteredMessagesTo); - } + [Theory] + [InlineData("sb://fakepath/", 260)] + [InlineData("sb://fakepath//", 260)] + [InlineData("", 260)] + [DisplayTestMethodName] + public void ForwardDeadLetteredMessagesToAllowsMaxLengthMinusBaseUrl(string baseUrl, int lengthOfName) + { + var longName = string.Join(string.Empty, Enumerable.Repeat('a', lengthOfName)); + var sub = new SubscriptionDescription("sb://fakeservicebus", "Fake SubscriptionName"); + sub.ForwardDeadLetteredMessagesTo = $"{baseUrl}{longName}"; + Assert.Equal($"{baseUrl}{longName}", sub.ForwardDeadLetteredMessagesTo); + } + } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs index 5491bc1dca58..83bee9d03570 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs @@ -1,13 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Extensions; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests.MessageInterop { using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; - using InteropExtensions; using Xunit; public class MessageInteropTests diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs index b4dd5dc03995..272c7c68689c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Extensions; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + #if FullNetFx namespace Microsoft.Azure.ServiceBus.UnitTests.MessageInterop { @@ -10,7 +13,6 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.MessageInterop using System.Text; using System.Threading.Tasks; using Xunit; - using InteropExtensions; public class MessageInteropEnd2EndTests { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageSenderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageSenderTests.cs index 0e02d4145522..67e7f3040789 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageSenderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageSenderTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using Core; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs index ac65cf839635..e884cbdd43ec 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs index c55f760a25b1..e85d966d5c1f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs index 6dfd8e852fed..a6713ec34014 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageTopicSubscriptionTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System.Collections.Generic; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs index 391668caff3e..8ad38db4cdc2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs index e1091cc0e8f0..152fb3571120 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/PluginTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/PluginTests.cs index 3d37a93c44cb..f0e422da182d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/PluginTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/PluginTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs index 0983b8a1e788..be1ffa301d8d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueClientTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System.Collections.Generic; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs index b19c07ba238a..46f7270f375f 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryPolicyTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryPolicyTests.cs index a620caa36c8a..767ec1683140 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryPolicyTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryPolicyTests.cs @@ -1,4 +1,6 @@ -namespace Microsoft.Azure.ServiceBus.UnitTests +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + +namespace Microsoft.Azure.ServiceBus.UnitTests { using System; using System.Threading.Tasks; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs index f48fcb32c3c9..cb48544183b4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverClientTestBase.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverClientTestBase.cs index 2430b0d7b18c..c2bdc45ffd5d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverClientTestBase.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverClientTestBase.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs index 8ff7778c7293..470e4dd4a474 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs index 6566b15b04cf..135d4c308d7f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SubscriptionClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SubscriptionClientTests.cs index 2e9c748fee54..01f0a565ae03 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SubscriptionClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SubscriptionClientTests.cs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Filters; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs index 123d604154fe..cf28be64ef25 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs index 37d101438d84..1af06ce88929 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs index a0a222286fb9..85fc3a6441bb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System.Collections.Generic; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs index 8f493c6660ae..dd0da9ce8599 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/WebSocketsEnd2EndTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/WebSocketsEnd2EndTests.cs index 36edb5fc4f58..c303a55490b5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/WebSocketsEnd2EndTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/WebSocketsEnd2EndTests.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; From 5b98ae77b35c9cbc7dafe7918b1692846647aab2 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:12:32 -0400 Subject: [PATCH 04/82] Added missing access modifiers --- .../src/Amqp/ActiveClientLinkManager.cs | 36 +++--- .../src/Amqp/ActiveClientLinkObject.cs | 4 +- .../src/Amqp/ActiveRequestResponseLink.cs | 2 +- .../src/Amqp/ActiveSendReceiveClientLink.cs | 2 +- .../src/Amqp/AmqpClientConstants.cs | 2 +- .../src/Amqp/AmqpConnectionHelper.cs | 2 +- .../src/Amqp/AmqpExceptionHelper.cs | 6 +- .../src/Amqp/AmqpLinkCreator.cs | 14 +-- .../src/Amqp/AmqpMessageConverter.cs | 42 +++---- .../src/Amqp/AmqpRequestMessage.cs | 4 +- .../Amqp/AmqpRequestResponseLinkCreator.cs | 2 +- .../src/Amqp/AmqpResponseMessage.cs | 4 +- .../src/Amqp/AmqpSubscriptionClient.cs | 16 +-- .../src/Amqp/AmqpTransactionEnlistment.cs | 12 +- .../src/Amqp/AmqpTransactionManager.cs | 4 +- .../Framing/AmqpCorrelationFilterCodec.cs | 6 +- .../Amqp/Framing/AmqpEmptyRuleActionCodec.cs | 4 +- .../src/Amqp/Framing/AmqpFalseFilterCodec.cs | 2 +- .../src/Amqp/Framing/AmqpFilterCodec.cs | 2 +- .../src/Amqp/Framing/AmqpRuleActionCodec.cs | 2 +- .../Amqp/Framing/AmqpRuleDescriptionCodec.cs | 4 +- .../src/Amqp/Framing/AmqpSqlFilterCodec.cs | 4 +- .../Amqp/Framing/AmqpSqlRuleActionCodec.cs | 4 +- .../src/Amqp/Framing/AmqpTrueFilterCodec.cs | 2 +- .../src/Amqp/ManagementConstants.cs | 2 +- .../src/Amqp/MappingType.cs | 2 +- .../src/Amqp/SerializationUtilities.cs | 6 +- .../src/ClientEntity.cs | 8 +- .../src/Constants.cs | 2 +- .../src/Core/MessageReceiver.cs | 56 ++++----- .../src/Core/MessageSender.cs | 38 +++--- .../DataContractBinarySerializer.cs | 4 +- .../src/Filters/CorrelationFilter.cs | 2 +- .../src/Filters/RuleActionExtensions.cs | 2 +- .../src/Filters/RuleDescription.cs | 4 +- .../src/Management/QueueDescription.cs | 14 +-- .../SharedAccessAuthorizationRule.cs | 4 +- .../src/Management/SubscriptionDescription.cs | 16 +-- .../SubscriptionDescriptionExtensions.cs | 2 +- .../src/Management/TopicDescription.cs | 6 +- .../Management/TopicRuntimeInfoExtensions.cs | 2 +- .../Microsoft.Azure.ServiceBus/src/Message.cs | 18 +-- .../src/MessageHandlerOptions.cs | 4 +- .../src/MessageReceivePump.cs | 34 +++--- .../src/MessagingEventSource.cs | 114 +++++++++--------- .../src/MessagingUtilities.cs | 2 +- .../AzureActiveDirectoryTokenProvider.cs | 6 +- .../src/Primitives/ClaimConstants.cs | 2 +- .../src/Primitives/ClientInfo.cs | 2 +- .../src/Primitives/ConcurrentExpiringSet.cs | 20 +-- .../src/Primitives/ConcurrentRandom.cs | 8 +- .../src/Primitives/DispositionStatus.cs | 2 +- .../src/Primitives/ExceptionUtility.cs | 2 +- .../src/Primitives/Fx.cs | 20 +-- .../src/Primitives/JsonSecurityToken.cs | 2 +- .../src/Primitives/PropertyDictionary.cs | 6 +- .../src/Primitives/SecurityToken.cs | 8 +- .../src/Primitives/ServiceBusUriHelper.cs | 2 +- .../Primitives/SharedAccessSignatureToken.cs | 16 +-- .../SharedAccessSignatureTokenProvider.cs | 20 +-- .../src/Primitives/StringUtility.cs | 2 +- .../src/Primitives/TaskExtensionHelper.cs | 4 +- .../src/Primitives/Ticks.cs | 2 +- .../src/Primitives/TimeoutHelper.cs | 10 +- .../src/Primitives/TokenProviderAdapter.cs | 6 +- .../src/QueueClient.cs | 16 +-- .../src/RetryPolicy.cs | 10 +- .../src/ServiceBusConnection.cs | 18 +-- .../src/ServiceBusConnectionStringBuilder.cs | 28 ++--- .../src/SessionClient.cs | 10 +- .../src/SessionHandlerOptions.cs | 6 +- .../src/SessionPumpHost.cs | 14 +-- .../src/SessionReceivePump.cs | 40 +++--- .../src/SubscriptionClient.cs | 14 +-- .../src/TopicClient.cs | 8 +- .../src/WebSocketConstants.cs | 2 +- .../tests/API/APIApprovals.cs | 4 +- .../tests/Diagnostics/ExtractActivityTests.cs | 12 +- .../tests/Infrastructure/TestConstants.cs | 2 +- .../tests/Infrastructure/TestUtility.cs | 2 +- .../tests/Performance/Program.cs | 4 +- .../tests/TestSessionHandler.cs | 18 +-- .../tests/TransactionTests.cs | 4 +- 83 files changed, 437 insertions(+), 439 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs index ca1e6ef6005c..09b6c7563954 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs @@ -9,20 +9,20 @@ namespace Microsoft.Azure.ServiceBus.Amqp using System.Threading; using System.Threading.Tasks; - sealed class ActiveClientLinkManager + internal sealed class ActiveClientLinkManager { - static readonly TimeSpan SendTokenTimeout = TimeSpan.FromMinutes(1); - static readonly TimeSpan TokenRefreshBuffer = TimeSpan.FromSeconds(10); - static readonly TimeSpan MaxTokenRefreshTime = TimeSpan.FromDays(30); + private static readonly TimeSpan SendTokenTimeout = TimeSpan.FromMinutes(1); + private static readonly TimeSpan TokenRefreshBuffer = TimeSpan.FromSeconds(10); + private static readonly TimeSpan MaxTokenRefreshTime = TimeSpan.FromDays(30); - readonly string clientId; - readonly RetryPolicy retryPolicy; - readonly ICbsTokenProvider cbsTokenProvider; - Timer sendReceiveLinkCbsTokenRenewalTimer; - Timer requestResponseLinkCbsTokenRenewalTimer; + private readonly string clientId; + private readonly RetryPolicy retryPolicy; + private readonly ICbsTokenProvider cbsTokenProvider; + private Timer sendReceiveLinkCbsTokenRenewalTimer; + private Timer requestResponseLinkCbsTokenRenewalTimer; - ActiveSendReceiveClientLink activeSendReceiveClientLink; - ActiveRequestResponseLink activeRequestResponseClientLink; + private ActiveSendReceiveClientLink activeSendReceiveClientLink; + private ActiveRequestResponseLink activeRequestResponseClientLink; public ActiveClientLinkManager(ClientEntity client, ICbsTokenProvider tokenProvider) { @@ -51,7 +51,7 @@ public void SetActiveSendReceiveLink(ActiveSendReceiveClientLink sendReceiveClie } } - void OnSendReceiveLinkClosed(object sender, EventArgs e) + private void OnSendReceiveLinkClosed(object sender, EventArgs e) { ChangeRenewTimer(activeSendReceiveClientLink, Timeout.InfiniteTimeSpan); } @@ -66,19 +66,19 @@ public void SetActiveRequestResponseLink(ActiveRequestResponseLink requestRespon } } - static async void OnRenewSendReceiveCbsToken(object state) + private static async void OnRenewSendReceiveCbsToken(object state) { var activeClientLinkManager = (ActiveClientLinkManager)state; await activeClientLinkManager.RenewCbsTokenAsync(activeClientLinkManager.activeSendReceiveClientLink).ConfigureAwait(false); } - static async void OnRenewRequestResponseCbsToken(object state) + private static async void OnRenewRequestResponseCbsToken(object state) { var activeClientLinkManager = (ActiveClientLinkManager)state; await activeClientLinkManager.RenewCbsTokenAsync(activeClientLinkManager.activeRequestResponseClientLink).ConfigureAwait(false); } - async Task RenewCbsTokenAsync(ActiveClientLinkObject activeClientLinkObject) + private async Task RenewCbsTokenAsync(ActiveClientLinkObject activeClientLinkObject) { try { @@ -118,12 +118,12 @@ await cbsLink.SendTokenAsync( } } - void OnRequestResponseLinkClosed(object sender, EventArgs e) + private void OnRequestResponseLinkClosed(object sender, EventArgs e) { ChangeRenewTimer(activeRequestResponseClientLink, Timeout.InfiniteTimeSpan); } - void SetRenewCbsTokenTimer(ActiveClientLinkObject activeClientLinkObject) + private void SetRenewCbsTokenTimer(ActiveClientLinkObject activeClientLinkObject) { var utcNow = DateTime.UtcNow; if (activeClientLinkObject.AuthorizationValidUntilUtc < utcNow) @@ -140,7 +140,7 @@ void SetRenewCbsTokenTimer(ActiveClientLinkObject activeClientLinkObject) ChangeRenewTimer(activeClientLinkObject, interval); } - void ChangeRenewTimer(ActiveClientLinkObject activeClientLinkObject, TimeSpan dueTime) + private void ChangeRenewTimer(ActiveClientLinkObject activeClientLinkObject, TimeSpan dueTime) { if (activeClientLinkObject is ActiveSendReceiveClientLink) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs index 131a38f34cd7..9f6a34c597b2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs @@ -6,9 +6,9 @@ namespace Microsoft.Azure.ServiceBus.Amqp using Microsoft.Azure.Amqp; using System; - abstract class ActiveClientLinkObject + internal abstract class ActiveClientLinkObject { - readonly string[] requiredClaims; + private readonly string[] requiredClaims; protected ActiveClientLinkObject(AmqpObject amqpLinkObject, Uri endpointUri, string[] audience, string[] requiredClaims, DateTime authorizationValidUntilUtc) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveRequestResponseLink.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveRequestResponseLink.cs index ded0ce6e8886..e8fe42f8a003 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveRequestResponseLink.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveRequestResponseLink.cs @@ -6,7 +6,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp using Microsoft.Azure.Amqp; using System; - sealed class ActiveRequestResponseLink : ActiveClientLinkObject + internal sealed class ActiveRequestResponseLink : ActiveClientLinkObject { public ActiveRequestResponseLink(RequestResponseAmqpLink link, Uri endpointUri, string[] audience, string[] requiredClaims, DateTime authorizationValidUntilUtc) : base(link, endpointUri, audience, requiredClaims, authorizationValidUntilUtc) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveSendReceiveClientLink.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveSendReceiveClientLink.cs index bc2eebce195f..655de0cf03e0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveSendReceiveClientLink.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveSendReceiveClientLink.cs @@ -6,7 +6,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp using Microsoft.Azure.Amqp; using System; - sealed class ActiveSendReceiveClientLink : ActiveClientLinkObject + internal sealed class ActiveSendReceiveClientLink : ActiveClientLinkObject { public ActiveSendReceiveClientLink(AmqpLink link, Uri endpointUri, string[] audience, string[] requiredClaims, DateTime authorizationValidUntilUtc) : base(link, endpointUri, audience, requiredClaims, authorizationValidUntilUtc) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpClientConstants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpClientConstants.cs index 9613207d76ca..582c803e37ff 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpClientConstants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpClientConstants.cs @@ -7,7 +7,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp using Microsoft.Azure.Amqp; using Microsoft.Azure.Amqp.Encoding; - class AmqpClientConstants + internal class AmqpClientConstants { // AMQP Management Operation public const string ManagementAddress = "$management"; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpConnectionHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpConnectionHelper.cs index 8552b6f74cfd..b7aea66d328e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpConnectionHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpConnectionHelper.cs @@ -12,7 +12,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal class AmqpConnectionHelper { - const string CbsSaslMechanismName = "MSSBCBS"; + private const string CbsSaslMechanismName = "MSSBCBS"; public static AmqpSettings CreateAmqpSettings( Version amqpVersion, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs index 18e16bbcb786..140438b7cdce 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs @@ -13,9 +13,9 @@ namespace Microsoft.Azure.ServiceBus.Amqp using Microsoft.Azure.Amqp.Encoding; using Microsoft.Azure.Amqp.Framing; - static class AmqpExceptionHelper + internal static class AmqpExceptionHelper { - static readonly Dictionary ConditionToStatusMap = new Dictionary + private static readonly Dictionary ConditionToStatusMap = new Dictionary { { AmqpClientConstants.TimeoutError.Value, AmqpResponseStatusCode.RequestTimeout }, { AmqpErrorCode.NotFound.Value, AmqpResponseStatusCode.NotFound }, @@ -89,7 +89,7 @@ public static Exception ToMessagingContractException(this Error error, bool conn return ToMessagingContractException(error.Condition.Value, error.Description, connectionError); } - static Exception ToMessagingContractException(string condition, string message, bool connectionError = false) + private static Exception ToMessagingContractException(string condition, string message, bool connectionError = false) { if (string.Equals(condition, AmqpClientConstants.TimeoutError.Value)) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs index dba68cbcfebe..95901a6f32e6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs @@ -11,13 +11,13 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal abstract class AmqpLinkCreator { - readonly string entityPath; - readonly ServiceBusConnection serviceBusConnection; - readonly Uri endpointAddress; - readonly string[] audience; - readonly string[] requiredClaims; - readonly ICbsTokenProvider cbsTokenProvider; - readonly AmqpLinkSettings amqpLinkSettings; + private readonly string entityPath; + private readonly ServiceBusConnection serviceBusConnection; + private readonly Uri endpointAddress; + private readonly string[] audience; + private readonly string[] requiredClaims; + private readonly ICbsTokenProvider cbsTokenProvider; + private readonly AmqpLinkSettings amqpLinkSettings; protected AmqpLinkCreator(string entityPath, ServiceBusConnection serviceBusConnection, Uri endpointAddress, string[] audience, string[] requiredClaims, ICbsTokenProvider cbsTokenProvider, AmqpLinkSettings amqpLinkSettings, string clientId) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index c52ffb6d5545..d85c09060497 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -17,22 +17,22 @@ namespace Microsoft.Azure.ServiceBus.Amqp using Primitives; using SBMessage = Message; - static class AmqpMessageConverter + internal static class AmqpMessageConverter { - const string EnqueuedTimeUtcName = "x-opt-enqueued-time"; - const string ScheduledEnqueueTimeUtcName = "x-opt-scheduled-enqueue-time"; - const string SequenceNumberName = "x-opt-sequence-number"; - const string EnqueueSequenceNumberName = "x-opt-enqueue-sequence-number"; - const string LockedUntilName = "x-opt-locked-until"; - const string PublisherName = "x-opt-publisher"; - const string PartitionKeyName = "x-opt-partition-key"; - const string PartitionIdName = "x-opt-partition-id"; - const string ViaPartitionKeyName = "x-opt-via-partition-key"; - const string DeadLetterSourceName = "x-opt-deadletter-source"; - const string TimeSpanName = AmqpConstants.Vendor + ":timespan"; - const string UriName = AmqpConstants.Vendor + ":uri"; - const string DateTimeOffsetName = AmqpConstants.Vendor + ":datetime-offset"; - const int GuidSize = 16; + private const string EnqueuedTimeUtcName = "x-opt-enqueued-time"; + private const string ScheduledEnqueueTimeUtcName = "x-opt-scheduled-enqueue-time"; + private const string SequenceNumberName = "x-opt-sequence-number"; + private const string EnqueueSequenceNumberName = "x-opt-enqueue-sequence-number"; + private const string LockedUntilName = "x-opt-locked-until"; + private const string PublisherName = "x-opt-publisher"; + private const string PartitionKeyName = "x-opt-partition-key"; + private const string PartitionIdName = "x-opt-partition-id"; + private const string ViaPartitionKeyName = "x-opt-via-partition-key"; + private const string DeadLetterSourceName = "x-opt-deadletter-source"; + private const string TimeSpanName = AmqpConstants.Vendor + ":timespan"; + private const string UriName = AmqpConstants.Vendor + ":uri"; + private const string DateTimeOffsetName = AmqpConstants.Vendor + ":datetime-offset"; + private const int GuidSize = 16; public static AmqpMessage BatchSBMessagesAsAmqpMessage(IEnumerable sbMessages) { @@ -437,7 +437,7 @@ public static Filter GetFilter(AmqpFilterCodec amqpFilter) return filter; } - static RuleAction GetRuleAction(AmqpRuleActionCodec amqpAction) + private static RuleAction GetRuleAction(AmqpRuleActionCodec amqpAction) { RuleAction action; @@ -534,7 +534,7 @@ internal static bool TryGetAmqpObjectFromNetObject(object netObject, MappingType return amqpObject != null; } - static bool TryGetNetObjectFromAmqpObject(object amqpObject, MappingType mappingType, out object netObject) + private static bool TryGetNetObjectFromAmqpObject(object amqpObject, MappingType mappingType, out object netObject) { netObject = null; if (amqpObject == null) @@ -624,7 +624,7 @@ static bool TryGetNetObjectFromAmqpObject(object amqpObject, MappingType mapping return netObject != null; } - static ArraySegment StreamToBytes(Stream stream) + private static ArraySegment StreamToBytes(Stream stream) { ArraySegment buffer; if (stream == null || stream.Length < 1) @@ -651,7 +651,7 @@ private static Data ToData(AmqpMessage message) return new Data { Value = value }; } - static AmqpMap GetSqlFilterMap(SqlFilter sqlFilter) + private static AmqpMap GetSqlFilterMap(SqlFilter sqlFilter) { var amqpFilterMap = new AmqpMap { @@ -660,7 +660,7 @@ static AmqpMap GetSqlFilterMap(SqlFilter sqlFilter) return amqpFilterMap; } - static AmqpMap GetCorrelationFilterMap(CorrelationFilter correlationFilter) + private static AmqpMap GetCorrelationFilterMap(CorrelationFilter correlationFilter) { var correlationFilterMap = new AmqpMap { @@ -685,7 +685,7 @@ static AmqpMap GetCorrelationFilterMap(CorrelationFilter correlationFilter) return correlationFilterMap; } - static AmqpMap GetRuleActionMap(SqlRuleAction sqlRuleAction) + private static AmqpMap GetRuleActionMap(SqlRuleAction sqlRuleAction) { AmqpMap ruleActionMap = null; if (sqlRuleAction != null) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs index a7f72d076417..ab9c2c95c20d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs @@ -10,9 +10,9 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal sealed class AmqpRequestMessage { - readonly AmqpMessage requestMessage; + private readonly AmqpMessage requestMessage; - AmqpRequestMessage(string operation, TimeSpan timeout, string trackingId) + private AmqpRequestMessage(string operation, TimeSpan timeout, string trackingId) { Map = new AmqpMap(); requestMessage = AmqpMessage.Create(new AmqpValue { Value = Map }); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs index 25a44b690fc5..fc9362e50969 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs @@ -9,7 +9,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal class AmqpRequestResponseLinkCreator : AmqpLinkCreator { - readonly string entityPath; + private readonly string entityPath; public AmqpRequestResponseLinkCreator(string entityPath, ServiceBusConnection serviceBusConnection, Uri endpointAddress, string[] audience, string[] requiredClaims, ICbsTokenProvider cbsTokenProvider, AmqpLinkSettings linkSettings, string clientId) : base(entityPath, serviceBusConnection, endpointAddress, audience, requiredClaims, cbsTokenProvider, linkSettings, clientId) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs index a782e06894b3..175658621d99 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs @@ -12,9 +12,9 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal sealed class AmqpResponseMessage { - readonly AmqpMessage responseMessage; + private readonly AmqpMessage responseMessage; - AmqpResponseMessage(AmqpMessage responseMessage) + private AmqpResponseMessage(AmqpMessage responseMessage) { this.responseMessage = responseMessage; StatusCode = this.responseMessage.GetResponseStatusCode(); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs index f6475f9e5cb1..0a2f7067ee97 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs @@ -16,9 +16,9 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal sealed class AmqpSubscriptionClient : IInnerSubscriptionClient { - int prefetchCount; - readonly object syncLock; - MessageReceiver innerReceiver; + private int prefetchCount; + private readonly object syncLock; + private MessageReceiver innerReceiver; static AmqpSubscriptionClient() { @@ -95,15 +95,15 @@ public int PrefetchCount } } - ServiceBusConnection ServiceBusConnection { get; } + private ServiceBusConnection ServiceBusConnection { get; } - RetryPolicy RetryPolicy { get; } + private RetryPolicy RetryPolicy { get; } - ICbsTokenProvider CbsTokenProvider { get; } + private ICbsTokenProvider CbsTokenProvider { get; } - ReceiveMode ReceiveMode { get; } + private ReceiveMode ReceiveMode { get; } - string Path { get; } + private string Path { get; } public Task CloseAsync() { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs index 55b55f3eb2ff..934c8bffbc2b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs @@ -9,11 +9,11 @@ namespace Microsoft.Azure.ServiceBus.Amqp using Microsoft.Azure.Amqp; using Primitives; - class AmqpTransactionEnlistment : Singleton, IPromotableSinglePhaseNotification + internal class AmqpTransactionEnlistment : Singleton, IPromotableSinglePhaseNotification { - readonly string transactionId; - readonly AmqpTransactionManager transactionManager; - readonly ServiceBusConnection serviceBusConnection; + private readonly string transactionId; + private readonly AmqpTransactionManager transactionManager; + private readonly ServiceBusConnection serviceBusConnection; public AmqpTransactionEnlistment( Transaction transaction, @@ -59,7 +59,7 @@ void IPromotableSinglePhaseNotification.SinglePhaseCommit(SinglePhaseEnlistment TaskExtensionHelper.Schedule(() => SinglePhaseCommitAsync(singlePhaseEnlistment)); } - async Task SinglePhaseCommitAsync(SinglePhaseEnlistment singlePhaseEnlistment) + private async Task SinglePhaseCommitAsync(SinglePhaseEnlistment singlePhaseEnlistment) { try { @@ -85,7 +85,7 @@ void IPromotableSinglePhaseNotification.Rollback(SinglePhaseEnlistment singlePha TaskExtensionHelper.Schedule(() => RollbackAsync(singlePhaseEnlistment)); } - async Task RollbackAsync(SinglePhaseEnlistment singlePhaseEnlistment) + private async Task RollbackAsync(SinglePhaseEnlistment singlePhaseEnlistment) { try { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs index ff78de04f9a4..2adab435db85 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs @@ -10,8 +10,8 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal class AmqpTransactionManager { - readonly object syncRoot = new object(); - readonly Dictionary enlistmentMap = new Dictionary(StringComparer.Ordinal); + private readonly object syncRoot = new object(); + private readonly Dictionary enlistmentMap = new Dictionary(StringComparer.Ordinal); public static AmqpTransactionManager Instance { get; } = new AmqpTransactionManager(); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs index c62fafb9b815..cd63901e04aa 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs @@ -7,13 +7,13 @@ namespace Microsoft.Azure.ServiceBus.Amqp.Framing using Azure.Amqp; using Azure.Amqp.Encoding; - sealed class AmqpCorrelationFilterCodec : AmqpFilterCodec + internal sealed class AmqpCorrelationFilterCodec : AmqpFilterCodec { public static readonly string Name = AmqpConstants.Vendor + ":correlation-filter:list"; public const ulong Code = 0x000001370000009; - const int Fields = 9; + private const int Fields = 9; - AmqpMap properties; + private AmqpMap properties; public AmqpCorrelationFilterCodec() : base(Name, Code) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpEmptyRuleActionCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpEmptyRuleActionCodec.cs index fc421f22ab04..a0d15b942702 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpEmptyRuleActionCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpEmptyRuleActionCodec.cs @@ -5,11 +5,11 @@ namespace Microsoft.Azure.ServiceBus.Amqp.Framing { using Azure.Amqp; - sealed class AmqpEmptyRuleActionCodec : AmqpRuleActionCodec + internal sealed class AmqpEmptyRuleActionCodec : AmqpRuleActionCodec { public static readonly string Name = AmqpConstants.Vendor + ":empty-rule-action:list"; public const ulong Code = 0x0000013700000005; - const int Fields = 0; + private const int Fields = 0; public AmqpEmptyRuleActionCodec() : base(Name, Code) { } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpFalseFilterCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpFalseFilterCodec.cs index 455d7f516c46..2f67d9060178 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpFalseFilterCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpFalseFilterCodec.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp.Framing { using Azure.Amqp; - sealed class AmqpFalseFilterCodec : AmqpFilterCodec + internal sealed class AmqpFalseFilterCodec : AmqpFilterCodec { public static readonly string Name = AmqpConstants.Vendor + ":false-filter:list"; public const ulong Code = 0x000001370000008; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpFilterCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpFilterCodec.cs index c2f3f7af4a98..9140a58f8610 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpFilterCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpFilterCodec.cs @@ -6,7 +6,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp.Framing using Azure.Amqp.Framing; using Azure.Amqp; - abstract class AmqpFilterCodec : DescribedList + internal abstract class AmqpFilterCodec : DescribedList { protected AmqpFilterCodec(string name, ulong code) : base(name, code) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleActionCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleActionCodec.cs index a4a6ca401e37..33430b229ad2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleActionCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleActionCodec.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp.Framing { using Azure.Amqp.Framing; - abstract class AmqpRuleActionCodec : DescribedList + internal abstract class AmqpRuleActionCodec : DescribedList { protected AmqpRuleActionCodec(string name, ulong code) : base(name, code) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleDescriptionCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleDescriptionCodec.cs index 7dee6d14f418..326e27e1ca56 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleDescriptionCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpRuleDescriptionCodec.cs @@ -7,11 +7,11 @@ namespace Microsoft.Azure.ServiceBus.Amqp.Framing using Azure.Amqp; using Azure.Amqp.Framing; - sealed class AmqpRuleDescriptionCodec : DescribedList + internal sealed class AmqpRuleDescriptionCodec : DescribedList { public static readonly string Name = AmqpConstants.Vendor + ":rule-description:list"; public const ulong Code = 0x0000013700000004; - const int Fields = 4; + private const int Fields = 4; public AmqpRuleDescriptionCodec() : base(Name, Code) { } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlFilterCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlFilterCodec.cs index fac21fb72a83..b02a88217639 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlFilterCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlFilterCodec.cs @@ -6,11 +6,11 @@ namespace Microsoft.Azure.ServiceBus.Amqp.Framing using System.Text; using Azure.Amqp; - sealed class AmqpSqlFilterCodec : AmqpFilterCodec + internal sealed class AmqpSqlFilterCodec : AmqpFilterCodec { public static readonly string Name = AmqpConstants.Vendor + ":sql-filter:list"; public const ulong Code = 0x000001370000006; - const int Fields = 2; + private const int Fields = 2; public AmqpSqlFilterCodec() : base(Name, Code) { } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlRuleActionCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlRuleActionCodec.cs index a46b47f1ed91..660df523bc40 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlRuleActionCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpSqlRuleActionCodec.cs @@ -6,11 +6,11 @@ namespace Microsoft.Azure.ServiceBus.Amqp.Framing using System.Text; using Azure.Amqp; - sealed class AmqpSqlRuleActionCodec : AmqpRuleActionCodec + internal sealed class AmqpSqlRuleActionCodec : AmqpRuleActionCodec { public static readonly string Name = AmqpConstants.Vendor + ":sql-rule-action:list"; public const ulong Code = 0x0000013700000006; - const int Fields = 2; + private const int Fields = 2; public AmqpSqlRuleActionCodec() : base(Name, Code) { } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpTrueFilterCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpTrueFilterCodec.cs index df27eb86bbac..5d62a65e5059 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpTrueFilterCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpTrueFilterCodec.cs @@ -2,7 +2,7 @@ { using Microsoft.Azure.Amqp; - sealed class AmqpTrueFilterCodec : AmqpFilterCodec + internal sealed class AmqpTrueFilterCodec : AmqpFilterCodec { public static readonly string Name = AmqpConstants.Vendor + ":true-filter:list"; public const ulong Code = 0x000001370000007; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ManagementConstants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ManagementConstants.cs index ed4c99dc4042..bb867602e206 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ManagementConstants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ManagementConstants.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp { using Microsoft.Azure.Amqp.Encoding; - static class ManagementConstants + internal static class ManagementConstants { public const string Microsoft = "com.microsoft"; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/MappingType.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/MappingType.cs index d8983ffe417a..15b0fc9b6a61 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/MappingType.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/MappingType.cs @@ -3,7 +3,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp { - enum MappingType + internal enum MappingType { ApplicationProperty, MessageBody diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/SerializationUtilities.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/SerializationUtilities.cs index 08951d39d1b0..8732ebcb7ced 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/SerializationUtilities.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/SerializationUtilities.cs @@ -9,7 +9,7 @@ namespace Microsoft.Azure.ServiceBus.Amqp // WARNING: Consult filter engine owner before modifying this enum. // Introducing a new member here has impact to filtering engine in data type precedence and data conversion. // ALWAYS insert new types before Unknown! - enum PropertyValueType + internal enum PropertyValueType { Null, Byte, SByte, Char, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, // Numeric types @@ -18,9 +18,9 @@ enum PropertyValueType Unknown, } - class SerializationUtilities + internal class SerializationUtilities { - static readonly Dictionary TypeToIntMap = new Dictionary + private static readonly Dictionary TypeToIntMap = new Dictionary { { typeof(byte), PropertyValueType.Byte }, { typeof(sbyte), PropertyValueType.SByte }, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs index 8c0d425afd22..abc2553f1eab 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs @@ -15,10 +15,10 @@ namespace Microsoft.Azure.ServiceBus /// public abstract class ClientEntity : IClientEntity { - static int nextId; - readonly string clientTypeName; - readonly object syncLock; - bool isClosedOrClosing; + private static int nextId; + private readonly string clientTypeName; + private readonly object syncLock; + private bool isClosedOrClosing; protected ClientEntity(string clientTypeName, string postfix, RetryPolicy retryPolicy) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Constants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Constants.cs index e5efe756fa5d..4b891edded0f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Constants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Constants.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus { using System; - static class Constants + internal static class Constants { public const int MaxMessageIdLength = 128; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index da1b8327a7df..3851a1d7f75f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -45,16 +45,16 @@ public class MessageReceiver : ClientEntity, IMessageReceiver { private static readonly TimeSpan DefaultBatchFlushInterval = TimeSpan.FromMilliseconds(20); - readonly ConcurrentExpiringSet requestResponseLockedMessages; - readonly bool isSessionReceiver; - readonly object messageReceivePumpSyncLock; - readonly ActiveClientLinkManager clientLinkManager; - readonly ServiceBusDiagnosticSource diagnosticSource; + private readonly ConcurrentExpiringSet requestResponseLockedMessages; + private readonly bool isSessionReceiver; + private readonly object messageReceivePumpSyncLock; + private readonly ActiveClientLinkManager clientLinkManager; + private readonly ServiceBusDiagnosticSource diagnosticSource; - int prefetchCount; - long lastPeekedSequenceNumber; - MessageReceivePump receivePump; - CancellationTokenSource receivePumpCancellationTokenSource; + private int prefetchCount; + private long lastPeekedSequenceNumber; + private MessageReceivePump receivePump; + private CancellationTokenSource receivePumpCancellationTokenSource; /// /// Creates a new MessageReceiver from a . @@ -290,13 +290,13 @@ public override TimeSpan OperationTimeout { internal MessagingEntityType? EntityType { get; } - Exception LinkException { get; set; } + private Exception LinkException { get; set; } - ICbsTokenProvider CbsTokenProvider { get; } + private ICbsTokenProvider CbsTokenProvider { get; } internal FaultTolerantAmqpObject ReceiveLinkManager { get; } - FaultTolerantAmqpObject RequestResponseLinkManager { get; } + private FaultTolerantAmqpObject RequestResponseLinkManager { get; } /// /// Receive a message from the entity defined by using mode. @@ -1305,17 +1305,17 @@ protected virtual void OnMessageHandler( MessagingEventSource.Log.RegisterOnMessageHandlerStop(ClientId); } - static void CloseSession(ReceivingAmqpLink link) + private static void CloseSession(ReceivingAmqpLink link) { link.Session.SafeClose(); } - static void CloseRequestResponseSession(RequestResponseAmqpLink requestResponseAmqpLink) + private static void CloseRequestResponseSession(RequestResponseAmqpLink requestResponseAmqpLink) { requestResponseAmqpLink.Session.SafeClose(); } - async Task ProcessMessage(Message message) + private async Task ProcessMessage(Message message) { var processedMessage = message; foreach (var plugin in RegisteredPlugins) @@ -1338,7 +1338,7 @@ async Task ProcessMessage(Message message) return processedMessage; } - async Task> ProcessMessages(IList messageList) + private async Task> ProcessMessages(IList messageList) { if (RegisteredPlugins.Count < 1) { @@ -1355,7 +1355,7 @@ async Task> ProcessMessages(IList messageList) return processedMessageList; } - async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome outcome) + private async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome outcome) { if(isSessionReceiver) { @@ -1431,7 +1431,7 @@ async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome outcome) } } - async Task DisposeMessageRequestResponseAsync(Guid[] lockTokens, DispositionStatus dispositionStatus, IDictionary propertiesToModify = null, string deadLetterReason = null, string deadLetterDescription = null) + private async Task DisposeMessageRequestResponseAsync(Guid[] lockTokens, DispositionStatus dispositionStatus, IDictionary propertiesToModify = null, string deadLetterReason = null, string deadLetterDescription = null) { try { @@ -1494,7 +1494,7 @@ async Task DisposeMessageRequestResponseAsync(Guid[] lockTokens, DispositionStat } } - async Task CreateLinkAsync(TimeSpan timeout) + private async Task CreateLinkAsync(TimeSpan timeout) { FilterSet filterMap = null; @@ -1551,7 +1551,7 @@ async Task CreateLinkAsync(TimeSpan timeout) } // TODO: Consolidate the link creation paths - async Task CreateRequestResponseLinkAsync(TimeSpan timeout) + private async Task CreateRequestResponseLinkAsync(TimeSpan timeout) { var entityPath = Path + '/' + AmqpClientConstants.ManagementAddress; @@ -1586,7 +1586,7 @@ async Task CreateRequestResponseLinkAsync(TimeSpan time return requestResponseAmqpLink; } - void OnSessionReceiverLinkClosed(object sender, EventArgs e) + private void OnSessionReceiverLinkClosed(object sender, EventArgs e) { var receivingAmqpLink = (ReceivingAmqpLink)sender; if (receivingAmqpLink != null) @@ -1602,12 +1602,12 @@ void OnSessionReceiverLinkClosed(object sender, EventArgs e) } } - List> ConvertLockTokensToDeliveryTags(IEnumerable lockTokens) + private List> ConvertLockTokensToDeliveryTags(IEnumerable lockTokens) { return lockTokens.Select(lockToken => new ArraySegment(lockToken.ToByteArray())).ToList(); } - void ThrowIfNotPeekLockMode() + private void ThrowIfNotPeekLockMode() { if (ReceiveMode != ReceiveMode.PeekLock) { @@ -1615,7 +1615,7 @@ void ThrowIfNotPeekLockMode() } } - void ThrowIfSessionLockLost() + private void ThrowIfSessionLockLost() { if (LinkException != null) { @@ -1623,17 +1623,17 @@ void ThrowIfSessionLockLost() } } - Outcome GetAbandonOutcome(IDictionary propertiesToModify) + private Outcome GetAbandonOutcome(IDictionary propertiesToModify) { return GetModifiedOutcome(propertiesToModify, false); } - Outcome GetDeferOutcome(IDictionary propertiesToModify) + private Outcome GetDeferOutcome(IDictionary propertiesToModify) { return GetModifiedOutcome(propertiesToModify, true); } - Outcome GetModifiedOutcome(IDictionary propertiesToModify, bool undeliverableHere) + private Outcome GetModifiedOutcome(IDictionary propertiesToModify, bool undeliverableHere) { Modified modified = new Modified(); if (undeliverableHere) @@ -1660,7 +1660,7 @@ Outcome GetModifiedOutcome(IDictionary propertiesToModify, bool return modified; } - Rejected GetRejectedOutcome(IDictionary propertiesToModify, string deadLetterReason, string deadLetterErrorDescription) + private Rejected GetRejectedOutcome(IDictionary propertiesToModify, string deadLetterReason, string deadLetterErrorDescription) { var rejected = AmqpConstants.RejectedOutcome; if (deadLetterReason != null || deadLetterErrorDescription != null || propertiesToModify != null) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs index e53b681e8a58..05ec467104bf 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs @@ -36,10 +36,10 @@ namespace Microsoft.Azure.ServiceBus.Core /// This uses AMQP protocol to communicate with service. public class MessageSender : ClientEntity, IMessageSender { - int deliveryCount; - readonly ActiveClientLinkManager clientLinkManager; - readonly ServiceBusDiagnosticSource diagnosticSource; - readonly bool isViaSender; + private int deliveryCount; + private readonly ActiveClientLinkManager clientLinkManager; + private readonly ServiceBusDiagnosticSource diagnosticSource; + private readonly bool isViaSender; /// /// Creates a new AMQP MessageSender. @@ -223,11 +223,11 @@ public override TimeSpan OperationTimeout internal string SendingLinkDestination { get; set; } - ICbsTokenProvider CbsTokenProvider { get; } + private ICbsTokenProvider CbsTokenProvider { get; } - FaultTolerantAmqpObject SendLinkManager { get; } + private FaultTolerantAmqpObject SendLinkManager { get; } - FaultTolerantAmqpObject RequestResponseLinkManager { get; } + private FaultTolerantAmqpObject RequestResponseLinkManager { get; } /// /// Sends a message to the entity as described by . @@ -459,7 +459,7 @@ protected override async Task OnClosingAsync() await RequestResponseLinkManager.CloseAsync().ConfigureAwait(false); } - static int ValidateMessages(IList messageList) + private static int ValidateMessages(IList messageList) { var count = 0; if (messageList == null) @@ -476,7 +476,7 @@ static int ValidateMessages(IList messageList) return count; } - static void ValidateMessage(Message message) + private static void ValidateMessage(Message message) { if (message.SystemProperties.IsLockTokenSet) { @@ -484,18 +484,18 @@ static void ValidateMessage(Message message) } } - static void CloseSession(SendingAmqpLink link) + private static void CloseSession(SendingAmqpLink link) { // Note we close the session (which includes the link). link.Session.SafeClose(); } - static void CloseRequestResponseSession(RequestResponseAmqpLink requestResponseAmqpLink) + private static void CloseRequestResponseSession(RequestResponseAmqpLink requestResponseAmqpLink) { requestResponseAmqpLink.Session.SafeClose(); } - async Task ProcessMessage(Message message) + private async Task ProcessMessage(Message message) { var processedMessage = message; foreach (var plugin in RegisteredPlugins) @@ -518,7 +518,7 @@ async Task ProcessMessage(Message message) return processedMessage; } - async Task> ProcessMessages(IList messageList) + private async Task> ProcessMessages(IList messageList) { if (RegisteredPlugins.Count < 1) { @@ -535,7 +535,7 @@ async Task> ProcessMessages(IList messageList) return processedMessageList; } - async Task OnSendAsync(IList messageList) + private async Task OnSendAsync(IList messageList) { var timeoutHelper = new TimeoutHelper(OperationTimeout, true); using (var amqpMessage = AmqpMessageConverter.BatchSBMessagesAsAmqpMessage(messageList)) @@ -578,7 +578,7 @@ async Task OnSendAsync(IList messageList) } } - async Task OnScheduleMessageAsync(Message message) + private async Task OnScheduleMessageAsync(Message message) { using (var amqpMessage = AmqpMessageConverter.SBMessageToAmqpMessage(message)) { @@ -647,7 +647,7 @@ async Task OnScheduleMessageAsync(Message message) } } - async Task OnCancelScheduledMessageAsync(long sequenceNumber) + private async Task OnCancelScheduledMessageAsync(long sequenceNumber) { var request = AmqpRequestMessage.CreateRequest( @@ -679,7 +679,7 @@ async Task OnCancelScheduledMessageAsync(long sequenceNumber) } } - async Task CreateLinkAsync(TimeSpan timeout) + private async Task CreateLinkAsync(TimeSpan timeout) { MessagingEventSource.Log.AmqpSendLinkCreateStart(ClientId, EntityType, SendingLinkDestination); @@ -727,7 +727,7 @@ async Task CreateLinkAsync(TimeSpan timeout) return sendingAmqpLink; } - async Task CreateRequestResponseLinkAsync(TimeSpan timeout) + private async Task CreateRequestResponseLinkAsync(TimeSpan timeout) { var entityPath = SendingLinkDestination + '/' + AmqpClientConstants.ManagementAddress; var amqpLinkSettings = new AmqpLinkSettings(); @@ -773,7 +773,7 @@ async Task CreateRequestResponseLinkAsync(TimeSpan time return requestResponseAmqpLink; } - ArraySegment GetNextDeliveryTag() + private ArraySegment GetNextDeliveryTag() { var deliveryId = Interlocked.Increment(ref deliveryCount); return new ArraySegment(BitConverter.GetBytes(deliveryId)); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs index 18528debf976..de802aa264d7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs @@ -14,9 +14,9 @@ namespace Microsoft.Azure.ServiceBus.Extensions /// ReadObject(Stream) and WriteObject(Stream, object) pick Binary Xml Reader/Writer /// instead of text. /// - sealed class DataContractBinarySerializer : XmlObjectSerializer + internal sealed class DataContractBinarySerializer : XmlObjectSerializer { - readonly DataContractSerializer dataContractSerializer; + private readonly DataContractSerializer dataContractSerializer; /// /// Initializes a new DataContractBinarySerializer instance diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs index 9c078a17c01d..6d12ca7e5a2a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs @@ -182,7 +182,7 @@ public override string ToString() return stringBuilder.ToString(); } - void AppendPropertyExpression(ref bool firstExpression, StringBuilder builder, string propertyName, object value) + private void AppendPropertyExpression(ref bool firstExpression, StringBuilder builder, string propertyName, object value) { if (value != null) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs index 04a2d859caed..ddd758001928 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs @@ -34,7 +34,7 @@ internal static RuleAction ParseFromXElement(XElement xElement) } - static RuleAction ParseFromXElementSqlRuleAction(XElement xElement) + private static RuleAction ParseFromXElementSqlRuleAction(XElement xElement) { var expression = xElement.Element(XName.Get("SqlExpression", ManagementClientConstants.ServiceBusNamespace))?.Value; if (string.IsNullOrWhiteSpace(expression)) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs index 112182d7c071..f4b04e783384 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs @@ -20,8 +20,8 @@ public sealed class RuleDescription : IEquatable /// public const string DefaultRuleName = "$Default"; - Filter filter; - string name; + private Filter filter; + private string name; /// /// Initializes a new instance of the class with default values. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index 9528a0944088..a23fd733346e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -14,13 +14,13 @@ public class QueueDescription : IEquatable { internal TimeSpan duplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1); internal string path; - TimeSpan lockDuration = TimeSpan.FromSeconds(60); - TimeSpan defaultMessageTimeToLive = TimeSpan.MaxValue; - TimeSpan autoDeleteOnIdle = TimeSpan.MaxValue; - int maxDeliveryCount = 10; - string forwardTo = null; - string forwardDeadLetteredMessagesTo = null; - string userMetadata = null; + private TimeSpan lockDuration = TimeSpan.FromSeconds(60); + private TimeSpan defaultMessageTimeToLive = TimeSpan.MaxValue; + private TimeSpan autoDeleteOnIdle = TimeSpan.MaxValue; + private int maxDeliveryCount = 10; + private string forwardTo = null; + private string forwardDeadLetteredMessagesTo = null; + private string userMetadata = null; /// /// Initializes a new instance of QueueDescription class with the specified relative path. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs index 92ceccd96213..e1f7d80cfc5e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs @@ -18,8 +18,8 @@ namespace Microsoft.Azure.ServiceBus.Management /// public class SharedAccessAuthorizationRule : AuthorizationRule { - const int SupportedSASKeyLength = 44; - const string FixedClaimType = "SharedAccessKey"; + private const int SupportedSASKeyLength = 44; + private const string FixedClaimType = "SharedAccessKey"; private string internalKeyName; private string internalPrimaryKey; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs index bb74cae986c9..82936d11f055 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -14,14 +14,14 @@ namespace Microsoft.Azure.ServiceBus.Management /// public class SubscriptionDescription : IEquatable { - string topicPath, subscriptionName; - TimeSpan lockDuration = TimeSpan.FromSeconds(60); - TimeSpan defaultMessageTimeToLive = TimeSpan.MaxValue; - TimeSpan autoDeleteOnIdle = TimeSpan.MaxValue; - int maxDeliveryCount = 10; - string forwardTo = null; - string forwardDeadLetteredMessagesTo = null; - string userMetadata = null; + private string topicPath, subscriptionName; + private TimeSpan lockDuration = TimeSpan.FromSeconds(60); + private TimeSpan defaultMessageTimeToLive = TimeSpan.MaxValue; + private TimeSpan autoDeleteOnIdle = TimeSpan.MaxValue; + private int maxDeliveryCount = 10; + private string forwardTo = null; + private string forwardDeadLetteredMessagesTo = null; + private string userMetadata = null; /// /// Initializes a new instance of SubscriptionDescription class with the specified name and topic path. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescriptionExtensions.cs index 6ae39b63a05b..7b9e21690724 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescriptionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescriptionExtensions.cs @@ -25,7 +25,7 @@ public static void NormalizeDescription(this SubscriptionDescription description } } - static string NormalizeForwardToAddress(string forwardTo, string baseAddress) + private static string NormalizeForwardToAddress(string forwardTo, string baseAddress) { if (!Uri.TryCreate(forwardTo, UriKind.Absolute, out var forwardToUri)) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs index 9759f71e6e98..c0b8f1b7186a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs @@ -13,9 +13,9 @@ public class TopicDescription : IEquatable { internal TimeSpan duplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1); internal string path; - TimeSpan defaultMessageTimeToLive = TimeSpan.MaxValue; - TimeSpan autoDeleteOnIdle = TimeSpan.MaxValue; - string userMetadata = null; + private TimeSpan defaultMessageTimeToLive = TimeSpan.MaxValue; + private TimeSpan autoDeleteOnIdle = TimeSpan.MaxValue; + private string userMetadata = null; /// /// Initializes a new instance of TopicDescription class with the specified relative path. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicRuntimeInfoExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicRuntimeInfoExtensions.cs index 4da9396ebeb2..cfa8ce3ad31b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicRuntimeInfoExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicRuntimeInfoExtensions.cs @@ -30,7 +30,7 @@ public static TopicRuntimeInfo ParseFromContent(string xml) throw new MessagingEntityNotFoundException("Topic was not found"); } - static TopicRuntimeInfo ParseFromEntryElement(XElement xEntry) + private static TopicRuntimeInfo ParseFromEntryElement(XElement xEntry) { var name = xEntry.Element(XName.Get("title", ManagementClientConstants.AtomNamespace)).Value; var topicRuntimeInfo = new TopicRuntimeInfo(name); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs index 137a7e295c5c..6921aba7249b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs @@ -343,14 +343,14 @@ private static void ValidatePartitionKey(string partitionKeyPropertyName, string /// public sealed class SystemPropertiesCollection { - int deliveryCount; - DateTime lockedUntilUtc; - long sequenceNumber = -1; - short partitionId; - long enqueuedSequenceNumber; - DateTime enqueuedTimeUtc; - Guid lockTokenGuid; - string deadLetterSource; + private int deliveryCount; + private DateTime lockedUntilUtc; + private long sequenceNumber = -1; + private short partitionId; + private long enqueuedSequenceNumber; + private DateTime enqueuedTimeUtc; + private Guid lockTokenGuid; + private string deadLetterSource; /// /// Specifies whether or not there is a lock token set on the current message. @@ -508,7 +508,7 @@ internal object BodyObject set; } - void ThrowIfNotReceived() + private void ThrowIfNotReceived() { if (!IsReceived) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs index 7a0797e73fc9..bc276d25d0d0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs @@ -13,8 +13,8 @@ namespace Microsoft.Azure.ServiceBus /// . public sealed class MessageHandlerOptions { - int maxConcurrentCalls; - TimeSpan maxAutoRenewDuration; + private int maxConcurrentCalls; + private TimeSpan maxAutoRenewDuration; /// Initializes a new instance of the class. /// Default Values: diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs index 475d332f0e6b..902f2a9df357 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs @@ -10,15 +10,15 @@ namespace Microsoft.Azure.ServiceBus using Core; using Primitives; - sealed class MessageReceivePump + internal sealed class MessageReceivePump { - readonly Func onMessageCallback; - readonly string endpoint; - readonly MessageHandlerOptions registerHandlerOptions; - readonly IMessageReceiver messageReceiver; - readonly CancellationToken pumpCancellationToken; - readonly SemaphoreSlim maxConcurrentCallsSemaphoreSlim; - readonly ServiceBusDiagnosticSource diagnosticSource; + private readonly Func onMessageCallback; + private readonly string endpoint; + private readonly MessageHandlerOptions registerHandlerOptions; + private readonly IMessageReceiver messageReceiver; + private readonly CancellationToken pumpCancellationToken; + private readonly SemaphoreSlim maxConcurrentCallsSemaphoreSlim; + private readonly ServiceBusDiagnosticSource diagnosticSource; public MessageReceivePump(IMessageReceiver messageReceiver, MessageHandlerOptions registerHandlerOptions, @@ -40,20 +40,20 @@ public void StartPump() TaskExtensionHelper.Schedule(() => MessagePumpTaskAsync()); } - bool ShouldRenewLock() + private bool ShouldRenewLock() { return messageReceiver.ReceiveMode == ReceiveMode.PeekLock && registerHandlerOptions.AutoRenewLock; } - Task RaiseExceptionReceived(Exception e, string action) + private Task RaiseExceptionReceived(Exception e, string action) { var eventArgs = new ExceptionReceivedEventArgs(e, action, endpoint, messageReceiver.Path, messageReceiver.ClientId); return registerHandlerOptions.RaiseExceptionReceived(eventArgs); } - async Task MessagePumpTaskAsync() + private async Task MessagePumpTaskAsync() { while (!pumpCancellationToken.IsCancellationRequested) { @@ -124,7 +124,7 @@ async Task MessagePumpTaskAsync() } } - async Task MessageDispatchTaskInstrumented(Message message) + private async Task MessageDispatchTaskInstrumented(Message message) { Activity activity = diagnosticSource.ProcessStart(message); Task processTask = null; @@ -144,7 +144,7 @@ async Task MessageDispatchTaskInstrumented(Message message) } } - async Task MessageDispatchTask(Message message) + private async Task MessageDispatchTask(Message message) { CancellationTokenSource renewLockCancellationTokenSource = null; Timer autoRenewLockCancellationTimer = null; @@ -201,7 +201,7 @@ async Task MessageDispatchTask(Message message) MessagingEventSource.Log.MessageReceiverPumpDispatchTaskStop(messageReceiver.ClientId, message, maxConcurrentCallsSemaphoreSlim.CurrentCount); } - void CancelAutoRenewLock(object state) + private void CancelAutoRenewLock(object state) { var renewLockCancellationTokenSource = (CancellationTokenSource)state; try @@ -214,7 +214,7 @@ void CancelAutoRenewLock(object state) } } - async Task AbandonMessageIfNeededAsync(Message message) + private async Task AbandonMessageIfNeededAsync(Message message) { try { @@ -229,7 +229,7 @@ async Task AbandonMessageIfNeededAsync(Message message) } } - async Task CompleteMessageIfNeededAsync(Message message) + private async Task CompleteMessageIfNeededAsync(Message message) { try { @@ -245,7 +245,7 @@ async Task CompleteMessageIfNeededAsync(Message message) } } - async Task RenewMessageLockTask(Message message, CancellationToken renewLockCancellationToken) + private async Task RenewMessageLockTask(Message message, CancellationToken renewLockCancellationToken) { while (!pumpCancellationToken.IsCancellationRequested && !renewLockCancellationToken.IsCancellationRequested) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingEventSource.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingEventSource.cs index 05139bd93b87..e974aec49cd0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingEventSource.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingEventSource.cs @@ -100,7 +100,7 @@ public void MessageSendException(string clientId, Exception exception) } [Event(9, Level = EventLevel.Error, Message = "{0}: SendAsync Exception: {1}.")] - void MessageSendException(string clientId, string exception) + private void MessageSendException(string clientId, string exception) { WriteEvent(9, clientId, exception); } @@ -133,7 +133,7 @@ public void MessageReceiveException(string clientId, Exception exception) } [Event(12, Level = EventLevel.Error, Message = "{0}: ReceiveAsync Exception: {1}.")] - void MessageReceiveException(string clientId, string exception) + private void MessageReceiveException(string clientId, string exception) { WriteEvent(12, clientId, exception); } @@ -149,7 +149,7 @@ public void MessageCompleteStart(string clientId, int messageCount, IEnumerable< } [Event(13, Level = EventLevel.Informational, Message = "{0}: CompleteAsync start. MessageCount = {1}, LockTokens = {2}")] - void MessageCompleteStart(string clientId, int messageCount, string lockTokens) + private void MessageCompleteStart(string clientId, int messageCount, string lockTokens) { WriteEvent(13, clientId, messageCount, lockTokens); } @@ -173,7 +173,7 @@ public void MessageCompleteException(string clientId, Exception exception) } [Event(15, Level = EventLevel.Error, Message = "{0}: CompleteAsync Exception: {1}.")] - void MessageCompleteException(string clientId, string exception) + private void MessageCompleteException(string clientId, string exception) { WriteEvent(15, clientId, exception); } @@ -206,7 +206,7 @@ public void MessageAbandonException(string clientId, Exception exception) } [Event(18, Level = EventLevel.Error, Message = "{0}: AbandonAsync Exception: {1}.")] - void MessageAbandonException(string clientId, string exception) + private void MessageAbandonException(string clientId, string exception) { WriteEvent(18, clientId, exception); } @@ -239,7 +239,7 @@ public void MessageDeferException(string clientId, Exception exception) } [Event(21, Level = EventLevel.Error, Message = "{0}: DeferAsync Exception: {1}.")] - void MessageDeferException(string clientId, string exception) + private void MessageDeferException(string clientId, string exception) { WriteEvent(21, clientId, exception); } @@ -272,7 +272,7 @@ public void MessageDeadLetterException(string clientId, Exception exception) } [Event(24, Level = EventLevel.Error, Message = "{0}: DeadLetterAsync Exception: {1}.")] - void MessageDeadLetterException(string clientId, string exception) + private void MessageDeadLetterException(string clientId, string exception) { WriteEvent(24, clientId, exception); } @@ -305,7 +305,7 @@ public void MessageRenewLockException(string clientId, Exception exception) } [Event(27, Level = EventLevel.Error, Message = "{0}: RenewLockAsync Exception: {1}.")] - void MessageRenewLockException(string clientId, string exception) + private void MessageRenewLockException(string clientId, string exception) { WriteEvent(27, clientId, exception); } @@ -321,7 +321,7 @@ public void MessageReceiveDeferredMessageStart(string clientId, int messageCount } [Event(28, Level = EventLevel.Informational, Message = "{0}: ReceiveDeferredMessageAsync start. MessageCount = {1}, LockTokens = {2}")] - void MessageReceiveDeferredMessageStart(string clientId, int messageCount, string sequenceNumbers) + private void MessageReceiveDeferredMessageStart(string clientId, int messageCount, string sequenceNumbers) { WriteEvent(28, clientId, messageCount, sequenceNumbers); } @@ -345,7 +345,7 @@ public void MessageReceiveDeferredMessageException(string clientId, Exception ex } [Event(30, Level = EventLevel.Error, Message = "{0}: ReceiveDeferredMessageAsync Exception: {1}.")] - void MessageReceiveDeferredMessageException(string clientId, string exception) + private void MessageReceiveDeferredMessageException(string clientId, string exception) { WriteEvent(30, clientId, exception); } @@ -362,7 +362,7 @@ public void AmqpSendLinkCreateStart(string clientId, MessagingEntityType? entity } [Event(34, Level = EventLevel.Informational, Message = "{0}: AmqpSendLinkCreate started. EntityType: {1}, EntityPath: {2}")] - void AmqpSendLinkCreateStart(string clientId, string entityType, string entityPath) + private void AmqpSendLinkCreateStart(string clientId, string entityType, string entityPath) { WriteEvent(34, clientId, entityType, entityPath); } @@ -386,7 +386,7 @@ public void AmqpReceiveLinkCreateStart(string clientId, bool isRequestResponseLi } [Event(36, Level = EventLevel.Informational, Message = "{0}: AmqpReceiveLinkCreate started. IsRequestResponseLink: {1}, EntityType: {1}, EntityPath: {2}")] - void AmqpReceiveLinkCreateStart(string clientId, string isRequestResponseLink, string entityType, string entityPath) + private void AmqpReceiveLinkCreateStart(string clientId, string isRequestResponseLink, string entityType, string entityPath) { WriteEvent(36, clientId, isRequestResponseLink, entityType, entityPath); } @@ -428,7 +428,7 @@ public void AmqpSendAuthenticationTokenStart(Uri address, string audience, strin } [Event(40, Level = EventLevel.Verbose, Message = "AmqpSendAuthenticanToken started. Address: {0}, Audience: {1}, Resource: {2}, Claims: {3}")] - void AmqpSendAuthenticationTokenStart(string address, string audience, string resource, string claims) + private void AmqpSendAuthenticationTokenStart(string address, string audience, string resource, string claims) { WriteEvent(40, address, audience, resource, claims); } @@ -470,7 +470,7 @@ public void MessagePeekException(string clientId, Exception exception) } [Event(44, Level = EventLevel.Error, Message = "{0}: MessagePeekAsync Exception: {1}.")] - void MessagePeekException(string clientId, string exception) + private void MessagePeekException(string clientId, string exception) { WriteEvent(44, clientId, exception); } @@ -521,7 +521,7 @@ public void ScheduleMessageStart(string clientId, DateTimeOffset scheduleEnqueue } [Event(49, Level = EventLevel.Informational, Message = "{0}: ScheduleMessageAsync start. ScheduleTimeUtc = {1}")] - void ScheduleMessageStart(string clientId, string scheduleEnqueueTimeUtc) + private void ScheduleMessageStart(string clientId, string scheduleEnqueueTimeUtc) { if (IsEnabled()) { @@ -548,7 +548,7 @@ public void ScheduleMessageException(string clientId, Exception exception) } [Event(51, Level = EventLevel.Error, Message = "{0}: ScheduleMessageAsync Exception: {1}.")] - void ScheduleMessageException(string clientId, string exception) + private void ScheduleMessageException(string clientId, string exception) { WriteEvent(51, clientId, exception); } @@ -581,7 +581,7 @@ public void CancelScheduledMessageException(string clientId, Exception exception } [Event(54, Level = EventLevel.Error, Message = "{0}: CancelScheduledMessageAsync Exception: {1}.")] - void CancelScheduledMessageException(string clientId, string exception) + private void CancelScheduledMessageException(string clientId, string exception) { WriteEvent(54, clientId, exception); } @@ -614,7 +614,7 @@ public void AddRuleException(string clientId, Exception exception) } [Event(57, Level = EventLevel.Error, Message = "{0}: AddRuleAsync Exception: {1}.")] - void AddRuleException(string clientId, string exception) + private void AddRuleException(string clientId, string exception) { WriteEvent(57, clientId, exception); } @@ -647,7 +647,7 @@ public void RemoveRuleException(string clientId, Exception exception) } [Event(60, Level = EventLevel.Error, Message = "{0}: RemoveRuleAsync Exception: {1}.")] - void RemoveRuleException(string clientId, string exception) + private void RemoveRuleException(string clientId, string exception) { WriteEvent(60, clientId, exception); } @@ -662,7 +662,7 @@ public void RegisterOnMessageHandlerStart(string clientId, MessageHandlerOptions } [Event(61, Level = EventLevel.Informational, Message = "{0}: Register OnMessageHandler start: OnMessage Options: AutoComplete: {1}, AutoRenewLock: {2}, MaxConcurrentCalls: {3}, AutoRenewTimeout: {4}")] - void RegisterOnMessageHandlerStart(string clientId, bool autoComplete, bool autorenewLock, int maxConcurrentCalls, long autorenewTimeoutInSeconds) + private void RegisterOnMessageHandlerStart(string clientId, bool autoComplete, bool autorenewLock, int maxConcurrentCalls, long autorenewTimeoutInSeconds) { WriteEvent(61, clientId, autoComplete, autorenewLock, maxConcurrentCalls, autorenewTimeoutInSeconds); } @@ -686,7 +686,7 @@ public void RegisterOnMessageHandlerException(string clientId, Exception excepti } [Event(63, Level = EventLevel.Error, Message = "{0}: Register OnMessageHandler Exception: {1}")] - void RegisterOnMessageHandlerException(string clientId, string exception) + private void RegisterOnMessageHandlerException(string clientId, string exception) { WriteEvent(63, clientId, exception); } @@ -701,7 +701,7 @@ public void MessageReceiverPumpTaskStart(string clientId, Message message, int c } [Event(66, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump PumpTask Started: Message: SequenceNumber: {1}, Available Semaphore Count: {2}")] - void MessageReceiverPumpTaskStart(string clientId, long sequenceNumber, int currentSemaphoreCount) + private void MessageReceiverPumpTaskStart(string clientId, long sequenceNumber, int currentSemaphoreCount) { WriteEvent(66, clientId, sequenceNumber, currentSemaphoreCount); } @@ -725,7 +725,7 @@ public void MessageReceivePumpTaskException(string clientId, string sessionId, E } [Event(68, Level = EventLevel.Error, Message = "{0}: MessageReceiverPump PumpTask Exception: SessionId: {1}, Exception: {2}")] - void MessageReceivePumpTaskException(string clientId, string sessionId, string exception) + private void MessageReceivePumpTaskException(string clientId, string sessionId, string exception) { WriteEvent(68, clientId, sessionId, exception); } @@ -740,7 +740,7 @@ public void MessageReceiverPumpDispatchTaskStart(string clientId, Message messag } [Event(69, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump DispatchTask start: Message: SequenceNumber: {1}")] - void MessageReceiverPumpDispatchTaskStart(string clientId, long sequenceNumber) + private void MessageReceiverPumpDispatchTaskStart(string clientId, long sequenceNumber) { WriteEvent(69, clientId, sequenceNumber); } @@ -755,7 +755,7 @@ public void MessageReceiverPumpDispatchTaskStop(string clientId, Message message } [Event(70, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump DispatchTask done: Message: SequenceNumber: {1}, Current Semaphore Count: {2}")] - void MessageReceiverPumpDispatchTaskStop(string clientId, long sequenceNumber, int currentSemaphoreCount) + private void MessageReceiverPumpDispatchTaskStop(string clientId, long sequenceNumber, int currentSemaphoreCount) { WriteEvent(70, clientId, sequenceNumber, currentSemaphoreCount); } @@ -770,7 +770,7 @@ public void MessageReceiverPumpUserCallbackStart(string clientId, Message messag } [Event(71, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump UserCallback start: Message: SequenceNumber: {1}")] - void MessageReceiverPumpUserCallbackStart(string clientId, long sequenceNumber) + private void MessageReceiverPumpUserCallbackStart(string clientId, long sequenceNumber) { WriteEvent(71, clientId, sequenceNumber); } @@ -785,7 +785,7 @@ public void MessageReceiverPumpUserCallbackStop(string clientId, Message message } [Event(72, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump UserCallback done: Message: SequenceNumber: {1}")] - void MessageReceiverPumpUserCallbackStop(string clientId, long sequenceNumber) + private void MessageReceiverPumpUserCallbackStop(string clientId, long sequenceNumber) { WriteEvent(72, clientId, sequenceNumber); } @@ -800,7 +800,7 @@ public void MessageReceiverPumpUserCallbackException(string clientId, Message me } [Event(73, Level = EventLevel.Error, Message = "{0}: MessageReceiverPump UserCallback Exception: Message: SequenceNumber: {1}, Exception: {2}")] - void MessageReceiverPumpUserCallbackException(string clientId, long sequenceNumber, string exception) + private void MessageReceiverPumpUserCallbackException(string clientId, long sequenceNumber, string exception) { WriteEvent(73, clientId, sequenceNumber, exception); } @@ -815,7 +815,7 @@ public void MessageReceiverPumpRenewMessageStart(string clientId, Message messag } [Event(74, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump RenewMessage start: Message: SequenceNumber: {1}, RenewAfterTimeInSeconds: {2}")] - void MessageReceiverPumpRenewMessageStart(string clientId, long sequenceNumber, long renewAfterTimeSpanInSeconds) + private void MessageReceiverPumpRenewMessageStart(string clientId, long sequenceNumber, long renewAfterTimeSpanInSeconds) { WriteEvent(74, clientId, sequenceNumber, renewAfterTimeSpanInSeconds); } @@ -830,7 +830,7 @@ public void MessageReceiverPumpRenewMessageStop(string clientId, Message message } [Event(75, Level = EventLevel.Informational, Message = "{0}: MessageReceiverPump RenewMessage done: Message: SequenceNumber: {1}")] - void MessageReceiverPumpRenewMessageStop(string clientId, long sequenceNumber) + private void MessageReceiverPumpRenewMessageStop(string clientId, long sequenceNumber) { WriteEvent(75, clientId, sequenceNumber); } @@ -845,7 +845,7 @@ public void MessageReceiverPumpRenewMessageException(string clientId, Message me } [Event(76, Level = EventLevel.Error, Message = "{0}: MessageReceiverPump RenewMessage Exception: Message: SequenceNumber: {1}, Exception: {2}")] - void MessageReceiverPumpRenewMessageException(string clientId, long sequenceNumber, string exception) + private void MessageReceiverPumpRenewMessageException(string clientId, long sequenceNumber, string exception) { WriteEvent(76, clientId, sequenceNumber, exception); } @@ -860,7 +860,7 @@ public void RunOperationExceptionEncountered(Exception exception) } [Event(77, Level = EventLevel.Warning, Message = "RunOperation encountered an exception and will retry. Exception: {0}")] - void RunOperationExceptionEncountered(string exception) + private void RunOperationExceptionEncountered(string exception) { WriteEvent(77, exception); } @@ -875,7 +875,7 @@ public void RegisterOnSessionHandlerStart(string clientId, SessionHandlerOptions } [Event(78, Level = EventLevel.Informational, Message = "{0}: Register OnSessionHandler start: RegisterSessionHandler Options: AutoComplete: {1}, MaxConcurrentSessions: {2}, MessageWaitTimeout: {3}, AutoRenewTimeout: {4}")] - void RegisterOnSessionHandlerStart(string clientId, bool autoComplete, int maxConcurrentSessions, long messageWaitTimeoutInSeconds, long autorenewTimeoutInSeconds) + private void RegisterOnSessionHandlerStart(string clientId, bool autoComplete, int maxConcurrentSessions, long messageWaitTimeoutInSeconds, long autorenewTimeoutInSeconds) { WriteEvent(78, clientId, autoComplete, maxConcurrentSessions, messageWaitTimeoutInSeconds, autorenewTimeoutInSeconds); } @@ -899,7 +899,7 @@ public void RegisterOnSessionHandlerException(string clientId, Exception excepti } [Event(80, Level = EventLevel.Error, Message = "{0}: Register OnSessionHandler Exception: {1}")] - void RegisterOnSessionHandlerException(string clientId, string exception) + private void RegisterOnSessionHandlerException(string clientId, string exception) { WriteEvent(80, clientId, exception); } @@ -914,7 +914,7 @@ public void SessionReceivePumpSessionReceiveException(string clientId, Exception } [Event(81, Level = EventLevel.Error, Message = "{0}: Exception while Receving a session: SessionId: {1}")] - void SessionReceivePumpSessionReceiveException(string clientId, string exception) + private void SessionReceivePumpSessionReceiveException(string clientId, string exception) { WriteEvent(81, clientId, exception); } @@ -947,7 +947,7 @@ public void SessionReceivePumpSessionCloseException(string clientId, string sess } [Event(84, Level = EventLevel.Error, Message = "{0}: Exception while closing session: SessionId: {1}, Exception: {2}")] - void SessionReceivePumpSessionCloseException(string clientId, string sessionId, string exception) + private void SessionReceivePumpSessionCloseException(string clientId, string sessionId, string exception) { WriteEvent(84, clientId, sessionId, exception); } @@ -962,7 +962,7 @@ public void SessionReceivePumpSessionRenewLockStart(string clientId, string sess } [Event(85, Level = EventLevel.Informational, Message = "{0}: SessionRenewLock start. SessionId: {1}, RenewAfterTimeInSeconds: {2}")] - void SessionReceivePumpSessionRenewLockStart(string clientId, string sessionId, long totalSeconds) + private void SessionReceivePumpSessionRenewLockStart(string clientId, string sessionId, long totalSeconds) { WriteEvent(85, clientId, sessionId, totalSeconds); } @@ -986,7 +986,7 @@ public void SessionReceivePumpSessionRenewLockException(string clientId, string } [Event(87, Level = EventLevel.Error, Message = "{0}: Exception while renewing session lock: SessionId: {1}, Exception: {2}")] - void SessionReceivePumpSessionRenewLockException(string clientId, string sessionId, string exception) + private void SessionReceivePumpSessionRenewLockException(string clientId, string sessionId, string exception) { WriteEvent(87, clientId, sessionId, exception); } @@ -1001,7 +1001,7 @@ public void AmqpSessionClientAcceptMessageSessionStart(string clientId, string e } [Event(88, Level = EventLevel.Informational, Message = "{0}: AcceptMessageSession start: EntityPath: {1}, ReceiveMode: {2}, PrefetchCount: {3}, SessionId: {4}")] - void AmqpSessionClientAcceptMessageSessionStart(string clientId, string entityPath, string receiveMode, int prefetchCount, string sessionId) + private void AmqpSessionClientAcceptMessageSessionStart(string clientId, string entityPath, string receiveMode, int prefetchCount, string sessionId) { WriteEvent(88, clientId, entityPath, receiveMode, prefetchCount, sessionId); } @@ -1025,7 +1025,7 @@ public void AmqpSessionClientAcceptMessageSessionException(string clientId, stri } [Event(90, Level = EventLevel.Error, Message = "{0}: AcceptMessageSession Exception: EntityPath: {1}, Exception: {2}")] - void AmqpSessionClientAcceptMessageSessionException(string clientId, string entityPath, string exception) + private void AmqpSessionClientAcceptMessageSessionException(string clientId, string entityPath, string exception) { WriteEvent(90, clientId, entityPath, exception); } @@ -1040,7 +1040,7 @@ public void AmqpLinkCreationException(string entityPath, AmqpSession session, Am } [Event(91, Level = EventLevel.Error, Message = "AmqpLinkCreatorException Exception: EntityPath: {0}, SessionString: {1}, SessionState: {2}, TerminalException: {3}, ConnectionInfo: {4}, ConnectionState: {5}, Exception: {6}")] - void AmqpLinkCreationException(string entityPath, string session, string sessionState, string terminalException, string connectionInfo, string connectionState, string exception) + private void AmqpLinkCreationException(string entityPath, string session, string sessionState, string terminalException, string connectionInfo, string connectionState, string exception) { WriteEvent(91, entityPath, session, sessionState, terminalException, connectionInfo, connectionState, exception); } @@ -1055,7 +1055,7 @@ public void AmqpConnectionCreated(string hostName, AmqpConnection connection) } [Event(92, Level = EventLevel.Verbose, Message = "AmqpConnectionCreated: HostName: {0}, ConnectionInfo: {1}, ConnectionState: {2}")] - void AmqpConnectionCreated(string hostName, string connectionInfo, string connectionState) + private void AmqpConnectionCreated(string hostName, string connectionInfo, string connectionState) { WriteEvent(92, hostName, connectionInfo, connectionState); } @@ -1085,7 +1085,7 @@ public void AmqpSessionCreationException(string entityPath, AmqpConnection conne } [Event(94, Level = EventLevel.Error, Message = "AmqpSessionCreationException Exception: EntityPath: {0}, ConnectionInfo: {1}, ConnectionState: {2}, Exception: {3}")] - void AmqpSessionCreationException(string entityPath, string connectionInfo, string connectionState, string exception) + private void AmqpSessionCreationException(string entityPath, string connectionInfo, string connectionState, string exception) { WriteEvent(94, entityPath, connectionInfo, connectionState, exception); } @@ -1118,7 +1118,7 @@ public void PluginCallFailed(string pluginName, string messageId, Exception exce } [Event(97, Level = EventLevel.Error, Message = "Exception during {0} plugin execution. MessageId: {1}, Exception {2}")] - void PluginCallFailed(string pluginName, string messageId, string exception) + private void PluginCallFailed(string pluginName, string messageId, string exception) { WriteEvent(97, pluginName, messageId, exception); } @@ -1133,7 +1133,7 @@ public void ScheduleTaskFailed(Func task, Exception exception) } [Event(98, Level = EventLevel.Error, Message = "Exception during Schedule Task. FunctionTargetName: {0}, MethodInfoName: {1}, Exception:{2}")] - void ScheduleTaskFailed(string funcTargetName, string methodInfoName, string exception) + private void ScheduleTaskFailed(string funcTargetName, string methodInfoName, string exception) { WriteEvent(98, funcTargetName, methodInfoName, exception); } @@ -1148,7 +1148,7 @@ public void ExceptionReceivedHandlerThrewException(Exception exception) } [Event(99, Level = EventLevel.Error, Message = "ExceptionReceivedHandler threw exception. Exception:{0}")] - void ExceptionReceivedHandlerThrewException(string exception) + private void ExceptionReceivedHandlerThrewException(string exception) { WriteEvent(99, exception); } @@ -1163,7 +1163,7 @@ public void LinkStateLost(string clientId, string receiveLinkName, AmqpObjectSta } [Event(100, Level = EventLevel.Error, Message = "Link state lost. Throwing LockLostException for clientId: {0}, receiveLinkName: {1}, receiveLinkState: {2}, isSessionReceiver: {3}, exception: {4}.")] - void LinkStateLost(string clientId, string receiveLinkName, string receiveLinkState, bool isSessionReceiver, string exception) + private void LinkStateLost(string clientId, string receiveLinkName, string receiveLinkState, bool isSessionReceiver, string exception) { WriteEvent(100, clientId, receiveLinkName, receiveLinkState, isSessionReceiver, exception); } @@ -1205,7 +1205,7 @@ public void GetRulesException(string clientId, Exception exception) } [Event(104, Level = EventLevel.Error, Message = "{0}: GetRulesException Exception: {1}.")] - void GetRulesException(string clientId, string exception) + private void GetRulesException(string clientId, string exception) { WriteEvent(104, clientId, exception); } @@ -1220,7 +1220,7 @@ public void CreatingNewLink(string clientId, bool isSessionReceiver, string sess } [Event(105, Level = EventLevel.Informational, Message = "Creating/Recreating New Link. ClientId: {0}, IsSessionReceiver: {1}, SessionId: {2}, IsRequestResponseLink: {3}, LinkError: {4}.")] - void CreatingNewLink(string clientId, bool isSessionReceiver, string sessionId, bool isRequestResponseLink, string linkError) + private void CreatingNewLink(string clientId, bool isSessionReceiver, string sessionId, bool isRequestResponseLink, string linkError) { WriteEvent(105, clientId, isSessionReceiver, sessionId, isRequestResponseLink, linkError); } @@ -1235,7 +1235,7 @@ public void SessionReceiverLinkClosed(string clientId, string sessionId, Excepti } [Event(106, Level = EventLevel.Error, Message = "SessionReceiver Link Closed. ClientId: {0}, SessionId: {1}, linkException: {2}.")] - void SessionReceiverLinkClosed(string clientId, string sessionId, string linkException) + private void SessionReceiverLinkClosed(string clientId, string sessionId, string linkException) { WriteEvent(106, clientId, sessionId, linkException); } @@ -1250,7 +1250,7 @@ public void AmqpSendAuthenticationTokenException(string clientId, Exception exce } [Event(107, Level = EventLevel.Error, Message = "{0}: AmqpSendAuthenticationTokenException Exception: {1}.")] - void AmqpSendAuthenticationTokenException(string clientId, string exception) + private void AmqpSendAuthenticationTokenException(string clientId, string exception) { WriteEvent(107, clientId, exception); } @@ -1265,7 +1265,7 @@ public void AmqpTransactionInitializeException(string transactionId, Exception e } [Event(108, Level = EventLevel.Error, Message = "AmqpTransactionInitializeException for TransactionId: {0} Exception: {1}.")] - void AmqpTransactionInitializeException(string transactionId, string exception) + private void AmqpTransactionInitializeException(string transactionId, string exception) { WriteEvent(108, transactionId, exception); } @@ -1280,7 +1280,7 @@ public void AmqpTransactionDeclared(string localTransactionId, ArraySegment public class AzureActiveDirectoryTokenProvider : TokenProvider { - readonly string authority; - readonly object authCallbackState; - event AuthenticationCallback AuthCallback; + private readonly string authority; + private readonly object authCallbackState; + private event AuthenticationCallback AuthCallback; public delegate Task AuthenticationCallback(string audience, string authority, object state); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ClaimConstants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ClaimConstants.cs index b40316d82916..a7f8316cf331 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ClaimConstants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ClaimConstants.cs @@ -3,7 +3,7 @@ namespace Microsoft.Azure.ServiceBus.Primitives { - static class ClaimConstants + internal static class ClaimConstants { public const string Manage = "Manage"; public const string Send = "Send"; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ClientInfo.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ClientInfo.cs index 2318fd1b4508..8f862f084ee5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ClientInfo.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ClientInfo.cs @@ -38,7 +38,7 @@ static ClientInfo() } } - static string GetAssemblyAttributeValue(Assembly assembly, Func getter) where T : Attribute + private static string GetAssemblyAttributeValue(Assembly assembly, Func getter) where T : Attribute { return !(assembly.GetCustomAttribute(typeof(T)) is T attribute) ? null : getter(attribute); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs index 732af30e8d47..6dbf6413f74a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs @@ -9,15 +9,15 @@ namespace Microsoft.Azure.ServiceBus.Primitives using System.Threading; using System.Threading.Tasks; - sealed class ConcurrentExpiringSet + internal sealed class ConcurrentExpiringSet { - readonly ConcurrentDictionary dictionary; - readonly ICollection> dictionaryAsCollection; - readonly CancellationTokenSource tokenSource = new CancellationTokenSource(); - volatile TaskCompletionSource cleanupTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - int closeSignaled; - bool closed; - static readonly TimeSpan delayBetweenCleanups = TimeSpan.FromSeconds(30); + private readonly ConcurrentDictionary dictionary; + private readonly ICollection> dictionaryAsCollection; + private readonly CancellationTokenSource tokenSource = new CancellationTokenSource(); + private volatile TaskCompletionSource cleanupTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + private int closeSignaled; + private bool closed; + private static readonly TimeSpan delayBetweenCleanups = TimeSpan.FromSeconds(30); public ConcurrentExpiringSet() { @@ -56,7 +56,7 @@ public void Close() tokenSource.Dispose(); } - async Task CollectExpiredEntriesAsync(CancellationToken token) + private async Task CollectExpiredEntriesAsync(CancellationToken token) { while (!token.IsCancellationRequested) { @@ -89,7 +89,7 @@ async Task CollectExpiredEntriesAsync(CancellationToken token) } } - void ThrowIfClosed() + private void ThrowIfClosed() { if (closed) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentRandom.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentRandom.cs index 3c47b0d23f12..2cbdd89c1b2f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentRandom.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentRandom.cs @@ -8,11 +8,9 @@ namespace Microsoft.Azure.ServiceBus.Primitives internal static class ConcurrentRandom { // We lock on this when generating a seed for a threadLocalRandom - [Fx.Tag.SynchronizationObject] - static readonly Random SeedGenerator = new Random(); + [Fx.Tag.SynchronizationObject] private static readonly Random SeedGenerator = new Random(); - [ThreadStatic] - static Random threadLocalRandom; + [ThreadStatic] private static Random threadLocalRandom; public static int Next(int minValue, int maxValue) { @@ -30,7 +28,7 @@ public static long NextPositiveLong() return Math.Abs(ulongValue); } - static Random GetThreadLocalRandom() + private static Random GetThreadLocalRandom() { if (threadLocalRandom == null) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/DispositionStatus.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/DispositionStatus.cs index 213c2b94a9fd..54a28ebd4994 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/DispositionStatus.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/DispositionStatus.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Primitives { // Enum.ToString() is used while serializing the AMQP disposition request. // DO NOT rename the enums. - enum DispositionStatus + internal enum DispositionStatus { Completed = 1, Defered = 2, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ExceptionUtility.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ExceptionUtility.cs index 8a84ce07f6f9..84902d94a4a6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ExceptionUtility.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ExceptionUtility.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Primitives { using System; - class ExceptionUtility + internal class ExceptionUtility { public ArgumentException Argument(string paramName, string message) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs index f3b359168889..52da2227ff18 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs @@ -6,9 +6,9 @@ namespace Microsoft.Azure.ServiceBus.Primitives using System; using System.Diagnostics; - static class Fx + internal static class Fx { - static ExceptionUtility exceptionUtility; + private static ExceptionUtility exceptionUtility; public static ExceptionUtility Exception { @@ -103,8 +103,8 @@ public static class Strings [Conditional("CODE_ANALYSIS")] public sealed class ExternalResourceAttribute : Attribute { - readonly Location location; - readonly string description; + private readonly Location location; + private readonly string description; public ExternalResourceAttribute(Location location, string description) { @@ -121,8 +121,8 @@ public ExternalResourceAttribute(Location location, string description) [Conditional("CODE_ANALYSIS")] public sealed class CacheAttribute : Attribute { - readonly Type elementType; - readonly CacheAttrition cacheAttrition; + private readonly Type elementType; + private readonly CacheAttrition cacheAttrition; public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) { @@ -154,7 +154,7 @@ public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) [Conditional("CODE_ANALYSIS")] public sealed class QueueAttribute : Attribute { - readonly Type elementType; + private readonly Type elementType; public QueueAttribute(Type elementType) { @@ -204,7 +204,7 @@ public SynchronizationObjectAttribute() [Conditional("CODE_ANALYSIS")] public sealed class SynchronizationPrimitiveAttribute : Attribute { - readonly BlocksUsing blocksUsing; + private readonly BlocksUsing blocksUsing; public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing) { @@ -252,8 +252,8 @@ public sealed class NonThrowingAttribute : Attribute [Conditional("CODE_ANALYSIS")] public class ThrowsAttribute : Attribute { - readonly Type exceptionType; - readonly string diagnosis; + private readonly Type exceptionType; + private readonly string diagnosis; public ThrowsAttribute(Type exceptionType, string diagnosis) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/JsonSecurityToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/JsonSecurityToken.cs index b4c04ce491da..8effe4ef0395 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/JsonSecurityToken.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/JsonSecurityToken.cs @@ -23,7 +23,7 @@ public JsonSecurityToken(string rawToken, string audience) { } - static DateTime GetExpirationDateTimeUtcFromToken(string token) + private static DateTime GetExpirationDateTimeUtcFromToken(string token) { var jwtSecurityToken = new JwtSecurityToken(token); return jwtSecurityToken.ValidTo; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs index 696991cf3e28..5e57986aae2a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs @@ -8,9 +8,9 @@ namespace Microsoft.Azure.ServiceBus.Primitives using System.Collections.Generic; using Amqp; - sealed class PropertyDictionary : IDictionary + internal sealed class PropertyDictionary : IDictionary { - readonly IDictionary inner; + private readonly IDictionary inner; public PropertyDictionary() { @@ -101,7 +101,7 @@ IEnumerator IEnumerable.GetEnumerator() return inner.GetEnumerator(); } - bool IsSupportedObject(object value) + private bool IsSupportedObject(object value) { if (value != null) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs index 6cc177317178..bc024e9446b5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs @@ -13,22 +13,22 @@ public class SecurityToken /// /// Token literal /// - string token; + private string token; /// /// Expiry date-time /// - DateTime expiresAtUtc; + private DateTime expiresAtUtc; /// /// Token audience /// - string audience; + private string audience; /// /// Token type /// - string tokenType; + private string tokenType; /// /// Creates a new instance of the class. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ServiceBusUriHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ServiceBusUriHelper.cs index 7b6f73c96b59..6dbbcfa0a2d3 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ServiceBusUriHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ServiceBusUriHelper.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Primitives { using System; - static class ServiceBusUriHelper + internal static class ServiceBusUriHelper { internal static string NormalizeUri(string uri, string scheme, bool stripQueryParameters = true, bool stripPath = false, bool ensureTrailingSlash = false) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs index 480bb15248bb..0ebac7391ebf 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs @@ -21,11 +21,11 @@ internal class SharedAccessSignatureToken : SecurityToken internal const int MaxKeyNameLength = 256; internal const int MaxKeyLength = 256; - const string SignedResourceFullFieldName = SharedAccessSignature + " " + SignedResource; - const string SasPairSeparator = "&"; - const string SasKeyValueSeparator = "="; + private const string SignedResourceFullFieldName = SharedAccessSignature + " " + SignedResource; + private const string SasPairSeparator = "&"; + private const string SasKeyValueSeparator = "="; - static readonly Func Decoder = WebUtility.UrlDecode; + private static readonly Func Decoder = WebUtility.UrlDecode; /// /// Creates a new instance of the class. @@ -70,7 +70,7 @@ internal static void Validate(string sharedAccessSignature) } } - static IDictionary ExtractFieldValues(string sharedAccessSignature) + private static IDictionary ExtractFieldValues(string sharedAccessSignature) { string[] tokenLines = sharedAccessSignature.Split(); @@ -103,7 +103,7 @@ static IDictionary ExtractFieldValues(string sharedAccessSignatu return parsedFields; } - static string GetAudienceFromToken(string token) + private static string GetAudienceFromToken(string token) { IDictionary decodedToken = Decode(token, Decoder, Decoder, SasKeyValueSeparator, SasPairSeparator); if (!decodedToken.TryGetValue(SignedResourceFullFieldName, out var audience)) @@ -114,7 +114,7 @@ static string GetAudienceFromToken(string token) return audience; } - static DateTime GetExpirationDateTimeUtcFromToken(string token) + private static DateTime GetExpirationDateTimeUtcFromToken(string token) { IDictionary decodedToken = Decode(token, Decoder, Decoder, SasKeyValueSeparator, SasPairSeparator); if (!decodedToken.TryGetValue(SignedExpiry, out var expiresIn)) @@ -127,7 +127,7 @@ static DateTime GetExpirationDateTimeUtcFromToken(string token) return expiresOn; } - static IDictionary Decode(string encodedString, Func keyDecoder, Func valueDecoder, string keyValueSeparator, string pairSeparator) + private static IDictionary Decode(string encodedString, Func keyDecoder, Func valueDecoder, string keyValueSeparator, string pairSeparator) { IDictionary dictionary = new Dictionary(); IEnumerable valueEncodedPairs = encodedString.Split(new[] { pairSeparator }, StringSplitOptions.None); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs index 888478119068..768e78e72a8c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs @@ -17,15 +17,15 @@ namespace Microsoft.Azure.ServiceBus.Primitives /// public class SharedAccessSignatureTokenProvider : TokenProvider { - const TokenScope DefaultTokenScope = TokenScope.Entity; + private const TokenScope DefaultTokenScope = TokenScope.Entity; internal static readonly TimeSpan DefaultTokenTTL = TimeSpan.FromMinutes(60); - readonly byte[] encodedSharedAccessKey; - readonly string keyName; - readonly TimeSpan tokenTimeToLive; - readonly TokenScope tokenScope; - readonly string sharedAccessSignature; + private readonly byte[] encodedSharedAccessKey; + private readonly string keyName; + private readonly TimeSpan tokenTimeToLive; + private readonly TokenScope tokenScope; + private readonly string sharedAccessSignature; internal static readonly Func MessagingTokenProviderKeyEncoder = Encoding.UTF8.GetBytes; internal SharedAccessSignatureTokenProvider(string sharedAccessSignature) @@ -117,12 +117,12 @@ protected virtual string BuildSignature(string targetUri) : sharedAccessSignature; } - string NormalizeAppliesTo(string appliesTo) + private string NormalizeAppliesTo(string appliesTo) { return ServiceBusUriHelper.NormalizeUri(appliesTo, "https", true, stripPath: tokenScope == TokenScope.Namespace, ensureTrailingSlash: true); } - static class SharedAccessSignatureBuilder + private static class SharedAccessSignatureBuilder { [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "Uris are normalized to lowercase")] public static string BuildSignature( @@ -154,7 +154,7 @@ public static string BuildSignature( SharedAccessSignatureToken.SignedKeyName, WebUtility.UrlEncode(keyName)); } - static string BuildExpiresOn(TimeSpan timeToLive) + private static string BuildExpiresOn(TimeSpan timeToLive) { DateTime expiresOn = DateTime.UtcNow.Add(timeToLive); TimeSpan secondsFromBaseTime = expiresOn.Subtract(Constants.EpochTime); @@ -162,7 +162,7 @@ static string BuildExpiresOn(TimeSpan timeToLive) return Convert.ToString(seconds, CultureInfo.InvariantCulture); } - static string Sign(string requestString, byte[] encodedSharedAccessKey) + private static string Sign(string requestString, byte[] encodedSharedAccessKey) { using (var hmac = new HMACSHA256(encodedSharedAccessKey)) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/StringUtility.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/StringUtility.cs index ffa256036337..f58159889709 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/StringUtility.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/StringUtility.cs @@ -7,7 +7,7 @@ namespace Microsoft.Azure.ServiceBus.Primitives using System.Globalization; using System.Text; - static class StringUtility + internal static class StringUtility { public static string GetFormattedLockTokens(IEnumerable lockTokens) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TaskExtensionHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TaskExtensionHelper.cs index 674413ac5b03..d8bb03523fb0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TaskExtensionHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TaskExtensionHelper.cs @@ -6,14 +6,14 @@ namespace Microsoft.Azure.ServiceBus.Primitives using System; using System.Threading.Tasks; - static class TaskExtensionHelper + internal static class TaskExtensionHelper { public static void Schedule(Func func) { _ = ScheduleInternal(func); } - static async Task ScheduleInternal(Func func) + private static async Task ScheduleInternal(Func func) { try { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Ticks.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Ticks.cs index c4c4dae9f440..795e06c3199b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Ticks.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Ticks.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.Primitives { using System; - static class Ticks + internal static class Ticks { public static long Now => DateTime.UtcNow.ToFileTimeUtc(); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs index 7e9e78bea61f..f9b7aab76f0e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs @@ -7,11 +7,11 @@ namespace Microsoft.Azure.ServiceBus.Primitives using System.Diagnostics; [DebuggerStepThrough] - struct TimeoutHelper + internal struct TimeoutHelper { - DateTime deadline; - bool deadlineSet; - TimeSpan originalTimeout; + private DateTime deadline; + private bool deadlineSet; + private TimeSpan originalTimeout; public TimeoutHelper(TimeSpan timeout, bool startTimeout) { @@ -128,7 +128,7 @@ public TimeSpan ElapsedTime() return originalTimeout - RemainingTime(); } - void SetDeadline() + private void SetDeadline() { Debug.Assert(!deadlineSet, "TimeoutHelper deadline set twice."); deadline = DateTime.UtcNow + originalTimeout; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs index 6d3b7401911d..0fedd80eccbc 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs @@ -12,10 +12,10 @@ namespace Microsoft.Azure.ServiceBus.Primitives /// /// Provides an adapter from TokenProvider to ICbsTokenProvider for AMQP CBS usage. /// - sealed class TokenProviderAdapter : ICbsTokenProvider + internal sealed class TokenProviderAdapter : ICbsTokenProvider { - readonly ITokenProvider tokenProvider; - readonly TimeSpan operationTimeout; + private readonly ITokenProvider tokenProvider; + private readonly TimeSpan operationTimeout; public TokenProviderAdapter(ITokenProvider tokenProvider, TimeSpan operationTimeout) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs index 509cd2e15e52..962bd14fdd68 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs @@ -54,13 +54,13 @@ namespace Microsoft.Azure.ServiceBus /// It uses AMQP protocol for communicating with servicebus. public class QueueClient : ClientEntity, IQueueClient { - readonly object syncLock; + private readonly object syncLock; - int prefetchCount; - MessageSender innerSender; - MessageReceiver innerReceiver; - SessionClient sessionClient; - SessionPumpHost sessionPumpHost; + private int prefetchCount; + private MessageSender innerSender; + private MessageReceiver innerReceiver; + private SessionClient sessionClient; + private SessionPumpHost sessionPumpHost; /// /// Instantiates a new to perform operations on a queue. @@ -328,8 +328,8 @@ internal SessionPumpHost SessionPumpHost return sessionPumpHost; } } - - ICbsTokenProvider CbsTokenProvider { get; } + + private ICbsTokenProvider CbsTokenProvider { get; } /// /// Sends a message to Service Bus. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs index 34e8fb0519f1..1edaed97e98e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs @@ -18,14 +18,14 @@ public abstract class RetryPolicy { internal static readonly TimeSpan ServerBusyBaseSleepTime = TimeSpan.FromSeconds(10); - const int DefaultRetryMaxCount = 5; - static readonly TimeSpan DefaultRetryMinBackoff = TimeSpan.Zero; - static readonly TimeSpan DefaultRetryMaxBackoff = TimeSpan.FromSeconds(30); + private const int DefaultRetryMaxCount = 5; + private static readonly TimeSpan DefaultRetryMinBackoff = TimeSpan.Zero; + private static readonly TimeSpan DefaultRetryMaxBackoff = TimeSpan.FromSeconds(30); - readonly object serverBusyLock = new object(); + private readonly object serverBusyLock = new object(); // This is a volatile copy of IsServerBusy. IsServerBusy is synchronized with a lock, whereas encounteredServerBusy is kept volatile for performance reasons. - volatile bool encounteredServerBusy; + private volatile bool encounteredServerBusy; protected RetryPolicy() { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs index c2dcf1e842d4..2dbab9c44a11 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs @@ -18,9 +18,9 @@ namespace Microsoft.Azure.ServiceBus /// public class ServiceBusConnection { - static readonly Version AmqpVersion = new Version(1, 0, 0, 0); - readonly object syncLock; - bool isClosedOrClosing; + private static readonly Version AmqpVersion = new Version(1, 0, 0, 0); + private readonly object syncLock; + private bool isClosedOrClosing; /// /// Creates a new connection to service bus. @@ -206,7 +206,7 @@ public async Task CloseAsync() } } - void InitializeConnection(ServiceBusConnectionStringBuilder builder) + private void InitializeConnection(ServiceBusConnectionStringBuilder builder) { Endpoint = new Uri(builder.Endpoint); @@ -229,18 +229,18 @@ void InitializeConnection(ServiceBusConnectionStringBuilder builder) TransactionController = new FaultTolerantAmqpObject(CreateControllerAsync, CloseController); } - static void CloseConnection(AmqpConnection connection) + private static void CloseConnection(AmqpConnection connection) { MessagingEventSource.Log.AmqpConnectionClosed(connection); connection.SafeClose(); } - static void CloseController(Controller controller) + private static void CloseController(Controller controller) { controller.Close(); } - async Task CreateConnectionAsync(TimeSpan timeout) + private async Task CreateConnectionAsync(TimeSpan timeout) { var hostName = Endpoint.Host; @@ -272,7 +272,7 @@ async Task CreateConnectionAsync(TimeSpan timeout) return connection; } - async Task CreateControllerAsync(TimeSpan timeout) + private async Task CreateControllerAsync(TimeSpan timeout) { var timeoutHelper = new TimeoutHelper(timeout, true); var connection = await ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); @@ -303,7 +303,7 @@ async Task CreateControllerAsync(TimeSpan timeout) return controller; } - TransportSettings CreateTransportSettings() + private TransportSettings CreateTransportSettings() { var hostName = Endpoint.Host; var networkHost = Endpoint.Host; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs index ae6481fa9959..d595d76e092c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs @@ -14,22 +14,22 @@ namespace Microsoft.Azure.ServiceBus /// public class ServiceBusConnectionStringBuilder { - const char KeyValueSeparator = '='; - const char KeyValuePairDelimiter = ';'; - const string EndpointScheme = "amqps"; - const string EndpointConfigName = "Endpoint"; - const string SharedAccessKeyNameConfigName = "SharedAccessKeyName"; - const string SharedAccessKeyConfigName = "SharedAccessKey"; - const string SharedAccessSignatureConfigName = "SharedAccessSignature"; - const string AuthenticationConfigName = "Authentication"; + private const char KeyValueSeparator = '='; + private const char KeyValuePairDelimiter = ';'; + private const string EndpointScheme = "amqps"; + private const string EndpointConfigName = "Endpoint"; + private const string SharedAccessKeyNameConfigName = "SharedAccessKeyName"; + private const string SharedAccessKeyConfigName = "SharedAccessKey"; + private const string SharedAccessSignatureConfigName = "SharedAccessSignature"; + private const string AuthenticationConfigName = "Authentication"; - const string EntityPathConfigName = "EntityPath"; - const string TransportTypeConfigName = "TransportType"; + private const string EntityPathConfigName = "EntityPath"; + private const string TransportTypeConfigName = "TransportType"; - const string OperationTimeoutConfigName = "OperationTimeout"; + private const string OperationTimeoutConfigName = "OperationTimeout"; - string entityPath, sasKeyName, sasKey, sasToken, endpoint; - AuthenticationType authType = AuthenticationType.Other; + private string entityPath, sasKeyName, sasKey, sasToken, endpoint; + private AuthenticationType authType = AuthenticationType.Other; public enum AuthenticationType { @@ -341,7 +341,7 @@ public override string ToString() return GetEntityConnectionString(); } - void ParseConnectionString(string connectionString) + private void ParseConnectionString(string connectionString) { // First split based on ';' var keyValuePairs = connectionString.Split(new[] { KeyValuePairDelimiter }, StringSplitOptions.RemoveEmptyEntries); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs index 02af8274e181..663d21caa136 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs @@ -44,8 +44,8 @@ namespace Microsoft.Azure.ServiceBus /// public sealed class SessionClient : ClientEntity, ISessionClient { - const int DefaultPrefetchCount = 0; - readonly ServiceBusDiagnosticSource diagnosticSource; + private const int DefaultPrefetchCount = 0; + private readonly ServiceBusDiagnosticSource diagnosticSource; /// /// Creates a new SessionClient from a @@ -209,7 +209,7 @@ internal SessionClient( } } - ReceiveMode ReceiveMode { get; } + private ReceiveMode ReceiveMode { get; } /// /// Gets the path of the entity. This is either the name of the queue, or the full path of the subscription. @@ -235,11 +235,11 @@ public override TimeSpan OperationTimeout /// public override ServiceBusConnection ServiceBusConnection { get; } - MessagingEntityType? EntityType { get; } + private MessagingEntityType? EntityType { get; } internal int PrefetchCount { get; set; } - ICbsTokenProvider CbsTokenProvider { get; } + private ICbsTokenProvider CbsTokenProvider { get; } /// /// Gets a list of currently registered plugins. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs index b8d9d5e90a7e..593a4a5536b8 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs @@ -13,9 +13,9 @@ namespace Microsoft.Azure.ServiceBus /// . public sealed class SessionHandlerOptions { - int maxConcurrentSessions; - TimeSpan messageWaitTimeout; - TimeSpan maxAutoRenewDuration; + private int maxConcurrentSessions; + private TimeSpan messageWaitTimeout; + private TimeSpan maxAutoRenewDuration; /// Initializes a new instance of the class. /// Default Values: diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs index 447a63538a1e..0e104acce992 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs @@ -9,10 +9,10 @@ namespace Microsoft.Azure.ServiceBus internal sealed class SessionPumpHost { - readonly object syncLock; - SessionReceivePump sessionReceivePump; - CancellationTokenSource sessionPumpCancellationTokenSource; - readonly Uri endpoint; + private readonly object syncLock; + private SessionReceivePump sessionReceivePump; + private CancellationTokenSource sessionPumpCancellationTokenSource; + private readonly Uri endpoint; public SessionPumpHost(string clientId, ReceiveMode receiveMode, ISessionClient sessionClient, Uri endpoint) { @@ -23,11 +23,11 @@ public SessionPumpHost(string clientId, ReceiveMode receiveMode, ISessionClient this.endpoint = endpoint; } - ReceiveMode ReceiveMode { get; } + private ReceiveMode ReceiveMode { get; } - ISessionClient SessionClient { get; } + private ISessionClient SessionClient { get; } - string ClientId { get; } + private string ClientId { get; } public void Close() { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs index a234363b0473..5fbd199e95eb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs @@ -9,17 +9,17 @@ namespace Microsoft.Azure.ServiceBus using System.Threading.Tasks; using Primitives; - sealed class SessionReceivePump + internal sealed class SessionReceivePump { - readonly string clientId; - readonly ISessionClient client; - readonly Func userOnSessionCallback; - readonly SessionHandlerOptions sessionHandlerOptions; - readonly string endpoint; - readonly string entityPath; - readonly CancellationToken pumpCancellationToken; - readonly SemaphoreSlim maxConcurrentSessionsSemaphoreSlim; - readonly SemaphoreSlim maxPendingAcceptSessionsSemaphoreSlim; + private readonly string clientId; + private readonly ISessionClient client; + private readonly Func userOnSessionCallback; + private readonly SessionHandlerOptions sessionHandlerOptions; + private readonly string endpoint; + private readonly string entityPath; + private readonly CancellationToken pumpCancellationToken; + private readonly SemaphoreSlim maxConcurrentSessionsSemaphoreSlim; + private readonly SemaphoreSlim maxPendingAcceptSessionsSemaphoreSlim; private readonly ServiceBusDiagnosticSource diagnosticSource; public SessionReceivePump(string clientId, @@ -43,7 +43,7 @@ public SessionReceivePump(string clientId, diagnosticSource = new ServiceBusDiagnosticSource(client.EntityPath, endpoint); } - ReceiveMode ReceiveMode { get; } + private ReceiveMode ReceiveMode { get; } public void StartPump() { @@ -54,7 +54,7 @@ public void StartPump() } } - static void CancelAutoRenewLock(object state) + private static void CancelAutoRenewLock(object state) { var renewCancellationTokenSource = (CancellationTokenSource)state; @@ -68,20 +68,20 @@ static void CancelAutoRenewLock(object state) } } - bool ShouldRenewSessionLock() + private bool ShouldRenewSessionLock() { return ReceiveMode == ReceiveMode.PeekLock && sessionHandlerOptions.AutoRenewLock; } - Task RaiseExceptionReceived(Exception e, string action) + private Task RaiseExceptionReceived(Exception e, string action) { var eventArgs = new ExceptionReceivedEventArgs(e, action, endpoint, entityPath, clientId); return sessionHandlerOptions.RaiseExceptionReceived(eventArgs); } - async Task CompleteMessageIfNeededAsync(IMessageSession session, Message message) + private async Task CompleteMessageIfNeededAsync(IMessageSession session, Message message) { try { @@ -97,7 +97,7 @@ async Task CompleteMessageIfNeededAsync(IMessageSession session, Message message } } - async Task AbandonMessageIfNeededAsync(IMessageSession session, Message message) + private async Task AbandonMessageIfNeededAsync(IMessageSession session, Message message) { try { @@ -112,7 +112,7 @@ async Task AbandonMessageIfNeededAsync(IMessageSession session, Message message) } } - async Task SessionPumpTaskAsync() + private async Task SessionPumpTaskAsync() { while (!pumpCancellationToken.IsCancellationRequested) { @@ -167,7 +167,7 @@ async Task SessionPumpTaskAsync() } } - async Task MessagePumpTaskAsync(IMessageSession session) + private async Task MessagePumpTaskAsync(IMessageSession session) { if (session == null) { @@ -279,7 +279,7 @@ async Task MessagePumpTaskAsync(IMessageSession session) } } - async Task CloseSessionIfNeededAsync(IMessageSession session) + private async Task CloseSessionIfNeededAsync(IMessageSession session) { if (!session.IsClosedOrClosing) { @@ -296,7 +296,7 @@ async Task CloseSessionIfNeededAsync(IMessageSession session) } } - async Task RenewSessionLockTaskAsync(IMessageSession session, CancellationToken renewLockCancellationToken) + private async Task RenewSessionLockTaskAsync(IMessageSession session, CancellationToken renewLockCancellationToken) { while (!pumpCancellationToken.IsCancellationRequested && !renewLockCancellationToken.IsCancellationRequested) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs index 92405c2272e0..572857e75368 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs @@ -52,13 +52,13 @@ namespace Microsoft.Azure.ServiceBus /// It uses AMQP protocol for communicating with service bus. Use for advanced set of functionality. public class SubscriptionClient : ClientEntity, ISubscriptionClient { - int prefetchCount; - readonly object syncLock; - readonly ServiceBusDiagnosticSource diagnosticSource; + private int prefetchCount; + private readonly object syncLock; + private readonly ServiceBusDiagnosticSource diagnosticSource; - IInnerSubscriptionClient innerSubscriptionClient; - SessionClient sessionClient; - SessionPumpHost sessionPumpHost; + private IInnerSubscriptionClient innerSubscriptionClient; + private SessionClient sessionClient; + private SessionPumpHost sessionPumpHost; /// /// Instantiates a new to perform operations on a subscription. @@ -306,7 +306,7 @@ internal SessionPumpHost SessionPumpHost } } - ICbsTokenProvider CbsTokenProvider { get; } + private ICbsTokenProvider CbsTokenProvider { get; } /// /// Completes a using its lock token. This will delete the message from the subscription. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs index d455d585ed41..33ec12b5950f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs @@ -31,8 +31,8 @@ namespace Microsoft.Azure.ServiceBus /// It uses AMQP protocol for communicating with servicebus. public class TopicClient : ClientEntity, ITopicClient { - readonly object syncLock; - MessageSender innerSender; + private readonly object syncLock; + private MessageSender innerSender; /// /// Instantiates a new to perform operations on a topic. @@ -164,8 +164,8 @@ internal MessageSender InnerSender return innerSender; } } - - ICbsTokenProvider CbsTokenProvider { get; } + + private ICbsTokenProvider CbsTokenProvider { get; } /// /// Sends a message to Service Bus. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/WebSocketConstants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/WebSocketConstants.cs index 3cc077456dda..f2031791c9a5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/WebSocketConstants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/WebSocketConstants.cs @@ -3,7 +3,7 @@ namespace Microsoft.Azure.ServiceBus { - static class WebSocketConstants + internal static class WebSocketConstants { internal const string WebSocketSecureScheme = "wss"; internal const int WebSocketSecurePort = 443; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/API/APIApprovals.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/API/APIApprovals.cs index 1286ed0ef1d0..1e0119a238b2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/API/APIApprovals.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/API/APIApprovals.cs @@ -38,7 +38,7 @@ public void ApproveAzureServiceBus() } } - string Filter(string text) + private string Filter(string text) { return string.Join(Environment.NewLine, text.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) .Where(l => !l.StartsWith("[assembly: System.Runtime.Versioning.TargetFramework")) @@ -51,7 +51,7 @@ string Filter(string text) /// a concern for local runs. /// /// - void CleanApprovalsTempFiles(string approvalsWorkingdDirectory) + private void CleanApprovalsTempFiles(string approvalsWorkingdDirectory) { foreach (var file in Directory.EnumerateFiles(approvalsWorkingdDirectory, $"{ nameof(ApiApprovals) }.*received.txt", SearchOption.AllDirectories)) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs index 2ac749273eab..c506017acd28 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs @@ -13,7 +13,7 @@ public class ExtractActivityTests { [Fact] [DisplayTestMethodName] - void ValidIdAndContextAreExtracted() + private void ValidIdAndContextAreExtracted() { var message = new Message(); message.UserProperties["Diagnostic-Id"] = "diagnostic-id"; @@ -34,7 +34,7 @@ void ValidIdAndContextAreExtracted() [Fact] [DisplayTestMethodName] - void ValidIdAndMultipleContextAreExtracted() + private void ValidIdAndMultipleContextAreExtracted() { var message = new Message(); message.UserProperties["Diagnostic-Id"] = "diagnostic-id"; @@ -59,7 +59,7 @@ void ValidIdAndMultipleContextAreExtracted() [Fact] [DisplayTestMethodName] - void ActivityNameCouldBeChanged() + private void ActivityNameCouldBeChanged() { var message = new Message(); message.UserProperties["Diagnostic-Id"] = "diagnostic-id"; @@ -71,7 +71,7 @@ void ActivityNameCouldBeChanged() [Fact] [DisplayTestMethodName] - void ValidIdAndNoContextAreExtracted() + private void ValidIdAndNoContextAreExtracted() { var message = new Message(); message.UserProperties["Diagnostic-Id"] = "diagnostic-id"; @@ -92,7 +92,7 @@ void ValidIdAndNoContextAreExtracted() [InlineData("not valid context")] [InlineData("not,valid,context")] [DisplayTestMethodName] - void ValidIdAndInvalidContextAreExtracted(string context) + private void ValidIdAndInvalidContextAreExtracted(string context) { var message = new Message(); message.UserProperties["Diagnostic-Id"] = "diagnostic-id"; @@ -112,7 +112,7 @@ void ValidIdAndInvalidContextAreExtracted(string context) [InlineData(null)] [InlineData("")] [DisplayTestMethodName] - void EmptyIdResultsInActivityWithoutParent(string id) + private void EmptyIdResultsInActivityWithoutParent(string id) { var message = new Message(); message.UserProperties["Diagnostic-Id"] = id; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestConstants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestConstants.cs index 250c4dfee52b..81024a2a066a 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestConstants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestConstants.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure { - static class TestConstants + internal static class TestConstants { // Enviornment Variables internal const string ConnectionStringEnvironmentVariable = "SERVICE_BUS_CONNECTION_STRING"; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestUtility.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestUtility.cs index a9b98649931c..3676ee63a9a5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestUtility.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/TestUtility.cs @@ -12,7 +12,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure { - static class TestUtility + internal static class TestUtility { private static readonly Lazy NamespaceConnectionStringInstance = new Lazy( () => new ServiceBusConnectionStringBuilder(ReadEnvironmentConnectionString()).ToString(), LazyThreadSafetyMode.PublicationOnly); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index d9c22fb38059..16eb10d74d9e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -10,7 +10,7 @@ namespace Microsoft.Azure.ServiceBus.Performance using System.Threading; using System.Threading.Tasks; - class Program + internal class Program { private static readonly Stopwatch _stopwatch = Stopwatch.StartNew(); @@ -18,7 +18,7 @@ class Program private static long _messages; - static async Task Main(string[] args) + private static async Task Main(string[] args) { var maxInflight = (args.Length >= 1 ? int.Parse(args[0]) : 1); Log($"Maximum inflight messages: {maxInflight}"); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs index cf28be64ef25..3ee9049fbb5a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs @@ -14,17 +14,17 @@ namespace Microsoft.Azure.ServiceBus.UnitTests using Core; using Xunit; - class TestSessionHandler + internal class TestSessionHandler { - const int NumberOfSessions = 5; - const int MessagesPerSession = 10; + private const int NumberOfSessions = 5; + private const int MessagesPerSession = 10; - readonly SessionPumpHost sessionPumpHost; - readonly ReceiveMode receiveMode; - readonly MessageSender sender; - readonly SessionHandlerOptions sessionHandlerOptions; - ConcurrentDictionary sessionMessageMap; - int totalMessageCount; + private readonly SessionPumpHost sessionPumpHost; + private readonly ReceiveMode receiveMode; + private readonly MessageSender sender; + private readonly SessionHandlerOptions sessionHandlerOptions; + private ConcurrentDictionary sessionMessageMap; + private int totalMessageCount; public TestSessionHandler( ReceiveMode receiveMode, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs index dd0da9ce8599..b5c7e119b5a2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs @@ -15,8 +15,8 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class TransactionTests { - static readonly string ConnectionString = TestUtility.NamespaceConnectionString; - static readonly TimeSpan ReceiveTimeout = TimeSpan.FromSeconds(5); + private static readonly string ConnectionString = TestUtility.NamespaceConnectionString; + private static readonly TimeSpan ReceiveTimeout = TimeSpan.FromSeconds(5); public static IEnumerable TestPermutations => new[] { From ede08a3173909d41d9aad38a0d8cd0c52245dd72 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:20:56 -0400 Subject: [PATCH 05/82] Added missing braces --- .../src/Amqp/ActiveClientLinkManager.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs index 09b6c7563954..642201e65d02 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs @@ -132,8 +132,11 @@ private void SetRenewCbsTokenTimer(ActiveClientLinkObject activeClientLinkObject } var interval = activeClientLinkObject.AuthorizationValidUntilUtc.Subtract(utcNow) - TokenRefreshBuffer; + if (interval < TokenRefreshBuffer) - interval = TimeSpan.Zero; + { + interval = TimeSpan.Zero; + } interval = TimeoutHelper.Min(interval, MaxTokenRefreshTime); From 3addeebf3b91fa6a1014a3c6c0e1601a35bb4b78 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:21:53 -0400 Subject: [PATCH 06/82] Removed redundant argument values --- .../src/Amqp/AmqpTransactionEnlistment.cs | 4 ++-- .../tests/AmqpConverterTests.cs | 4 ++-- .../Diagnostics/QueueClientDiagnosticsTests.cs | 14 +++++++------- .../tests/MessageTests.cs | 6 +++--- .../tests/OnSessionQueueTests.cs | 3 +-- .../tests/OnSessionTopicSubscriptionTests.cs | 6 ++---- 6 files changed, 17 insertions(+), 20 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs index 934c8bffbc2b..c110169cb93c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs @@ -73,7 +73,7 @@ private async Task SinglePhaseCommitAsync(SinglePhaseEnlistment singlePhaseEnlis } catch (Exception e) { - Exception exception = AmqpExceptionHelper.GetClientException(e, null); + Exception exception = AmqpExceptionHelper.GetClientException(e); MessagingEventSource.Log.AmqpTransactionDischargeException(transactionId, AmqpTransactionId, exception); singlePhaseEnlistment.InDoubt(exception); } @@ -98,7 +98,7 @@ private async Task RollbackAsync(SinglePhaseEnlistment singlePhaseEnlistment) } catch (Exception e) { - Exception exception = AmqpExceptionHelper.GetClientException(e, null); + Exception exception = AmqpExceptionHelper.GetClientException(e); MessagingEventSource.Log.AmqpTransactionDischargeException(transactionId, AmqpTransactionId, exception); singlePhaseEnlistment.Aborted(exception); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs index c2be374b8913..2363c02faffc 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs @@ -26,7 +26,7 @@ public void Convert_Amqp_message_with_Amqp_value_array_segment_to_SB_message() var amqpMessage = AmqpMessage.Create(amqpValue); var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); - Assert.Equal(messageBody, sbMessage.GetBody(null)); + Assert.Equal(messageBody, sbMessage.GetBody()); } [Fact] @@ -40,7 +40,7 @@ public void Convert_Amqp_message_with_Amqp_value_byte_array_to_SB_message() var amqpMessage = AmqpMessage.Create(amqpValue); var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); - Assert.Equal(messageBody, sbMessage.GetBody(null)); + Assert.Equal(messageBody, sbMessage.GetBody()); } [Fact] diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs index f802fd9b7527..f1f81bdc3f68 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs @@ -21,7 +21,7 @@ public async Task SendAndHandlerFireEvents() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { - var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); + var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); var eventQueue = CreateEventQueue(); try @@ -102,7 +102,7 @@ public async Task SendAndHandlerFireExceptionEvents() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { - var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); + var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); var eventQueue = CreateEventQueue(); try @@ -188,7 +188,7 @@ public async Task AbandonCompleteFireEvents() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { - var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); + var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); var eventQueue = CreateEventQueue(); try @@ -334,7 +334,7 @@ public async Task PeekFireEvents() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { - var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); + var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); var eventQueue = CreateEventQueue(); try @@ -381,7 +381,7 @@ private async Task DeadLetterFireEvents() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { - var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); + var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); var eventQueue = CreateEventQueue(); try @@ -430,7 +430,7 @@ public async Task RenewLockFireEvents() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { - var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); + var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); var eventQueue = CreateEventQueue(); try @@ -470,7 +470,7 @@ public async Task DeferReceiveDeferredFireEvents() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { - var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); + var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); var eventQueue = CreateEventQueue(); try diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs index e884cbdd43ec..ec4c20631f73 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs @@ -114,7 +114,7 @@ public async Task Should_return_true_for_peeked_message() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { - var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); + var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); try { @@ -139,7 +139,7 @@ public async Task MessageWithMaxMessageSizeShouldWorkAsExpected() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { - var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); + var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); try { @@ -184,7 +184,7 @@ public async Task LargeMessageShouldThrowMessageSizeExceededException() { await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, async queueName => { - var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock); + var queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); try { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs index 8ad38db4cdc2..ed09de4f6d7f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionQueueTests.cs @@ -65,8 +65,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, { var queueClient = new QueueClient( TestUtility.NamespaceConnectionString, - queueName, - ReceiveMode.PeekLock); + queueName); try { var sessionHandlerOptions = diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs index 152fb3571120..112697a09944 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnSessionTopicSubscriptionTests.cs @@ -52,8 +52,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned: false, sessionEnabled: false, var subscriptionClient = new SubscriptionClient( TestUtility.NamespaceConnectionString, topicClient.TopicName, - subscriptionName, - ReceiveMode.PeekLock); + subscriptionName); var sessionHandlerOptions = new SessionHandlerOptions(eventArgs => { @@ -104,8 +103,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN var subscriptionClient = new SubscriptionClient( TestUtility.NamespaceConnectionString, topicClient.TopicName, - subscriptionName, - ReceiveMode.PeekLock); + subscriptionName); try { From 30e18791f064ce91ff66ebb3e8a1a89d64af1ebc Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:30:41 -0400 Subject: [PATCH 07/82] Remove unused values --- .../src/Filters/RuleDescriptionExtensions.cs | 1 - .../src/Management/AuthorizationRules.cs | 4 +- .../src/Management/ManagementClient.cs | 12 +- .../SharedAccessSignatureTokenProvider.cs | 4 +- .../tests/AmqpConverterTests.cs | 1 - .../QueueClientDiagnosticsTests.cs | 519 +++++++++--------- .../Diagnostics/SessionDiagnosticsTests.cs | 208 +++---- .../SubscriptionClientDiagnosticsTests.cs | 38 +- .../FakeDiagnosticsListenerTests.cs | 168 +++--- .../tests/Management/ManagementClientTests.cs | 18 +- .../tests/MessageTests.cs | 2 - .../tests/RetryPolicyTests.cs | 26 +- .../ServiceBusConnectionStringBuilderTests.cs | 2 +- .../tests/TokenProviderTests.cs | 2 +- .../tests/TransactionTests.cs | 22 +- 15 files changed, 510 insertions(+), 517 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs index b3100633cdca..348df2c358bb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs @@ -97,7 +97,6 @@ public static IList ParseCollectionFromContent(string xml) private static RuleDescription ParseFromEntryElement(XElement xEntry) { - var name = xEntry.Element(XName.Get("title", ManagementClientConstants.AtomNamespace)).Value; var ruleDescription = new RuleDescription(); var rdXml = xEntry.Element(XName.Get("content", ManagementClientConstants.AtomNamespace))? diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs index cdf60779b5e2..d506bc4e2c0e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs @@ -10,9 +10,7 @@ namespace Microsoft.Azure.ServiceBus.Management public class AuthorizationRules : List, IEquatable { - private bool RequiresEncryption => Count > 0; - - internal XElement Serialize() + internal XElement Serialize() { var rules = new XElement( XName.Get("AuthorizationRules", ManagementClientConstants.ServiceBusNamespace), diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs index fc8e09e3d3b0..e501d84f8dbd 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs @@ -907,8 +907,8 @@ public virtual async Task QueueExistsAsync(string queuePath, CancellationT try { - // TODO: Optimize by removing deserialization costs. - var qd = await GetQueueAsync(queuePath, cancellationToken).ConfigureAwait(false); + // TODO: Optimize by removing deserialization costs. + await GetQueueAsync(queuePath, cancellationToken).ConfigureAwait(false); } catch (MessagingEntityNotFoundException) { @@ -935,8 +935,8 @@ public virtual async Task TopicExistsAsync(string topicPath, CancellationT try { - // TODO: Optimize by removing deserialization costs. - var td = await GetTopicAsync(topicPath, cancellationToken).ConfigureAwait(false); + // TODO: Optimize by removing deserialization costs. + await GetTopicAsync(topicPath, cancellationToken).ConfigureAwait(false); } catch (MessagingEntityNotFoundException) { @@ -965,8 +965,8 @@ public virtual async Task SubscriptionExistsAsync(string topicPath, string try { - // TODO: Optimize by removing deserialization costs. - var sd = await GetSubscriptionAsync(topicPath, subscriptionName, cancellationToken).ConfigureAwait(false); + // TODO: Optimize by removing deserialization costs. + await GetSubscriptionAsync(topicPath, subscriptionName, cancellationToken).ConfigureAwait(false); } catch (MessagingEntityNotFoundException) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs index 768e78e72a8c..315c073b4eec 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs @@ -17,9 +17,7 @@ namespace Microsoft.Azure.ServiceBus.Primitives /// public class SharedAccessSignatureTokenProvider : TokenProvider { - private const TokenScope DefaultTokenScope = TokenScope.Entity; - - internal static readonly TimeSpan DefaultTokenTTL = TimeSpan.FromMinutes(60); + internal static readonly TimeSpan DefaultTokenTTL = TimeSpan.FromMinutes(60); private readonly byte[] encodedSharedAccessKey; private readonly string keyName; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs index 2363c02faffc..95c98761d100 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs @@ -86,7 +86,6 @@ public void Convert_SB_message_to_Amqp_message_and_back() var contentType = Guid.NewGuid().ToString(); var replyTo = Guid.NewGuid().ToString(); var replyToSessionId = Guid.NewGuid().ToString(); - var publisher = Guid.NewGuid().ToString(); var timeToLive = TimeSpan.FromDays(5); var sbMessage = new Message(messageBody) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs index f1f81bdc3f68..ca3f1f1698ba 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs @@ -27,65 +27,65 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Enable((name, queue, arg) => !name.Contains("Receive") && !name.Contains("Exception")); + listener.Enable((name, queue, arg) => !name.Contains("Receive") && !name.Contains("Exception")); - var parentActivity = new Activity("test").AddBaggage("k1", "v1").AddBaggage("k2", "v2"); + var parentActivity = new Activity("test").AddBaggage("k1", "v1").AddBaggage("k2", "v2"); - parentActivity.Start(); - await TestUtility.SendSessionMessagesAsync(queueClient.InnerSender, 1, 1); - parentActivity.Stop(); + parentActivity.Start(); + await TestUtility.SendSessionMessagesAsync(queueClient.InnerSender, 1, 1); + parentActivity.Stop(); - var exceptionCalled = false; - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var exceptionCalled = false; + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - queueClient.RegisterMessageHandler((msg, ct) => - { - tcs.TrySetResult(Activity.Current); - return Task.CompletedTask; - }, - exArgs => - { - // Do not set the completion source exception to avoid throwing - // when the task is awaited. The sentinal variable is checked to detect - // exception cases. - exceptionCalled = true; - return Task.CompletedTask; - }); + queueClient.RegisterMessageHandler((msg, ct) => + { + tcs.TrySetResult(Activity.Current); + return Task.CompletedTask; + }, + exArgs => + { + // Do not set the completion source exception to avoid throwing + // when the task is awaited. The sentinal variable is checked to detect + // exception cases. + exceptionCalled = true; + return Task.CompletedTask; + }); - var processActivity = await tcs.Task.WithTimeout(DefaultTimeout); + var processActivity = await tcs.Task.WithTimeout(DefaultTimeout); - Assert.True(eventQueue.TryDequeue(out var sendStart)); - AssertSendStart(queueName, sendStart.eventName, sendStart.payload, sendStart.activity, parentActivity); + Assert.True(eventQueue.TryDequeue(out var sendStart)); + AssertSendStart(queueName, sendStart.eventName, sendStart.payload, sendStart.activity, parentActivity); - Assert.True(eventQueue.TryDequeue(out var sendStop)); - AssertSendStop(queueName, sendStop.eventName, sendStop.payload, sendStop.activity, sendStart.activity); + Assert.True(eventQueue.TryDequeue(out var sendStop)); + AssertSendStop(queueName, sendStop.eventName, sendStop.payload, sendStop.activity, sendStart.activity); - Assert.True(eventQueue.TryDequeue(out var processStart)); - AssertProcessStart(queueName, processStart.eventName, processStart.payload, processStart.activity, sendStart.activity); + Assert.True(eventQueue.TryDequeue(out var processStart)); + AssertProcessStart(queueName, processStart.eventName, processStart.payload, processStart.activity, sendStart.activity); - // message is processed, but complete happens after that - // let's wat until Complete starts and ends and Process ends - int wait = 0; - while (wait++ < MaxWaitSec && eventQueue.Count < 3) - { - await Task.Delay(TimeSpan.FromSeconds(1)); - } + // message is processed, but complete happens after that + // let's wat until Complete starts and ends and Process ends + int wait = 0; + while (wait++ < MaxWaitSec && eventQueue.Count < 3) + { + await Task.Delay(TimeSpan.FromSeconds(1)); + } - Assert.True(eventQueue.TryDequeue(out var completeStart)); - AssertCompleteStart(queueName, completeStart.eventName, completeStart.payload, completeStart.activity, processStart.activity); + Assert.True(eventQueue.TryDequeue(out var completeStart)); + AssertCompleteStart(queueName, completeStart.eventName, completeStart.payload, completeStart.activity, processStart.activity); - Assert.True(eventQueue.TryDequeue(out var completeStop)); - AssertCompleteStop(queueName, completeStop.eventName, completeStop.payload, completeStop.activity, completeStart.activity, processStart.activity); + Assert.True(eventQueue.TryDequeue(out var completeStop)); + AssertCompleteStop(queueName, completeStop.eventName, completeStop.payload, completeStop.activity, completeStart.activity, processStart.activity); - Assert.True(eventQueue.TryDequeue(out var processStop)); - AssertProcessStop(queueName, processStop.eventName, processStop.payload, processStop.activity, processStart.activity); + Assert.True(eventQueue.TryDequeue(out var processStop)); + AssertProcessStop(queueName, processStop.eventName, processStop.payload, processStop.activity, processStart.activity); - Assert.False(eventQueue.TryDequeue(out var evnt)); + Assert.False(eventQueue.TryDequeue(out _)); - Assert.Equal(processStop.activity, processActivity); - Assert.False(exceptionCalled); + Assert.Equal(processStop.activity, processActivity); + Assert.False(exceptionCalled); } } finally @@ -108,70 +108,70 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); - listener.Enable((name, queue, arg) => !name.EndsWith(".Start") && !name.Contains("Receive") ); - - var count = 0; - var exceptionCalled = false; - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - queueClient.RegisterMessageHandler((msg, ct) => - { - if (count++ == 0) - { - throw new Exception("123"); - } - tcs.TrySetResult(count); - return Task.CompletedTask; - }, - exArgs => - { - // Do not set the completion source exception to avoid throwing - // when the task is awaited. The sentinal variable is checked to detect - // exception cases. - exceptionCalled = true; - return Task.CompletedTask; - }); - - await tcs.Task.WithTimeout(DefaultTimeout); - Assert.True(exceptionCalled); - - // message is processed, but abandon happens after that - // let's spin until Complete call starts and ends - int wait = 0; - while (wait++ < MaxWaitSec && eventQueue.Count < 3) - { - await Task.Delay(TimeSpan.FromSeconds(1)); - } - - Assert.True(eventQueue.TryDequeue(out var abandonStop)); - AssertAbandonStop(queueName, abandonStop.eventName, abandonStop.payload, abandonStop.activity, null); - - Assert.True(eventQueue.TryDequeue(out var exception)); - AssertException(queueName, exception.eventName, exception.payload, exception.activity, null); - - Assert.True(eventQueue.TryDequeue(out var processStop)); - AssertProcessStop(queueName, processStop.eventName, processStop.payload, processStop.activity, null); - - Assert.Equal(processStop.activity, abandonStop.activity.Parent); - Assert.Equal(processStop.activity, exception.activity); - - // message will be processed and compelted again - wait = 0; - while (wait++ < MaxWaitSec && eventQueue.Count < 2 ) - { - await Task.Delay(TimeSpan.FromSeconds(1)); - } - - Assert.True(eventQueue.TryDequeue(out var completeStop)); - AssertCompleteStop(queueName, completeStop.eventName, completeStop.payload, completeStop.activity, null, null); - - Assert.True(eventQueue.TryDequeue(out processStop)); - AssertProcessStop(queueName, processStop.eventName, processStop.payload, processStop.activity, null); - - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); + listener.Enable((name, queue, arg) => !name.EndsWith(".Start") && !name.Contains("Receive") ); + + var count = 0; + var exceptionCalled = false; + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + queueClient.RegisterMessageHandler((msg, ct) => + { + if (count++ == 0) + { + throw new Exception("123"); + } + tcs.TrySetResult(count); + return Task.CompletedTask; + }, + exArgs => + { + // Do not set the completion source exception to avoid throwing + // when the task is awaited. The sentinal variable is checked to detect + // exception cases. + exceptionCalled = true; + return Task.CompletedTask; + }); + + await tcs.Task.WithTimeout(DefaultTimeout); + Assert.True(exceptionCalled); + + // message is processed, but abandon happens after that + // let's spin until Complete call starts and ends + int wait = 0; + while (wait++ < MaxWaitSec && eventQueue.Count < 3) + { + await Task.Delay(TimeSpan.FromSeconds(1)); + } + + Assert.True(eventQueue.TryDequeue(out var abandonStop)); + AssertAbandonStop(queueName, abandonStop.eventName, abandonStop.payload, abandonStop.activity, null); + + Assert.True(eventQueue.TryDequeue(out var exception)); + AssertException(queueName, exception.eventName, exception.payload, exception.activity, null); + + Assert.True(eventQueue.TryDequeue(out var processStop)); + AssertProcessStop(queueName, processStop.eventName, processStop.payload, processStop.activity, null); + + Assert.Equal(processStop.activity, abandonStop.activity.Parent); + Assert.Equal(processStop.activity, exception.activity); + + // message will be processed and compelted again + wait = 0; + while (wait++ < MaxWaitSec && eventQueue.Count < 2 ) + { + await Task.Delay(TimeSpan.FromSeconds(1)); + } + + Assert.True(eventQueue.TryDequeue(out var completeStop)); + AssertCompleteStop(queueName, completeStop.eventName, completeStop.payload, completeStop.activity, null, null); + + Assert.True(eventQueue.TryDequeue(out processStop)); + AssertProcessStop(queueName, processStop.eventName, processStop.payload, processStop.activity, null); + + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -194,31 +194,31 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); - var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); + var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); - listener.Enable((name, queue, arg) => name.Contains("Abandon") || name.Contains("Complete")); - await TestUtility.AbandonMessagesAsync(queueClient.InnerReceiver, messages); + listener.Enable((name, queue, arg) => name.Contains("Abandon") || name.Contains("Complete")); + await TestUtility.AbandonMessagesAsync(queueClient.InnerReceiver, messages); - messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); + messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); - await TestUtility.CompleteMessagesAsync(queueClient.InnerReceiver, messages); + await TestUtility.CompleteMessagesAsync(queueClient.InnerReceiver, messages); - Assert.True(eventQueue.TryDequeue(out var abandonStart)); - AssertAbandonStart(queueName, abandonStart.eventName, abandonStart.payload, abandonStart.activity, null); + Assert.True(eventQueue.TryDequeue(out var abandonStart)); + AssertAbandonStart(queueName, abandonStart.eventName, abandonStart.payload, abandonStart.activity, null); - Assert.True(eventQueue.TryDequeue(out var abandonStop)); - AssertAbandonStop(queueName, abandonStop.eventName, abandonStop.payload, abandonStop.activity, abandonStart.activity); + Assert.True(eventQueue.TryDequeue(out var abandonStop)); + AssertAbandonStop(queueName, abandonStop.eventName, abandonStop.payload, abandonStop.activity, abandonStart.activity); - Assert.True(eventQueue.TryDequeue(out var completeStart)); - AssertCompleteStart(queueName, completeStart.eventName, completeStart.payload, completeStart.activity, null); + Assert.True(eventQueue.TryDequeue(out var completeStart)); + AssertCompleteStart(queueName, completeStart.eventName, completeStart.payload, completeStart.activity, null); - Assert.True(eventQueue.TryDequeue(out var completeStop)); - AssertCompleteStop(queueName, completeStop.eventName, completeStop.payload, completeStop.activity, completeStart.activity, null); + Assert.True(eventQueue.TryDequeue(out var completeStop)); + AssertCompleteStop(queueName, completeStop.eventName, completeStop.payload, completeStop.activity, completeStart.activity, null); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -241,23 +241,24 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Enable((name, queue, arg) => name.Contains("Send") || name.Contains("Receive")); - var messages = await queueClient.InnerReceiver.ReceiveAsync(2, TimeSpan.FromSeconds(5)); - - int receivedStopCount = 0; - Assert.Equal(2, eventQueue.Count); - while (eventQueue.TryDequeue(out var receiveStart)) - { - var startCount = AssertReceiveStart(queueName, receiveStart.eventName, receiveStart.payload, receiveStart.activity, -1); - - Assert.True(eventQueue.TryDequeue(out var receiveStop)); - receivedStopCount += AssertReceiveStop(queueName, receiveStop.eventName, receiveStop.payload, receiveStop.activity, receiveStart.activity, null, startCount, -1); - } - - Assert.Equal(0, receivedStopCount); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + listener.Enable((name, queue, arg) => name.Contains("Send") || name.Contains("Receive")); + + await queueClient.InnerReceiver.ReceiveAsync(2, TimeSpan.FromSeconds(5)); + + int receivedStopCount = 0; + Assert.Equal(2, eventQueue.Count); + while (eventQueue.TryDequeue(out var receiveStart)) + { + var startCount = AssertReceiveStart(queueName, receiveStart.eventName, receiveStart.payload, receiveStart.activity, -1); + + Assert.True(eventQueue.TryDequeue(out var receiveStop)); + receivedStopCount += AssertReceiveStop(queueName, receiveStop.eventName, receiveStop.payload, receiveStop.activity, receiveStart.activity, null, startCount, -1); + } + + Assert.Equal(0, receivedStopCount); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -280,44 +281,44 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Enable( (name, queue, arg) => name.Contains("Send") || name.Contains("Receive") ); - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 2); - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 3); - var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 5); + listener.Enable( (name, queue, arg) => name.Contains("Send") || name.Contains("Receive") ); + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 2); + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 3); + await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 5); - Assert.True(eventQueue.TryDequeue(out var sendStart1)); - AssertSendStart(queueName, sendStart1.eventName, sendStart1.payload, sendStart1.activity, null, 2); + Assert.True(eventQueue.TryDequeue(out var sendStart1)); + AssertSendStart(queueName, sendStart1.eventName, sendStart1.payload, sendStart1.activity, null, 2); - Assert.True(eventQueue.TryDequeue(out var sendStop1)); - AssertSendStop(queueName, sendStop1.eventName, sendStop1.payload, sendStop1.activity, sendStop1.activity, 2); + Assert.True(eventQueue.TryDequeue(out var sendStop1)); + AssertSendStop(queueName, sendStop1.eventName, sendStop1.payload, sendStop1.activity, sendStop1.activity, 2); - Assert.True(eventQueue.TryDequeue(out var sendStart2)); - AssertSendStart(queueName, sendStart2.eventName, sendStart2.payload, sendStart2.activity, null, 3); + Assert.True(eventQueue.TryDequeue(out var sendStart2)); + AssertSendStart(queueName, sendStart2.eventName, sendStart2.payload, sendStart2.activity, null, 3); - Assert.True(eventQueue.TryDequeue(out var sendStop2)); - AssertSendStop(queueName, sendStop2.eventName, sendStop2.payload, sendStop2.activity, sendStop2.activity, 3); + Assert.True(eventQueue.TryDequeue(out var sendStop2)); + AssertSendStop(queueName, sendStop2.eventName, sendStop2.payload, sendStop2.activity, sendStop2.activity, 3); - int receivedStopCount = 0; - string relatedTo = ""; - while (eventQueue.TryDequeue(out var receiveStart)) - { - var startCount = AssertReceiveStart(queueName, receiveStart.eventName, receiveStart.payload, receiveStart.activity, -1); + int receivedStopCount = 0; + string relatedTo = ""; + while (eventQueue.TryDequeue(out var receiveStart)) + { + var startCount = AssertReceiveStart(queueName, receiveStart.eventName, receiveStart.payload, receiveStart.activity, -1); - Assert.True(eventQueue.TryDequeue(out var receiveStop)); + Assert.True(eventQueue.TryDequeue(out var receiveStop)); - receivedStopCount += - AssertReceiveStop(queueName, receiveStop.eventName, receiveStop.payload, receiveStop.activity, receiveStart.activity, null, startCount, -1); + receivedStopCount += + AssertReceiveStop(queueName, receiveStop.eventName, receiveStop.payload, receiveStop.activity, receiveStart.activity, null, startCount, -1); - relatedTo += receiveStop.activity.Tags.Single(t => t.Key == "RelatedTo").Value; - } + relatedTo += receiveStop.activity.Tags.Single(t => t.Key == "RelatedTo").Value; + } - Assert.Equal(5, receivedStopCount); - Assert.Contains(sendStart1.activity.Id, relatedTo); - Assert.Contains(sendStart2.activity.Id, relatedTo); + Assert.Equal(5, receivedStopCount); + Assert.Contains(sendStart1.activity.Id, relatedTo); + Assert.Contains(sendStart2.activity.Id, relatedTo); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -340,31 +341,31 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Enable((name, queuName, arg) => name.Contains("Send") || name.Contains("Peek")); + listener.Enable((name, queuName, arg) => name.Contains("Send") || name.Contains("Peek")); - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); - await TestUtility.PeekMessageAsync(queueClient.InnerReceiver); + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); + await TestUtility.PeekMessageAsync(queueClient.InnerReceiver); - listener.Disable(); + listener.Disable(); - var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); - await TestUtility.CompleteMessagesAsync(queueClient.InnerReceiver, messages); + var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); + await TestUtility.CompleteMessagesAsync(queueClient.InnerReceiver, messages); - Assert.True(eventQueue.TryDequeue(out var sendStart)); - AssertSendStart(queueName, sendStart.eventName, sendStart.payload, sendStart.activity, null); + Assert.True(eventQueue.TryDequeue(out var sendStart)); + AssertSendStart(queueName, sendStart.eventName, sendStart.payload, sendStart.activity, null); - Assert.True(eventQueue.TryDequeue(out var sendStop)); - AssertSendStop(queueName, sendStop.eventName, sendStop.payload, sendStop.activity, sendStart.activity); + Assert.True(eventQueue.TryDequeue(out var sendStop)); + AssertSendStop(queueName, sendStop.eventName, sendStop.payload, sendStop.activity, sendStart.activity); - Assert.True(eventQueue.TryDequeue(out var peekStart)); - AssertPeekStart(queueName, peekStart.eventName, peekStart.payload, peekStart.activity); + Assert.True(eventQueue.TryDequeue(out var peekStart)); + AssertPeekStart(queueName, peekStart.eventName, peekStart.payload, peekStart.activity); - Assert.True(eventQueue.TryDequeue(out var peekStop)); - AssertPeekStop(queueName, peekStop.eventName, peekStop.payload, peekStop.activity, peekStart.activity, sendStart.activity); + Assert.True(eventQueue.TryDequeue(out var peekStop)); + AssertPeekStop(queueName, peekStop.eventName, peekStop.payload, peekStop.activity, peekStart.activity, sendStart.activity); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -387,33 +388,33 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); - var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); - - listener.Enable((name, queue, arg) => name.Contains("DeadLetter")); - await TestUtility.DeadLetterMessagesAsync(queueClient.InnerReceiver, messages); - listener.Disable(); - - QueueClient deadLetterQueueClient = null; - try - { - deadLetterQueueClient = new QueueClient(TestUtility.NamespaceConnectionString, EntityNameHelper.FormatDeadLetterPath(queueClient.QueueName), ReceiveMode.ReceiveAndDelete); - await TestUtility.ReceiveMessagesAsync(deadLetterQueueClient.InnerReceiver, 1); - } - finally - { - await deadLetterQueueClient?.CloseAsync(); - } - - Assert.True(eventQueue.TryDequeue(out var deadLetterStart)); - AssertDeadLetterStart(queueName, deadLetterStart.eventName, deadLetterStart.payload, deadLetterStart.activity, null); - - Assert.True(eventQueue.TryDequeue(out var deadLetterStop)); - AssertDeadLetterStop(queueName, deadLetterStop.eventName, deadLetterStop.payload, deadLetterStop.activity, deadLetterStart.activity); - - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); + var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); + + listener.Enable((name, queue, arg) => name.Contains("DeadLetter")); + await TestUtility.DeadLetterMessagesAsync(queueClient.InnerReceiver, messages); + listener.Disable(); + + QueueClient deadLetterQueueClient = null; + try + { + deadLetterQueueClient = new QueueClient(TestUtility.NamespaceConnectionString, EntityNameHelper.FormatDeadLetterPath(queueClient.QueueName), ReceiveMode.ReceiveAndDelete); + await TestUtility.ReceiveMessagesAsync(deadLetterQueueClient.InnerReceiver, 1); + } + finally + { + await deadLetterQueueClient?.CloseAsync(); + } + + Assert.True(eventQueue.TryDequeue(out var deadLetterStart)); + AssertDeadLetterStart(queueName, deadLetterStart.eventName, deadLetterStart.payload, deadLetterStart.activity, null); + + Assert.True(eventQueue.TryDequeue(out var deadLetterStop)); + AssertDeadLetterStop(queueName, deadLetterStop.eventName, deadLetterStop.payload, deadLetterStop.activity, deadLetterStart.activity); + + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -436,24 +437,24 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener) ?? throw new ArgumentNullException("SubscribeToEvents(listener)")) { - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); - var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); + var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); - listener.Enable((name, queue, arg) => name.Contains("RenewLock")); - await queueClient.InnerReceiver.RenewLockAsync(messages[0]); - listener.Disable(); + listener.Enable((name, queue, arg) => name.Contains("RenewLock")); + await queueClient.InnerReceiver.RenewLockAsync(messages[0]); + listener.Disable(); - await TestUtility.CompleteMessagesAsync(queueClient.InnerReceiver, messages); + await TestUtility.CompleteMessagesAsync(queueClient.InnerReceiver, messages); - Assert.True(eventQueue.TryDequeue(out var renewStart)); - AssertRenewLockStart(queueName, renewStart.eventName, renewStart.payload, renewStart.activity, null); + Assert.True(eventQueue.TryDequeue(out var renewStart)); + AssertRenewLockStart(queueName, renewStart.eventName, renewStart.payload, renewStart.activity, null); - Assert.True(eventQueue.TryDequeue(out var renewStop)); - AssertRenewLockStop(queueName, renewStop.eventName, renewStop.payload, renewStop.activity, renewStart.activity); + Assert.True(eventQueue.TryDequeue(out var renewStop)); + AssertRenewLockStop(queueName, renewStop.eventName, renewStop.payload, renewStop.activity, renewStart.activity); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -476,37 +477,37 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Enable((name, queue, arg) => name.Contains("Send") || name.Contains("Defer") || name.Contains("Receive")); + listener.Enable((name, queue, arg) => name.Contains("Send") || name.Contains("Defer") || name.Contains("Receive")); - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); - var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); - await TestUtility.DeferMessagesAsync(queueClient.InnerReceiver, messages); - var message = await queueClient.InnerReceiver.ReceiveDeferredMessageAsync(messages[0].SystemProperties.SequenceNumber); + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); + var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); + await TestUtility.DeferMessagesAsync(queueClient.InnerReceiver, messages); + var message = await queueClient.InnerReceiver.ReceiveDeferredMessageAsync(messages[0].SystemProperties.SequenceNumber); - listener.Disable(); - await TestUtility.CompleteMessagesAsync(queueClient.InnerReceiver, new[] {message}); + listener.Disable(); + await TestUtility.CompleteMessagesAsync(queueClient.InnerReceiver, new[] {message}); - Assert.True(eventQueue.TryDequeue(out var sendStart)); - Assert.True(eventQueue.TryDequeue(out var sendStop)); - Assert.True(eventQueue.TryDequeue(out var receiveStart)); - Assert.True(eventQueue.TryDequeue(out var receiveStop)); + Assert.True(eventQueue.TryDequeue(out var sendStart)); + Assert.True(eventQueue.TryDequeue(out _)); + Assert.True(eventQueue.TryDequeue(out _)); + Assert.True(eventQueue.TryDequeue(out _)); - Assert.True(eventQueue.TryDequeue(out var deferStart)); - AssertDeferStart(queueName, deferStart.eventName, deferStart.payload, deferStart.activity, null); + Assert.True(eventQueue.TryDequeue(out var deferStart)); + AssertDeferStart(queueName, deferStart.eventName, deferStart.payload, deferStart.activity, null); - Assert.True(eventQueue.TryDequeue(out var deferStop)); - AssertDeferStop(queueName, deferStop.eventName, deferStop.payload, deferStop.activity, deferStart.activity); + Assert.True(eventQueue.TryDequeue(out var deferStop)); + AssertDeferStop(queueName, deferStop.eventName, deferStop.payload, deferStop.activity, deferStart.activity); - Assert.True(eventQueue.TryDequeue(out var receiveDeferredStart)); - AssertReceiveDeferredStart(queueName, receiveDeferredStart.eventName, receiveDeferredStart.payload, receiveDeferredStart.activity); + Assert.True(eventQueue.TryDequeue(out var receiveDeferredStart)); + AssertReceiveDeferredStart(queueName, receiveDeferredStart.eventName, receiveDeferredStart.payload, receiveDeferredStart.activity); - Assert.True(eventQueue.TryDequeue(out var receiveDeferredStop)); - AssertReceiveDeferredStop(queueName, receiveDeferredStop.eventName, receiveDeferredStop.payload, - receiveDeferredStop.activity, receiveDeferredStart.activity, sendStart.activity); + Assert.True(eventQueue.TryDequeue(out var receiveDeferredStop)); + AssertReceiveDeferredStop(queueName, receiveDeferredStop.eventName, receiveDeferredStop.payload, + receiveDeferredStop.activity, receiveDeferredStart.activity, sendStart.activity); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -529,31 +530,31 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - Activity parentActivity = new Activity("test"); - listener.Enable((name, queue, arg) => name.Contains("Schedule") || name.Contains("Cancel")); + Activity parentActivity = new Activity("test"); + listener.Enable((name, queue, arg) => name.Contains("Schedule") || name.Contains("Cancel")); - parentActivity.Start(); + parentActivity.Start(); - var sequenceNumber = await queueClient.InnerSender.ScheduleMessageAsync(new Message(), DateTimeOffset.UtcNow.AddHours(1)); - await queueClient.InnerSender.CancelScheduledMessageAsync(sequenceNumber); + var sequenceNumber = await queueClient.InnerSender.ScheduleMessageAsync(new Message(), DateTimeOffset.UtcNow.AddHours(1)); + await queueClient.InnerSender.CancelScheduledMessageAsync(sequenceNumber); - Assert.True(eventQueue.TryDequeue(out var scheduleStart)); - AssertScheduleStart(queueName, scheduleStart.eventName, scheduleStart.payload, scheduleStart.activity, - parentActivity); + Assert.True(eventQueue.TryDequeue(out var scheduleStart)); + AssertScheduleStart(queueName, scheduleStart.eventName, scheduleStart.payload, scheduleStart.activity, + parentActivity); - Assert.True(eventQueue.TryDequeue(out var scheduleStop)); - AssertScheduleStop(queueName, scheduleStop.eventName, scheduleStop.payload, scheduleStop.activity, - scheduleStart.activity); + Assert.True(eventQueue.TryDequeue(out var scheduleStop)); + AssertScheduleStop(queueName, scheduleStop.eventName, scheduleStop.payload, scheduleStop.activity, + scheduleStart.activity); - Assert.True(eventQueue.TryDequeue(out var cancelStart)); - AssertCancelStart(queueName, cancelStart.eventName, cancelStart.payload, cancelStart.activity, parentActivity); + Assert.True(eventQueue.TryDequeue(out var cancelStart)); + AssertCancelStart(queueName, cancelStart.eventName, cancelStart.payload, cancelStart.activity, parentActivity); - Assert.True(eventQueue.TryDequeue(out var cancelStop)); - AssertCancelStop(queueName, cancelStop.eventName, cancelStop.payload, cancelStop.activity, cancelStart.activity); + Assert.True(eventQueue.TryDequeue(out var cancelStop)); + AssertCancelStop(queueName, cancelStop.eventName, cancelStop.payload, cancelStop.activity, cancelStart.activity); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs index a9dcebfe65f5..8743a71fd6a5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs @@ -30,62 +30,62 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Enable(); + listener.Enable(); - var sessionId = Guid.NewGuid().ToString(); - await messageSender.SendAsync(new Message - { - MessageId = "messageId", - SessionId = sessionId - }); + var sessionId = Guid.NewGuid().ToString(); + await messageSender.SendAsync(new Message + { + MessageId = "messageId", + SessionId = sessionId + }); - messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId); + messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId); - await messageSession.SetStateAsync(new byte[] {1}); - await messageSession.GetStateAsync(); - await messageSession.SetStateAsync(new byte[] { }); - await messageSession.ReceiveAsync(); + await messageSession.SetStateAsync(new byte[] {1}); + await messageSession.GetStateAsync(); + await messageSession.SetStateAsync(new byte[] { }); + await messageSession.ReceiveAsync(); - Assert.True(eventQueue.TryDequeue(out var sendStart)); - AssertSendStart(queueName, sendStart.eventName, sendStart.payload, sendStart.activity, null); + Assert.True(eventQueue.TryDequeue(out var sendStart)); + AssertSendStart(queueName, sendStart.eventName, sendStart.payload, sendStart.activity, null); - Assert.True(eventQueue.TryDequeue(out var sendStop)); - AssertSendStop(queueName, sendStop.eventName, sendStop.payload, sendStop.activity, sendStart.activity); + Assert.True(eventQueue.TryDequeue(out var sendStop)); + AssertSendStop(queueName, sendStop.eventName, sendStop.payload, sendStop.activity, sendStart.activity); - Assert.True(eventQueue.TryDequeue(out var acceptStart)); - AssertAcceptMessageSessionStart(queueName, acceptStart.eventName, acceptStart.payload, acceptStart.activity); + Assert.True(eventQueue.TryDequeue(out var acceptStart)); + AssertAcceptMessageSessionStart(queueName, acceptStart.eventName, acceptStart.payload, acceptStart.activity); - Assert.True(eventQueue.TryDequeue(out var acceptStop)); - AssertAcceptMessageSessionStop(queueName, acceptStop.eventName, acceptStop.payload, acceptStop.activity, - acceptStart.activity); + Assert.True(eventQueue.TryDequeue(out var acceptStop)); + AssertAcceptMessageSessionStop(queueName, acceptStop.eventName, acceptStop.payload, acceptStop.activity, + acceptStart.activity); - Assert.True(eventQueue.TryDequeue(out var setStateStart)); - AssertSetSessionStateStart(queueName, setStateStart.eventName, setStateStart.payload, setStateStart.activity); + Assert.True(eventQueue.TryDequeue(out var setStateStart)); + AssertSetSessionStateStart(queueName, setStateStart.eventName, setStateStart.payload, setStateStart.activity); - Assert.True(eventQueue.TryDequeue(out var setStateStop)); - AssertSetSessionStateStop(queueName, setStateStop.eventName, setStateStop.payload, setStateStop.activity, - setStateStart.activity); + Assert.True(eventQueue.TryDequeue(out var setStateStop)); + AssertSetSessionStateStop(queueName, setStateStop.eventName, setStateStop.payload, setStateStop.activity, + setStateStart.activity); - Assert.True(eventQueue.TryDequeue(out var getStateStart)); - AssertGetSessionStateStart(queueName, getStateStart.eventName, getStateStart.payload, getStateStart.activity); + Assert.True(eventQueue.TryDequeue(out var getStateStart)); + AssertGetSessionStateStart(queueName, getStateStart.eventName, getStateStart.payload, getStateStart.activity); - Assert.True(eventQueue.TryDequeue(out var getStateStop)); - AssertGetSessionStateStop(queueName, getStateStop.eventName, getStateStop.payload, getStateStop.activity, - getStateStop.activity); + Assert.True(eventQueue.TryDequeue(out var getStateStop)); + AssertGetSessionStateStop(queueName, getStateStop.eventName, getStateStop.payload, getStateStop.activity, + getStateStop.activity); - Assert.True(eventQueue.TryDequeue(out var setStateStart2)); - Assert.True(eventQueue.TryDequeue(out var setStateStop2)); + Assert.True(eventQueue.TryDequeue(out _)); + Assert.True(eventQueue.TryDequeue(out _)); - Assert.True(eventQueue.TryDequeue(out var receiveStart)); - AssertReceiveStart(queueName, receiveStart.eventName, receiveStart.payload, receiveStart.activity); + Assert.True(eventQueue.TryDequeue(out var receiveStart)); + AssertReceiveStart(queueName, receiveStart.eventName, receiveStart.payload, receiveStart.activity); - Assert.True(eventQueue.TryDequeue(out var receiveStop)); - AssertReceiveStop(queueName, receiveStop.eventName, receiveStop.payload, receiveStop.activity, receiveStart.activity, - sendStart.activity); + Assert.True(eventQueue.TryDequeue(out var receiveStop)); + AssertReceiveStop(queueName, receiveStop.eventName, receiveStop.payload, receiveStop.activity, receiveStart.activity, + sendStart.activity); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -116,72 +116,72 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - queueClient.ServiceBusConnection.OperationTimeout = timeout; - queueClient.SessionClient.OperationTimeout = timeout; + queueClient.ServiceBusConnection.OperationTimeout = timeout; + queueClient.SessionClient.OperationTimeout = timeout; - var sw = Stopwatch.StartNew(); + var sw = Stopwatch.StartNew(); - listener.Enable((name, queue, arg) => !name.Contains("AcceptMessageSession") && - !name.Contains("Receive") && - !name.Contains("Exception")); - var sessionId = Guid.NewGuid().ToString(); - var message = new Message - { - MessageId = "messageId", - SessionId = sessionId - }; - await queueClient.SendAsync(message); - - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - queueClient.RegisterSessionHandler((session, msg, ct) => - { - tcs.TrySetResult(0); - return Task.CompletedTask; - }, - exArgs => - { - tcs.TrySetException(exArgs.Exception); - return Task.CompletedTask; - }); - - await tcs.Task.WithTimeout(DefaultTimeout); - - Assert.True(eventQueue.TryDequeue(out var sendStart)); - AssertSendStart(queueName, sendStart.eventName, sendStart.payload, sendStart.activity, null); - - Assert.True(eventQueue.TryDequeue(out var sendStop)); - AssertSendStop(queueName, sendStop.eventName, sendStop.payload, sendStop.activity, sendStart.activity); - - Assert.True(eventQueue.TryDequeue(out var processStart)); - AssertProcessSessionStart(queueName, processStart.eventName, processStart.payload, processStart.activity, sendStart.activity); - - int wait = 0; - while (wait++ < MaxWaitSec && eventQueue.Count < 1) - { - await Task.Delay(TimeSpan.FromSeconds(1)); - } - - Assert.True(eventQueue.TryDequeue(out var processStop)); - AssertProcessSessionStop(queueName, processStop.eventName, processStop.payload, processStop.activity, - processStart.activity); - - Assert.True(eventQueue.IsEmpty); - - // workaround for https://github.com/Azure/azure-service-bus-dotnet/issues/372: - // SessionPumpTaskAsync calls AcceptMessageSessionAsync() without cancellation token. - // Even after SessionPump is stopped, this Task may still wait for session during operation timeout - // It may interferee with other tests by acception it's sessions and throwing exceptions. - // So, let's wait for timeout and a bit more to make sure all created tasks are completed - sw.Stop(); - - var timeToWait = (timeout - sw.Elapsed).TotalMilliseconds + 1000; - if (timeToWait > 0) - { - await Task.Delay((int)timeToWait); - } + listener.Enable((name, queue, arg) => !name.Contains("AcceptMessageSession") && + !name.Contains("Receive") && + !name.Contains("Exception")); + var sessionId = Guid.NewGuid().ToString(); + var message = new Message + { + MessageId = "messageId", + SessionId = sessionId + }; + await queueClient.SendAsync(message); + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + queueClient.RegisterSessionHandler((session, msg, ct) => + { + tcs.TrySetResult(0); + return Task.CompletedTask; + }, + exArgs => + { + tcs.TrySetException(exArgs.Exception); + return Task.CompletedTask; + }); + + await tcs.Task.WithTimeout(DefaultTimeout); + + Assert.True(eventQueue.TryDequeue(out var sendStart)); + AssertSendStart(queueName, sendStart.eventName, sendStart.payload, sendStart.activity, null); + + Assert.True(eventQueue.TryDequeue(out var sendStop)); + AssertSendStop(queueName, sendStop.eventName, sendStop.payload, sendStop.activity, sendStart.activity); + + Assert.True(eventQueue.TryDequeue(out var processStart)); + AssertProcessSessionStart(queueName, processStart.eventName, processStart.payload, processStart.activity, sendStart.activity); + + int wait = 0; + while (wait++ < MaxWaitSec && eventQueue.Count < 1) + { + await Task.Delay(TimeSpan.FromSeconds(1)); + } + + Assert.True(eventQueue.TryDequeue(out var processStop)); + AssertProcessSessionStop(queueName, processStop.eventName, processStop.payload, processStop.activity, + processStart.activity); + + Assert.True(eventQueue.IsEmpty); + + // workaround for https://github.com/Azure/azure-service-bus-dotnet/issues/372: + // SessionPumpTaskAsync calls AcceptMessageSessionAsync() without cancellation token. + // Even after SessionPump is stopped, this Task may still wait for session during operation timeout + // It may interferee with other tests by acception it's sessions and throwing exceptions. + // So, let's wait for timeout and a bit more to make sure all created tasks are completed + sw.Stop(); + + var timeToWait = (timeout - sw.Elapsed).TotalMilliseconds + 1000; + if (timeToWait > 0) + { + await Task.Delay((int)timeToWait); + } } } finally @@ -311,7 +311,7 @@ protected void AssertProcessSessionStop(string entityName, string eventName, obj Assert.Equal("Microsoft.Azure.ServiceBus.ProcessSession.Stop", eventName); AssertCommonStopPayloadProperties(entityName, payload); GetPropertyValueFromAnonymousTypeInstance(payload, "Session"); - var message = GetPropertyValueFromAnonymousTypeInstance(payload, "Message"); + GetPropertyValueFromAnonymousTypeInstance(payload, "Message"); if (processActivity != null) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs index 34cdac8a4491..eca8a4e15df8 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SubscriptionClientDiagnosticsTests.cs @@ -29,34 +29,34 @@ await ServiceBusScope.UsingTopicAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(entityName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Enable((name, queue, id) => name.Contains("Rule")); + listener.Enable((name, queue, id) => name.Contains("Rule")); - var ruleName = Guid.NewGuid().ToString(); - await subscriptionClient.AddRuleAsync(ruleName, new TrueFilter()); - await subscriptionClient.GetRulesAsync(); - await subscriptionClient.RemoveRuleAsync(ruleName); + var ruleName = Guid.NewGuid().ToString(); + await subscriptionClient.AddRuleAsync(ruleName, new TrueFilter()); + await subscriptionClient.GetRulesAsync(); + await subscriptionClient.RemoveRuleAsync(ruleName); - Assert.True(eventQueue.TryDequeue(out var addRuleStart)); - AssertAddRuleStart(entityName, addRuleStart.eventName, addRuleStart.payload, addRuleStart.activity); + Assert.True(eventQueue.TryDequeue(out var addRuleStart)); + AssertAddRuleStart(entityName, addRuleStart.eventName, addRuleStart.payload, addRuleStart.activity); - Assert.True(eventQueue.TryDequeue(out var addRuleStop)); - AssertAddRuleStop(entityName, addRuleStop.eventName, addRuleStop.payload, addRuleStop.activity, addRuleStart.activity); + Assert.True(eventQueue.TryDequeue(out var addRuleStop)); + AssertAddRuleStop(entityName, addRuleStop.eventName, addRuleStop.payload, addRuleStop.activity, addRuleStart.activity); - Assert.True(eventQueue.TryDequeue(out var getRulesStart)); - AssertGetRulesStart(entityName, getRulesStart.eventName, getRulesStart.payload, getRulesStart.activity); + Assert.True(eventQueue.TryDequeue(out var getRulesStart)); + AssertGetRulesStart(entityName, getRulesStart.eventName, getRulesStart.payload, getRulesStart.activity); - Assert.True(eventQueue.TryDequeue(out var getRulesStop)); - AssertGetRulesStop(entityName, getRulesStop.eventName, getRulesStop.payload, getRulesStop.activity, getRulesStart.activity); + Assert.True(eventQueue.TryDequeue(out var getRulesStop)); + AssertGetRulesStop(entityName, getRulesStop.eventName, getRulesStop.payload, getRulesStop.activity, getRulesStart.activity); - Assert.True(eventQueue.TryDequeue(out var removeRuleStart)); - AssertRemoveRuleStart(entityName, removeRuleStart.eventName, removeRuleStart.payload, removeRuleStart.activity); + Assert.True(eventQueue.TryDequeue(out var removeRuleStart)); + AssertRemoveRuleStart(entityName, removeRuleStart.eventName, removeRuleStart.payload, removeRuleStart.activity); - Assert.True(eventQueue.TryDequeue(out var removeRuleStop)); - AssertRemoveRuleStop(entityName, removeRuleStop.eventName, removeRuleStop.payload, removeRuleStop.activity, removeRuleStart.activity); + Assert.True(eventQueue.TryDequeue(out var removeRuleStop)); + AssertRemoveRuleStop(entityName, removeRuleStop.eventName, removeRuleStop.payload, removeRuleStop.activity, removeRuleStart.activity); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs index b10e0e2e9aa6..fd5fac872506 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs @@ -27,16 +27,16 @@ await ServiceBusScope.UsingTopicAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(entityName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Disable(); + listener.Disable(); - var ruleName = Guid.NewGuid().ToString(); - await subscriptionClient.AddRuleAsync(ruleName, new TrueFilter()); - await subscriptionClient.GetRulesAsync(); - await subscriptionClient.RemoveRuleAsync(ruleName); + var ruleName = Guid.NewGuid().ToString(); + await subscriptionClient.AddRuleAsync(ruleName, new TrueFilter()); + await subscriptionClient.GetRulesAsync(); + await subscriptionClient.RemoveRuleAsync(ruleName); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -59,27 +59,27 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Disable(); - - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); - queueClient.RegisterMessageHandler((msg, ct) => - { - tcs.TrySetResult(0); - return Task.CompletedTask; - }, - exArgs => - { - // An exception is not interesting in this context; ignore any - // that may occur. - return Task.CompletedTask; - }); - - await tcs.Task.WithTimeout(DefaultTimeout); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + listener.Disable(); + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); + queueClient.RegisterMessageHandler((msg, ct) => + { + tcs.TrySetResult(0); + return Task.CompletedTask; + }, + exArgs => + { + // An exception is not interesting in this context; ignore any + // that may occur. + return Task.CompletedTask; + }); + + await tcs.Task.WithTimeout(DefaultTimeout); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -102,28 +102,28 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Enable((name, queue, arg) => queue?.ToString() != queueName); - - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); - queueClient.RegisterMessageHandler((msg, ct) => - { - tcs.TrySetResult(0); - return Task.CompletedTask; - }, - exArgs => - { - // An exception is not interesting in this context; ignore any - // that may occur. - return Task.CompletedTask; - }); - - await tcs.Task.WithTimeout(DefaultTimeout); - - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + listener.Enable((name, queue, arg) => queue?.ToString() != queueName); + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); + queueClient.RegisterMessageHandler((msg, ct) => + { + tcs.TrySetResult(0); + return Task.CompletedTask; + }, + exArgs => + { + // An exception is not interesting in this context; ignore any + // that may occur. + return Task.CompletedTask; + }); + + await tcs.Task.WithTimeout(DefaultTimeout); + + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -148,25 +148,25 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Disable(); + listener.Disable(); - var sessionId = Guid.NewGuid().ToString(); - await messageSender.SendAsync(new Message - { - MessageId = "messageId", - SessionId = sessionId - }); + var sessionId = Guid.NewGuid().ToString(); + await messageSender.SendAsync(new Message + { + MessageId = "messageId", + SessionId = sessionId + }); - messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId); + messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId); - await messageSession.SetStateAsync(new byte[] { 1 }); - await messageSession.GetStateAsync(); - await messageSession.SetStateAsync(new byte[] { }); - await messageSession.ReceiveAsync(); + await messageSession.SetStateAsync(new byte[] { 1 }); + await messageSession.GetStateAsync(); + await messageSession.SetStateAsync(new byte[] { }); + await messageSession.ReceiveAsync(); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally @@ -192,29 +192,29 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (var subscription = SubscribeToEvents(listener)) + using (SubscribeToEvents(listener)) { - listener.Enable((name, queue, arg) => - !name.Contains("Send") && !name.Contains("Process") && !name.Contains("Receive") && !name.Contains("Exception")); - - await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); - - var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - queueClient.RegisterMessageHandler((msg, ct) => - { - tcs.TrySetResult(0); - return Task.CompletedTask; - }, - exArgs => - { - // An exception is not interesting in this context; ignore any - // that may occur. - return Task.CompletedTask; - }); - - await tcs.Task.WithTimeout(DefaultTimeout); - Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); + listener.Enable((name, queue, arg) => + !name.Contains("Send") && !name.Contains("Process") && !name.Contains("Receive") && !name.Contains("Exception")); + + await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + queueClient.RegisterMessageHandler((msg, ct) => + { + tcs.TrySetResult(0); + return Task.CompletedTask; + }, + exArgs => + { + // An exception is not interesting in this context; ignore any + // that may occur. + return Task.CompletedTask; + }); + + await tcs.Task.WithTimeout(DefaultTimeout); + Assert.True(eventQueue.IsEmpty, "There were events present when none were expected"); } } finally diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs index 7676b58e33ba..741c98d2db24 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs @@ -328,7 +328,7 @@ public async Task GetQueueRuntimeInfoTest() // Changing Last Updated Time qd.AutoDeleteOnIdle = TimeSpan.FromMinutes(100); - var updatedQ = await client.UpdateQueueAsync(qd); + await client.UpdateQueueAsync(qd); // Populating 1 active message, 1 dead letter message and 1 scheduled message // Changing Last Accessed Time @@ -709,18 +709,18 @@ public async Task ForwardingEntitySetupTest() try { - var dlqDestinationQ = await client.CreateQueueAsync(dlqDestinationName); - var destinationQ = await client.CreateQueueAsync( - new QueueDescription(destinationName) - { - ForwardDeadLetteredMessagesTo = dlqDestinationName - }); + await client.CreateQueueAsync(dlqDestinationName); + await client.CreateQueueAsync( + new QueueDescription(destinationName) + { + ForwardDeadLetteredMessagesTo = dlqDestinationName + }); var qd = new QueueDescription(queueName) { ForwardTo = destinationName }; - var baseQ = await client.CreateQueueAsync(qd); + await client.CreateQueueAsync(qd); await sender.SendAsync(new Message() { MessageId = "mid" }); @@ -893,7 +893,7 @@ public async Task CorrelationFilterPropertiesTest() await client.CreateTopicAsync(topicName); await client.CreateSubscriptionAsync(topicName, subscriptionName); - var sClient = new SubscriptionClient(TestUtility.NamespaceConnectionString, topicName, subscriptionName); + new SubscriptionClient(TestUtility.NamespaceConnectionString, topicName, subscriptionName); var filter = new CorrelationFilter(); filter.Properties.Add("stringKey", "stringVal"); filter.Properties.Add("intKey", 5); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs index ec4c20631f73..abd7c8b432f5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs @@ -30,8 +30,6 @@ public void TestClone() var contentType = Guid.NewGuid().ToString(); var replyTo = Guid.NewGuid().ToString(); var replyToSessionId = Guid.NewGuid().ToString(); - var publisher = Guid.NewGuid().ToString(); - var properties = Guid.NewGuid().ToString(); var brokeredMessage = new Message(messageBody) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryPolicyTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryPolicyTests.cs index 767ec1683140..22b21bfb56a9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryPolicyTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryPolicyTests.cs @@ -39,20 +39,20 @@ public async Task Should_not_retry_when_throttled_and_ambient_transaction_is_det var retryPolicy = RetryPolicy.Default; var numberOfExecutions = 0; - using (var tx = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled)) + using (new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled)) { - await Assert.ThrowsAsync(() => - retryPolicy.RunOperation(() => - { - if (numberOfExecutions > 1) - { - return Task.CompletedTask; - } - - numberOfExecutions++; - - throw new ServerBusyException("Rico KABOOM!"); - }, TimeSpan.FromSeconds(30))); + await Assert.ThrowsAsync(() => + retryPolicy.RunOperation(() => + { + if (numberOfExecutions > 1) + { + return Task.CompletedTask; + } + + numberOfExecutions++; + + throw new ServerBusyException("Rico KABOOM!"); + }, TimeSpan.FromSeconds(30))); } Assert.Equal(1, numberOfExecutions); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs index 135d4c308d7f..eaf5f08a57c7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs @@ -190,7 +190,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, csb.EntityPath = queueName; var receiver = new MessageReceiver(csb); - var msg = await receiver.ReceiveAsync(TimeSpan.FromSeconds(5)); + await receiver.ReceiveAsync(TimeSpan.FromSeconds(5)); await receiver.CloseAsync(); }); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs index 1af06ce88929..fe3f5109a524 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs @@ -30,7 +30,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { - var msg = await receiver.ReceiveAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); + await receiver.ReceiveAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); } finally { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs index b5c7e119b5a2..bb6e341ef6dc 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs @@ -82,9 +82,9 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa { string body = Guid.NewGuid().ToString("N"); var message = new Message(body.GetBytes()) { PartitionKey = "pk" }; - using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { - await sender.SendAsync(message).ConfigureAwait(false); + await sender.SendAsync(message).ConfigureAwait(false); } // Adding delay since transaction Commit/Rollback is an asynchronous operation. @@ -164,9 +164,9 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa Assert.NotNull(receivedMessage); Assert.Equal(body, receivedMessage.Body.GetString()); - using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { - await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken); + await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken); } // Adding delay since transaction Commit/Rollback is an asynchronous operation. @@ -210,9 +210,9 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa Assert.NotNull(receivedMessage); Assert.Equal(body, receivedMessage.Body.GetString()); - using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { - await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken); + await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken); } // Adding delay since transaction Commit/Rollback is an asynchronous operation. @@ -265,9 +265,9 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa var deferredMessage = await receiver.ReceiveDeferredMessageAsync(sequenceNumber); - using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { - await receiver.CompleteAsync(deferredMessage.SystemProperties.LockToken); + await receiver.CompleteAsync(deferredMessage.SystemProperties.LockToken); } // Adding delay since transaction Commit/Rollback is an asynchronous operation. @@ -448,10 +448,10 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, Assert.NotNull(receivedMessage); Assert.Equal(body1, receivedMessage.Body.GetString()); - using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { - await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken); - await sender.SendAsync(message2).ConfigureAwait(false); + await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken); + await sender.SendAsync(message2).ConfigureAwait(false); } // Adding delay since transaction Commit/Rollback is an asynchronous operation. From eca32c7237e6806f512db46ccd69c2ea87171db1 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:31:39 -0400 Subject: [PATCH 08/82] Fixed localization warnings --- .../src/Core/MessageReceiver.cs | 4 +-- .../src/Management/ManagementClient.cs | 28 +++++++++---------- .../src/Management/QueueDescription.cs | 10 +++---- .../SharedAccessAuthorizationRule.cs | 6 ++-- .../src/Management/SubscriptionDescription.cs | 8 +++--- .../src/Management/TopicDescription.cs | 8 +++--- 6 files changed, 32 insertions(+), 32 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index 3851a1d7f75f..65da87ea77a5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -1213,12 +1213,12 @@ protected virtual Task OnDeadLetterAsync(string lockToken, IDictionary Constants.MaxDeadLetterReasonLength) { - throw new ArgumentOutOfRangeException(nameof(deadLetterReason), $"Maximum permitted length is {Constants.MaxDeadLetterReasonLength}"); + throw new ArgumentOutOfRangeException(nameof(deadLetterReason), $@"Maximum permitted length is {Constants.MaxDeadLetterReasonLength}"); } if (deadLetterErrorDescription != null && deadLetterErrorDescription.Length > Constants.MaxDeadLetterReasonLength) { - throw new ArgumentOutOfRangeException(nameof(deadLetterErrorDescription), $"Maximum permitted length is {Constants.MaxDeadLetterReasonLength}"); + throw new ArgumentOutOfRangeException(nameof(deadLetterErrorDescription), $@"Maximum permitted length is {Constants.MaxDeadLetterReasonLength}"); } var lockTokens = new[] { new Guid(lockToken) }; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs index e501d84f8dbd..79d7d81998cc 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs @@ -364,11 +364,11 @@ public virtual async Task> GetQueuesAsync(int count = 10 { if (count > 100 || count < 1) { - throw new ArgumentOutOfRangeException(nameof(count), "Value should be between 1 and 100"); + throw new ArgumentOutOfRangeException(nameof(count), @"Value should be between 1 and 100"); } if (skip < 0) { - throw new ArgumentOutOfRangeException(nameof(skip), "Value cannot be negative"); + throw new ArgumentOutOfRangeException(nameof(skip), @"Value cannot be negative"); } var content = await GetEntity("$Resources/queues", $"$skip={skip}&$top={count}", false, cancellationToken).ConfigureAwait(false); @@ -393,11 +393,11 @@ public virtual async Task> GetTopicsAsync(int count = 10 { if (count > 100 || count < 1) { - throw new ArgumentOutOfRangeException(nameof(count), "Value should be between 1 and 100"); + throw new ArgumentOutOfRangeException(nameof(count), @"Value should be between 1 and 100"); } if (skip < 0) { - throw new ArgumentOutOfRangeException(nameof(skip), "Value cannot be negative"); + throw new ArgumentOutOfRangeException(nameof(skip), @"Value cannot be negative"); } var content = await GetEntity("$Resources/topics", $"$skip={skip}&$top={count}", false, cancellationToken).ConfigureAwait(false); @@ -424,11 +424,11 @@ public virtual async Task> GetSubscriptionsAsync( EntityNameHelper.CheckValidTopicName(topicPath); if (count > 100 || count < 1) { - throw new ArgumentOutOfRangeException(nameof(count), "Value should be between 1 and 100"); + throw new ArgumentOutOfRangeException(nameof(count), @"Value should be between 1 and 100"); } if (skip < 0) { - throw new ArgumentOutOfRangeException(nameof(skip), "Value cannot be negative"); + throw new ArgumentOutOfRangeException(nameof(skip), @"Value cannot be negative"); } var content = await GetEntity($"{topicPath}/Subscriptions", $"$skip={skip}&$top={count}", false, cancellationToken).ConfigureAwait(false); @@ -459,11 +459,11 @@ public virtual async Task> GetRulesAsync(string topicPath EntityNameHelper.CheckValidSubscriptionName(subscriptionName); if (count > 100 || count < 1) { - throw new ArgumentOutOfRangeException(nameof(count), "Value should be between 1 and 100"); + throw new ArgumentOutOfRangeException(nameof(count), @"Value should be between 1 and 100"); } if (skip < 0) { - throw new ArgumentOutOfRangeException(nameof(skip), "Value cannot be negative"); + throw new ArgumentOutOfRangeException(nameof(skip), @"Value cannot be negative"); } var content = await GetEntity($"{topicPath}/Subscriptions/{subscriptionName}/rules", $"$skip={skip}&$top={count}", false, cancellationToken).ConfigureAwait(false); @@ -491,11 +491,11 @@ public virtual async Task> GetQueuesRuntimeInfoAsync(int { if (count > 100 || count < 1) { - throw new ArgumentOutOfRangeException(nameof(count), "Value should be between 1 and 100"); + throw new ArgumentOutOfRangeException(nameof(count), @"Value should be between 1 and 100"); } if (skip < 0) { - throw new ArgumentOutOfRangeException(nameof(skip), "Value cannot be negative"); + throw new ArgumentOutOfRangeException(nameof(skip), @"Value cannot be negative"); } var content = await GetEntity("$Resources/queues", $"$skip={skip}&$top={count}", false, cancellationToken).ConfigureAwait(false); @@ -520,11 +520,11 @@ public virtual async Task> GetTopicsRuntimeInfoAsync(int { if (count > 100 || count < 1) { - throw new ArgumentOutOfRangeException(nameof(count), "Value should be between 1 and 100"); + throw new ArgumentOutOfRangeException(nameof(count), @"Value should be between 1 and 100"); } if (skip < 0) { - throw new ArgumentOutOfRangeException(nameof(skip), "Value cannot be negative"); + throw new ArgumentOutOfRangeException(nameof(skip), @"Value cannot be negative"); } var content = await GetEntity("$Resources/topics", $"$skip={skip}&$top={count}", false, cancellationToken).ConfigureAwait(false); @@ -551,11 +551,11 @@ public virtual async Task> GetSubscriptionsRuntim { if (count > 100 || count < 1) { - throw new ArgumentOutOfRangeException(nameof(count), "Value should be between 1 and 100"); + throw new ArgumentOutOfRangeException(nameof(count), @"Value should be between 1 and 100"); } if (skip < 0) { - throw new ArgumentOutOfRangeException(nameof(skip), "Value cannot be negative"); + throw new ArgumentOutOfRangeException(nameof(skip), @"Value cannot be negative"); } var content = await GetEntity($"{topicPath}/Subscriptions", $"$skip={skip}&$top={count}", false, cancellationToken).ConfigureAwait(false); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index a23fd733346e..0f96d86f016b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -101,7 +101,7 @@ public TimeSpan DefaultMessageTimeToLive if (value < ManagementClientConstants.MinimumAllowedTimeToLive || value > ManagementClientConstants.MaximumAllowedTimeToLive) { throw new ArgumentOutOfRangeException(nameof(DefaultMessageTimeToLive), - $"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); + $@"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); } defaultMessageTimeToLive = value; @@ -120,7 +120,7 @@ public TimeSpan AutoDeleteOnIdle if (value < ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle) { throw new ArgumentOutOfRangeException(nameof(AutoDeleteOnIdle), - $"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); + $@"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } autoDeleteOnIdle = value; @@ -147,7 +147,7 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow if (value < ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow || value > ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow) { throw new ArgumentOutOfRangeException(nameof(DuplicateDetectionHistoryTimeWindow), - $"The value must be between {ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow} and {ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow}"); + $@"The value must be between {ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow} and {ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow}"); } duplicateDetectionHistoryTimeWindow = value; @@ -168,7 +168,7 @@ public int MaxDeliveryCount if (value < ManagementClientConstants.MinAllowedMaxDeliveryCount) { throw new ArgumentOutOfRangeException(nameof(MaxDeliveryCount), - $"The value must be greater than {ManagementClientConstants.MinAllowedMaxDeliveryCount}"); + $@"The value must be greater than {ManagementClientConstants.MinAllowedMaxDeliveryCount}"); } maxDeliveryCount = value; @@ -266,7 +266,7 @@ public string UserMetadata if (value.Length > ManagementClientConstants.MaxUserMetadataLength) { - throw new ArgumentOutOfRangeException(nameof(UserMetadata), $"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); + throw new ArgumentOutOfRangeException(nameof(UserMetadata), $@"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } userMetadata = value; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs index e1f7d80cfc5e..4b3288a2b502 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs @@ -79,7 +79,7 @@ public override sealed string KeyName if (value.Length > SharedAccessSignatureToken.MaxKeyNameLength) { throw new ArgumentOutOfRangeException( - nameof(KeyName), $"The argument cannot exceed {SharedAccessSignatureToken.MaxKeyNameLength} characters"); + nameof(KeyName), $@"The argument cannot exceed {SharedAccessSignatureToken.MaxKeyNameLength} characters"); } if (!string.Equals(value, HttpUtility.UrlEncode(value))) @@ -105,7 +105,7 @@ public string PrimaryKey if (Encoding.ASCII.GetByteCount(value) != SupportedSASKeyLength) { - throw new ArgumentOutOfRangeException(nameof(PrimaryKey), $"{nameof(SharedAccessAuthorizationRule)} only supports keys of size {SupportedSASKeyLength} bytes"); + throw new ArgumentOutOfRangeException(nameof(PrimaryKey), $@"{nameof(SharedAccessAuthorizationRule)} only supports keys of size {SupportedSASKeyLength} bytes"); } if (!CheckBase64(value)) @@ -131,7 +131,7 @@ public string SecondaryKey if (Encoding.ASCII.GetByteCount(value) != SupportedSASKeyLength) { - throw new ArgumentOutOfRangeException(nameof(SecondaryKey), $"{nameof(SharedAccessAuthorizationRule)} only supports keys of size {SupportedSASKeyLength} bytes"); + throw new ArgumentOutOfRangeException(nameof(SecondaryKey), $@"{nameof(SharedAccessAuthorizationRule)} only supports keys of size {SupportedSASKeyLength} bytes"); } if (!CheckBase64(value)) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs index 82936d11f055..4dbee656cbf6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -75,7 +75,7 @@ public TimeSpan DefaultMessageTimeToLive if (value < ManagementClientConstants.MinimumAllowedTimeToLive || value > ManagementClientConstants.MaximumAllowedTimeToLive) { throw new ArgumentOutOfRangeException(nameof(DefaultMessageTimeToLive), - $"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); + $@"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); } defaultMessageTimeToLive = value; @@ -94,7 +94,7 @@ public TimeSpan AutoDeleteOnIdle if (value < ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle) { throw new ArgumentOutOfRangeException(nameof(AutoDeleteOnIdle), - $"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); + $@"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } autoDeleteOnIdle = value; @@ -157,7 +157,7 @@ public int MaxDeliveryCount if (value < ManagementClientConstants.MinAllowedMaxDeliveryCount) { throw new ArgumentOutOfRangeException(nameof(MaxDeliveryCount), - $"The value must be greater than {ManagementClientConstants.MinAllowedMaxDeliveryCount}"); + $@"The value must be greater than {ManagementClientConstants.MinAllowedMaxDeliveryCount}"); } maxDeliveryCount = value; @@ -244,7 +244,7 @@ public string UserMetadata if (value.Length > ManagementClientConstants.MaxUserMetadataLength) { - throw new ArgumentOutOfRangeException(nameof(UserMetadata), $"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); + throw new ArgumentOutOfRangeException(nameof(UserMetadata), $@"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } userMetadata = value; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs index c0b8f1b7186a..36e7aa21ef44 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs @@ -43,7 +43,7 @@ public TimeSpan DefaultMessageTimeToLive if (value < ManagementClientConstants.MinimumAllowedTimeToLive || value > ManagementClientConstants.MaximumAllowedTimeToLive) { throw new ArgumentOutOfRangeException(nameof(DefaultMessageTimeToLive), - $"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); + $@"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); } defaultMessageTimeToLive = value; @@ -62,7 +62,7 @@ public TimeSpan AutoDeleteOnIdle if (value < ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle) { throw new ArgumentOutOfRangeException(nameof(AutoDeleteOnIdle), - $"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); + $@"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } autoDeleteOnIdle = value; @@ -97,7 +97,7 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow if (value < ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow || value > ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow) { throw new ArgumentOutOfRangeException(nameof(DuplicateDetectionHistoryTimeWindow), - $"The value must be between {ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow} and {ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow}"); + $@"The value must be between {ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow} and {ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow}"); } duplicateDetectionHistoryTimeWindow = value; @@ -165,7 +165,7 @@ public string UserMetadata if (value.Length > ManagementClientConstants.MaxUserMetadataLength) { - throw new ArgumentOutOfRangeException(nameof(UserMetadata), $"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); + throw new ArgumentOutOfRangeException(nameof(UserMetadata), $@"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } userMetadata = value; From 382ec93fd453266f791e5a661492d0816a0c5790 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:39:22 -0400 Subject: [PATCH 09/82] Standardized naming throughout --- .../src/Amqp/ActiveClientLinkManager.cs | 62 +++---- .../src/Amqp/ActiveClientLinkObject.cs | 6 +- .../src/Amqp/AmqpLinkCreator.cs | 46 ++--- .../src/Amqp/AmqpRequestMessage.cs | 12 +- .../Amqp/AmqpRequestResponseLinkCreator.cs | 6 +- .../src/Amqp/AmqpResponseMessage.cs | 14 +- .../src/Amqp/AmqpSubscriptionClient.cs | 28 +-- .../src/Amqp/AmqpTransactionEnlistment.cs | 42 ++--- .../src/Amqp/AmqpTransactionManager.cs | 16 +- .../Framing/AmqpCorrelationFilterCodec.cs | 12 +- .../src/ClientEntity.cs | 26 +-- .../src/Core/MessageReceiver.cs | 162 +++++++++--------- .../src/Core/MessageSender.cs | 46 ++--- .../DataContractBinarySerializer.cs | 16 +- .../src/Filters/RuleDescription.cs | 14 +- .../src/Management/ManagementClient.cs | 66 +++---- .../src/Management/QueueDescription.cs | 48 +++--- .../SharedAccessAuthorizationRule.cs | 24 +-- .../src/Management/SubscriptionDescription.cs | 62 +++---- .../src/Management/TopicDescription.cs | 20 +-- .../Microsoft.Azure.ServiceBus/src/Message.cs | 90 +++++----- .../src/MessageHandlerOptions.cs | 12 +- .../src/MessageReceivePump.cs | 108 ++++++------ .../src/MessageSession.cs | 22 +-- .../AzureActiveDirectoryTokenProvider.cs | 10 +- .../src/Primitives/ConcurrentExpiringSet.cs | 46 ++--- .../src/Primitives/ConcurrentRandom.cs | 8 +- .../src/Primitives/Fx.cs | 56 +++--- .../ManagedIdentityTokenProvider.cs | 6 +- .../src/Primitives/PropertyDictionary.cs | 40 ++--- .../src/Primitives/SecurityToken.cs | 24 +-- .../SharedAccessSignatureTokenProvider.cs | 32 ++-- .../src/Primitives/TimeoutHelper.cs | 30 ++-- .../src/Primitives/TokenProviderAdapter.cs | 10 +- .../src/QueueClient.cs | 80 ++++----- .../src/RetryPolicy.cs | 20 +-- .../src/ServiceBusConnection.cs | 16 +- .../src/ServiceBusConnectionStringBuilder.cs | 32 ++-- .../src/ServiceBusDiagnosticsSource.cs | 162 +++++++++--------- .../src/SessionClient.cs | 10 +- .../src/SessionHandlerOptions.cs | 18 +- .../src/SessionPumpHost.cs | 42 ++--- .../src/SessionReceivePump.cs | 110 ++++++------ .../src/SubscriptionClient.cs | 84 ++++----- .../src/TopicClient.cs | 20 +-- .../Diagnostics/FakeDiagnosticListener.cs | 28 +-- .../TaskExtensionTests.cs | 42 ++--- .../tests/Infrastructure/ServiceBusScope.cs | 16 +- .../tests/Management/ManagementClientTests.cs | 82 ++++----- .../MessageInterop/MessageInterOpTests.cs | 6 +- .../tests/MessageSenderTests.cs | 20 +-- .../tests/RetryTests.cs | 6 +- .../tests/SenderReceiverTests.cs | 12 +- .../tests/TestSessionHandler.cs | 46 ++--- .../tests/TokenProviderTests.cs | 6 +- 55 files changed, 1040 insertions(+), 1040 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs index 642201e65d02..b2926251c878 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs @@ -15,37 +15,37 @@ internal sealed class ActiveClientLinkManager private static readonly TimeSpan TokenRefreshBuffer = TimeSpan.FromSeconds(10); private static readonly TimeSpan MaxTokenRefreshTime = TimeSpan.FromDays(30); - private readonly string clientId; - private readonly RetryPolicy retryPolicy; - private readonly ICbsTokenProvider cbsTokenProvider; - private Timer sendReceiveLinkCbsTokenRenewalTimer; - private Timer requestResponseLinkCbsTokenRenewalTimer; + private readonly string _clientId; + private readonly RetryPolicy _retryPolicy; + private readonly ICbsTokenProvider _cbsTokenProvider; + private Timer _sendReceiveLinkCbsTokenRenewalTimer; + private Timer _requestResponseLinkCbsTokenRenewalTimer; - private ActiveSendReceiveClientLink activeSendReceiveClientLink; - private ActiveRequestResponseLink activeRequestResponseClientLink; + private ActiveSendReceiveClientLink _activeSendReceiveClientLink; + private ActiveRequestResponseLink _activeRequestResponseClientLink; public ActiveClientLinkManager(ClientEntity client, ICbsTokenProvider tokenProvider) { - clientId = client.ClientId; - retryPolicy = client.RetryPolicy ?? RetryPolicy.Default; - cbsTokenProvider = tokenProvider; - sendReceiveLinkCbsTokenRenewalTimer = new Timer(OnRenewSendReceiveCbsToken, this, Timeout.Infinite, Timeout.Infinite); - requestResponseLinkCbsTokenRenewalTimer = new Timer(OnRenewRequestResponseCbsToken, this, Timeout.Infinite, Timeout.Infinite); + _clientId = client.ClientId; + _retryPolicy = client.RetryPolicy ?? RetryPolicy.Default; + _cbsTokenProvider = tokenProvider; + _sendReceiveLinkCbsTokenRenewalTimer = new Timer(OnRenewSendReceiveCbsToken, this, Timeout.Infinite, Timeout.Infinite); + _requestResponseLinkCbsTokenRenewalTimer = new Timer(OnRenewRequestResponseCbsToken, this, Timeout.Infinite, Timeout.Infinite); } public void Close() { - sendReceiveLinkCbsTokenRenewalTimer.Dispose(); - sendReceiveLinkCbsTokenRenewalTimer = null; - requestResponseLinkCbsTokenRenewalTimer.Dispose(); - requestResponseLinkCbsTokenRenewalTimer = null; + _sendReceiveLinkCbsTokenRenewalTimer.Dispose(); + _sendReceiveLinkCbsTokenRenewalTimer = null; + _requestResponseLinkCbsTokenRenewalTimer.Dispose(); + _requestResponseLinkCbsTokenRenewalTimer = null; } public void SetActiveSendReceiveLink(ActiveSendReceiveClientLink sendReceiveClientLink) { - activeSendReceiveClientLink = sendReceiveClientLink; - activeSendReceiveClientLink.Link.Closed += OnSendReceiveLinkClosed; - if (activeSendReceiveClientLink.Link.State == AmqpObjectState.Opened) + _activeSendReceiveClientLink = sendReceiveClientLink; + _activeSendReceiveClientLink.Link.Closed += OnSendReceiveLinkClosed; + if (_activeSendReceiveClientLink.Link.State == AmqpObjectState.Opened) { SetRenewCbsTokenTimer(sendReceiveClientLink); } @@ -53,14 +53,14 @@ public void SetActiveSendReceiveLink(ActiveSendReceiveClientLink sendReceiveClie private void OnSendReceiveLinkClosed(object sender, EventArgs e) { - ChangeRenewTimer(activeSendReceiveClientLink, Timeout.InfiniteTimeSpan); + ChangeRenewTimer(_activeSendReceiveClientLink, Timeout.InfiniteTimeSpan); } public void SetActiveRequestResponseLink(ActiveRequestResponseLink requestResponseLink) { - activeRequestResponseClientLink = requestResponseLink; - activeRequestResponseClientLink.Link.Closed += OnRequestResponseLinkClosed; - if (activeRequestResponseClientLink.Link.State == AmqpObjectState.Opened) + _activeRequestResponseClientLink = requestResponseLink; + _activeRequestResponseClientLink.Link.Closed += OnRequestResponseLinkClosed; + if (_activeRequestResponseClientLink.Link.State == AmqpObjectState.Opened) { SetRenewCbsTokenTimer(requestResponseLink); } @@ -69,13 +69,13 @@ public void SetActiveRequestResponseLink(ActiveRequestResponseLink requestRespon private static async void OnRenewSendReceiveCbsToken(object state) { var activeClientLinkManager = (ActiveClientLinkManager)state; - await activeClientLinkManager.RenewCbsTokenAsync(activeClientLinkManager.activeSendReceiveClientLink).ConfigureAwait(false); + await activeClientLinkManager.RenewCbsTokenAsync(activeClientLinkManager._activeSendReceiveClientLink).ConfigureAwait(false); } private static async void OnRenewRequestResponseCbsToken(object state) { var activeClientLinkManager = (ActiveClientLinkManager)state; - await activeClientLinkManager.RenewCbsTokenAsync(activeClientLinkManager.activeRequestResponseClientLink).ConfigureAwait(false); + await activeClientLinkManager.RenewCbsTokenAsync(activeClientLinkManager._activeRequestResponseClientLink).ConfigureAwait(false); } private async Task RenewCbsTokenAsync(ActiveClientLinkObject activeClientLinkObject) @@ -89,13 +89,13 @@ private async Task RenewCbsTokenAsync(ActiveClientLinkObject activeClientLinkObj { MessagingEventSource.Log.AmqpSendAuthenticationTokenStart(activeClientLinkObject.EndpointUri, resource, resource, activeClientLinkObject.RequiredClaims); - await retryPolicy.RunOperation( + await _retryPolicy.RunOperation( async () => { cbsTokenExpiresAtUtc = TimeoutHelper.Min( cbsTokenExpiresAtUtc, await cbsLink.SendTokenAsync( - cbsTokenProvider, + _cbsTokenProvider, activeClientLinkObject.EndpointUri, resource, resource, @@ -112,7 +112,7 @@ await cbsLink.SendTokenAsync( catch (Exception e) { // failed to refresh token, no need to do anything since the server will shut the link itself - MessagingEventSource.Log.AmqpSendAuthenticationTokenException(clientId, e); + MessagingEventSource.Log.AmqpSendAuthenticationTokenException(_clientId, e); ChangeRenewTimer(activeClientLinkObject, Timeout.InfiniteTimeSpan); } @@ -120,7 +120,7 @@ await cbsLink.SendTokenAsync( private void OnRequestResponseLinkClosed(object sender, EventArgs e) { - ChangeRenewTimer(activeRequestResponseClientLink, Timeout.InfiniteTimeSpan); + ChangeRenewTimer(_activeRequestResponseClientLink, Timeout.InfiniteTimeSpan); } private void SetRenewCbsTokenTimer(ActiveClientLinkObject activeClientLinkObject) @@ -147,11 +147,11 @@ private void ChangeRenewTimer(ActiveClientLinkObject activeClientLinkObject, Tim { if (activeClientLinkObject is ActiveSendReceiveClientLink) { - sendReceiveLinkCbsTokenRenewalTimer?.Change(dueTime, Timeout.InfiniteTimeSpan); + _sendReceiveLinkCbsTokenRenewalTimer?.Change(dueTime, Timeout.InfiniteTimeSpan); } else { - requestResponseLinkCbsTokenRenewalTimer?.Change(dueTime, Timeout.InfiniteTimeSpan); + _requestResponseLinkCbsTokenRenewalTimer?.Change(dueTime, Timeout.InfiniteTimeSpan); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs index 9f6a34c597b2..b7675e553c8c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs @@ -8,14 +8,14 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal abstract class ActiveClientLinkObject { - private readonly string[] requiredClaims; + private readonly string[] _requiredClaims; protected ActiveClientLinkObject(AmqpObject amqpLinkObject, Uri endpointUri, string[] audience, string[] requiredClaims, DateTime authorizationValidUntilUtc) { LinkObject = amqpLinkObject; EndpointUri = endpointUri; Audience = audience; - this.requiredClaims = requiredClaims; + this._requiredClaims = requiredClaims; AuthorizationValidUntilUtc = authorizationValidUntilUtc; } @@ -25,7 +25,7 @@ protected ActiveClientLinkObject(AmqpObject amqpLinkObject, Uri endpointUri, st public Uri EndpointUri { get; } - public string[] RequiredClaims => (string[])requiredClaims.Clone(); + public string[] RequiredClaims => (string[])_requiredClaims.Clone(); public DateTime AuthorizationValidUntilUtc { get; set; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs index 95901a6f32e6..57845a7ae082 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs @@ -11,23 +11,23 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal abstract class AmqpLinkCreator { - private readonly string entityPath; - private readonly ServiceBusConnection serviceBusConnection; - private readonly Uri endpointAddress; - private readonly string[] audience; - private readonly string[] requiredClaims; - private readonly ICbsTokenProvider cbsTokenProvider; - private readonly AmqpLinkSettings amqpLinkSettings; + private readonly string _entityPath; + private readonly ServiceBusConnection _serviceBusConnection; + private readonly Uri _endpointAddress; + private readonly string[] _audience; + private readonly string[] _requiredClaims; + private readonly ICbsTokenProvider _cbsTokenProvider; + private readonly AmqpLinkSettings _amqpLinkSettings; protected AmqpLinkCreator(string entityPath, ServiceBusConnection serviceBusConnection, Uri endpointAddress, string[] audience, string[] requiredClaims, ICbsTokenProvider cbsTokenProvider, AmqpLinkSettings amqpLinkSettings, string clientId) { - this.entityPath = entityPath; - this.serviceBusConnection = serviceBusConnection; - this.endpointAddress = endpointAddress; - this.audience = audience; - this.requiredClaims = requiredClaims; - this.cbsTokenProvider = cbsTokenProvider; - this.amqpLinkSettings = amqpLinkSettings; + this._entityPath = entityPath; + this._serviceBusConnection = serviceBusConnection; + this._endpointAddress = endpointAddress; + this._audience = audience; + this._requiredClaims = requiredClaims; + this._cbsTokenProvider = cbsTokenProvider; + this._amqpLinkSettings = amqpLinkSettings; ClientId = clientId; } @@ -35,22 +35,22 @@ protected AmqpLinkCreator(string entityPath, ServiceBusConnection serviceBusConn public async Task> CreateAndOpenAmqpLinkAsync() { - var timeoutHelper = new TimeoutHelper(serviceBusConnection.OperationTimeout, true); + var timeoutHelper = new TimeoutHelper(_serviceBusConnection.OperationTimeout, true); MessagingEventSource.Log.AmqpGetOrCreateConnectionStart(); - var amqpConnection = await serviceBusConnection.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); - MessagingEventSource.Log.AmqpGetOrCreateConnectionStop(entityPath, amqpConnection.ToString(), amqpConnection.State.ToString()); + var amqpConnection = await _serviceBusConnection.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); + MessagingEventSource.Log.AmqpGetOrCreateConnectionStop(_entityPath, amqpConnection.ToString(), amqpConnection.State.ToString()); // Authenticate over CBS var cbsLink = amqpConnection.Extensions.Find(); DateTime cbsTokenExpiresAtUtc = DateTime.MaxValue; - foreach (var resource in audience) + foreach (var resource in _audience) { - MessagingEventSource.Log.AmqpSendAuthenticationTokenStart(endpointAddress, resource, resource, requiredClaims); + MessagingEventSource.Log.AmqpSendAuthenticationTokenStart(_endpointAddress, resource, resource, _requiredClaims); cbsTokenExpiresAtUtc = TimeoutHelper.Min( cbsTokenExpiresAtUtc, - await cbsLink.SendTokenAsync(cbsTokenProvider, endpointAddress, resource, resource, requiredClaims, timeoutHelper.RemainingTime()).ConfigureAwait(false)); + await cbsLink.SendTokenAsync(_cbsTokenProvider, _endpointAddress, resource, resource, _requiredClaims, timeoutHelper.RemainingTime()).ConfigureAwait(false)); MessagingEventSource.Log.AmqpSendAuthenticationTokenStop(); } @@ -64,7 +64,7 @@ public async Task> CreateAndOpenAmqpLinkAsync() } catch (Exception exception) { - MessagingEventSource.Log.AmqpSessionCreationException(entityPath, amqpConnection, exception); + MessagingEventSource.Log.AmqpSessionCreationException(_entityPath, amqpConnection, exception); session?.Abort(); throw AmqpExceptionHelper.GetClientException(exception, null, session.GetInnerException(), amqpConnection.IsClosing()); } @@ -73,14 +73,14 @@ public async Task> CreateAndOpenAmqpLinkAsync() try { // Create Link - link = OnCreateAmqpLink(amqpConnection, amqpLinkSettings, session); + link = OnCreateAmqpLink(amqpConnection, _amqpLinkSettings, session); await link.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); return new Tuple(link, cbsTokenExpiresAtUtc); } catch (Exception exception) { MessagingEventSource.Log.AmqpLinkCreationException( - entityPath, + _entityPath, session, amqpConnection, exception); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs index ab9c2c95c20d..01bda5cda913 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestMessage.cs @@ -10,18 +10,18 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal sealed class AmqpRequestMessage { - private readonly AmqpMessage requestMessage; + private readonly AmqpMessage _requestMessage; private AmqpRequestMessage(string operation, TimeSpan timeout, string trackingId) { Map = new AmqpMap(); - requestMessage = AmqpMessage.Create(new AmqpValue { Value = Map }); - requestMessage.ApplicationProperties.Map[ManagementConstants.Request.Operation] = operation; - requestMessage.ApplicationProperties.Map[ManagementConstants.Properties.ServerTimeout] = (uint)timeout.TotalMilliseconds; - requestMessage.ApplicationProperties.Map[ManagementConstants.Properties.TrackingId] = trackingId ?? Guid.NewGuid().ToString(); + _requestMessage = AmqpMessage.Create(new AmqpValue { Value = Map }); + _requestMessage.ApplicationProperties.Map[ManagementConstants.Request.Operation] = operation; + _requestMessage.ApplicationProperties.Map[ManagementConstants.Properties.ServerTimeout] = (uint)timeout.TotalMilliseconds; + _requestMessage.ApplicationProperties.Map[ManagementConstants.Properties.TrackingId] = trackingId ?? Guid.NewGuid().ToString(); } - public AmqpMessage AmqpMessage => requestMessage; + public AmqpMessage AmqpMessage => _requestMessage; public AmqpMap Map { get; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs index fc9362e50969..a6fd11bd9cea 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs @@ -9,17 +9,17 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal class AmqpRequestResponseLinkCreator : AmqpLinkCreator { - private readonly string entityPath; + private readonly string _entityPath; public AmqpRequestResponseLinkCreator(string entityPath, ServiceBusConnection serviceBusConnection, Uri endpointAddress, string[] audience, string[] requiredClaims, ICbsTokenProvider cbsTokenProvider, AmqpLinkSettings linkSettings, string clientId) : base(entityPath, serviceBusConnection, endpointAddress, audience, requiredClaims, cbsTokenProvider, linkSettings, clientId) { - this.entityPath = entityPath; + this._entityPath = entityPath; } protected override AmqpObject OnCreateAmqpLink(AmqpConnection connection, AmqpLinkSettings linkSettings, AmqpSession amqpSession) { - AmqpObject link = new RequestResponseAmqpLink(AmqpClientConstants.EntityTypeManagement, amqpSession, entityPath, linkSettings.Properties); + AmqpObject link = new RequestResponseAmqpLink(AmqpClientConstants.EntityTypeManagement, amqpSession, _entityPath, linkSettings.Properties); linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{amqpSession.Identifier}:{link.Identifier}:{ClientId}"; return link; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs index 175658621d99..cb573b90a9e1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs @@ -12,13 +12,13 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal sealed class AmqpResponseMessage { - private readonly AmqpMessage responseMessage; + private readonly AmqpMessage _responseMessage; private AmqpResponseMessage(AmqpMessage responseMessage) { - this.responseMessage = responseMessage; - StatusCode = this.responseMessage.GetResponseStatusCode(); - if (this.responseMessage.ApplicationProperties.Map.TryGetValue(ManagementConstants.Properties.TrackingId, out var trackingId)) + this._responseMessage = responseMessage; + StatusCode = this._responseMessage.GetResponseStatusCode(); + if (this._responseMessage.ApplicationProperties.Map.TryGetValue(ManagementConstants.Properties.TrackingId, out var trackingId)) { TrackingId = trackingId; } @@ -29,7 +29,7 @@ private AmqpResponseMessage(AmqpMessage responseMessage) } } - public AmqpMessage AmqpMessage => responseMessage; + public AmqpMessage AmqpMessage => _responseMessage; public AmqpResponseStatusCode StatusCode { get; } @@ -77,14 +77,14 @@ public IEnumerable GetListValue(MapKey key) public AmqpSymbol GetResponseErrorCondition() { - var condition = responseMessage.ApplicationProperties.Map[ManagementConstants.Response.ErrorCondition]; + var condition = _responseMessage.ApplicationProperties.Map[ManagementConstants.Response.ErrorCondition]; return condition is AmqpSymbol amqpSymbol ? amqpSymbol : null; } public Exception ToMessagingContractException() { - return responseMessage.ToMessagingContractException(StatusCode); + return _responseMessage.ToMessagingContractException(StatusCode); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs index 0a2f7067ee97..c7e080748979 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs @@ -16,9 +16,9 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal sealed class AmqpSubscriptionClient : IInnerSubscriptionClient { - private int prefetchCount; - private readonly object syncLock; - private MessageReceiver innerReceiver; + private int _prefetchCount; + private readonly object _syncLock; + private MessageReceiver _innerReceiver; static AmqpSubscriptionClient() { @@ -39,7 +39,7 @@ public AmqpSubscriptionClient( int prefetchCount = 0, ReceiveMode mode = ReceiveMode.ReceiveAndDelete) { - syncLock = new object(); + _syncLock = new object(); Path = path; ServiceBusConnection = servicebusConnection; RetryPolicy = retryPolicy; @@ -52,13 +52,13 @@ public MessageReceiver InnerReceiver { get { - if (innerReceiver == null) + if (_innerReceiver == null) { - lock (syncLock) + lock (_syncLock) { - if (innerReceiver == null) + if (_innerReceiver == null) { - innerReceiver = new MessageReceiver( + _innerReceiver = new MessageReceiver( Path, MessagingEntityType.Subscriber, ReceiveMode, @@ -70,7 +70,7 @@ public MessageReceiver InnerReceiver } } - return innerReceiver; + return _innerReceiver; } } @@ -80,17 +80,17 @@ public MessageReceiver InnerReceiver /// The number of messages that the subscription client can simultaneously request. public int PrefetchCount { - get => prefetchCount; + get => _prefetchCount; set { if (value < 0) { throw Fx.Exception.ArgumentOutOfRange(nameof(PrefetchCount), value, "Value cannot be less than 0."); } - prefetchCount = value; - if (innerReceiver != null) + _prefetchCount = value; + if (_innerReceiver != null) { - innerReceiver.PrefetchCount = value; + _innerReceiver.PrefetchCount = value; } } } @@ -107,7 +107,7 @@ public int PrefetchCount public Task CloseAsync() { - return innerReceiver?.CloseAsync(); + return _innerReceiver?.CloseAsync(); } public async Task OnAddRuleAsync(RuleDescription description) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs index c110169cb93c..fb9459bfa53d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs @@ -11,18 +11,18 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal class AmqpTransactionEnlistment : Singleton, IPromotableSinglePhaseNotification { - private readonly string transactionId; - private readonly AmqpTransactionManager transactionManager; - private readonly ServiceBusConnection serviceBusConnection; + private readonly string _transactionId; + private readonly AmqpTransactionManager _transactionManager; + private readonly ServiceBusConnection _serviceBusConnection; public AmqpTransactionEnlistment( Transaction transaction, AmqpTransactionManager transactionManager, ServiceBusConnection serviceBusConnection) { - transactionId = transaction.TransactionInformation.LocalIdentifier; - this.transactionManager = transactionManager; - this.serviceBusConnection = serviceBusConnection; + _transactionId = transaction.TransactionInformation.LocalIdentifier; + this._transactionManager = transactionManager; + this._serviceBusConnection = serviceBusConnection; } public ArraySegment AmqpTransactionId { get; private set; } @@ -31,16 +31,16 @@ protected override async Task OnCreateAsync(TimeSpan { try { - var faultTolerantController = serviceBusConnection.TransactionController; - var controller = await faultTolerantController.GetOrCreateAsync(serviceBusConnection.OperationTimeout).ConfigureAwait(false); + var faultTolerantController = _serviceBusConnection.TransactionController; + var controller = await faultTolerantController.GetOrCreateAsync(_serviceBusConnection.OperationTimeout).ConfigureAwait(false); AmqpTransactionId = await controller.DeclareAsync().ConfigureAwait(false); - MessagingEventSource.Log.AmqpTransactionDeclared(transactionId, AmqpTransactionId); + MessagingEventSource.Log.AmqpTransactionDeclared(_transactionId, AmqpTransactionId); return this; } catch (Exception exception) { - MessagingEventSource.Log.AmqpTransactionInitializeException(transactionId, exception); - transactionManager.RemoveEnlistment(transactionId); + MessagingEventSource.Log.AmqpTransactionInitializeException(_transactionId, exception); + _transactionManager.RemoveEnlistment(_transactionId); throw; } } @@ -55,7 +55,7 @@ void IPromotableSinglePhaseNotification.Initialize() void IPromotableSinglePhaseNotification.SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment) { - transactionManager.RemoveEnlistment(transactionId); + _transactionManager.RemoveEnlistment(_transactionId); TaskExtensionHelper.Schedule(() => SinglePhaseCommitAsync(singlePhaseEnlistment)); } @@ -63,25 +63,25 @@ private async Task SinglePhaseCommitAsync(SinglePhaseEnlistment singlePhaseEnlis { try { - var faultTolerantController = serviceBusConnection.TransactionController; - var controller = await faultTolerantController.GetOrCreateAsync(serviceBusConnection.OperationTimeout).ConfigureAwait(false); + var faultTolerantController = _serviceBusConnection.TransactionController; + var controller = await faultTolerantController.GetOrCreateAsync(_serviceBusConnection.OperationTimeout).ConfigureAwait(false); await controller.DischargeAsync(AmqpTransactionId, fail: false).ConfigureAwait(false); singlePhaseEnlistment.Committed(); - MessagingEventSource.Log.AmqpTransactionDischarged(transactionId, AmqpTransactionId, false); + MessagingEventSource.Log.AmqpTransactionDischarged(_transactionId, AmqpTransactionId, false); await CloseAsync().ConfigureAwait(false); } catch (Exception e) { Exception exception = AmqpExceptionHelper.GetClientException(e); - MessagingEventSource.Log.AmqpTransactionDischargeException(transactionId, AmqpTransactionId, exception); + MessagingEventSource.Log.AmqpTransactionDischargeException(_transactionId, AmqpTransactionId, exception); singlePhaseEnlistment.InDoubt(exception); } } void IPromotableSinglePhaseNotification.Rollback(SinglePhaseEnlistment singlePhaseEnlistment) { - transactionManager.RemoveEnlistment(transactionId); + _transactionManager.RemoveEnlistment(_transactionId); TaskExtensionHelper.Schedule(() => RollbackAsync(singlePhaseEnlistment)); } @@ -89,17 +89,17 @@ private async Task RollbackAsync(SinglePhaseEnlistment singlePhaseEnlistment) { try { - var faultTolerantController = serviceBusConnection.TransactionController; - var controller = await faultTolerantController.GetOrCreateAsync(serviceBusConnection.OperationTimeout).ConfigureAwait(false); + var faultTolerantController = _serviceBusConnection.TransactionController; + var controller = await faultTolerantController.GetOrCreateAsync(_serviceBusConnection.OperationTimeout).ConfigureAwait(false); await controller.DischargeAsync(AmqpTransactionId, fail: true).ConfigureAwait(false); singlePhaseEnlistment.Aborted(); - MessagingEventSource.Log.AmqpTransactionDischarged(transactionId, AmqpTransactionId, true); + MessagingEventSource.Log.AmqpTransactionDischarged(_transactionId, AmqpTransactionId, true); } catch (Exception e) { Exception exception = AmqpExceptionHelper.GetClientException(e); - MessagingEventSource.Log.AmqpTransactionDischargeException(transactionId, AmqpTransactionId, exception); + MessagingEventSource.Log.AmqpTransactionDischargeException(_transactionId, AmqpTransactionId, exception); singlePhaseEnlistment.Aborted(exception); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs index 2adab435db85..8bce689fa5c4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs @@ -10,8 +10,8 @@ namespace Microsoft.Azure.ServiceBus.Amqp internal class AmqpTransactionManager { - private readonly object syncRoot = new object(); - private readonly Dictionary enlistmentMap = new Dictionary(StringComparer.Ordinal); + private readonly object _syncRoot = new object(); + private readonly Dictionary _enlistmentMap = new Dictionary(StringComparer.Ordinal); public static AmqpTransactionManager Instance { get; } = new AmqpTransactionManager(); @@ -27,16 +27,16 @@ public async Task> EnlistAsync( string transactionId = transaction.TransactionInformation.LocalIdentifier; AmqpTransactionEnlistment transactionEnlistment; - lock (syncRoot) + lock (_syncRoot) { - if (!enlistmentMap.TryGetValue(transactionId, out transactionEnlistment)) + if (!_enlistmentMap.TryGetValue(transactionId, out transactionEnlistment)) { transactionEnlistment = new AmqpTransactionEnlistment(transaction, this, serviceBusConnection); - enlistmentMap.Add(transactionId, transactionEnlistment); + _enlistmentMap.Add(transactionId, transactionEnlistment); if (!transaction.EnlistPromotableSinglePhase(transactionEnlistment)) { - enlistmentMap.Remove(transactionId); + _enlistmentMap.Remove(transactionId); throw new InvalidOperationException("Local transactions are not supported with other resource managers/DTC."); } } @@ -48,9 +48,9 @@ public async Task> EnlistAsync( public void RemoveEnlistment(string transactionId) { - lock (syncRoot) + lock (_syncRoot) { - enlistmentMap.Remove(transactionId); + _enlistmentMap.Remove(transactionId); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs index cd63901e04aa..e58db1bd9f2c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs @@ -13,11 +13,11 @@ internal sealed class AmqpCorrelationFilterCodec : AmqpFilterCodec public const ulong Code = 0x000001370000009; private const int Fields = 9; - private AmqpMap properties; + private AmqpMap _properties; public AmqpCorrelationFilterCodec() : base(Name, Code) { - properties = new AmqpMap(); + _properties = new AmqpMap(); } public string CorrelationId { get; set; } @@ -36,7 +36,7 @@ public AmqpCorrelationFilterCodec() : base(Name, Code) public string ContentType { get; set; } - public AmqpMap Properties => properties; + public AmqpMap Properties => _properties; protected override int FieldCount => Fields; @@ -59,7 +59,7 @@ protected override void OnEncode(ByteBuffer buffer) AmqpCodec.EncodeString(SessionId, buffer); AmqpCodec.EncodeString(ReplyToSessionId, buffer); AmqpCodec.EncodeString(ContentType, buffer); - AmqpCodec.EncodeMap(properties, buffer); + AmqpCodec.EncodeMap(_properties, buffer); } protected override void OnDecode(ByteBuffer buffer, int count) @@ -106,7 +106,7 @@ protected override void OnDecode(ByteBuffer buffer, int count) if (count > 0) { - properties = AmqpCodec.DecodeMap(buffer); + _properties = AmqpCodec.DecodeMap(buffer); } } @@ -120,7 +120,7 @@ protected override int OnValueSize() AmqpCodec.GetStringEncodeSize(SessionId) + AmqpCodec.GetStringEncodeSize(ReplyToSessionId) + AmqpCodec.GetStringEncodeSize(ContentType) + - AmqpCodec.GetMapEncodeSize(properties); + AmqpCodec.GetMapEncodeSize(_properties); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs index abc2553f1eab..e1c8cb614b39 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs @@ -15,17 +15,17 @@ namespace Microsoft.Azure.ServiceBus /// public abstract class ClientEntity : IClientEntity { - private static int nextId; - private readonly string clientTypeName; - private readonly object syncLock; - private bool isClosedOrClosing; + private static int _nextId; + private readonly string _clientTypeName; + private readonly object _syncLock; + private bool _isClosedOrClosing; protected ClientEntity(string clientTypeName, string postfix, RetryPolicy retryPolicy) { - this.clientTypeName = clientTypeName; + this._clientTypeName = clientTypeName; ClientId = GenerateClientId(clientTypeName, postfix); RetryPolicy = retryPolicy ?? RetryPolicy.Default; - syncLock = new object(); + _syncLock = new object(); } /// @@ -35,16 +35,16 @@ public bool IsClosedOrClosing { get { - lock (syncLock) + lock (_syncLock) { - return isClosedOrClosing; + return _isClosedOrClosing; } } internal set { - lock (syncLock) + lock (_syncLock) { - isClosedOrClosing = value; + _isClosedOrClosing = value; } } } @@ -86,7 +86,7 @@ internal set public async Task CloseAsync() { var callClose = false; - lock (syncLock) + lock (_syncLock) { if (!IsClosedOrClosing) { @@ -126,7 +126,7 @@ public async Task CloseAsync() protected static long GetNextId() { - return Interlocked.Increment(ref nextId); + return Interlocked.Increment(ref _nextId); } /// @@ -146,7 +146,7 @@ protected virtual void ThrowIfClosed() ServiceBusConnection.ThrowIfClosed(); if (IsClosedOrClosing) { - throw new ObjectDisposedException($"{clientTypeName} with Id '{ClientId}' has already been closed. Please create a new {clientTypeName}."); + throw new ObjectDisposedException($"{_clientTypeName} with Id '{ClientId}' has already been closed. Please create a new {_clientTypeName}."); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index 65da87ea77a5..230c75f548b7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -45,16 +45,16 @@ public class MessageReceiver : ClientEntity, IMessageReceiver { private static readonly TimeSpan DefaultBatchFlushInterval = TimeSpan.FromMilliseconds(20); - private readonly ConcurrentExpiringSet requestResponseLockedMessages; - private readonly bool isSessionReceiver; - private readonly object messageReceivePumpSyncLock; - private readonly ActiveClientLinkManager clientLinkManager; - private readonly ServiceBusDiagnosticSource diagnosticSource; + private readonly ConcurrentExpiringSet _requestResponseLockedMessages; + private readonly bool _isSessionReceiver; + private readonly object _messageReceivePumpSyncLock; + private readonly ActiveClientLinkManager _clientLinkManager; + private readonly ServiceBusDiagnosticSource _diagnosticSource; - private int prefetchCount; - private long lastPeekedSequenceNumber; - private MessageReceivePump receivePump; - private CancellationTokenSource receivePumpCancellationTokenSource; + private int _prefetchCount; + private long _lastPeekedSequenceNumber; + private MessageReceivePump _receivePump; + private CancellationTokenSource _receivePumpCancellationTokenSource; /// /// Creates a new MessageReceiver from a . @@ -186,14 +186,14 @@ internal MessageReceiver( } SessionIdInternal = sessionId; - this.isSessionReceiver = isSessionReceiver; + this._isSessionReceiver = isSessionReceiver; ReceiveLinkManager = new FaultTolerantAmqpObject(CreateLinkAsync, CloseSession); RequestResponseLinkManager = new FaultTolerantAmqpObject(CreateRequestResponseLinkAsync, CloseRequestResponseSession); - requestResponseLockedMessages = new ConcurrentExpiringSet(); + _requestResponseLockedMessages = new ConcurrentExpiringSet(); PrefetchCount = prefetchCount; - messageReceivePumpSyncLock = new object(); - clientLinkManager = new ActiveClientLinkManager(this, CbsTokenProvider); - diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); + _messageReceivePumpSyncLock = new object(); + _clientLinkManager = new ActiveClientLinkManager(this, CbsTokenProvider); + _diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); MessagingEventSource.Log.MessageReceiverCreateStop(serviceBusConnection.Endpoint.Authority, entityPath, ClientId); } @@ -229,7 +229,7 @@ internal MessageReceiver( /// public int PrefetchCount { - get => prefetchCount; + get => _prefetchCount; set { @@ -237,7 +237,7 @@ public int PrefetchCount { throw Fx.Exception.ArgumentOutOfRange(nameof(PrefetchCount), value, "Value cannot be less than 0."); } - prefetchCount = value; + _prefetchCount = value; if (ReceiveLinkManager.TryGetOpenedObject(out var link)) { link.SetTotalLinkCredit((uint)value, true, true); @@ -249,7 +249,7 @@ public int PrefetchCount /// public long LastPeekedSequenceNumber { - get => lastPeekedSequenceNumber; + get => _lastPeekedSequenceNumber; internal set { @@ -258,7 +258,7 @@ internal set throw new ArgumentOutOfRangeException(nameof(LastPeekedSequenceNumber), value.ToString()); } - lastPeekedSequenceNumber = value; + _lastPeekedSequenceNumber = value; } } @@ -363,7 +363,7 @@ public async Task> ReceiveAsync(int maxMessageCount, TimeSpan ope MessagingEventSource.Log.MessageReceiveStart(ClientId, maxMessageCount); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.ReceiveStart(maxMessageCount) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.ReceiveStart(maxMessageCount) : null; Task receiveTask = null; IList unprocessedMessageList = null; @@ -382,7 +382,7 @@ public async Task> ReceiveAsync(int maxMessageCount, TimeSpan ope { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessageReceiveException(ClientId, exception); @@ -390,7 +390,7 @@ public async Task> ReceiveAsync(int maxMessageCount, TimeSpan ope } finally { - diagnosticSource.ReceiveStop(activity, maxMessageCount, receiveTask?.Status, unprocessedMessageList); + _diagnosticSource.ReceiveStop(activity, maxMessageCount, receiveTask?.Status, unprocessedMessageList); } MessagingEventSource.Log.MessageReceiveStop(ClientId, unprocessedMessageList?.Count ?? 0); @@ -446,7 +446,7 @@ public async Task> ReceiveDeferredMessageAsync(IEnumerable MessagingEventSource.Log.MessageReceiveDeferredMessageStart(ClientId, sequenceNumberList.Length, sequenceNumberList); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.ReceiveDeferredStart(sequenceNumberList) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.ReceiveDeferredStart(sequenceNumberList) : null; Task receiveTask = null; IList messages = null; @@ -463,7 +463,7 @@ public async Task> ReceiveDeferredMessageAsync(IEnumerable { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessageReceiveDeferredMessageException(ClientId, exception); @@ -471,7 +471,7 @@ public async Task> ReceiveDeferredMessageAsync(IEnumerable } finally { - diagnosticSource.ReceiveDeferredStop(activity, sequenceNumberList, receiveTask?.Status, messages); + _diagnosticSource.ReceiveDeferredStop(activity, sequenceNumberList, receiveTask?.Status, messages); } MessagingEventSource.Log.MessageReceiveDeferredMessageStop(ClientId, messages?.Count ?? 0); @@ -517,7 +517,7 @@ public async Task CompleteAsync(IEnumerable lockTokens) MessagingEventSource.Log.MessageCompleteStart(ClientId, lockTokenList.Count, lockTokenList); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.CompleteStart(lockTokenList) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.CompleteStart(lockTokenList) : null; Task completeTask = null; try @@ -530,7 +530,7 @@ public async Task CompleteAsync(IEnumerable lockTokens) { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessageCompleteException(ClientId, exception); @@ -539,7 +539,7 @@ public async Task CompleteAsync(IEnumerable lockTokens) } finally { - diagnosticSource.CompleteStop(activity, lockTokenList, completeTask?.Status); + _diagnosticSource.CompleteStop(activity, lockTokenList, completeTask?.Status); } MessagingEventSource.Log.MessageCompleteStop(ClientId); @@ -562,7 +562,7 @@ public async Task AbandonAsync(string lockToken, IDictionary pro MessagingEventSource.Log.MessageAbandonStart(ClientId, 1, lockToken); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.DisposeStart("Abandon", lockToken) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("Abandon", lockToken) : null; Task abandonTask = null; try @@ -575,7 +575,7 @@ public async Task AbandonAsync(string lockToken, IDictionary pro { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessageAbandonException(ClientId, exception); @@ -583,7 +583,7 @@ public async Task AbandonAsync(string lockToken, IDictionary pro } finally { - diagnosticSource.DisposeStop(activity, lockToken, abandonTask?.Status); + _diagnosticSource.DisposeStop(activity, lockToken, abandonTask?.Status); } @@ -608,7 +608,7 @@ public async Task DeferAsync(string lockToken, IDictionary prope MessagingEventSource.Log.MessageDeferStart(ClientId, 1, lockToken); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.DisposeStart("Defer", lockToken) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("Defer", lockToken) : null; Task deferTask = null; try @@ -621,7 +621,7 @@ public async Task DeferAsync(string lockToken, IDictionary prope { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessageDeferException(ClientId, exception); @@ -629,7 +629,7 @@ public async Task DeferAsync(string lockToken, IDictionary prope } finally { - diagnosticSource.DisposeStop(activity, lockToken, deferTask?.Status); + _diagnosticSource.DisposeStop(activity, lockToken, deferTask?.Status); } MessagingEventSource.Log.MessageDeferStop(ClientId); } @@ -653,7 +653,7 @@ public async Task DeadLetterAsync(string lockToken, IDictionary MessagingEventSource.Log.MessageDeadLetterStart(ClientId, 1, lockToken); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; Task deadLetterTask = null; try @@ -666,7 +666,7 @@ public async Task DeadLetterAsync(string lockToken, IDictionary { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessageDeadLetterException(ClientId, exception); @@ -674,7 +674,7 @@ public async Task DeadLetterAsync(string lockToken, IDictionary } finally { - diagnosticSource.DisposeStop(activity, lockToken, deadLetterTask?.Status); + _diagnosticSource.DisposeStop(activity, lockToken, deadLetterTask?.Status); } MessagingEventSource.Log.MessageDeadLetterStop(ClientId); } @@ -699,7 +699,7 @@ public async Task DeadLetterAsync(string lockToken, string deadLetterReason, str MessagingEventSource.Log.MessageDeadLetterStart(ClientId, 1, lockToken); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; Task deadLetterTask = null; try @@ -714,7 +714,7 @@ public async Task DeadLetterAsync(string lockToken, string deadLetterReason, str { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessageDeadLetterException(ClientId, exception); @@ -722,7 +722,7 @@ public async Task DeadLetterAsync(string lockToken, string deadLetterReason, str } finally { - diagnosticSource.DisposeStop(activity, lockToken, deadLetterTask?.Status); + _diagnosticSource.DisposeStop(activity, lockToken, deadLetterTask?.Status); } MessagingEventSource.Log.MessageDeadLetterStop(ClientId); @@ -760,7 +760,7 @@ public async Task RenewLockAsync(string lockToken) MessagingEventSource.Log.MessageRenewLockStart(ClientId, 1, lockToken); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.RenewLockStart(lockToken) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.RenewLockStart(lockToken) : null; Task renewTask = null; var lockedUntilUtc = DateTime.MinValue; @@ -776,7 +776,7 @@ public async Task RenewLockAsync(string lockToken) { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessageRenewLockException(ClientId, exception); @@ -784,7 +784,7 @@ public async Task RenewLockAsync(string lockToken) } finally { - diagnosticSource.RenewLockStop(activity, lockToken, renewTask?.Status, lockedUntilUtc); + _diagnosticSource.RenewLockStop(activity, lockToken, renewTask?.Status, lockedUntilUtc); } MessagingEventSource.Log.MessageRenewLockStop(ClientId); @@ -803,7 +803,7 @@ public async Task RenewLockAsync(string lockToken) /// The that represents the next message to be read. Returns null when nothing to peek. public Task PeekAsync() { - return PeekBySequenceNumberAsync(lastPeekedSequenceNumber + 1); + return PeekBySequenceNumberAsync(_lastPeekedSequenceNumber + 1); } /// @@ -818,7 +818,7 @@ public Task PeekAsync() /// List of that represents the next message to be read. Returns null when nothing to peek. public Task> PeekAsync(int maxMessageCount) { - return PeekBySequenceNumberAsync(lastPeekedSequenceNumber + 1, maxMessageCount); + return PeekBySequenceNumberAsync(_lastPeekedSequenceNumber + 1, maxMessageCount); } /// @@ -843,7 +843,7 @@ public async Task> PeekBySequenceNumberAsync(long fromSequenceNum MessagingEventSource.Log.MessagePeekStart(ClientId, fromSequenceNumber, messageCount); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.PeekStart(fromSequenceNumber, messageCount) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.PeekStart(fromSequenceNumber, messageCount) : null; Task peekTask = null; try @@ -860,7 +860,7 @@ public async Task> PeekBySequenceNumberAsync(long fromSequenceNum { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessagePeekException(ClientId, exception); @@ -868,7 +868,7 @@ public async Task> PeekBySequenceNumberAsync(long fromSequenceNum } finally { - diagnosticSource.PeekStop(activity, fromSequenceNumber, messageCount, peekTask?.Status, messages); + _diagnosticSource.PeekStop(activity, fromSequenceNumber, messageCount, peekTask?.Status, messages); } MessagingEventSource.Log.MessagePeekStop(ClientId, messages?.Count ?? 0); @@ -966,7 +966,7 @@ internal async Task GetSessionReceiverLinkAsync(TimeSpan serverWaitTime) internal async Task ExecuteRequestResponseAsync(AmqpRequestMessage amqpRequestMessage) { var amqpMessage = amqpRequestMessage.AmqpMessage; - if (isSessionReceiver) + if (_isSessionReceiver) { ThrowIfSessionLockLost(); } @@ -982,7 +982,7 @@ internal async Task ExecuteRequestResponseAsync(AmqpRequest if (!RequestResponseLinkManager.TryGetOpenedObject(out var requestResponseAmqpLink)) { - MessagingEventSource.Log.CreatingNewLink(ClientId, isSessionReceiver, SessionIdInternal, true, LinkException); + MessagingEventSource.Log.CreatingNewLink(ClientId, _isSessionReceiver, SessionIdInternal, true, LinkException); requestResponseAmqpLink = await RequestResponseLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } @@ -996,26 +996,26 @@ internal async Task ExecuteRequestResponseAsync(AmqpRequest protected override async Task OnClosingAsync() { - clientLinkManager.Close(); - lock (messageReceivePumpSyncLock) + _clientLinkManager.Close(); + lock (_messageReceivePumpSyncLock) { - if (receivePump != null) + if (_receivePump != null) { - receivePumpCancellationTokenSource.Cancel(); - receivePumpCancellationTokenSource.Dispose(); - receivePump = null; + _receivePumpCancellationTokenSource.Cancel(); + _receivePumpCancellationTokenSource.Dispose(); + _receivePump = null; } } await ReceiveLinkManager.CloseAsync().ConfigureAwait(false); await RequestResponseLinkManager.CloseAsync().ConfigureAwait(false); - requestResponseLockedMessages.Close(); + _requestResponseLockedMessages.Close(); } protected virtual async Task> OnReceiveAsync(int maxMessageCount, TimeSpan serverWaitTime) { ReceivingAmqpLink receiveLink = null; - if (isSessionReceiver) + if (_isSessionReceiver) { ThrowIfSessionLockLost(); } @@ -1025,7 +1025,7 @@ protected virtual async Task> OnReceiveAsync(int maxMessageCount, var timeoutHelper = new TimeoutHelper(serverWaitTime, true); if(!ReceiveLinkManager.TryGetOpenedObject(out receiveLink)) { - MessagingEventSource.Log.CreatingNewLink(ClientId, isSessionReceiver, SessionIdInternal, false, LinkException); + MessagingEventSource.Log.CreatingNewLink(ClientId, _isSessionReceiver, SessionIdInternal, false, LinkException); receiveLink = await ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } @@ -1160,7 +1160,7 @@ protected virtual async Task> OnReceiveDeferredMessageAsync(long[ if (entry.TryGetValue(ManagementConstants.Properties.LockToken, out var lockToken)) { message.SystemProperties.LockTokenGuid = lockToken; - requestResponseLockedMessages.AddOrUpdate(lockToken, message.SystemProperties.LockedUntilUtc); + _requestResponseLockedMessages.AddOrUpdate(lockToken, message.SystemProperties.LockedUntilUtc); } messages.Add(message); @@ -1182,7 +1182,7 @@ protected virtual async Task> OnReceiveDeferredMessageAsync(long[ protected virtual Task OnCompleteAsync(IEnumerable lockTokens) { var lockTokenGuids = lockTokens.Select(lt => new Guid(lt)).ToArray(); - if (lockTokenGuids.Any(lt => requestResponseLockedMessages.Contains(lt))) + if (lockTokenGuids.Any(lt => _requestResponseLockedMessages.Contains(lt))) { return DisposeMessageRequestResponseAsync(lockTokenGuids, DispositionStatus.Completed); } @@ -1192,7 +1192,7 @@ protected virtual Task OnCompleteAsync(IEnumerable lockTokens) protected virtual Task OnAbandonAsync(string lockToken, IDictionary propertiesToModify = null) { var lockTokens = new[] { new Guid(lockToken) }; - if (lockTokens.Any(lt => requestResponseLockedMessages.Contains(lt))) + if (lockTokens.Any(lt => _requestResponseLockedMessages.Contains(lt))) { return DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Abandoned, propertiesToModify); } @@ -1202,7 +1202,7 @@ protected virtual Task OnAbandonAsync(string lockToken, IDictionary propertiesToModify = null) { var lockTokens = new[] { new Guid(lockToken) }; - if (lockTokens.Any(lt => requestResponseLockedMessages.Contains(lt))) + if (lockTokens.Any(lt => _requestResponseLockedMessages.Contains(lt))) { return DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Defered, propertiesToModify); } @@ -1222,7 +1222,7 @@ protected virtual Task OnDeadLetterAsync(string lockToken, IDictionary requestResponseLockedMessages.Contains(lt))) + if (lockTokens.Any(lt => _requestResponseLockedMessages.Contains(lt))) { return DisposeMessageRequestResponseAsync(lockTokens, DispositionStatus.Suspended, propertiesToModify, deadLetterReason, deadLetterErrorDescription); } @@ -1271,31 +1271,31 @@ protected virtual void OnMessageHandler( { MessagingEventSource.Log.RegisterOnMessageHandlerStart(ClientId, registerHandlerOptions); - lock (messageReceivePumpSyncLock) + lock (_messageReceivePumpSyncLock) { - if (receivePump != null) + if (_receivePump != null) { throw new InvalidOperationException(Resources.MessageHandlerAlreadyRegistered); } - receivePumpCancellationTokenSource = new CancellationTokenSource(); - receivePump = new MessageReceivePump(this, registerHandlerOptions, callback, ServiceBusConnection.Endpoint, receivePumpCancellationTokenSource.Token); + _receivePumpCancellationTokenSource = new CancellationTokenSource(); + _receivePump = new MessageReceivePump(this, registerHandlerOptions, callback, ServiceBusConnection.Endpoint, _receivePumpCancellationTokenSource.Token); } try { - receivePump.StartPump(); + _receivePump.StartPump(); } catch (Exception exception) { MessagingEventSource.Log.RegisterOnMessageHandlerException(ClientId, exception); - lock (messageReceivePumpSyncLock) + lock (_messageReceivePumpSyncLock) { - if (receivePump != null) + if (_receivePump != null) { - receivePumpCancellationTokenSource.Cancel(); - receivePumpCancellationTokenSource.Dispose(); - receivePump = null; + _receivePumpCancellationTokenSource.Cancel(); + _receivePumpCancellationTokenSource.Dispose(); + _receivePump = null; } } @@ -1357,7 +1357,7 @@ private async Task> ProcessMessages(IList messageList) private async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome outcome) { - if(isSessionReceiver) + if(_isSessionReceiver) { ThrowIfSessionLockLost(); } @@ -1377,7 +1377,7 @@ private async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome ou if (!ReceiveLinkManager.TryGetOpenedObject(out receiveLink)) { - MessagingEventSource.Log.CreatingNewLink(ClientId, isSessionReceiver, SessionIdInternal, false, LinkException); + MessagingEventSource.Log.CreatingNewLink(ClientId, _isSessionReceiver, SessionIdInternal, false, LinkException); receiveLink = await ReceiveLinkManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false); } @@ -1400,7 +1400,7 @@ private async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome ou { if (error.Condition.Equals(AmqpErrorCode.NotFound)) { - if (isSessionReceiver) + if (_isSessionReceiver) { throw new SessionLockLostException(Resources.SessionLockExpiredOnMessageSession); } @@ -1418,8 +1418,8 @@ private async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome ou receiveLink != null && receiveLink.State != AmqpObjectState.Opened) { // The link state is lost, We need to return a non-retriable error. - MessagingEventSource.Log.LinkStateLost(ClientId, receiveLink.Name, receiveLink.State, isSessionReceiver, exception); - if (isSessionReceiver) + MessagingEventSource.Log.LinkStateLost(ClientId, receiveLink.Name, receiveLink.State, _isSessionReceiver, exception); + if (_isSessionReceiver) { throw new SessionLockLostException(Resources.SessionLockExpiredOnMessageSession); } @@ -1500,7 +1500,7 @@ private async Task CreateLinkAsync(TimeSpan timeout) MessagingEventSource.Log.AmqpReceiveLinkCreateStart(ClientId, false, EntityType, Path); - if (isSessionReceiver) + if (_isSessionReceiver) { filterMap = new FilterSet { { AmqpClientConstants.SessionFilterName, SessionIdInternal } }; } @@ -1543,7 +1543,7 @@ private async Task CreateLinkAsync(TimeSpan timeout) claims, linkDetails.Item2); - clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); + _clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); MessagingEventSource.Log.AmqpReceiveLinkCreateStop(ClientId); @@ -1580,7 +1580,7 @@ private async Task CreateRequestResponseLinkAsync(TimeS new[] { endpointUri.AbsoluteUri }, claims, linkDetails.Item2); - clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); + _clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); MessagingEventSource.Log.AmqpReceiveLinkCreateStop(ClientId); return requestResponseAmqpLink; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs index 05ec467104bf..8e9910753e30 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs @@ -36,10 +36,10 @@ namespace Microsoft.Azure.ServiceBus.Core /// This uses AMQP protocol to communicate with service. public class MessageSender : ClientEntity, IMessageSender { - private int deliveryCount; - private readonly ActiveClientLinkManager clientLinkManager; - private readonly ServiceBusDiagnosticSource diagnosticSource; - private readonly bool isViaSender; + private int _deliveryCount; + private readonly ActiveClientLinkManager _clientLinkManager; + private readonly ServiceBusDiagnosticSource _diagnosticSource; + private readonly bool _isViaSender; /// /// Creates a new AMQP MessageSender. @@ -170,12 +170,12 @@ internal MessageSender( SendLinkManager = new FaultTolerantAmqpObject(CreateLinkAsync, CloseSession); RequestResponseLinkManager = new FaultTolerantAmqpObject(CreateRequestResponseLinkAsync, CloseRequestResponseSession); - clientLinkManager = new ActiveClientLinkManager(this, CbsTokenProvider); - diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); + _clientLinkManager = new ActiveClientLinkManager(this, CbsTokenProvider); + _diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); if (!string.IsNullOrWhiteSpace(transferDestinationPath)) { - isViaSender = true; + _isViaSender = true; TransferDestinationPath = transferDestinationPath; ViaEntityPath = entityPath; } @@ -254,7 +254,7 @@ public async Task SendAsync(IList messageList) MessagingEventSource.Log.MessageSendStart(ClientId, count); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.SendStart(messageList) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.SendStart(messageList) : null; Task sendTask = null; try @@ -268,7 +268,7 @@ public async Task SendAsync(IList messageList) { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.MessageSendException(ClientId, exception); @@ -276,7 +276,7 @@ public async Task SendAsync(IList messageList) } finally { - diagnosticSource.SendStop(activity, messageList, sendTask?.Status); + _diagnosticSource.SendStop(activity, messageList, sendTask?.Status); } MessagingEventSource.Log.MessageSendStop(ClientId); @@ -304,7 +304,7 @@ public async Task ScheduleMessageAsync(Message message, DateTimeOffset sch "Cannot schedule messages in the past"); } - if (isViaSender && Transaction.Current != null) + if (_isViaSender && Transaction.Current != null) { throw new ServiceBusException(false, $"{nameof(ScheduleMessageAsync)} method is not supported in a Via-Sender with transactions."); } @@ -315,7 +315,7 @@ public async Task ScheduleMessageAsync(Message message, DateTimeOffset sch long result = 0; bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.ScheduleStart(message, scheduleEnqueueTimeUtc) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.ScheduleStart(message, scheduleEnqueueTimeUtc) : null; Task scheduleTask = null; try @@ -333,7 +333,7 @@ public async Task ScheduleMessageAsync(Message message, DateTimeOffset sch { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.ScheduleMessageException(ClientId, exception); @@ -341,7 +341,7 @@ public async Task ScheduleMessageAsync(Message message, DateTimeOffset sch } finally { - diagnosticSource.ScheduleStop(activity, message, scheduleEnqueueTimeUtc, scheduleTask?.Status, result); + _diagnosticSource.ScheduleStop(activity, message, scheduleEnqueueTimeUtc, scheduleTask?.Status, result); } MessagingEventSource.Log.ScheduleMessageStop(ClientId); @@ -363,7 +363,7 @@ public async Task CancelScheduledMessageAsync(long sequenceNumber) MessagingEventSource.Log.CancelScheduledMessageStart(ClientId, sequenceNumber); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.CancelStart(sequenceNumber) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.CancelStart(sequenceNumber) : null; Task cancelTask = null; try @@ -376,7 +376,7 @@ public async Task CancelScheduledMessageAsync(long sequenceNumber) { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.CancelScheduledMessageException(ClientId, exception); @@ -384,7 +384,7 @@ public async Task CancelScheduledMessageAsync(long sequenceNumber) } finally { - diagnosticSource.CancelStop(activity, sequenceNumber, cancelTask?.Status); + _diagnosticSource.CancelStop(activity, sequenceNumber, cancelTask?.Status); } MessagingEventSource.Log.CancelScheduledMessageStop(ClientId); } @@ -454,7 +454,7 @@ internal async Task ExecuteRequestResponseAsync(AmqpRequest /// Closes the connection. protected override async Task OnClosingAsync() { - clientLinkManager.Close(); + _clientLinkManager.Close(); await SendLinkManager.CloseAsync().ConfigureAwait(false); await RequestResponseLinkManager.CloseAsync().ConfigureAwait(false); } @@ -698,7 +698,7 @@ private async Task CreateLinkAsync(TimeSpan timeout) var endpointUri = new Uri(ServiceBusConnection.Endpoint, SendingLinkDestination); string[] audience; - if (isViaSender) + if (_isViaSender) { var transferDestinationEndpointUri = new Uri(ServiceBusConnection.Endpoint, TransferDestinationPath); audience = new[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; @@ -721,7 +721,7 @@ private async Task CreateLinkAsync(TimeSpan timeout) claims, linkDetails.Item2); - clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); + _clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); MessagingEventSource.Log.AmqpSendLinkCreateStop(ClientId); return sendingAmqpLink; @@ -736,7 +736,7 @@ private async Task CreateRequestResponseLinkAsync(TimeS var endpointUri = new Uri(ServiceBusConnection.Endpoint, entityPath); string[] audience; - if (isViaSender) + if (_isViaSender) { var transferDestinationEndpointUri = new Uri(ServiceBusConnection.Endpoint, TransferDestinationPath); audience = new[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; @@ -768,14 +768,14 @@ private async Task CreateRequestResponseLinkAsync(TimeS audience, claims, linkDetails.Item2); - clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); + _clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); return requestResponseAmqpLink; } private ArraySegment GetNextDeliveryTag() { - var deliveryId = Interlocked.Increment(ref deliveryCount); + var deliveryId = Interlocked.Increment(ref _deliveryCount); return new ArraySegment(BitConverter.GetBytes(deliveryId)); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs index de802aa264d7..39cc8baea125 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs @@ -16,14 +16,14 @@ namespace Microsoft.Azure.ServiceBus.Extensions /// internal sealed class DataContractBinarySerializer : XmlObjectSerializer { - private readonly DataContractSerializer dataContractSerializer; + private readonly DataContractSerializer _dataContractSerializer; /// /// Initializes a new DataContractBinarySerializer instance /// public DataContractBinarySerializer(Type type) { - dataContractSerializer = new DataContractSerializer(type); + _dataContractSerializer = new DataContractSerializer(type); } /// @@ -62,7 +62,7 @@ public override void WriteObject(XmlDictionaryWriter writer, object graph) throw new ArgumentNullException(nameof(writer)); } - dataContractSerializer.WriteObject(writer, graph); + _dataContractSerializer.WriteObject(writer, graph); } /// @@ -70,7 +70,7 @@ public override void WriteObject(XmlDictionaryWriter writer, object graph) /// public override bool IsStartObject(XmlDictionaryReader reader) { - return dataContractSerializer.IsStartObject(reader); + return _dataContractSerializer.IsStartObject(reader); } /// @@ -78,7 +78,7 @@ public override bool IsStartObject(XmlDictionaryReader reader) /// public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { - return dataContractSerializer.ReadObject(reader, verifyObjectName); + return _dataContractSerializer.ReadObject(reader, verifyObjectName); } /// @@ -86,7 +86,7 @@ public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectN /// public override void WriteEndObject(XmlDictionaryWriter writer) { - dataContractSerializer.WriteEndObject(writer); + _dataContractSerializer.WriteEndObject(writer); } /// @@ -94,7 +94,7 @@ public override void WriteEndObject(XmlDictionaryWriter writer) /// public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) { - dataContractSerializer.WriteObjectContent(writer, graph); + _dataContractSerializer.WriteObjectContent(writer, graph); } /// @@ -102,7 +102,7 @@ public override void WriteObjectContent(XmlDictionaryWriter writer, object graph /// public override void WriteStartObject(XmlDictionaryWriter writer, object graph) { - dataContractSerializer.WriteStartObject(writer, graph); + _dataContractSerializer.WriteStartObject(writer, graph); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs index f4b04e783384..53cba0255190 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs @@ -20,8 +20,8 @@ public sealed class RuleDescription : IEquatable /// public const string DefaultRuleName = "$Default"; - private Filter filter; - private string name; + private Filter _filter; + private string _name; /// /// Initializes a new instance of the class with default values. @@ -66,9 +66,9 @@ public RuleDescription(string name, Filter filter) /// null (Nothing in Visual Basic) is assigned. public Filter Filter { - get => filter; + get => _filter; - set => filter = value ?? throw Fx.Exception.ArgumentNull(nameof(Filter)); + set => _filter = value ?? throw Fx.Exception.ArgumentNull(nameof(Filter)); } /// @@ -84,12 +84,12 @@ public Filter Filter /// Max allowed length of rule name is 50 chars. public string Name { - get => name; + get => _name; set { EntityNameHelper.CheckValidRuleName(value); - name = value; + _name = value; } } @@ -104,7 +104,7 @@ public override int GetHashCode() int hash = 13; unchecked { - hash = (hash * 7) + filter?.GetHashCode() ?? 0; + hash = (hash * 7) + _filter?.GetHashCode() ?? 0; hash = (hash * 7) + Action?.GetHashCode() ?? 0; } return hash; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs index 79d7d81998cc..f92c3f6cbc6d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs @@ -17,11 +17,11 @@ namespace Microsoft.Azure.ServiceBus.Management public class ManagementClient { - private HttpClient httpClient; - private readonly string endpointFQDN; - private readonly ITokenProvider tokenProvider; - private readonly int port; - private readonly string clientId; + private HttpClient _httpClient; + private readonly string _endpointFqdn; + private readonly ITokenProvider _tokenProvider; + private readonly int _port; + private readonly string _clientId; /// /// Initializes a new which can be used to perform management opertions on ServiceBus entities. @@ -49,13 +49,13 @@ public ManagementClient(string endpoint, ITokenProvider tokenProvider) /// Token provider which will generate security tokens for authorization. public ManagementClient(ServiceBusConnectionStringBuilder connectionStringBuilder, ITokenProvider tokenProvider = default) { - httpClient = new HttpClient { Timeout = connectionStringBuilder.OperationTimeout }; - endpointFQDN = connectionStringBuilder.Endpoint; - this.tokenProvider = tokenProvider ?? CreateTokenProvider(connectionStringBuilder); - port = GetPort(connectionStringBuilder.Endpoint); - clientId = nameof(ManagementClient) + Guid.NewGuid().ToString("N").Substring(0, 6); + _httpClient = new HttpClient { Timeout = connectionStringBuilder.OperationTimeout }; + _endpointFqdn = connectionStringBuilder.Endpoint; + this._tokenProvider = tokenProvider ?? CreateTokenProvider(connectionStringBuilder); + _port = GetPort(connectionStringBuilder.Endpoint); + _clientId = nameof(ManagementClient) + Guid.NewGuid().ToString("N").Substring(0, 6); - MessagingEventSource.Log.ManagementClientCreated(clientId, httpClient.Timeout.TotalSeconds, this.tokenProvider.ToString()); + MessagingEventSource.Log.ManagementClientCreated(_clientId, _httpClient.Timeout.TotalSeconds, this._tokenProvider.ToString()); } public static HttpRequestMessage CloneRequest(HttpRequestMessage req) @@ -604,7 +604,7 @@ public virtual Task CreateQueueAsync(string queuePath, Cancell public virtual async Task CreateQueueAsync(QueueDescription queueDescription, CancellationToken cancellationToken = default) { queueDescription = queueDescription ?? throw new ArgumentNullException(nameof(queueDescription)); - queueDescription.NormalizeDescription(endpointFQDN); + queueDescription.NormalizeDescription(_endpointFqdn); var atomRequest = queueDescription.Serialize().ToString(); var content = await PutEntity( queueDescription.Path, @@ -723,7 +723,7 @@ public virtual Task CreateSubscriptionAsync(Subscriptio public virtual async Task CreateSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule, CancellationToken cancellationToken = default) { subscriptionDescription = subscriptionDescription ?? throw new ArgumentNullException(nameof(subscriptionDescription)); - subscriptionDescription.NormalizeDescription(endpointFQDN); + subscriptionDescription.NormalizeDescription(_endpointFqdn); subscriptionDescription.DefaultRuleDescription = defaultRule; var atomRequest = subscriptionDescription.Serialize().ToString(); var content = await PutEntity( @@ -789,7 +789,7 @@ public virtual async Task CreateRuleAsync(string topicPath, str public virtual async Task UpdateQueueAsync(QueueDescription queueDescription, CancellationToken cancellationToken = default) { queueDescription = queueDescription ?? throw new ArgumentNullException(nameof(queueDescription)); - queueDescription.NormalizeDescription(endpointFQDN); + queueDescription.NormalizeDescription(_endpointFqdn); var atomRequest = queueDescription.Serialize().ToString(); @@ -843,7 +843,7 @@ public virtual async Task UpdateTopicAsync(TopicDescription to public virtual async Task UpdateSubscriptionAsync(SubscriptionDescription subscriptionDescription, CancellationToken cancellationToken = default) { subscriptionDescription = subscriptionDescription ?? throw new ArgumentNullException(nameof(subscriptionDescription)); - subscriptionDescription.NormalizeDescription(endpointFQDN); + subscriptionDescription.NormalizeDescription(_endpointFqdn); var atomRequest = subscriptionDescription.Serialize().ToString(); var content = await PutEntity( EntityNameHelper.FormatSubscriptionPath(subscriptionDescription.TopicPath, subscriptionDescription.SubscriptionName), @@ -978,8 +978,8 @@ public virtual async Task SubscriptionExistsAsync(string topicPath, string public Task CloseAsync() { - httpClient?.Dispose(); - httpClient = null; + _httpClient?.Dispose(); + _httpClient = null; return Task.CompletedTask; } @@ -1106,24 +1106,24 @@ private Task GetToken(Uri requestUri) private async Task GetToken(string requestUri) { - var token = await tokenProvider.GetTokenAsync(requestUri, TimeSpan.FromHours(1)).ConfigureAwait(false); + var token = await _tokenProvider.GetTokenAsync(requestUri, TimeSpan.FromHours(1)).ConfigureAwait(false); return token.TokenValue; } private async Task GetEntity(string path, string query, bool enrich, CancellationToken cancellationToken) { - MessagingEventSource.Log.ManagementOperationStart(clientId, nameof(GetEntity), $"path:{path},query:{query},enrich:{enrich}"); + MessagingEventSource.Log.ManagementOperationStart(_clientId, nameof(GetEntity), $"path:{path},query:{query},enrich:{enrich}"); var queryString = $"{ManagementClientConstants.apiVersionQuery}&enrich={enrich}"; if (query != null) { queryString = queryString + "&" + query; } - var uri = new UriBuilder(endpointFQDN) + var uri = new UriBuilder(_endpointFqdn) { Path = path, Scheme = Uri.UriSchemeHttps, - Port = port, + Port = _port, Query = queryString }.Uri; @@ -1131,18 +1131,18 @@ private async Task GetEntity(string path, string query, bool enrich, Can HttpResponseMessage response = await SendHttpRequest(request, cancellationToken).ConfigureAwait(false); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - MessagingEventSource.Log.ManagementOperationEnd(clientId, nameof(GetEntity), $"path:{path},query:{query},enrich:{enrich}"); + MessagingEventSource.Log.ManagementOperationEnd(_clientId, nameof(GetEntity), $"path:{path},query:{query},enrich:{enrich}"); return result; } private async Task PutEntity(string path, string requestBody, bool isUpdate, string forwardTo, string fwdDeadLetterTo, CancellationToken cancellationToken) { - MessagingEventSource.Log.ManagementOperationStart(clientId, nameof(PutEntity), $"path:{path},isUpdate:{isUpdate}"); + MessagingEventSource.Log.ManagementOperationStart(_clientId, nameof(PutEntity), $"path:{path},isUpdate:{isUpdate}"); - var uri = new UriBuilder(endpointFQDN) + var uri = new UriBuilder(_endpointFqdn) { Path = path, - Port = port, + Port = _port, Scheme = Uri.UriSchemeHttps, Query = $"{ManagementClientConstants.apiVersionQuery}" }.Uri; @@ -1174,25 +1174,25 @@ private async Task PutEntity(string path, string requestBody, bool isUpd HttpResponseMessage response = await SendHttpRequest(request, cancellationToken).ConfigureAwait(false); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - MessagingEventSource.Log.ManagementOperationEnd(clientId, nameof(PutEntity), $"path:{path},isUpdate:{isUpdate}"); + MessagingEventSource.Log.ManagementOperationEnd(_clientId, nameof(PutEntity), $"path:{path},isUpdate:{isUpdate}"); return result; } private async Task DeleteEntity(string path, CancellationToken cancellationToken) { - MessagingEventSource.Log.ManagementOperationStart(clientId, nameof(DeleteEntity), path); + MessagingEventSource.Log.ManagementOperationStart(_clientId, nameof(DeleteEntity), path); - var uri = new UriBuilder(endpointFQDN) + var uri = new UriBuilder(_endpointFqdn) { Path = path, Scheme = Uri.UriSchemeHttps, - Port = port, + Port = _port, Query = ManagementClientConstants.apiVersionQuery }.Uri; var request = new HttpRequestMessage(HttpMethod.Delete, uri); await SendHttpRequest(request, cancellationToken).ConfigureAwait(false); - MessagingEventSource.Log.ManagementOperationEnd(clientId, nameof(DeleteEntity), path); + MessagingEventSource.Log.ManagementOperationEnd(_clientId, nameof(DeleteEntity), path); } private async Task SendHttpRequest(HttpRequestMessage request, CancellationToken cancellationToken) @@ -1213,11 +1213,11 @@ private async Task SendHttpRequest(HttpRequestMessage reque HttpResponseMessage response; try { - response = await httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); + response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); } catch (HttpRequestException exception) { - MessagingEventSource.Log.ManagementOperationException(clientId, nameof(SendHttpRequest), exception); + MessagingEventSource.Log.ManagementOperationException(_clientId, nameof(SendHttpRequest), exception); throw new ServiceBusException(true, exception); } @@ -1228,7 +1228,7 @@ private async Task SendHttpRequest(HttpRequestMessage reque } else { - MessagingEventSource.Log.ManagementOperationException(clientId, nameof(SendHttpRequest), exceptionReturned); + MessagingEventSource.Log.ManagementOperationException(_clientId, nameof(SendHttpRequest), exceptionReturned); throw exceptionReturned; } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index 0f96d86f016b..b5b83f025dc6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -14,13 +14,13 @@ public class QueueDescription : IEquatable { internal TimeSpan duplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1); internal string path; - private TimeSpan lockDuration = TimeSpan.FromSeconds(60); - private TimeSpan defaultMessageTimeToLive = TimeSpan.MaxValue; - private TimeSpan autoDeleteOnIdle = TimeSpan.MaxValue; - private int maxDeliveryCount = 10; - private string forwardTo = null; - private string forwardDeadLetteredMessagesTo = null; - private string userMetadata = null; + private TimeSpan _lockDuration = TimeSpan.FromSeconds(60); + private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; + private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; + private int _maxDeliveryCount = 10; + private string _forwardTo = null; + private string _forwardDeadLetteredMessagesTo = null; + private string _userMetadata = null; /// /// Initializes a new instance of QueueDescription class with the specified relative path. @@ -53,11 +53,11 @@ public string Path /// Max value is 5 minutes. Default value is 60 seconds. public TimeSpan LockDuration { - get => lockDuration; + get => _lockDuration; set { TimeoutHelper.ThrowIfNonPositiveArgument(value, nameof(LockDuration)); - lockDuration = value; + _lockDuration = value; } } @@ -95,7 +95,7 @@ public TimeSpan LockDuration /// public TimeSpan DefaultMessageTimeToLive { - get => defaultMessageTimeToLive; + get => _defaultMessageTimeToLive; set { if (value < ManagementClientConstants.MinimumAllowedTimeToLive || value > ManagementClientConstants.MaximumAllowedTimeToLive) @@ -104,7 +104,7 @@ public TimeSpan DefaultMessageTimeToLive $@"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); } - defaultMessageTimeToLive = value; + _defaultMessageTimeToLive = value; } } @@ -114,7 +114,7 @@ public TimeSpan DefaultMessageTimeToLive /// The minimum duration is 5 minutes. Default value is . public TimeSpan AutoDeleteOnIdle { - get => autoDeleteOnIdle; + get => _autoDeleteOnIdle; set { if (value < ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle) @@ -123,7 +123,7 @@ public TimeSpan AutoDeleteOnIdle $@"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } - autoDeleteOnIdle = value; + _autoDeleteOnIdle = value; } } @@ -162,7 +162,7 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow /// Default value is 10. Minimum value is 1. public int MaxDeliveryCount { - get => maxDeliveryCount; + get => _maxDeliveryCount; set { if (value < ManagementClientConstants.MinAllowedMaxDeliveryCount) @@ -171,7 +171,7 @@ public int MaxDeliveryCount $@"The value must be greater than {ManagementClientConstants.MinAllowedMaxDeliveryCount}"); } - maxDeliveryCount = value; + _maxDeliveryCount = value; } } @@ -199,12 +199,12 @@ public int MaxDeliveryCount /// must be an already existing entity. public string ForwardTo { - get => forwardTo; + get => _forwardTo; set { if (string.IsNullOrWhiteSpace(value)) { - forwardTo = value; + _forwardTo = value; return; } @@ -214,7 +214,7 @@ public string ForwardTo throw new InvalidOperationException("Entity cannot have auto-forwarding policy to itself"); } - forwardTo = value; + _forwardTo = value; } } @@ -225,12 +225,12 @@ public string ForwardTo /// entity must already exist. public string ForwardDeadLetteredMessagesTo { - get => forwardDeadLetteredMessagesTo; + get => _forwardDeadLetteredMessagesTo; set { if (string.IsNullOrWhiteSpace(value)) { - forwardDeadLetteredMessagesTo = value; + _forwardDeadLetteredMessagesTo = value; return; } @@ -240,7 +240,7 @@ public string ForwardDeadLetteredMessagesTo throw new InvalidOperationException("Entity cannot have auto-forwarding policy to itself"); } - forwardDeadLetteredMessagesTo = value; + _forwardDeadLetteredMessagesTo = value; } } @@ -256,7 +256,7 @@ public string ForwardDeadLetteredMessagesTo /// Cannot be null. Max length is 1024 chars. public string UserMetadata { - get => userMetadata; + get => _userMetadata; set { if (value == null) @@ -269,7 +269,7 @@ public string UserMetadata throw new ArgumentOutOfRangeException(nameof(UserMetadata), $@"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } - userMetadata = value; + _userMetadata = value; } } @@ -308,7 +308,7 @@ public bool Equals(QueueDescription otherDescription) && RequiresDuplicateDetection.Equals(other.RequiresDuplicateDetection) && RequiresSession.Equals(other.RequiresSession) && Status.Equals(other.Status) - && string.Equals(userMetadata, other.userMetadata, StringComparison.OrdinalIgnoreCase) + && string.Equals(_userMetadata, other._userMetadata, StringComparison.OrdinalIgnoreCase) && (AuthorizationRules != null && other.AuthorizationRules != null || AuthorizationRules == null && other.AuthorizationRules == null) && (AuthorizationRules == null || AuthorizationRules.Equals(other.AuthorizationRules))) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs index 4b3288a2b502..a21d94f6d34e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs @@ -21,10 +21,10 @@ public class SharedAccessAuthorizationRule : AuthorizationRule private const int SupportedSASKeyLength = 44; private const string FixedClaimType = "SharedAccessKey"; - private string internalKeyName; - private string internalPrimaryKey; - private string internalSecondaryKey; - private List internalRights; + private string _internalKeyName; + private string _internalPrimaryKey; + private string _internalSecondaryKey; + private List _internalRights; internal SharedAccessAuthorizationRule() { @@ -68,7 +68,7 @@ public SharedAccessAuthorizationRule(string keyName, string primaryKey, string s /// The authorization rule key name. public override sealed string KeyName { - get { return internalKeyName; } + get { return _internalKeyName; } set { if (string.IsNullOrWhiteSpace(value)) @@ -87,7 +87,7 @@ public override sealed string KeyName throw new ArgumentException("The key name specified contains invalid characters"); } - internalKeyName = value; + _internalKeyName = value; } } @@ -95,7 +95,7 @@ public override sealed string KeyName /// The primary key for the authorization rule. public string PrimaryKey { - get { return internalPrimaryKey; } + get { return _internalPrimaryKey; } set { if (string.IsNullOrWhiteSpace(value)) @@ -113,7 +113,7 @@ public string PrimaryKey throw new ArgumentException(nameof(PrimaryKey), $"{nameof(SharedAccessAuthorizationRule)} only supports base64 keys."); } - internalPrimaryKey = value; + _internalPrimaryKey = value; } } @@ -121,7 +121,7 @@ public string PrimaryKey /// The secondary key for the authorization rule. public string SecondaryKey { - get { return internalSecondaryKey; } + get { return _internalSecondaryKey; } set { if (string.IsNullOrWhiteSpace(value)) @@ -139,13 +139,13 @@ public string SecondaryKey throw new ArgumentException(nameof(SecondaryKey), $"{nameof(SharedAccessAuthorizationRule)} only supports base64 keys."); } - internalSecondaryKey = value; + _internalSecondaryKey = value; } } public override List Rights { - get => internalRights; + get => _internalRights; set { if (value == null || value.Count < 0 || value.Count > ManagementClientConstants.SupportedClaimsCount) @@ -164,7 +164,7 @@ public override List Rights throw new ArgumentException(nameof(Rights), "Manage permission should also include Send and Listen"); } - internalRights = value; + _internalRights = value; } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs index 4dbee656cbf6..e4ebbe252284 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -14,14 +14,14 @@ namespace Microsoft.Azure.ServiceBus.Management /// public class SubscriptionDescription : IEquatable { - private string topicPath, subscriptionName; - private TimeSpan lockDuration = TimeSpan.FromSeconds(60); - private TimeSpan defaultMessageTimeToLive = TimeSpan.MaxValue; - private TimeSpan autoDeleteOnIdle = TimeSpan.MaxValue; - private int maxDeliveryCount = 10; - private string forwardTo = null; - private string forwardDeadLetteredMessagesTo = null; - private string userMetadata = null; + private string _topicPath, _subscriptionName; + private TimeSpan _lockDuration = TimeSpan.FromSeconds(60); + private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; + private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; + private int _maxDeliveryCount = 10; + private string _forwardTo = null; + private string _forwardDeadLetteredMessagesTo = null; + private string _userMetadata = null; /// /// Initializes a new instance of SubscriptionDescription class with the specified name and topic path. @@ -41,11 +41,11 @@ public SubscriptionDescription(string topicPath, string subscriptionName) /// Max value is 5 minutes. Default value is 60 seconds. public TimeSpan LockDuration { - get => lockDuration; + get => _lockDuration; set { TimeoutHelper.ThrowIfNonPositiveArgument(value, nameof(LockDuration)); - lockDuration = value; + _lockDuration = value; } } @@ -69,7 +69,7 @@ public TimeSpan LockDuration /// public TimeSpan DefaultMessageTimeToLive { - get => defaultMessageTimeToLive; + get => _defaultMessageTimeToLive; set { if (value < ManagementClientConstants.MinimumAllowedTimeToLive || value > ManagementClientConstants.MaximumAllowedTimeToLive) @@ -78,7 +78,7 @@ public TimeSpan DefaultMessageTimeToLive $@"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); } - defaultMessageTimeToLive = value; + _defaultMessageTimeToLive = value; } } @@ -88,7 +88,7 @@ public TimeSpan DefaultMessageTimeToLive /// The minimum duration is 5 minutes. Default value is . public TimeSpan AutoDeleteOnIdle { - get => autoDeleteOnIdle; + get => _autoDeleteOnIdle; set { if (value < ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle) @@ -97,7 +97,7 @@ public TimeSpan AutoDeleteOnIdle $@"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } - autoDeleteOnIdle = value; + _autoDeleteOnIdle = value; } } @@ -120,11 +120,11 @@ public TimeSpan AutoDeleteOnIdle /// Cannot have restricted characters: '@','?','#','*' public string TopicPath { - get => topicPath; + get => _topicPath; set { EntityNameHelper.CheckValidTopicName(value, nameof(TopicPath)); - topicPath = value; + _topicPath = value; } } @@ -135,11 +135,11 @@ public string TopicPath /// Cannot have restricted characters: '@','?','#','*','/','\' public string SubscriptionName { - get => subscriptionName; + get => _subscriptionName; set { EntityNameHelper.CheckValidSubscriptionName(value, nameof(SubscriptionName)); - subscriptionName = value; + _subscriptionName = value; } } @@ -151,7 +151,7 @@ public string SubscriptionName /// Default value is 10. Minimum value is 1. public int MaxDeliveryCount { - get => maxDeliveryCount; + get => _maxDeliveryCount; set { if (value < ManagementClientConstants.MinAllowedMaxDeliveryCount) @@ -160,7 +160,7 @@ public int MaxDeliveryCount $@"The value must be greater than {ManagementClientConstants.MinAllowedMaxDeliveryCount}"); } - maxDeliveryCount = value; + _maxDeliveryCount = value; } } @@ -177,22 +177,22 @@ public int MaxDeliveryCount /// must be an already existing entity. public string ForwardTo { - get => forwardTo; + get => _forwardTo; set { if (string.IsNullOrWhiteSpace(value)) { - forwardTo = value; + _forwardTo = value; return; } EntityNameHelper.CheckValidQueueName(value, nameof(ForwardTo)); - if (topicPath.Equals(value, StringComparison.CurrentCultureIgnoreCase)) + if (_topicPath.Equals(value, StringComparison.CurrentCultureIgnoreCase)) { throw new InvalidOperationException("Entity cannot have auto-forwarding policy to itself"); } - forwardTo = value; + _forwardTo = value; } } @@ -203,22 +203,22 @@ public string ForwardTo /// entity must already exist. public string ForwardDeadLetteredMessagesTo { - get => forwardDeadLetteredMessagesTo; + get => _forwardDeadLetteredMessagesTo; set { if (string.IsNullOrWhiteSpace(value)) { - forwardDeadLetteredMessagesTo = value; + _forwardDeadLetteredMessagesTo = value; return; } EntityNameHelper.CheckValidQueueName(value, nameof(ForwardDeadLetteredMessagesTo)); - if (topicPath.Equals(value, StringComparison.CurrentCultureIgnoreCase)) + if (_topicPath.Equals(value, StringComparison.CurrentCultureIgnoreCase)) { throw new InvalidOperationException("Entity cannot have auto-forwarding policy to itself"); } - forwardDeadLetteredMessagesTo = value; + _forwardDeadLetteredMessagesTo = value; } } @@ -234,7 +234,7 @@ public string ForwardDeadLetteredMessagesTo /// Cannot be null. Max length is 1024 chars. public string UserMetadata { - get => userMetadata; + get => _userMetadata; set { if (value == null) @@ -247,7 +247,7 @@ public string UserMetadata throw new ArgumentOutOfRangeException(nameof(UserMetadata), $@"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } - userMetadata = value; + _userMetadata = value; } } @@ -293,7 +293,7 @@ public bool Equals(SubscriptionDescription otherDescription) && MaxDeliveryCount == other.MaxDeliveryCount && RequiresSession.Equals(other.RequiresSession) && Status.Equals(other.Status) - && string.Equals(userMetadata, other.userMetadata, StringComparison.OrdinalIgnoreCase)) + && string.Equals(_userMetadata, other._userMetadata, StringComparison.OrdinalIgnoreCase)) { return true; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs index 36e7aa21ef44..ee15b67140ad 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs @@ -13,9 +13,9 @@ public class TopicDescription : IEquatable { internal TimeSpan duplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1); internal string path; - private TimeSpan defaultMessageTimeToLive = TimeSpan.MaxValue; - private TimeSpan autoDeleteOnIdle = TimeSpan.MaxValue; - private string userMetadata = null; + private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; + private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; + private string _userMetadata = null; /// /// Initializes a new instance of TopicDescription class with the specified relative path. @@ -37,7 +37,7 @@ public TopicDescription(string path) /// public TimeSpan DefaultMessageTimeToLive { - get => defaultMessageTimeToLive; + get => _defaultMessageTimeToLive; set { if (value < ManagementClientConstants.MinimumAllowedTimeToLive || value > ManagementClientConstants.MaximumAllowedTimeToLive) @@ -46,7 +46,7 @@ public TimeSpan DefaultMessageTimeToLive $@"The value must be between {ManagementClientConstants.MinimumAllowedTimeToLive} and {ManagementClientConstants.MaximumAllowedTimeToLive}"); } - defaultMessageTimeToLive = value; + _defaultMessageTimeToLive = value; } } @@ -56,7 +56,7 @@ public TimeSpan DefaultMessageTimeToLive /// The minimum duration is 5 minutes. Default value is . public TimeSpan AutoDeleteOnIdle { - get => autoDeleteOnIdle; + get => _autoDeleteOnIdle; set { if (value < ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle) @@ -65,7 +65,7 @@ public TimeSpan AutoDeleteOnIdle $@"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } - autoDeleteOnIdle = value; + _autoDeleteOnIdle = value; } } @@ -155,7 +155,7 @@ public string Path /// Cannot be null. Max length is 1024 chars. public string UserMetadata { - get => userMetadata; + get => _userMetadata; set { if (value == null) @@ -168,7 +168,7 @@ public string UserMetadata throw new ArgumentOutOfRangeException(nameof(UserMetadata), $@"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } - userMetadata = value; + _userMetadata = value; } } @@ -201,7 +201,7 @@ public bool Equals(TopicDescription otherDescription) && MaxSizeInMB == other.MaxSizeInMB && RequiresDuplicateDetection.Equals(other.RequiresDuplicateDetection) && Status.Equals(other.Status) - && string.Equals(userMetadata, other.userMetadata, StringComparison.OrdinalIgnoreCase) + && string.Equals(_userMetadata, other._userMetadata, StringComparison.OrdinalIgnoreCase) && (AuthorizationRules != null && other.AuthorizationRules != null || AuthorizationRules == null && other.AuthorizationRules == null) && (AuthorizationRules == null || AuthorizationRules.Equals(other.AuthorizationRules))) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs index 6921aba7249b..59e6384ea48f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Message.cs @@ -26,12 +26,12 @@ public class Message /// public static string DeadLetterErrorDescriptionHeader = "DeadLetterErrorDescription"; - private string messageId; - private string sessionId; - private string replyToSessionId; - private string partitionKey; - private string viaPartitionKey; - private TimeSpan timeToLive; + private string _messageId; + private string _sessionId; + private string _replyToSessionId; + private string _partitionKey; + private string _viaPartitionKey; + private TimeSpan _timeToLive; /// /// Creates a new Message @@ -76,12 +76,12 @@ public Message(byte[] body) /// public string MessageId { - get => messageId; + get => _messageId; set { ValidateMessageId(value); - messageId = value; + _messageId = value; } } @@ -95,12 +95,12 @@ public string MessageId /// public string PartitionKey { - get => partitionKey; + get => _partitionKey; set { ValidatePartitionKey(nameof(PartitionKey), value); - partitionKey = value; + _partitionKey = value; } } @@ -114,12 +114,12 @@ public string PartitionKey /// public string ViaPartitionKey { - get => viaPartitionKey; + get => _viaPartitionKey; set { ValidatePartitionKey(nameof(ViaPartitionKey), value); - viaPartitionKey = value; + _viaPartitionKey = value; } } @@ -134,12 +134,12 @@ public string ViaPartitionKey /// public string SessionId { - get => sessionId; + get => _sessionId; set { ValidateSessionId(nameof(SessionId), value); - sessionId = value; + _sessionId = value; } } @@ -151,12 +151,12 @@ public string SessionId /// public string ReplyToSessionId { - get => replyToSessionId; + get => _replyToSessionId; set { ValidateSessionId(nameof(ReplyToSessionId), value); - replyToSessionId = value; + _replyToSessionId = value; } } @@ -196,18 +196,18 @@ public TimeSpan TimeToLive { get { - if (timeToLive == TimeSpan.Zero) + if (_timeToLive == TimeSpan.Zero) { return TimeSpan.MaxValue; } - return timeToLive; + return _timeToLive; } set { TimeoutHelper.ThrowIfNonPositiveArgument(value); - timeToLive = value; + _timeToLive = value; } } @@ -343,20 +343,20 @@ private static void ValidatePartitionKey(string partitionKeyPropertyName, string /// public sealed class SystemPropertiesCollection { - private int deliveryCount; - private DateTime lockedUntilUtc; - private long sequenceNumber = -1; - private short partitionId; - private long enqueuedSequenceNumber; - private DateTime enqueuedTimeUtc; - private Guid lockTokenGuid; - private string deadLetterSource; + private int _deliveryCount; + private DateTime _lockedUntilUtc; + private long _sequenceNumber = -1; + private short _partitionId; + private long _enqueuedSequenceNumber; + private DateTime _enqueuedTimeUtc; + private Guid _lockTokenGuid; + private string _deadLetterSource; /// /// Specifies whether or not there is a lock token set on the current message. /// /// A lock token will only be specified if the message was received using - public bool IsLockTokenSet => lockTokenGuid != default; + public bool IsLockTokenSet => _lockTokenGuid != default; /// /// Gets the lock token for the current message. @@ -370,7 +370,7 @@ public sealed class SystemPropertiesCollection public string LockToken => LockTokenGuid.ToString(); /// Specifies if the message has been obtained from the broker. - public bool IsReceived => sequenceNumber > -1; + public bool IsReceived => _sequenceNumber > -1; /// /// Get the current delivery count. @@ -385,10 +385,10 @@ public int DeliveryCount get { ThrowIfNotReceived(); - return deliveryCount; + return _deliveryCount; } - internal set => deliveryCount = value; + internal set => _deliveryCount = value; } /// Gets the date and time in UTC until which the message will be locked in the queue/subscription. @@ -403,10 +403,10 @@ public DateTime LockedUntilUtc get { ThrowIfNotReceived(); - return lockedUntilUtc; + return _lockedUntilUtc; } - internal set => lockedUntilUtc = value; + internal set => _lockedUntilUtc = value; } /// Gets the unique number assigned to a message by Service Bus. @@ -421,10 +421,10 @@ public long SequenceNumber get { ThrowIfNotReceived(); - return sequenceNumber; + return _sequenceNumber; } - internal set => sequenceNumber = value; + internal set => _sequenceNumber = value; } /// @@ -439,10 +439,10 @@ public string DeadLetterSource get { ThrowIfNotReceived(); - return deadLetterSource; + return _deadLetterSource; } - internal set => deadLetterSource = value; + internal set => _deadLetterSource = value; } internal short PartitionId @@ -450,10 +450,10 @@ internal short PartitionId get { ThrowIfNotReceived(); - return partitionId; + return _partitionId; } - set => partitionId = value; + set => _partitionId = value; } /// Gets or sets the original sequence number of the message. @@ -467,10 +467,10 @@ public long EnqueuedSequenceNumber get { ThrowIfNotReceived(); - return enqueuedSequenceNumber; + return _enqueuedSequenceNumber; } - internal set => enqueuedSequenceNumber = value; + internal set => _enqueuedSequenceNumber = value; } /// Gets or sets the date and time of the sent time in UTC. @@ -485,10 +485,10 @@ public DateTime EnqueuedTimeUtc get { ThrowIfNotReceived(); - return enqueuedTimeUtc; + return _enqueuedTimeUtc; } - internal set => enqueuedTimeUtc = value; + internal set => _enqueuedTimeUtc = value; } internal Guid LockTokenGuid @@ -496,10 +496,10 @@ internal Guid LockTokenGuid get { ThrowIfNotReceived(); - return lockTokenGuid; + return _lockTokenGuid; } - set => lockTokenGuid = value; + set => _lockTokenGuid = value; } internal object BodyObject diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs index bc276d25d0d0..fbd89e3498ad 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageHandlerOptions.cs @@ -13,8 +13,8 @@ namespace Microsoft.Azure.ServiceBus /// . public sealed class MessageHandlerOptions { - private int maxConcurrentCalls; - private TimeSpan maxAutoRenewDuration; + private int _maxConcurrentCalls; + private TimeSpan _maxAutoRenewDuration; /// Initializes a new instance of the class. /// Default Values: @@ -42,7 +42,7 @@ public MessageHandlerOptions(Func exceptionRec /// The maximum number of concurrent calls to the callback. public int MaxConcurrentCalls { - get => maxConcurrentCalls; + get => _maxConcurrentCalls; set { @@ -51,7 +51,7 @@ public int MaxConcurrentCalls throw new ArgumentOutOfRangeException(Resources.MaxConcurrentCallsMustBeGreaterThanZero.FormatForUser(value)); } - maxConcurrentCalls = value; + _maxConcurrentCalls = value; } } @@ -68,12 +68,12 @@ public int MaxConcurrentCalls /// after completion of message and result in a few false MessageLockLostExceptions temporarily. public TimeSpan MaxAutoRenewDuration { - get => maxAutoRenewDuration; + get => _maxAutoRenewDuration; set { TimeoutHelper.ThrowIfNegativeArgument(value, nameof(value)); - maxAutoRenewDuration = value; + _maxAutoRenewDuration = value; } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs index 902f2a9df357..95ab6b1ae0ac 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs @@ -12,13 +12,13 @@ namespace Microsoft.Azure.ServiceBus internal sealed class MessageReceivePump { - private readonly Func onMessageCallback; - private readonly string endpoint; - private readonly MessageHandlerOptions registerHandlerOptions; - private readonly IMessageReceiver messageReceiver; - private readonly CancellationToken pumpCancellationToken; - private readonly SemaphoreSlim maxConcurrentCallsSemaphoreSlim; - private readonly ServiceBusDiagnosticSource diagnosticSource; + private readonly Func _onMessageCallback; + private readonly string _endpoint; + private readonly MessageHandlerOptions _registerHandlerOptions; + private readonly IMessageReceiver _messageReceiver; + private readonly CancellationToken _pumpCancellationToken; + private readonly SemaphoreSlim _maxConcurrentCallsSemaphoreSlim; + private readonly ServiceBusDiagnosticSource _diagnosticSource; public MessageReceivePump(IMessageReceiver messageReceiver, MessageHandlerOptions registerHandlerOptions, @@ -26,13 +26,13 @@ public MessageReceivePump(IMessageReceiver messageReceiver, Uri endpoint, CancellationToken pumpCancellationToken) { - this.messageReceiver = messageReceiver ?? throw new ArgumentNullException(nameof(messageReceiver)); - this.registerHandlerOptions = registerHandlerOptions; - onMessageCallback = callback; - this.endpoint = endpoint.Authority; - this.pumpCancellationToken = pumpCancellationToken; - maxConcurrentCallsSemaphoreSlim = new SemaphoreSlim(this.registerHandlerOptions.MaxConcurrentCalls); - diagnosticSource = new ServiceBusDiagnosticSource(messageReceiver.Path, endpoint); + this._messageReceiver = messageReceiver ?? throw new ArgumentNullException(nameof(messageReceiver)); + this._registerHandlerOptions = registerHandlerOptions; + _onMessageCallback = callback; + this._endpoint = endpoint.Authority; + this._pumpCancellationToken = pumpCancellationToken; + _maxConcurrentCallsSemaphoreSlim = new SemaphoreSlim(this._registerHandlerOptions.MaxConcurrentCalls); + _diagnosticSource = new ServiceBusDiagnosticSource(messageReceiver.Path, endpoint); } public void StartPump() @@ -43,33 +43,33 @@ public void StartPump() private bool ShouldRenewLock() { return - messageReceiver.ReceiveMode == ReceiveMode.PeekLock && - registerHandlerOptions.AutoRenewLock; + _messageReceiver.ReceiveMode == ReceiveMode.PeekLock && + _registerHandlerOptions.AutoRenewLock; } private Task RaiseExceptionReceived(Exception e, string action) { - var eventArgs = new ExceptionReceivedEventArgs(e, action, endpoint, messageReceiver.Path, messageReceiver.ClientId); - return registerHandlerOptions.RaiseExceptionReceived(eventArgs); + var eventArgs = new ExceptionReceivedEventArgs(e, action, _endpoint, _messageReceiver.Path, _messageReceiver.ClientId); + return _registerHandlerOptions.RaiseExceptionReceived(eventArgs); } private async Task MessagePumpTaskAsync() { - while (!pumpCancellationToken.IsCancellationRequested) + while (!_pumpCancellationToken.IsCancellationRequested) { try { - await maxConcurrentCallsSemaphoreSlim.WaitAsync(pumpCancellationToken).ConfigureAwait(false); + await _maxConcurrentCallsSemaphoreSlim.WaitAsync(_pumpCancellationToken).ConfigureAwait(false); TaskExtensionHelper.Schedule(async () => { Message message = null; try { - message = await messageReceiver.ReceiveAsync(registerHandlerOptions.ReceiveTimeOut).ConfigureAwait(false); + message = await _messageReceiver.ReceiveAsync(_registerHandlerOptions.ReceiveTimeOut).ConfigureAwait(false); if (message != null) { - MessagingEventSource.Log.MessageReceiverPumpTaskStart(messageReceiver.ClientId, message, maxConcurrentCallsSemaphoreSlim.CurrentCount); + MessagingEventSource.Log.MessageReceiverPumpTaskStart(_messageReceiver.ClientId, message, _maxConcurrentCallsSemaphoreSlim.CurrentCount); TaskExtensionHelper.Schedule(() => { @@ -84,17 +84,17 @@ private async Task MessagePumpTaskAsync() }); } } - catch (OperationCanceledException) when (pumpCancellationToken.IsCancellationRequested) + catch (OperationCanceledException) when (_pumpCancellationToken.IsCancellationRequested) { // Ignore as we are stopping the pump } - catch (ObjectDisposedException) when (pumpCancellationToken.IsCancellationRequested) + catch (ObjectDisposedException) when (_pumpCancellationToken.IsCancellationRequested) { // Ignore as we are stopping the pump } catch (Exception exception) { - MessagingEventSource.Log.MessageReceivePumpTaskException(messageReceiver.ClientId, string.Empty, exception); + MessagingEventSource.Log.MessageReceivePumpTaskException(_messageReceiver.ClientId, string.Empty, exception); await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Receive).ConfigureAwait(false); } finally @@ -102,23 +102,23 @@ private async Task MessagePumpTaskAsync() // Either an exception or for some reason message was null, release semaphore and retry. if (message == null) { - maxConcurrentCallsSemaphoreSlim.Release(); - MessagingEventSource.Log.MessageReceiverPumpTaskStop(messageReceiver.ClientId, maxConcurrentCallsSemaphoreSlim.CurrentCount); + _maxConcurrentCallsSemaphoreSlim.Release(); + MessagingEventSource.Log.MessageReceiverPumpTaskStop(_messageReceiver.ClientId, _maxConcurrentCallsSemaphoreSlim.CurrentCount); } } }); } - catch (OperationCanceledException) when (pumpCancellationToken.IsCancellationRequested) + catch (OperationCanceledException) when (_pumpCancellationToken.IsCancellationRequested) { // Ignore as we are stopping the pump } - catch (ObjectDisposedException) when (pumpCancellationToken.IsCancellationRequested) + catch (ObjectDisposedException) when (_pumpCancellationToken.IsCancellationRequested) { // Ignore as we are stopping the pump } catch (Exception exception) { - MessagingEventSource.Log.MessageReceivePumpTaskException(messageReceiver.ClientId, string.Empty, exception); + MessagingEventSource.Log.MessageReceivePumpTaskException(_messageReceiver.ClientId, string.Empty, exception); await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Receive).ConfigureAwait(false); } } @@ -126,7 +126,7 @@ private async Task MessagePumpTaskAsync() private async Task MessageDispatchTaskInstrumented(Message message) { - Activity activity = diagnosticSource.ProcessStart(message); + Activity activity = _diagnosticSource.ProcessStart(message); Task processTask = null; try { @@ -135,12 +135,12 @@ private async Task MessageDispatchTaskInstrumented(Message message) } catch (Exception e) { - diagnosticSource.ReportException(e); + _diagnosticSource.ReportException(e); throw; } finally { - diagnosticSource.ProcessStop(activity, message, processTask?.Status); + _diagnosticSource.ProcessStop(activity, message, processTask?.Status); } } @@ -149,7 +149,7 @@ private async Task MessageDispatchTask(Message message) CancellationTokenSource renewLockCancellationTokenSource = null; Timer autoRenewLockCancellationTimer = null; - MessagingEventSource.Log.MessageReceiverPumpDispatchTaskStart(messageReceiver.ClientId, message); + MessagingEventSource.Log.MessageReceiverPumpDispatchTaskStart(_messageReceiver.ClientId, message); if (ShouldRenewLock()) { @@ -157,19 +157,19 @@ private async Task MessageDispatchTask(Message message) TaskExtensionHelper.Schedule(() => RenewMessageLockTask(message, renewLockCancellationTokenSource.Token)); // After a threshold time of renewal('AutoRenewTimeout'), create timer to cancel anymore renewals. - autoRenewLockCancellationTimer = new Timer(CancelAutoRenewLock, renewLockCancellationTokenSource, registerHandlerOptions.MaxAutoRenewDuration, TimeSpan.FromMilliseconds(-1)); + autoRenewLockCancellationTimer = new Timer(CancelAutoRenewLock, renewLockCancellationTokenSource, _registerHandlerOptions.MaxAutoRenewDuration, TimeSpan.FromMilliseconds(-1)); } try { - MessagingEventSource.Log.MessageReceiverPumpUserCallbackStart(messageReceiver.ClientId, message); - await onMessageCallback(message, pumpCancellationToken).ConfigureAwait(false); + MessagingEventSource.Log.MessageReceiverPumpUserCallbackStart(_messageReceiver.ClientId, message); + await _onMessageCallback(message, _pumpCancellationToken).ConfigureAwait(false); - MessagingEventSource.Log.MessageReceiverPumpUserCallbackStop(messageReceiver.ClientId, message); + MessagingEventSource.Log.MessageReceiverPumpUserCallbackStop(_messageReceiver.ClientId, message); } catch (Exception exception) { - MessagingEventSource.Log.MessageReceiverPumpUserCallbackException(messageReceiver.ClientId, message, exception); + MessagingEventSource.Log.MessageReceiverPumpUserCallbackException(_messageReceiver.ClientId, message, exception); await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.UserCallback).ConfigureAwait(false); // Nothing much to do if UserCallback throws, Abandon message and Release semaphore. @@ -180,10 +180,10 @@ private async Task MessageDispatchTask(Message message) if (ServiceBusDiagnosticSource.IsEnabled()) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } // AbandonMessageIfNeededAsync should take care of not throwing exception - maxConcurrentCallsSemaphoreSlim.Release(); + _maxConcurrentCallsSemaphoreSlim.Release(); return; } @@ -196,9 +196,9 @@ private async Task MessageDispatchTask(Message message) // If we've made it this far, user callback completed fine. Complete message and Release semaphore. await CompleteMessageIfNeededAsync(message).ConfigureAwait(false); - maxConcurrentCallsSemaphoreSlim.Release(); + _maxConcurrentCallsSemaphoreSlim.Release(); - MessagingEventSource.Log.MessageReceiverPumpDispatchTaskStop(messageReceiver.ClientId, message, maxConcurrentCallsSemaphoreSlim.CurrentCount); + MessagingEventSource.Log.MessageReceiverPumpDispatchTaskStop(_messageReceiver.ClientId, message, _maxConcurrentCallsSemaphoreSlim.CurrentCount); } private void CancelAutoRenewLock(object state) @@ -218,9 +218,9 @@ private async Task AbandonMessageIfNeededAsync(Message message) { try { - if (messageReceiver.ReceiveMode == ReceiveMode.PeekLock) + if (_messageReceiver.ReceiveMode == ReceiveMode.PeekLock) { - await messageReceiver.AbandonAsync(message.SystemProperties.LockToken).ConfigureAwait(false); + await _messageReceiver.AbandonAsync(message.SystemProperties.LockToken).ConfigureAwait(false); } } catch (Exception exception) @@ -233,10 +233,10 @@ private async Task CompleteMessageIfNeededAsync(Message message) { try { - if (messageReceiver.ReceiveMode == ReceiveMode.PeekLock && - registerHandlerOptions.AutoComplete) + if (_messageReceiver.ReceiveMode == ReceiveMode.PeekLock && + _registerHandlerOptions.AutoComplete) { - await messageReceiver.CompleteAsync(new[] { message.SystemProperties.LockToken }).ConfigureAwait(false); + await _messageReceiver.CompleteAsync(new[] { message.SystemProperties.LockToken }).ConfigureAwait(false); } } catch (Exception exception) @@ -247,13 +247,13 @@ private async Task CompleteMessageIfNeededAsync(Message message) private async Task RenewMessageLockTask(Message message, CancellationToken renewLockCancellationToken) { - while (!pumpCancellationToken.IsCancellationRequested && + while (!_pumpCancellationToken.IsCancellationRequested && !renewLockCancellationToken.IsCancellationRequested) { try { var amount = MessagingUtilities.CalculateRenewAfterDuration(message.SystemProperties.LockedUntilUtc); - MessagingEventSource.Log.MessageReceiverPumpRenewMessageStart(messageReceiver.ClientId, message, amount); + MessagingEventSource.Log.MessageReceiverPumpRenewMessageStart(_messageReceiver.ClientId, message, amount); // We're awaiting the task created by 'ContinueWith' to avoid awaiting the Delay task which may be canceled // by the renewLockCancellationToken. This way we prevent a TaskCanceledException. @@ -265,11 +265,11 @@ private async Task RenewMessageLockTask(Message message, CancellationToken renew break; } - if (!pumpCancellationToken.IsCancellationRequested && + if (!_pumpCancellationToken.IsCancellationRequested && !renewLockCancellationToken.IsCancellationRequested) { - await messageReceiver.RenewLockAsync(message).ConfigureAwait(false); - MessagingEventSource.Log.MessageReceiverPumpRenewMessageStop(messageReceiver.ClientId, message); + await _messageReceiver.RenewLockAsync(message).ConfigureAwait(false); + MessagingEventSource.Log.MessageReceiverPumpRenewMessageStop(_messageReceiver.ClientId, message); } else { @@ -278,7 +278,7 @@ private async Task RenewMessageLockTask(Message message, CancellationToken renew } catch (Exception exception) { - MessagingEventSource.Log.MessageReceiverPumpRenewMessageException(messageReceiver.ClientId, message, exception); + MessagingEventSource.Log.MessageReceiverPumpRenewMessageException(_messageReceiver.ClientId, message, exception); // ObjectDisposedException should only happen here because the CancellationToken was disposed at which point // this renew exception is not relevant anymore. Lets not bother user with this exception. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs index 5d628a03bd83..2b153ac6987a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs @@ -14,7 +14,7 @@ namespace Microsoft.Azure.ServiceBus internal class MessageSession : MessageReceiver, IMessageSession { - private readonly ServiceBusDiagnosticSource diagnosticSource; + private readonly ServiceBusDiagnosticSource _diagnosticSource; public MessageSession( string entityPath, @@ -28,7 +28,7 @@ public MessageSession( bool isSessionReceiver = false) : base(entityPath, entityType, receiveMode, serviceBusConnection, cbsTokenProvider, retryPolicy, prefetchCount, sessionId, isSessionReceiver) { - diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); + _diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); } /// @@ -187,7 +187,7 @@ protected override void ThrowIfClosed() private async Task OnGetStateInstrumentedAsync() { - Activity activity = diagnosticSource.GetSessionStateStart(SessionId); + Activity activity = _diagnosticSource.GetSessionStateStart(SessionId); Task getStateTask = null; byte[] state = null; @@ -199,18 +199,18 @@ private async Task OnGetStateInstrumentedAsync() } catch (Exception ex) { - diagnosticSource.ReportException(ex); + _diagnosticSource.ReportException(ex); throw; } finally { - diagnosticSource.GetSessionStateStop(activity, SessionId, state, getStateTask?.Status); + _diagnosticSource.GetSessionStateStop(activity, SessionId, state, getStateTask?.Status); } } private async Task OnSetStateInstrumentedAsync(byte[] sessionState) { - Activity activity = diagnosticSource.SetSessionStateStart(SessionId, sessionState); + Activity activity = _diagnosticSource.SetSessionStateStart(SessionId, sessionState); Task setStateTask = null; try @@ -220,18 +220,18 @@ private async Task OnSetStateInstrumentedAsync(byte[] sessionState) } catch (Exception ex) { - diagnosticSource.ReportException(ex); + _diagnosticSource.ReportException(ex); throw; } finally { - diagnosticSource.SetSessionStateStop(activity, sessionState, SessionId, setStateTask?.Status); + _diagnosticSource.SetSessionStateStop(activity, sessionState, SessionId, setStateTask?.Status); } } private async Task OnRenewSessionLockInstrumentedAsync() { - Activity activity = diagnosticSource.RenewSessionLockStart(SessionId); + Activity activity = _diagnosticSource.RenewSessionLockStart(SessionId); Task renewTask = null; try @@ -241,12 +241,12 @@ private async Task OnRenewSessionLockInstrumentedAsync() } catch (Exception ex) { - diagnosticSource.ReportException(ex); + _diagnosticSource.ReportException(ex); throw; } finally { - diagnosticSource.RenewSessionLockStop(activity, SessionId, renewTask?.Status); + _diagnosticSource.RenewSessionLockStop(activity, SessionId, renewTask?.Status); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs index 5f8641daad03..46b4862ea979 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs @@ -11,8 +11,8 @@ namespace Microsoft.Azure.ServiceBus.Primitives /// public class AzureActiveDirectoryTokenProvider : TokenProvider { - private readonly string authority; - private readonly object authCallbackState; + private readonly string _authority; + private readonly object _authCallbackState; private event AuthenticationCallback AuthCallback; public delegate Task AuthenticationCallback(string audience, string authority, object state); @@ -20,8 +20,8 @@ public class AzureActiveDirectoryTokenProvider : TokenProvider public AzureActiveDirectoryTokenProvider(AuthenticationCallback authenticationCallback, string authority, object state) { AuthCallback = authenticationCallback ?? throw Fx.Exception.ArgumentNull(nameof(authenticationCallback)); - this.authority = authority ?? throw Fx.Exception.ArgumentNull(nameof(authority)); - authCallbackState = state; + this._authority = authority ?? throw Fx.Exception.ArgumentNull(nameof(authority)); + _authCallbackState = state; } /// @@ -32,7 +32,7 @@ public AzureActiveDirectoryTokenProvider(AuthenticationCallback authenticationCa /// public override async Task GetTokenAsync(string appliesTo, TimeSpan timeout) { - var tokenString = await AuthCallback(Constants.AadServiceBusAudience, authority, authCallbackState).ConfigureAwait(false); + var tokenString = await AuthCallback(Constants.AadServiceBusAudience, _authority, _authCallbackState).ConfigureAwait(false); return new JsonSecurityToken(tokenString, appliesTo); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs index 6dbf6413f74a..99500a4e717d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs @@ -11,49 +11,49 @@ namespace Microsoft.Azure.ServiceBus.Primitives internal sealed class ConcurrentExpiringSet { - private readonly ConcurrentDictionary dictionary; - private readonly ICollection> dictionaryAsCollection; - private readonly CancellationTokenSource tokenSource = new CancellationTokenSource(); - private volatile TaskCompletionSource cleanupTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - private int closeSignaled; - private bool closed; + private readonly ConcurrentDictionary _dictionary; + private readonly ICollection> _dictionaryAsCollection; + private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource(); + private volatile TaskCompletionSource _cleanupTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + private int _closeSignaled; + private bool _closed; private static readonly TimeSpan delayBetweenCleanups = TimeSpan.FromSeconds(30); public ConcurrentExpiringSet() { - dictionary = new ConcurrentDictionary(); - dictionaryAsCollection = dictionary; - _ = CollectExpiredEntriesAsync(tokenSource.Token); + _dictionary = new ConcurrentDictionary(); + _dictionaryAsCollection = _dictionary; + _ = CollectExpiredEntriesAsync(_tokenSource.Token); } public void AddOrUpdate(TKey key, DateTime expiration) { ThrowIfClosed(); - dictionary[key] = expiration; - cleanupTaskCompletionSource.TrySetResult(true); + _dictionary[key] = expiration; + _cleanupTaskCompletionSource.TrySetResult(true); } public bool Contains(TKey key) { ThrowIfClosed(); - return dictionary.TryGetValue(key, out var expiration) && expiration > DateTime.UtcNow; + return _dictionary.TryGetValue(key, out var expiration) && expiration > DateTime.UtcNow; } public void Close() { - if (Interlocked.Exchange(ref closeSignaled, 1) != 0) + if (Interlocked.Exchange(ref _closeSignaled, 1) != 0) { return; } - closed = true; + _closed = true; - tokenSource.Cancel(); - cleanupTaskCompletionSource.TrySetCanceled(); - dictionary.Clear(); - tokenSource.Dispose(); + _tokenSource.Cancel(); + _cleanupTaskCompletionSource.TrySetCanceled(); + _dictionary.Clear(); + _tokenSource.Dispose(); } private async Task CollectExpiredEntriesAsync(CancellationToken token) @@ -62,7 +62,7 @@ private async Task CollectExpiredEntriesAsync(CancellationToken token) { try { - await cleanupTaskCompletionSource.Task.ConfigureAwait(false); + await _cleanupTaskCompletionSource.Task.ConfigureAwait(false); await Task.Delay(delayBetweenCleanups, token).ConfigureAwait(false); } catch (OperationCanceledException) @@ -72,26 +72,26 @@ private async Task CollectExpiredEntriesAsync(CancellationToken token) var isEmpty = true; var utcNow = DateTime.UtcNow; - foreach (var kvp in dictionary) + foreach (var kvp in _dictionary) { isEmpty = false; var expiration = kvp.Value; if (utcNow > expiration) { - dictionaryAsCollection.Remove(kvp); + _dictionaryAsCollection.Remove(kvp); } } if (isEmpty) { - cleanupTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _cleanupTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); } } } private void ThrowIfClosed() { - if (closed) + if (_closed) { throw new ObjectDisposedException($"ConcurrentExpiringSet has already been closed. Please create a new set instead."); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentRandom.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentRandom.cs index 2cbdd89c1b2f..7a5adb1ed855 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentRandom.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentRandom.cs @@ -10,7 +10,7 @@ internal static class ConcurrentRandom // We lock on this when generating a seed for a threadLocalRandom [Fx.Tag.SynchronizationObject] private static readonly Random SeedGenerator = new Random(); - [ThreadStatic] private static Random threadLocalRandom; + [ThreadStatic] private static Random _threadLocalRandom; public static int Next(int minValue, int maxValue) { @@ -30,7 +30,7 @@ public static long NextPositiveLong() private static Random GetThreadLocalRandom() { - if (threadLocalRandom == null) + if (_threadLocalRandom == null) { int seed; lock (SeedGenerator) @@ -38,10 +38,10 @@ private static Random GetThreadLocalRandom() seed = SeedGenerator.Next(); } - threadLocalRandom = new Random(seed); + _threadLocalRandom = new Random(seed); } - return threadLocalRandom; + return _threadLocalRandom; } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs index 52da2227ff18..5bd0c5b9a510 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs @@ -8,18 +8,18 @@ namespace Microsoft.Azure.ServiceBus.Primitives internal static class Fx { - private static ExceptionUtility exceptionUtility; + private static ExceptionUtility _exceptionUtility; public static ExceptionUtility Exception { get { - if (exceptionUtility == null) + if (_exceptionUtility == null) { - exceptionUtility = new ExceptionUtility(); + _exceptionUtility = new ExceptionUtility(); } - return exceptionUtility; + return _exceptionUtility; } } @@ -103,26 +103,26 @@ public static class Strings [Conditional("CODE_ANALYSIS")] public sealed class ExternalResourceAttribute : Attribute { - private readonly Location location; - private readonly string description; + private readonly Location _location; + private readonly string _description; public ExternalResourceAttribute(Location location, string description) { - this.location = location; - this.description = description; + this._location = location; + this._description = description; } - public Location Location => location; + public Location Location => _location; - public string Description => description; + public string Description => _description; } [AttributeUsage(AttributeTargets.Field)] [Conditional("CODE_ANALYSIS")] public sealed class CacheAttribute : Attribute { - private readonly Type elementType; - private readonly CacheAttrition cacheAttrition; + private readonly Type _elementType; + private readonly CacheAttrition _cacheAttrition; public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) { @@ -135,13 +135,13 @@ public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) throw Exception.ArgumentNull(nameof(elementType)); } - this.elementType = elementType; - this.cacheAttrition = cacheAttrition; + this._elementType = elementType; + this._cacheAttrition = cacheAttrition; } - public Type ElementType => elementType; + public Type ElementType => _elementType; - public CacheAttrition CacheAttrition => cacheAttrition; + public CacheAttrition CacheAttrition => _cacheAttrition; public string Scope { get; set; } @@ -154,7 +154,7 @@ public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) [Conditional("CODE_ANALYSIS")] public sealed class QueueAttribute : Attribute { - private readonly Type elementType; + private readonly Type _elementType; public QueueAttribute(Type elementType) { @@ -166,10 +166,10 @@ public QueueAttribute(Type elementType) throw Exception.ArgumentNull(nameof(elementType)); } - this.elementType = elementType; + this._elementType = elementType; } - public Type ElementType => elementType; + public Type ElementType => _elementType; public string Scope { get; set; } @@ -204,14 +204,14 @@ public SynchronizationObjectAttribute() [Conditional("CODE_ANALYSIS")] public sealed class SynchronizationPrimitiveAttribute : Attribute { - private readonly BlocksUsing blocksUsing; + private readonly BlocksUsing _blocksUsing; public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing) { - this.blocksUsing = blocksUsing; + this._blocksUsing = blocksUsing; } - public BlocksUsing BlocksUsing => blocksUsing; + public BlocksUsing BlocksUsing => _blocksUsing; public bool SupportsAsync { get; set; } @@ -252,8 +252,8 @@ public sealed class NonThrowingAttribute : Attribute [Conditional("CODE_ANALYSIS")] public class ThrowsAttribute : Attribute { - private readonly Type exceptionType; - private readonly string diagnosis; + private readonly Type _exceptionType; + private readonly string _diagnosis; public ThrowsAttribute(Type exceptionType, string diagnosis) { @@ -267,13 +267,13 @@ public ThrowsAttribute(Type exceptionType, string diagnosis) throw new ArgumentNullException(nameof(diagnosis)); } - this.exceptionType = exceptionType; - this.diagnosis = diagnosis; + this._exceptionType = exceptionType; + this._diagnosis = diagnosis; } - public Type ExceptionType => exceptionType; + public Type ExceptionType => _exceptionType; - public string Diagnosis => diagnosis; + public string Diagnosis => _diagnosis; } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)] diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs index 8dc906c747d2..074443803349 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs @@ -12,7 +12,7 @@ namespace Microsoft.Azure.ServiceBus.Primitives /// public class ManagedIdentityTokenProvider : TokenProvider { - private readonly AzureServiceTokenProvider azureServiceTokenProvider; + private readonly AzureServiceTokenProvider _azureServiceTokenProvider; /// Initializes new instance of class with default configuration. public ManagedIdentityTokenProvider() : this(new AzureServiceTokenProvider()){} @@ -21,7 +21,7 @@ public ManagedIdentityTokenProvider() : this(new AzureServiceTokenProvider()){} /// Call that constructore to set with required Managed Identity connection string. public ManagedIdentityTokenProvider(AzureServiceTokenProvider azureServiceTokenProvider) { - this.azureServiceTokenProvider = azureServiceTokenProvider; + this._azureServiceTokenProvider = azureServiceTokenProvider; } /// @@ -32,7 +32,7 @@ public ManagedIdentityTokenProvider(AzureServiceTokenProvider azureServiceTokenP /// public async override Task GetTokenAsync(string appliesTo, TimeSpan timeout) { - string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(Constants.AadServiceBusAudience).ConfigureAwait(false); + string accessToken = await _azureServiceTokenProvider.GetAccessTokenAsync(Constants.AadServiceBusAudience).ConfigureAwait(false); return new JsonSecurityToken(accessToken, appliesTo); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs index 5e57986aae2a..1c576e8b8cdd 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs @@ -10,35 +10,35 @@ namespace Microsoft.Azure.ServiceBus.Primitives internal sealed class PropertyDictionary : IDictionary { - private readonly IDictionary inner; + private readonly IDictionary _inner; public PropertyDictionary() { - inner = new Dictionary(StringComparer.OrdinalIgnoreCase); + _inner = new Dictionary(StringComparer.OrdinalIgnoreCase); } public PropertyDictionary(IDictionary container) { - inner = container; + _inner = container; } - public ICollection Keys => inner.Keys; + public ICollection Keys => _inner.Keys; - public ICollection Values => inner.Values; + public ICollection Values => _inner.Values; - public int Count => inner.Count; + public int Count => _inner.Count; - public bool IsReadOnly => inner.IsReadOnly; + public bool IsReadOnly => _inner.IsReadOnly; public object this[string key] { - get => inner[key]; + get => _inner[key]; set { if (IsSupportedObject(value)) { - inner[key] = value; + _inner[key] = value; } } } @@ -47,58 +47,58 @@ public void Add(string key, object value) { if (IsSupportedObject(value)) { - inner.Add(key, value); + _inner.Add(key, value); } } public bool ContainsKey(string key) { - return inner.ContainsKey(key); + return _inner.ContainsKey(key); } public bool Remove(string key) { - return inner.Remove(key); + return _inner.Remove(key); } public bool TryGetValue(string key, out object value) { - return inner.TryGetValue(key, out value); + return _inner.TryGetValue(key, out value); } public void Add(KeyValuePair item) { - inner.Add(item); + _inner.Add(item); } public void Clear() { - inner.Clear(); + _inner.Clear(); } public bool Contains(KeyValuePair item) { - return inner.Contains(item); + return _inner.Contains(item); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { - inner.CopyTo(array, arrayIndex); + _inner.CopyTo(array, arrayIndex); } public bool Remove(KeyValuePair item) { - return inner.Remove(item); + return _inner.Remove(item); } public IEnumerator> GetEnumerator() { - return inner.GetEnumerator(); + return _inner.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return inner.GetEnumerator(); + return _inner.GetEnumerator(); } private bool IsSupportedObject(object value) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs index bc024e9446b5..440cf3bcb8b4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs @@ -13,22 +13,22 @@ public class SecurityToken /// /// Token literal /// - private string token; + private string _token; /// /// Expiry date-time /// - private DateTime expiresAtUtc; + private DateTime _expiresAtUtc; /// /// Token audience /// - private string audience; + private string _audience; /// /// Token type /// - private string tokenType; + private string _tokenType; /// /// Creates a new instance of the class. @@ -49,30 +49,30 @@ public SecurityToken(string tokenString, DateTime expiresAtUtc, string audience, throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(audience)); } - token = tokenString; - this.expiresAtUtc = expiresAtUtc; - this.audience = audience; - this.tokenType = tokenType; + _token = tokenString; + this._expiresAtUtc = expiresAtUtc; + this._audience = audience; + this._tokenType = tokenType; } /// /// Gets the audience of this token. /// - public string Audience => audience; + public string Audience => _audience; /// /// Gets the expiration time of this token. /// - public DateTime ExpiresAtUtc => expiresAtUtc; + public DateTime ExpiresAtUtc => _expiresAtUtc; /// /// Gets the actual token. /// - public virtual string TokenValue => token; + public virtual string TokenValue => _token; /// /// Gets the token type. /// - public virtual string TokenType => tokenType; + public virtual string TokenType => _tokenType; } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs index 315c073b4eec..0ec95aaf3559 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs @@ -19,17 +19,17 @@ public class SharedAccessSignatureTokenProvider : TokenProvider { internal static readonly TimeSpan DefaultTokenTTL = TimeSpan.FromMinutes(60); - private readonly byte[] encodedSharedAccessKey; - private readonly string keyName; - private readonly TimeSpan tokenTimeToLive; - private readonly TokenScope tokenScope; - private readonly string sharedAccessSignature; + private readonly byte[] _encodedSharedAccessKey; + private readonly string _keyName; + private readonly TimeSpan _tokenTimeToLive; + private readonly TokenScope _tokenScope; + private readonly string _sharedAccessSignature; internal static readonly Func MessagingTokenProviderKeyEncoder = Encoding.UTF8.GetBytes; internal SharedAccessSignatureTokenProvider(string sharedAccessSignature) { SharedAccessSignatureToken.Validate(sharedAccessSignature); - this.sharedAccessSignature = sharedAccessSignature; + this._sharedAccessSignature = sharedAccessSignature; } internal SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TokenScope tokenScope = TokenScope.Entity) @@ -74,12 +74,12 @@ protected SharedAccessSignatureTokenProvider(string keyName, string sharedAccess Resources.ArgumentStringTooBig.FormatForUser(nameof(sharedAccessKey), SharedAccessSignatureToken.MaxKeyLength)); } - this.keyName = keyName; - this.tokenTimeToLive = tokenTimeToLive; - encodedSharedAccessKey = customKeyEncoder != null ? + this._keyName = keyName; + this._tokenTimeToLive = tokenTimeToLive; + _encodedSharedAccessKey = customKeyEncoder != null ? customKeyEncoder(sharedAccessKey) : MessagingTokenProviderKeyEncoder(sharedAccessKey); - this.tokenScope = tokenScope; + this._tokenScope = tokenScope; } /// @@ -106,18 +106,18 @@ public override Task GetTokenAsync(string appliesTo, TimeSpan tim /// protected virtual string BuildSignature(string targetUri) { - return string.IsNullOrWhiteSpace(sharedAccessSignature) + return string.IsNullOrWhiteSpace(_sharedAccessSignature) ? SharedAccessSignatureBuilder.BuildSignature( - keyName, - encodedSharedAccessKey, + _keyName, + _encodedSharedAccessKey, targetUri, - tokenTimeToLive) - : sharedAccessSignature; + _tokenTimeToLive) + : _sharedAccessSignature; } private string NormalizeAppliesTo(string appliesTo) { - return ServiceBusUriHelper.NormalizeUri(appliesTo, "https", true, stripPath: tokenScope == TokenScope.Namespace, ensureTrailingSlash: true); + return ServiceBusUriHelper.NormalizeUri(appliesTo, "https", true, stripPath: _tokenScope == TokenScope.Namespace, ensureTrailingSlash: true); } private static class SharedAccessSignatureBuilder diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs index f9b7aab76f0e..a50827bcb9e9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs @@ -9,19 +9,19 @@ namespace Microsoft.Azure.ServiceBus.Primitives [DebuggerStepThrough] internal struct TimeoutHelper { - private DateTime deadline; - private bool deadlineSet; - private TimeSpan originalTimeout; + private DateTime _deadline; + private bool _deadlineSet; + private TimeSpan _originalTimeout; public TimeoutHelper(TimeSpan timeout, bool startTimeout) { Debug.Assert(timeout >= TimeSpan.Zero, "timeout must be non-negative"); - originalTimeout = timeout; - deadline = DateTime.MaxValue; - deadlineSet = (timeout == TimeSpan.MaxValue); + _originalTimeout = timeout; + _deadline = DateTime.MaxValue; + _deadlineSet = (timeout == TimeSpan.MaxValue); - if (startTimeout && !deadlineSet) + if (startTimeout && !_deadlineSet) { SetDeadline(); } @@ -103,18 +103,18 @@ public static void ThrowIfNonPositiveArgument(TimeSpan timeout, string argumentN public TimeSpan RemainingTime() { - if (!deadlineSet) + if (!_deadlineSet) { SetDeadline(); - return originalTimeout; + return _originalTimeout; } - if (deadline == DateTime.MaxValue) + if (_deadline == DateTime.MaxValue) { return TimeSpan.MaxValue; } - var remaining = deadline - DateTime.UtcNow; + var remaining = _deadline - DateTime.UtcNow; if (remaining <= TimeSpan.Zero) { return TimeSpan.Zero; @@ -125,14 +125,14 @@ public TimeSpan RemainingTime() public TimeSpan ElapsedTime() { - return originalTimeout - RemainingTime(); + return _originalTimeout - RemainingTime(); } private void SetDeadline() { - Debug.Assert(!deadlineSet, "TimeoutHelper deadline set twice."); - deadline = DateTime.UtcNow + originalTimeout; - deadlineSet = true; + Debug.Assert(!_deadlineSet, "TimeoutHelper deadline set twice."); + _deadline = DateTime.UtcNow + _originalTimeout; + _deadlineSet = true; } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs index 0fedd80eccbc..af8d3a85392c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs @@ -14,20 +14,20 @@ namespace Microsoft.Azure.ServiceBus.Primitives /// internal sealed class TokenProviderAdapter : ICbsTokenProvider { - private readonly ITokenProvider tokenProvider; - private readonly TimeSpan operationTimeout; + private readonly ITokenProvider _tokenProvider; + private readonly TimeSpan _operationTimeout; public TokenProviderAdapter(ITokenProvider tokenProvider, TimeSpan operationTimeout) { Debug.Assert(tokenProvider != null, "tokenProvider cannot be null"); - this.tokenProvider = tokenProvider; - this.operationTimeout = operationTimeout; + this._tokenProvider = tokenProvider; + this._operationTimeout = operationTimeout; } public async Task GetTokenAsync(Uri namespaceAddress, string appliesTo, string[] requiredClaims) { var claim = requiredClaims?.FirstOrDefault(); - var securityToken = await tokenProvider.GetTokenAsync(appliesTo, operationTimeout).ConfigureAwait(false); + var securityToken = await _tokenProvider.GetTokenAsync(appliesTo, _operationTimeout).ConfigureAwait(false); return new CbsToken(securityToken.TokenValue, CbsConstants.ServiceBusSasTokenType, securityToken.ExpiresAtUtc); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs index 962bd14fdd68..a4b60cdd8b38 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs @@ -54,13 +54,13 @@ namespace Microsoft.Azure.ServiceBus /// It uses AMQP protocol for communicating with servicebus. public class QueueClient : ClientEntity, IQueueClient { - private readonly object syncLock; + private readonly object _syncLock; - private int prefetchCount; - private MessageSender innerSender; - private MessageReceiver innerReceiver; - private SessionClient sessionClient; - private SessionPumpHost sessionPumpHost; + private int _prefetchCount; + private MessageSender _innerSender; + private MessageReceiver _innerReceiver; + private SessionClient _sessionClient; + private SessionPumpHost _sessionPumpHost; /// /// Instantiates a new to perform operations on a queue. @@ -133,7 +133,7 @@ public QueueClient(ServiceBusConnection serviceBusConnection, string entityPath, } ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); - syncLock = new object(); + _syncLock = new object(); QueueName = entityPath; ReceiveMode = receiveMode; OwnsConnection = false; @@ -196,21 +196,21 @@ public override TimeSpan OperationTimeout /// public int PrefetchCount { - get => prefetchCount; + get => _prefetchCount; set { if (value < 0) { throw Fx.Exception.ArgumentOutOfRange(nameof(PrefetchCount), value, "Value cannot be less than 0."); } - prefetchCount = value; - if (innerReceiver != null) + _prefetchCount = value; + if (_innerReceiver != null) { - innerReceiver.PrefetchCount = value; + _innerReceiver.PrefetchCount = value; } - if (sessionClient != null) + if (_sessionClient != null) { - sessionClient.PrefetchCount = value; + _sessionClient.PrefetchCount = value; } } } @@ -229,13 +229,13 @@ internal MessageSender InnerSender { get { - if (innerSender == null) + if (_innerSender == null) { - lock (syncLock) + lock (_syncLock) { - if (innerSender == null) + if (_innerSender == null) { - innerSender = new MessageSender( + _innerSender = new MessageSender( QueueName, null, MessagingEntityType.Queue, @@ -246,7 +246,7 @@ internal MessageSender InnerSender } } - return innerSender; + return _innerSender; } } @@ -254,13 +254,13 @@ internal MessageReceiver InnerReceiver { get { - if (innerReceiver == null) + if (_innerReceiver == null) { - lock (syncLock) + lock (_syncLock) { - if (innerReceiver == null) + if (_innerReceiver == null) { - innerReceiver = new MessageReceiver( + _innerReceiver = new MessageReceiver( QueueName, MessagingEntityType.Queue, ReceiveMode, @@ -272,7 +272,7 @@ internal MessageReceiver InnerReceiver } } - return innerReceiver; + return _innerReceiver; } } @@ -280,13 +280,13 @@ internal SessionClient SessionClient { get { - if (sessionClient == null) + if (_sessionClient == null) { - lock (syncLock) + lock (_syncLock) { - if (sessionClient == null) + if (_sessionClient == null) { - sessionClient = new SessionClient( + _sessionClient = new SessionClient( ClientId, Path, MessagingEntityType.Queue, @@ -302,7 +302,7 @@ internal SessionClient SessionClient } } - return sessionClient; + return _sessionClient; } } @@ -310,13 +310,13 @@ internal SessionPumpHost SessionPumpHost { get { - if (sessionPumpHost == null) + if (_sessionPumpHost == null) { - lock (syncLock) + lock (_syncLock) { - if (sessionPumpHost == null) + if (_sessionPumpHost == null) { - sessionPumpHost = new SessionPumpHost( + _sessionPumpHost = new SessionPumpHost( ClientId, ReceiveMode, SessionClient, @@ -325,7 +325,7 @@ internal SessionPumpHost SessionPumpHost } } - return sessionPumpHost; + return _sessionPumpHost; } } @@ -520,21 +520,21 @@ public override void UnregisterPlugin(string serviceBusPluginName) protected override async Task OnClosingAsync() { - if (innerSender != null) + if (_innerSender != null) { - await innerSender.CloseAsync().ConfigureAwait(false); + await _innerSender.CloseAsync().ConfigureAwait(false); } - if (innerReceiver != null) + if (_innerReceiver != null) { - await innerReceiver.CloseAsync().ConfigureAwait(false); + await _innerReceiver.CloseAsync().ConfigureAwait(false); } - sessionPumpHost?.Close(); + _sessionPumpHost?.Close(); - if (sessionClient != null) + if (_sessionClient != null) { - await sessionClient.CloseAsync().ConfigureAwait(false); + await _sessionClient.CloseAsync().ConfigureAwait(false); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs index 1edaed97e98e..9ba3db482f81 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs @@ -22,10 +22,10 @@ public abstract class RetryPolicy private static readonly TimeSpan DefaultRetryMinBackoff = TimeSpan.Zero; private static readonly TimeSpan DefaultRetryMaxBackoff = TimeSpan.FromSeconds(30); - private readonly object serverBusyLock = new object(); + private readonly object _serverBusyLock = new object(); // This is a volatile copy of IsServerBusy. IsServerBusy is synchronized with a lock, whereas encounteredServerBusy is kept volatile for performance reasons. - private volatile bool encounteredServerBusy; + private volatile bool _encounteredServerBusy; protected RetryPolicy() { @@ -150,16 +150,16 @@ internal bool ShouldRetry(TimeSpan remainingTime, int currentRetryCount, Excepti internal void SetServerBusy(string exceptionMessage) { // multiple call to this method will not prolong the timer. - if (encounteredServerBusy) + if (_encounteredServerBusy) { return; } - lock (serverBusyLock) + lock (_serverBusyLock) { - if (!encounteredServerBusy) + if (!_encounteredServerBusy) { - encounteredServerBusy = true; + _encounteredServerBusy = true; ServerBusyExceptionMessage = string.IsNullOrWhiteSpace(exceptionMessage) ? Resources.DefaultServerBusyException : exceptionMessage; IsServerBusy = true; @@ -170,16 +170,16 @@ internal void SetServerBusy(string exceptionMessage) internal void ResetServerBusy() { - if (!encounteredServerBusy) + if (!_encounteredServerBusy) { return; } - lock (serverBusyLock) + lock (_serverBusyLock) { - if (encounteredServerBusy) + if (_encounteredServerBusy) { - encounteredServerBusy = false; + _encounteredServerBusy = false; ServerBusyExceptionMessage = Resources.DefaultServerBusyException; IsServerBusy = false; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs index 2dbab9c44a11..dea70305c105 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs @@ -19,8 +19,8 @@ namespace Microsoft.Azure.ServiceBus public class ServiceBusConnection { private static readonly Version AmqpVersion = new Version(1, 0, 0, 0); - private readonly object syncLock; - private bool isClosedOrClosing; + private readonly object _syncLock; + private bool _isClosedOrClosing; /// /// Creates a new connection to service bus. @@ -118,7 +118,7 @@ public ServiceBusConnection(string endpoint, TransportType transportType, RetryP internal ServiceBusConnection(RetryPolicy retryPolicy = null) { RetryPolicy = retryPolicy ?? RetryPolicy.Default; - syncLock = new object(); + _syncLock = new object(); } /// @@ -156,16 +156,16 @@ public bool IsClosedOrClosing { get { - lock (syncLock) + lock (_syncLock) { - return isClosedOrClosing; + return _isClosedOrClosing; } } internal set { - lock (syncLock) + lock (_syncLock) { - isClosedOrClosing = value; + _isClosedOrClosing = value; } } } @@ -191,7 +191,7 @@ internal virtual void ThrowIfClosed() public async Task CloseAsync() { var callClose = false; - lock (syncLock) + lock (_syncLock) { if (!IsClosedOrClosing) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs index d595d76e092c..634f7ec78182 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnectionStringBuilder.cs @@ -28,8 +28,8 @@ public class ServiceBusConnectionStringBuilder private const string OperationTimeoutConfigName = "OperationTimeout"; - private string entityPath, sasKeyName, sasKey, sasToken, endpoint; - private AuthenticationType authType = AuthenticationType.Other; + private string _entityPath, _sasKeyName, _sasKey, _sasToken, _endpoint; + private AuthenticationType _authType = AuthenticationType.Other; public enum AuthenticationType { @@ -167,7 +167,7 @@ public ServiceBusConnectionStringBuilder(string endpoint, string entityPath, str /// Throws when the hostname cannot be parsed public string Endpoint { - get => endpoint; + get => _endpoint; set { if (!value.Contains(".")) @@ -176,7 +176,7 @@ public string Endpoint } var uriBuilder = new UriBuilder(value.Trim()); - endpoint = (value.Contains("://") ? uriBuilder.Scheme : EndpointScheme) + "://" + uriBuilder.Host; + _endpoint = (value.Contains("://") ? uriBuilder.Scheme : EndpointScheme) + "://" + uriBuilder.Host; } } @@ -185,8 +185,8 @@ public string Endpoint /// public string EntityPath { - get => entityPath; - set => entityPath = value.Trim(); + get => _entityPath; + set => _entityPath = value.Trim(); } /// @@ -194,14 +194,14 @@ public string EntityPath /// public string SasKeyName { - get => sasKeyName; + get => _sasKeyName; set { if (Authentication != AuthenticationType.Other) { throw Fx.Exception.Argument("Authentication, SasKeyName", Resources.ArgumentInvalidCombination.FormatForUser("Authentication, SasKeyName")); } - sasKeyName = value.Trim(); + _sasKeyName = value.Trim(); } } @@ -211,8 +211,8 @@ public string SasKeyName /// Shared Access Signature key public string SasKey { - get => sasKey; - set => sasKey = value.Trim(); + get => _sasKey; + set => _sasKey = value.Trim(); } /// @@ -221,14 +221,14 @@ public string SasKey /// Shared Access Signature token public string SasToken { - get => sasToken; + get => _sasToken; set { if (Authentication != AuthenticationType.Other) { throw Fx.Exception.Argument("Authentication, SasToken", Resources.ArgumentInvalidCombination.FormatForUser("Authentication, SasToken")); } - sasToken = value.Trim(); + _sasToken = value.Trim(); } } @@ -248,7 +248,7 @@ public string SasToken /// public AuthenticationType Authentication { - get => authType; + get => _authType; set { if (!string.IsNullOrWhiteSpace(SasKeyName)) @@ -262,7 +262,7 @@ public AuthenticationType Authentication throw Fx.Exception.Argument(nameof(AuthenticationConfigName) + ", " + nameof(SharedAccessKeyConfigName), Resources.ArgumentInvalidCombination.FormatForUser(nameof(AuthenticationConfigName) + ", " + nameof(SharedAccessKeyConfigName))); } - authType = value; + _authType = value; } } @@ -411,9 +411,9 @@ private void ParseConnectionString(string connectionString) else if (key.Equals(AuthenticationConfigName, StringComparison.OrdinalIgnoreCase) && !int.TryParse(value, out _)) { value = value.Replace(" ", string.Empty); - if (!Enum.TryParse(value, true, out authType)) + if (!Enum.TryParse(value, true, out _authType)) { - authType = AuthenticationType.Other; + _authType = AuthenticationType.Other; } } else diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs index 9154f6912c48..00b266ec6b00 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs @@ -27,13 +27,13 @@ internal class ServiceBusDiagnosticSource public const string SessionIdTag = "SessionId"; private static readonly DiagnosticListener DiagnosticListener = new DiagnosticListener(DiagnosticListenerName); - private readonly string entityPath; - private readonly Uri endpoint; + private readonly string _entityPath; + private readonly Uri _endpoint; public ServiceBusDiagnosticSource(string entityPath, Uri endpoint) { - this.entityPath = entityPath; - this.endpoint = endpoint; + this._entityPath = entityPath; + this._endpoint = endpoint; } public static bool IsEnabled() @@ -49,8 +49,8 @@ internal Activity SendStart(IList messageList) Activity activity = Start("Send", () => new { Messages = messageList, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, a => SetTags(a, messageList) ); @@ -67,8 +67,8 @@ internal void SendStop(Activity activity, IList messageList, TaskStatus DiagnosticListener.StopActivity(activity, new { Messages = messageList, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -84,8 +84,8 @@ internal Activity ProcessStart(Message message) return ProcessStart("Process", message, () => new { Message = message, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, a => SetTags(a, message)); } @@ -97,8 +97,8 @@ internal void ProcessStop(Activity activity, Message message, TaskStatus? status DiagnosticListener.StopActivity(activity, new { Message = message, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -115,8 +115,8 @@ internal Activity ProcessSessionStart(IMessageSession session, Message message) { Session = session, Message = message, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, a => SetTags(a, message)); } @@ -129,8 +129,8 @@ internal void ProcessSessionStop(Activity activity, IMessageSession session, Mes { Session = session, Message = message, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -147,8 +147,8 @@ internal Activity ScheduleStart(Message message, DateTimeOffset scheduleEnqueueT { Message = message, ScheduleEnqueueTimeUtc = scheduleEnqueueTimeUtc, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, a => SetTags(a, message)); @@ -165,8 +165,8 @@ internal void ScheduleStop(Activity activity, Message message, DateTimeOffset sc { Message = message, ScheduleEnqueueTimeUtc = scheduleEnqueueTimeUtc, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, SequenceNumber = sequenceNumber, Status = status ?? TaskStatus.Faulted }); @@ -183,8 +183,8 @@ internal Activity CancelStart(long sequenceNumber) return Start("Cancel", () => new { SequenceNumber = sequenceNumber, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -196,8 +196,8 @@ internal void CancelStop(Activity activity, long sequenceNumber, TaskStatus? sta DiagnosticListener.StopActivity(activity, new { SequenceNumber = sequenceNumber, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -213,8 +213,8 @@ internal Activity ReceiveStart(int messageCount) return Start("Receive", () => new { RequestedMessageCount = messageCount, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -228,8 +228,8 @@ internal void ReceiveStop(Activity activity, int messageCount, TaskStatus? statu DiagnosticListener.StopActivity(activity, new { RequestedMessageCount = messageCount, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted, Messages = messageList }); @@ -247,8 +247,8 @@ internal Activity PeekStart(long fromSequenceNumber, int messageCount) { FromSequenceNumber = fromSequenceNumber, RequestedMessageCount = messageCount, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -264,8 +264,8 @@ internal void PeekStop(Activity activity, long fromSequenceNumber, int messageCo { FromSequenceNumber = fromSequenceNumber, RequestedMessageCount = messageCount, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted, Messages = messageList }); @@ -282,8 +282,8 @@ internal Activity ReceiveDeferredStart(IEnumerable sequenceNumbers) return Start("ReceiveDeferred", () => new { SequenceNumbers = sequenceNumbers, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -298,8 +298,8 @@ internal void ReceiveDeferredStop(Activity activity, IEnumerable sequenceN DiagnosticListener.StopActivity(activity, new { SequenceNumbers = sequenceNumbers, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Messages = messageList, Status = status ?? TaskStatus.Faulted }); @@ -316,8 +316,8 @@ internal Activity CompleteStart(IList lockTokens) return Start("Complete", () => new { LockTokens = lockTokens, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -329,8 +329,8 @@ internal void CompleteStop(Activity activity, IList lockTokens, TaskStat DiagnosticListener.StopActivity(activity, new { LockTokens = lockTokens, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -346,8 +346,8 @@ internal Activity DisposeStart(string operationName, string lockToken) return Start(operationName, () => new { LockToken = lockToken, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -359,8 +359,8 @@ internal void DisposeStop(Activity activity, string lockToken, TaskStatus? statu DiagnosticListener.StopActivity(activity, new { LockToken = lockToken, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -376,8 +376,8 @@ internal Activity RenewLockStart(string lockToken) return Start("RenewLock", () => new { LockToken = lockToken, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -389,8 +389,8 @@ internal void RenewLockStop(Activity activity, string lockToken, TaskStatus? sta DiagnosticListener.StopActivity(activity, new { LockToken = lockToken, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted, LockedUntilUtc = lockedUntilUtc }); @@ -407,8 +407,8 @@ internal Activity AddRuleStart(RuleDescription description) return Start("AddRule", () => new { Rule = description, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -420,8 +420,8 @@ internal void AddRuleStop(Activity activity, RuleDescription description, TaskSt DiagnosticListener.StopActivity(activity, new { Rule = description, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -437,8 +437,8 @@ internal Activity RemoveRuleStart(string ruleName) return Start("RemoveRule", () => new { RuleName = ruleName, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -450,8 +450,8 @@ internal void RemoveRuleStop(Activity activity, string ruleName, TaskStatus? sta DiagnosticListener.StopActivity(activity, new { RuleName = ruleName, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -466,8 +466,8 @@ internal Activity GetRulesStart() { return Start("GetRules", () => new { - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -479,8 +479,8 @@ internal void GetRulesStop(Activity activity, IEnumerable rules DiagnosticListener.StopActivity(activity, new { Rules = rules, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -496,8 +496,8 @@ internal Activity AcceptMessageSessionStart(string sessionId) return Start("AcceptMessageSession", () => new { SessionId = sessionId, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, a => SetSessionTag(a, sessionId) ); @@ -510,8 +510,8 @@ internal void AcceptMessageSessionStop(Activity activity, string sessionId, Task DiagnosticListener.StopActivity(activity, new { SessionId = sessionId, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -527,8 +527,8 @@ internal Activity GetSessionStateStart(string sessionId) return Start("GetSessionState", () => new { SessionId = sessionId, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, a => SetSessionTag(a, sessionId)); } @@ -540,8 +540,8 @@ internal void GetSessionStateStop(Activity activity, string sessionId, byte[] st DiagnosticListener.StopActivity(activity, new { SessionId = sessionId, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted, State = state }); @@ -559,8 +559,8 @@ internal Activity SetSessionStateStart(string sessionId, byte[] state) { State = state, SessionId = sessionId, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, a => SetSessionTag(a, sessionId)); } @@ -573,8 +573,8 @@ internal void SetSessionStateStop(Activity activity, byte[] state, string sessio { State = state, SessionId = sessionId, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -590,8 +590,8 @@ internal Activity RenewSessionLockStart(string sessionId) return Start("RenewSessionLock", () => new { SessionId = sessionId, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }, a => SetSessionTag(a, sessionId)); } @@ -603,8 +603,8 @@ internal void RenewSessionLockStop(Activity activity, string sessionId, TaskStat DiagnosticListener.StopActivity(activity, new { SessionId = sessionId, - Entity = entityPath, - Endpoint = endpoint, + Entity = _entityPath, + Endpoint = _endpoint, Status = status ?? TaskStatus.Faulted }); } @@ -620,8 +620,8 @@ internal void ReportException(Exception ex) new { Exception = ex, - Entity = entityPath, - Endpoint = endpoint + Entity = _entityPath, + Endpoint = _endpoint }); } } @@ -630,7 +630,7 @@ private Activity Start(string operationName, Func getPayload, Action /// Creates a new SessionClient from a @@ -197,7 +197,7 @@ internal SessionClient( throw new ArgumentNullException($"{nameof(ServiceBusConnection)} doesn't have a valid token provider"); } - diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); + _diagnosticSource = new ServiceBusDiagnosticSource(entityPath, serviceBusConnection.Endpoint); // Register plugins on the message session. if (registeredPlugins != null) @@ -297,7 +297,7 @@ public async Task AcceptMessageSessionAsync(string sessionId, T sessionId); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.AcceptMessageSessionStart(sessionId) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.AcceptMessageSessionStart(sessionId) : null; Task acceptMessageSessionTask = null; var session = new MessageSession( @@ -322,7 +322,7 @@ public async Task AcceptMessageSessionAsync(string sessionId, T { if (isDiagnosticSourceEnabled && !(exception is ServiceBusTimeoutException)) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.AmqpSessionClientAcceptMessageSessionException( @@ -335,7 +335,7 @@ public async Task AcceptMessageSessionAsync(string sessionId, T } finally { - diagnosticSource.AcceptMessageSessionStop(activity, session.SessionId, acceptMessageSessionTask?.Status); + _diagnosticSource.AcceptMessageSessionStop(activity, session.SessionId, acceptMessageSessionTask?.Status); } MessagingEventSource.Log.AmqpSessionClientAcceptMessageSessionStop( diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs index 593a4a5536b8..f43360fe9904 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionHandlerOptions.cs @@ -13,9 +13,9 @@ namespace Microsoft.Azure.ServiceBus /// . public sealed class SessionHandlerOptions { - private int maxConcurrentSessions; - private TimeSpan messageWaitTimeout; - private TimeSpan maxAutoRenewDuration; + private int _maxConcurrentSessions; + private TimeSpan _messageWaitTimeout; + private TimeSpan _maxAutoRenewDuration; /// Initializes a new instance of the class. /// Default Values: @@ -44,12 +44,12 @@ public SessionHandlerOptions(Func exceptionRec /// The duration for which the session renew its state. public TimeSpan MaxAutoRenewDuration { - get => maxAutoRenewDuration; + get => _maxAutoRenewDuration; set { TimeoutHelper.ThrowIfNegativeArgument(value, nameof(value)); - maxAutoRenewDuration = value; + _maxAutoRenewDuration = value; } } @@ -57,12 +57,12 @@ public TimeSpan MaxAutoRenewDuration /// The time to wait for receiving the message. public TimeSpan MessageWaitTimeout { - get => messageWaitTimeout; + get => _messageWaitTimeout; set { TimeoutHelper.ThrowIfNegativeArgument(value, nameof(value)); - messageWaitTimeout = value; + _messageWaitTimeout = value; } } @@ -70,7 +70,7 @@ public TimeSpan MessageWaitTimeout /// The maximum number of sessions that the User wants to handle concurrently. public int MaxConcurrentSessions { - get => maxConcurrentSessions; + get => _maxConcurrentSessions; set { @@ -79,7 +79,7 @@ public int MaxConcurrentSessions throw new ArgumentOutOfRangeException(Resources.MaxConcurrentCallsMustBeGreaterThanZero.FormatForUser(value)); } - maxConcurrentSessions = value; + _maxConcurrentSessions = value; MaxConcurrentAcceptSessionCalls = Math.Min(value, 2 * Environment.ProcessorCount); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs index 0e104acce992..e770ef03b53a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs @@ -9,18 +9,18 @@ namespace Microsoft.Azure.ServiceBus internal sealed class SessionPumpHost { - private readonly object syncLock; - private SessionReceivePump sessionReceivePump; - private CancellationTokenSource sessionPumpCancellationTokenSource; - private readonly Uri endpoint; + private readonly object _syncLock; + private SessionReceivePump _sessionReceivePump; + private CancellationTokenSource _sessionPumpCancellationTokenSource; + private readonly Uri _endpoint; public SessionPumpHost(string clientId, ReceiveMode receiveMode, ISessionClient sessionClient, Uri endpoint) { - syncLock = new object(); + _syncLock = new object(); ClientId = clientId; ReceiveMode = receiveMode; SessionClient = sessionClient; - this.endpoint = endpoint; + this._endpoint = endpoint; } private ReceiveMode ReceiveMode { get; } @@ -31,11 +31,11 @@ public SessionPumpHost(string clientId, ReceiveMode receiveMode, ISessionClient public void Close() { - if (sessionReceivePump != null) + if (_sessionReceivePump != null) { - sessionPumpCancellationTokenSource?.Cancel(); - sessionPumpCancellationTokenSource?.Dispose(); - sessionReceivePump = null; + _sessionPumpCancellationTokenSource?.Cancel(); + _sessionPumpCancellationTokenSource?.Dispose(); + _sessionReceivePump = null; } } @@ -45,36 +45,36 @@ public void OnSessionHandler( { MessagingEventSource.Log.RegisterOnSessionHandlerStart(ClientId, sessionHandlerOptions); - lock (syncLock) + lock (_syncLock) { - if (sessionReceivePump != null) + if (_sessionReceivePump != null) { throw new InvalidOperationException(Resources.SessionHandlerAlreadyRegistered); } - sessionPumpCancellationTokenSource = new CancellationTokenSource(); - sessionReceivePump = new SessionReceivePump( + _sessionPumpCancellationTokenSource = new CancellationTokenSource(); + _sessionReceivePump = new SessionReceivePump( ClientId, SessionClient, ReceiveMode, sessionHandlerOptions, callback, - endpoint, - sessionPumpCancellationTokenSource.Token); + _endpoint, + _sessionPumpCancellationTokenSource.Token); } try { - sessionReceivePump.StartPump(); + _sessionReceivePump.StartPump(); } catch (Exception exception) { MessagingEventSource.Log.RegisterOnSessionHandlerException(ClientId, exception); - if (sessionReceivePump != null) + if (_sessionReceivePump != null) { - sessionPumpCancellationTokenSource.Cancel(); - sessionPumpCancellationTokenSource.Dispose(); - sessionReceivePump = null; + _sessionPumpCancellationTokenSource.Cancel(); + _sessionPumpCancellationTokenSource.Dispose(); + _sessionReceivePump = null; } throw; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs index 5fbd199e95eb..a930fc505cdc 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs @@ -11,16 +11,16 @@ namespace Microsoft.Azure.ServiceBus internal sealed class SessionReceivePump { - private readonly string clientId; - private readonly ISessionClient client; - private readonly Func userOnSessionCallback; - private readonly SessionHandlerOptions sessionHandlerOptions; - private readonly string endpoint; - private readonly string entityPath; - private readonly CancellationToken pumpCancellationToken; - private readonly SemaphoreSlim maxConcurrentSessionsSemaphoreSlim; - private readonly SemaphoreSlim maxPendingAcceptSessionsSemaphoreSlim; - private readonly ServiceBusDiagnosticSource diagnosticSource; + private readonly string _clientId; + private readonly ISessionClient _client; + private readonly Func _userOnSessionCallback; + private readonly SessionHandlerOptions _sessionHandlerOptions; + private readonly string _endpoint; + private readonly string _entityPath; + private readonly CancellationToken _pumpCancellationToken; + private readonly SemaphoreSlim _maxConcurrentSessionsSemaphoreSlim; + private readonly SemaphoreSlim _maxPendingAcceptSessionsSemaphoreSlim; + private readonly ServiceBusDiagnosticSource _diagnosticSource; public SessionReceivePump(string clientId, ISessionClient client, @@ -30,17 +30,17 @@ public SessionReceivePump(string clientId, Uri endpoint, CancellationToken token) { - this.client = client ?? throw new ArgumentException(nameof(client)); - this.clientId = clientId; + this._client = client ?? throw new ArgumentException(nameof(client)); + this._clientId = clientId; ReceiveMode = receiveMode; - this.sessionHandlerOptions = sessionHandlerOptions; - userOnSessionCallback = callback; - this.endpoint = endpoint.Authority; - entityPath = client.EntityPath; - pumpCancellationToken = token; - maxConcurrentSessionsSemaphoreSlim = new SemaphoreSlim(this.sessionHandlerOptions.MaxConcurrentSessions); - maxPendingAcceptSessionsSemaphoreSlim = new SemaphoreSlim(this.sessionHandlerOptions.MaxConcurrentAcceptSessionCalls); - diagnosticSource = new ServiceBusDiagnosticSource(client.EntityPath, endpoint); + this._sessionHandlerOptions = sessionHandlerOptions; + _userOnSessionCallback = callback; + this._endpoint = endpoint.Authority; + _entityPath = client.EntityPath; + _pumpCancellationToken = token; + _maxConcurrentSessionsSemaphoreSlim = new SemaphoreSlim(this._sessionHandlerOptions.MaxConcurrentSessions); + _maxPendingAcceptSessionsSemaphoreSlim = new SemaphoreSlim(this._sessionHandlerOptions.MaxConcurrentAcceptSessionCalls); + _diagnosticSource = new ServiceBusDiagnosticSource(client.EntityPath, endpoint); } private ReceiveMode ReceiveMode { get; } @@ -48,7 +48,7 @@ public SessionReceivePump(string clientId, public void StartPump() { // Schedule Tasks for doing PendingAcceptSession calls - for (var i = 0; i < sessionHandlerOptions.MaxConcurrentAcceptSessionCalls; i++) + for (var i = 0; i < _sessionHandlerOptions.MaxConcurrentAcceptSessionCalls; i++) { TaskExtensionHelper.Schedule(SessionPumpTaskAsync); } @@ -72,13 +72,13 @@ private bool ShouldRenewSessionLock() { return ReceiveMode == ReceiveMode.PeekLock && - sessionHandlerOptions.AutoRenewLock; + _sessionHandlerOptions.AutoRenewLock; } private Task RaiseExceptionReceived(Exception e, string action) { - var eventArgs = new ExceptionReceivedEventArgs(e, action, endpoint, entityPath, clientId); - return sessionHandlerOptions.RaiseExceptionReceived(eventArgs); + var eventArgs = new ExceptionReceivedEventArgs(e, action, _endpoint, _entityPath, _clientId); + return _sessionHandlerOptions.RaiseExceptionReceived(eventArgs); } private async Task CompleteMessageIfNeededAsync(IMessageSession session, Message message) @@ -86,7 +86,7 @@ private async Task CompleteMessageIfNeededAsync(IMessageSession session, Message try { if (ReceiveMode == ReceiveMode.PeekLock && - sessionHandlerOptions.AutoComplete) + _sessionHandlerOptions.AutoComplete) { await session.CompleteAsync(new[] { message.SystemProperties.LockToken }).ConfigureAwait(false); } @@ -114,19 +114,19 @@ private async Task AbandonMessageIfNeededAsync(IMessageSession session, Message private async Task SessionPumpTaskAsync() { - while (!pumpCancellationToken.IsCancellationRequested) + while (!_pumpCancellationToken.IsCancellationRequested) { var concurrentSessionSemaphoreAcquired = false; try { - await maxConcurrentSessionsSemaphoreSlim.WaitAsync(pumpCancellationToken).ConfigureAwait(false); + await _maxConcurrentSessionsSemaphoreSlim.WaitAsync(_pumpCancellationToken).ConfigureAwait(false); concurrentSessionSemaphoreAcquired = true; - await maxPendingAcceptSessionsSemaphoreSlim.WaitAsync(pumpCancellationToken).ConfigureAwait(false); - var session = await client.AcceptMessageSessionAsync().ConfigureAwait(false); + await _maxPendingAcceptSessionsSemaphoreSlim.WaitAsync(_pumpCancellationToken).ConfigureAwait(false); + var session = await _client.AcceptMessageSessionAsync().ConfigureAwait(false); if (session == null) { - await Task.Delay(Constants.NoMessageBackoffTimeSpan, pumpCancellationToken).ConfigureAwait(false); + await Task.Delay(Constants.NoMessageBackoffTimeSpan, _pumpCancellationToken).ConfigureAwait(false); continue; } @@ -137,32 +137,32 @@ private async Task SessionPumpTaskAsync() } catch (Exception exception) { - MessagingEventSource.Log.SessionReceivePumpSessionReceiveException(clientId, exception); + MessagingEventSource.Log.SessionReceivePumpSessionReceiveException(_clientId, exception); if (concurrentSessionSemaphoreAcquired) { - maxConcurrentSessionsSemaphoreSlim.Release(); + _maxConcurrentSessionsSemaphoreSlim.Release(); } if (exception is ServiceBusTimeoutException) { - await Task.Delay(Constants.NoMessageBackoffTimeSpan, pumpCancellationToken).ConfigureAwait(false); + await Task.Delay(Constants.NoMessageBackoffTimeSpan, _pumpCancellationToken).ConfigureAwait(false); } else { - if (!(exception is ObjectDisposedException && pumpCancellationToken.IsCancellationRequested)) + if (!(exception is ObjectDisposedException && _pumpCancellationToken.IsCancellationRequested)) { await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.AcceptMessageSession).ConfigureAwait(false); } if (!MessagingUtilities.ShouldRetry(exception)) { - await Task.Delay(Constants.NoMessageBackoffTimeSpan, pumpCancellationToken).ConfigureAwait(false); + await Task.Delay(Constants.NoMessageBackoffTimeSpan, _pumpCancellationToken).ConfigureAwait(false); } } } finally { - maxPendingAcceptSessionsSemaphoreSlim.Release(); + _maxPendingAcceptSessionsSemaphoreSlim.Release(); } } } @@ -188,23 +188,23 @@ private async Task MessagePumpTaskAsync(IMessageSession session) try { - while (!pumpCancellationToken.IsCancellationRequested && !session.IsClosedOrClosing) + while (!_pumpCancellationToken.IsCancellationRequested && !session.IsClosedOrClosing) { Message message; try { - message = await session.ReceiveAsync(sessionHandlerOptions.MessageWaitTimeout).ConfigureAwait(false); + message = await session.ReceiveAsync(_sessionHandlerOptions.MessageWaitTimeout).ConfigureAwait(false); } catch (Exception exception) { - MessagingEventSource.Log.MessageReceivePumpTaskException(clientId, session.SessionId, exception); + MessagingEventSource.Log.MessageReceivePumpTaskException(_clientId, session.SessionId, exception); if (exception is ServiceBusTimeoutException) { // Timeout Exceptions are pretty common. Not alerting the User on this. continue; } - if (!(exception is ObjectDisposedException && pumpCancellationToken.IsCancellationRequested)) + if (!(exception is ObjectDisposedException && _pumpCancellationToken.IsCancellationRequested)) { await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.Receive).ConfigureAwait(false); } @@ -213,33 +213,33 @@ private async Task MessagePumpTaskAsync(IMessageSession session) if (message == null) { - MessagingEventSource.Log.SessionReceivePumpSessionEmpty(clientId, session.SessionId); + MessagingEventSource.Log.SessionReceivePumpSessionEmpty(_clientId, session.SessionId); break; } bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.ProcessSessionStart(session, message) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.ProcessSessionStart(session, message) : null; Task processTask = null; try { // Set the timer - autoRenewLockCancellationTimer.Change(sessionHandlerOptions.MaxAutoRenewDuration, + autoRenewLockCancellationTimer.Change(_sessionHandlerOptions.MaxAutoRenewDuration, TimeSpan.FromMilliseconds(-1)); var callbackExceptionOccurred = false; try { - processTask = userOnSessionCallback(session, message, pumpCancellationToken); + processTask = _userOnSessionCallback(session, message, _pumpCancellationToken); await processTask.ConfigureAwait(false); } catch (Exception exception) { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } - MessagingEventSource.Log.MessageReceivePumpTaskException(clientId, session.SessionId, exception); + MessagingEventSource.Log.MessageReceivePumpTaskException(_clientId, session.SessionId, exception); await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.UserCallback).ConfigureAwait(false); callbackExceptionOccurred = true; if (!(exception is MessageLockLostException || exception is SessionLockLostException)) @@ -264,7 +264,7 @@ private async Task MessagePumpTaskAsync(IMessageSession session) } finally { - diagnosticSource.ProcessSessionStop(activity, session, message, processTask?.Status); + _diagnosticSource.ProcessSessionStop(activity, session, message, processTask?.Status); } } } @@ -275,7 +275,7 @@ private async Task MessagePumpTaskAsync(IMessageSession session) autoRenewLockCancellationTimer.Dispose(); await CloseSessionIfNeededAsync(session).ConfigureAwait(false); - maxConcurrentSessionsSemaphoreSlim.Release(); + _maxConcurrentSessionsSemaphoreSlim.Release(); } } @@ -286,11 +286,11 @@ private async Task CloseSessionIfNeededAsync(IMessageSession session) try { await session.CloseAsync().ConfigureAwait(false); - MessagingEventSource.Log.SessionReceivePumpSessionClosed(clientId, session.SessionId); + MessagingEventSource.Log.SessionReceivePumpSessionClosed(_clientId, session.SessionId); } catch (Exception exception) { - MessagingEventSource.Log.SessionReceivePumpSessionCloseException(clientId, session.SessionId, exception); + MessagingEventSource.Log.SessionReceivePumpSessionCloseException(_clientId, session.SessionId, exception); await RaiseExceptionReceived(exception, ExceptionReceivedEventArgsAction.CloseMessageSession).ConfigureAwait(false); } } @@ -298,21 +298,21 @@ private async Task CloseSessionIfNeededAsync(IMessageSession session) private async Task RenewSessionLockTaskAsync(IMessageSession session, CancellationToken renewLockCancellationToken) { - while (!pumpCancellationToken.IsCancellationRequested && + while (!_pumpCancellationToken.IsCancellationRequested && !renewLockCancellationToken.IsCancellationRequested) { try { var amount = MessagingUtilities.CalculateRenewAfterDuration(session.LockedUntilUtc); - MessagingEventSource.Log.SessionReceivePumpSessionRenewLockStart(clientId, session.SessionId, amount); + MessagingEventSource.Log.SessionReceivePumpSessionRenewLockStart(_clientId, session.SessionId, amount); await Task.Delay(amount, renewLockCancellationToken).ConfigureAwait(false); - if (!pumpCancellationToken.IsCancellationRequested && + if (!_pumpCancellationToken.IsCancellationRequested && !renewLockCancellationToken.IsCancellationRequested) { await session.RenewSessionLockAsync().ConfigureAwait(false); - MessagingEventSource.Log.SessionReceivePumpSessionRenewLockStop(clientId, session.SessionId); + MessagingEventSource.Log.SessionReceivePumpSessionRenewLockStop(_clientId, session.SessionId); } else { @@ -321,7 +321,7 @@ private async Task RenewSessionLockTaskAsync(IMessageSession session, Cancellati } catch (Exception exception) { - MessagingEventSource.Log.SessionReceivePumpSessionRenewLockException(clientId, session.SessionId, exception); + MessagingEventSource.Log.SessionReceivePumpSessionRenewLockException(_clientId, session.SessionId, exception); // TaskCanceled is expected here as renewTasks will be cancelled after the Complete call is made. // ObjectDisposedException should only happen here because the CancellationToken was disposed at which point diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs index 572857e75368..fa0bc91c6ed4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs @@ -52,13 +52,13 @@ namespace Microsoft.Azure.ServiceBus /// It uses AMQP protocol for communicating with service bus. Use for advanced set of functionality. public class SubscriptionClient : ClientEntity, ISubscriptionClient { - private int prefetchCount; - private readonly object syncLock; - private readonly ServiceBusDiagnosticSource diagnosticSource; + private int _prefetchCount; + private readonly object _syncLock; + private readonly ServiceBusDiagnosticSource _diagnosticSource; - private IInnerSubscriptionClient innerSubscriptionClient; - private SessionClient sessionClient; - private SessionPumpHost sessionPumpHost; + private IInnerSubscriptionClient _innerSubscriptionClient; + private SessionClient _sessionClient; + private SessionPumpHost _sessionPumpHost; /// /// Instantiates a new to perform operations on a subscription. @@ -137,12 +137,12 @@ public SubscriptionClient(ServiceBusConnection serviceBusConnection, string topi MessagingEventSource.Log.SubscriptionClientCreateStart(serviceBusConnection?.Endpoint.Authority, topicPath, subscriptionName, receiveMode.ToString()); ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); - syncLock = new object(); + _syncLock = new object(); TopicPath = topicPath; SubscriptionName = subscriptionName; Path = EntityNameHelper.FormatSubscriptionPath(TopicPath, SubscriptionName); ReceiveMode = receiveMode; - diagnosticSource = new ServiceBusDiagnosticSource(Path, serviceBusConnection.Endpoint); + _diagnosticSource = new ServiceBusDiagnosticSource(Path, serviceBusConnection.Endpoint); OwnsConnection = false; ServiceBusConnection.ThrowIfClosed(); @@ -209,21 +209,21 @@ public override TimeSpan OperationTimeout /// public int PrefetchCount { - get => prefetchCount; + get => _prefetchCount; set { if (value < 0) { throw Fx.Exception.ArgumentOutOfRange(nameof(PrefetchCount), value, "Value cannot be less than 0."); } - prefetchCount = value; - if (innerSubscriptionClient != null) + _prefetchCount = value; + if (_innerSubscriptionClient != null) { - innerSubscriptionClient.PrefetchCount = value; + _innerSubscriptionClient.PrefetchCount = value; } - if (sessionClient != null) + if (_sessionClient != null) { - sessionClient.PrefetchCount = value; + _sessionClient.PrefetchCount = value; } } } @@ -237,11 +237,11 @@ internal IInnerSubscriptionClient InnerSubscriptionClient { get { - if (innerSubscriptionClient == null) + if (_innerSubscriptionClient == null) { - lock (syncLock) + lock (_syncLock) { - innerSubscriptionClient = new AmqpSubscriptionClient( + _innerSubscriptionClient = new AmqpSubscriptionClient( Path, ServiceBusConnection, RetryPolicy, @@ -251,7 +251,7 @@ internal IInnerSubscriptionClient InnerSubscriptionClient } } - return innerSubscriptionClient; + return _innerSubscriptionClient; } } @@ -259,13 +259,13 @@ internal SessionClient SessionClient { get { - if (sessionClient == null) + if (_sessionClient == null) { - lock (syncLock) + lock (_syncLock) { - if (sessionClient == null) + if (_sessionClient == null) { - sessionClient = new SessionClient( + _sessionClient = new SessionClient( ClientId, Path, MessagingEntityType.Subscriber, @@ -279,7 +279,7 @@ internal SessionClient SessionClient } } - return sessionClient; + return _sessionClient; } } @@ -287,13 +287,13 @@ internal SessionPumpHost SessionPumpHost { get { - if (sessionPumpHost == null) + if (_sessionPumpHost == null) { - lock (syncLock) + lock (_syncLock) { - if (sessionPumpHost == null) + if (_sessionPumpHost == null) { - sessionPumpHost = new SessionPumpHost( + _sessionPumpHost = new SessionPumpHost( ClientId, ReceiveMode, SessionClient, @@ -302,7 +302,7 @@ internal SessionPumpHost SessionPumpHost } } - return sessionPumpHost; + return _sessionPumpHost; } } @@ -492,7 +492,7 @@ public async Task AddRuleAsync(RuleDescription description) MessagingEventSource.Log.AddRuleStart(ClientId, description.Name); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.AddRuleStart(description) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.AddRuleStart(description) : null; Task addRuleTask = null; try @@ -504,7 +504,7 @@ public async Task AddRuleAsync(RuleDescription description) { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.AddRuleException(ClientId, exception); @@ -512,7 +512,7 @@ public async Task AddRuleAsync(RuleDescription description) } finally { - diagnosticSource.AddRuleStop(activity, description, addRuleTask?.Status); + _diagnosticSource.AddRuleStop(activity, description, addRuleTask?.Status); } MessagingEventSource.Log.AddRuleStop(ClientId); @@ -533,7 +533,7 @@ public async Task RemoveRuleAsync(string ruleName) MessagingEventSource.Log.RemoveRuleStart(ClientId, ruleName); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.RemoveRuleStart(ruleName) : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.RemoveRuleStart(ruleName) : null; Task removeRuleTask = null; try @@ -545,7 +545,7 @@ public async Task RemoveRuleAsync(string ruleName) { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.RemoveRuleException(ClientId, exception); @@ -554,7 +554,7 @@ public async Task RemoveRuleAsync(string ruleName) } finally { - diagnosticSource.RemoveRuleStop(activity, ruleName, removeRuleTask?.Status); + _diagnosticSource.RemoveRuleStop(activity, ruleName, removeRuleTask?.Status); } MessagingEventSource.Log.RemoveRuleStop(ClientId); @@ -569,7 +569,7 @@ public async Task> GetRulesAsync() MessagingEventSource.Log.GetRulesStart(ClientId); bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? diagnosticSource.GetRulesStart() : null; + Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.GetRulesStart() : null; Task> getRulesTask = null; var skip = 0; @@ -585,7 +585,7 @@ public async Task> GetRulesAsync() { if (isDiagnosticSourceEnabled) { - diagnosticSource.ReportException(exception); + _diagnosticSource.ReportException(exception); } MessagingEventSource.Log.GetRulesException(ClientId, exception); @@ -594,7 +594,7 @@ public async Task> GetRulesAsync() } finally { - diagnosticSource.GetRulesStop(activity, rules, getRulesTask?.Status); + _diagnosticSource.GetRulesStop(activity, rules, getRulesTask?.Status); } MessagingEventSource.Log.GetRulesStop(ClientId); @@ -628,16 +628,16 @@ public override void UnregisterPlugin(string serviceBusPluginName) protected override async Task OnClosingAsync() { - if (innerSubscriptionClient != null) + if (_innerSubscriptionClient != null) { - await innerSubscriptionClient.CloseAsync().ConfigureAwait(false); + await _innerSubscriptionClient.CloseAsync().ConfigureAwait(false); } - sessionPumpHost?.Close(); + _sessionPumpHost?.Close(); - if (sessionClient != null) + if (_sessionClient != null) { - await sessionClient.CloseAsync().ConfigureAwait(false); + await _sessionClient.CloseAsync().ConfigureAwait(false); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs index 33ec12b5950f..309a5c415693 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs @@ -31,8 +31,8 @@ namespace Microsoft.Azure.ServiceBus /// It uses AMQP protocol for communicating with servicebus. public class TopicClient : ClientEntity, ITopicClient { - private readonly object syncLock; - private MessageSender innerSender; + private readonly object _syncLock; + private MessageSender _innerSender; /// /// Instantiates a new to perform operations on a topic. @@ -99,7 +99,7 @@ public TopicClient(ServiceBusConnection serviceBusConnection, string entityPath, throw Fx.Exception.ArgumentNullOrWhiteSpace(entityPath); } ServiceBusConnection = serviceBusConnection ?? throw new ArgumentNullException(nameof(serviceBusConnection)); - syncLock = new object(); + _syncLock = new object(); TopicName = entityPath; OwnsConnection = false; ServiceBusConnection.ThrowIfClosed(); @@ -144,13 +144,13 @@ internal MessageSender InnerSender { get { - if (innerSender == null) + if (_innerSender == null) { - lock (syncLock) + lock (_syncLock) { - if (innerSender == null) + if (_innerSender == null) { - innerSender = new MessageSender( + _innerSender = new MessageSender( TopicName, null, MessagingEntityType.Topic, @@ -161,7 +161,7 @@ internal MessageSender InnerSender } } - return innerSender; + return _innerSender; } } @@ -233,9 +233,9 @@ public override void UnregisterPlugin(string serviceBusPluginName) protected override async Task OnClosingAsync() { - if (innerSender != null) + if (_innerSender != null) { - await innerSender.CloseAsync().ConfigureAwait(false); + await _innerSender.CloseAsync().ConfigureAwait(false); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs index b437dcf3e847..49285de9fb40 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs @@ -9,14 +9,14 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.Diagnostics public sealed class FakeDiagnosticListener : IObserver, IDisposable { - private IDisposable subscription; + private IDisposable _subscription; private class FakeDiagnosticSourceWriteObserver : IObserver> { - private readonly Action> writeCallback; + private readonly Action> _writeCallback; public FakeDiagnosticSourceWriteObserver(Action> writeCallback) { - this.writeCallback = writeCallback; + this._writeCallback = writeCallback; } public void OnCompleted() @@ -29,17 +29,17 @@ public void OnError(Exception error) public void OnNext(KeyValuePair value) { - writeCallback(value); + _writeCallback(value); } } - private readonly Action> writeCallback; + private readonly Action> _writeCallback; - private Func writeObserverEnabled = (name, arg1, arg2) => false; + private Func _writeObserverEnabled = (name, arg1, arg2) => false; public FakeDiagnosticListener(Action> writeCallback) { - this.writeCallback = writeCallback; + this._writeCallback = writeCallback; } public void OnCompleted() @@ -54,37 +54,37 @@ public void OnNext(DiagnosticListener value) { if (value.Name.Equals("Microsoft.Azure.ServiceBus")) { - subscription = value.Subscribe(new FakeDiagnosticSourceWriteObserver(writeCallback), IsEnabled); + _subscription = value.Subscribe(new FakeDiagnosticSourceWriteObserver(_writeCallback), IsEnabled); } } public void Enable() { - writeObserverEnabled = (name, arg1, arg2) => true; + _writeObserverEnabled = (name, arg1, arg2) => true; } public void Enable(Func writeObserverEnabled) { - this.writeObserverEnabled = (name, arg1, arg2) => writeObserverEnabled(name); + this._writeObserverEnabled = (name, arg1, arg2) => writeObserverEnabled(name); } public void Enable(Func writeObserverEnabled) { - this.writeObserverEnabled = (name, arg1, arg2) => writeObserverEnabled(name, arg1, arg2); + this._writeObserverEnabled = (name, arg1, arg2) => writeObserverEnabled(name, arg1, arg2); } public void Disable() { - writeObserverEnabled = (name, arg1, arg2) => false; + _writeObserverEnabled = (name, arg1, arg2) => false; } private bool IsEnabled(string s, object arg1, object arg2) => - writeObserverEnabled(s, arg1, arg2); + _writeObserverEnabled(s, arg1, arg2); public void Dispose() { Disable(); - subscription?.Dispose(); + _subscription?.Dispose(); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/TaskExtensionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/TaskExtensionTests.cs index bda95c1b4b96..d5bd0e46fba2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/TaskExtensionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/TaskExtensionTests.cs @@ -11,15 +11,15 @@ public class TaskExtensionsTests // 1-2 seconds and were causing intermitten failures as a result. The long delay has been set at 5 // seconds arbitrarily, which may delay results should tests fail but is otherwise not expected to // be an actual wait time under normal circumstances. - private readonly TimeSpan LongDelay = TimeSpan.FromSeconds(5); - private readonly TimeSpan TinyDelay = TimeSpan.FromMilliseconds(1); + private readonly TimeSpan _longDelay = TimeSpan.FromSeconds(5); + private readonly TimeSpan _tinyDelay = TimeSpan.FromMilliseconds(1); [Fact] public void WithTimeoutThrowsWhenATimeoutOccursAndNoActionIsSpecified() { Func actionUnderTest = async () => - await Task.Delay(LongDelay) - .WithTimeout(TinyDelay); + await Task.Delay(_longDelay) + .WithTimeout(_tinyDelay); Assert.ThrowsAsync(actionUnderTest); } @@ -31,7 +31,7 @@ public async Task WithTimeoutExecutesTheTimeoutActionWhenATimeoutOccurs() Action timeoutAction = () => { timeoutActionInvoked = true; }; - await Task.Delay(LongDelay).WithTimeout(TinyDelay, null, timeoutAction); + await Task.Delay(_longDelay).WithTimeout(_tinyDelay, null, timeoutAction); Assert.True(timeoutActionInvoked, "The timeout action should have been invoked."); } @@ -39,9 +39,9 @@ public async Task WithTimeoutExecutesTheTimeoutActionWhenATimeoutOccurs() public async Task WithTimeoutGenericThrowsWhenATimeoutOccursAndNoActionIsSpecified() { Func actionUnderTest = async () => - await Task.Delay(LongDelay) + await Task.Delay(_longDelay) .ContinueWith( _ => "blue") - .WithTimeout(TinyDelay); + .WithTimeout(_tinyDelay); await Assert.ThrowsAsync(actionUnderTest); } @@ -58,9 +58,9 @@ public async Task WithTimeoutGeneticExecutesTheTimeoutCallbackWhenATimeoutOccurs return expectedResult; }; - var result = await Task.Delay(LongDelay) + var result = await Task.Delay(_longDelay) .ContinueWith( _ => "blue") - .WithTimeout(TinyDelay, null, timeoutCallback); + .WithTimeout(_tinyDelay, null, timeoutCallback); Assert.True(timeoutActionInvoked, "The timeout action should have been invoked."); Assert.Equal(expectedResult, result); @@ -73,7 +73,7 @@ public async Task WithTimeoutDoesNotThrowWhenATimeoutDoesNotOccur() try { - await Task.Delay(TinyDelay).WithTimeout(LongDelay); + await Task.Delay(_tinyDelay).WithTimeout(_longDelay); } catch (TimeoutException) { @@ -90,7 +90,7 @@ public async Task WithTimeoutGenericDoesNotThrowsWhenATimeoutDoesNotOccur() try { - await Task.Delay(TinyDelay).ContinueWith( _ => "blue").WithTimeout(LongDelay); + await Task.Delay(_tinyDelay).ContinueWith( _ => "blue").WithTimeout(_longDelay); } catch (TimeoutException) { @@ -104,7 +104,7 @@ public async Task WithTimeoutGenericDoesNotThrowsWhenATimeoutDoesNotOccur() public async Task WithTimeoutGenericReturnsTheValueWhenATimeoutDoesNotOccur() { var expected = "hello"; - var result = await Task.Delay(TinyDelay).ContinueWith( _ => expected).WithTimeout(LongDelay); + var result = await Task.Delay(_tinyDelay).ContinueWith( _ => expected).WithTimeout(_longDelay); Assert.Equal(result, expected); } @@ -114,7 +114,7 @@ public async Task WithTimeoutPropagatesAnExceptionForACompletedTask() var completionSource = new TaskCompletionSource(); completionSource.SetException(new MissingFieldException("oops")); - Func actionUnderTest = async () => await completionSource.Task.WithTimeout(LongDelay); + Func actionUnderTest = async () => await completionSource.Task.WithTimeout(_longDelay); await Assert.ThrowsAsync(actionUnderTest); } @@ -122,9 +122,9 @@ public async Task WithTimeoutPropagatesAnExceptionForACompletedTask() public async Task WithTimeoutPropagatesAnExceptionThatCompletesBeforeTimeout() { Func actionUnderTest = async () => - await Task.Delay(TinyDelay) + await Task.Delay(_tinyDelay) .ContinueWith( _ => throw new MissingMemberException("oh no")) - .WithTimeout(LongDelay); + .WithTimeout(_longDelay); await Assert.ThrowsAsync(actionUnderTest); } @@ -133,9 +133,9 @@ await Task.Delay(TinyDelay) public async Task WithTimeoutGenericPropagatesAnExceptionThatCompletesBeforeTimeout() { Func actionUnderTest = async () => - await Task.Delay(TinyDelay) + await Task.Delay(_tinyDelay) .ContinueWith( _ => throw new MissingMemberException("oh no")) - .WithTimeout(LongDelay); + .WithTimeout(_longDelay); await Assert.ThrowsAsync(actionUnderTest); } @@ -146,7 +146,7 @@ public async Task WithTimeoutPropagatesACancelledTask() var completionSource = new TaskCompletionSource(); completionSource.SetCanceled(); - Func actionUnderTest = async () => await completionSource.Task.WithTimeout(LongDelay); + Func actionUnderTest = async () => await completionSource.Task.WithTimeout(_longDelay); await Assert.ThrowsAsync(actionUnderTest); } @@ -157,7 +157,7 @@ public async Task WithTimeoutInvokesTheCancellationTokenWhenATimeoutOccurs() try { - await Task.Delay(LongDelay).WithTimeout(TinyDelay, token); + await Task.Delay(_longDelay).WithTimeout(_tinyDelay, token); } catch (TimeoutException) @@ -175,9 +175,9 @@ public async Task WithTimeoutGenericInvokesTheCancellationTokenWhenATimeoutOccur try { - await Task.Delay(LongDelay) + await Task.Delay(_longDelay) .ContinueWith( _ => "hello") - .WithTimeout(TinyDelay, token); + .WithTimeout(_tinyDelay, token); } catch (TimeoutException) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs index 45de9abb0fd5..2f6a93ef6bdf 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs @@ -12,9 +12,9 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure { internal static class ServiceBusScope { - private static int randomSeed = Environment.TickCount; + private static int _randomSeed = Environment.TickCount; - private static readonly ThreadLocal Rng = new ThreadLocal( () => new Random(Interlocked.Increment(ref randomSeed)), false); + private static readonly ThreadLocal Rng = new ThreadLocal( () => new Random(Interlocked.Increment(ref _randomSeed)), false); private static readonly ManagementClient ManagementClient = new ManagementClient(TestUtility.NamespaceConnectionString); /// @@ -217,31 +217,31 @@ private static SubscriptionDescription BuildSubscriptionDescription(string subsc internal sealed class QueueScope { public readonly string Name; - private readonly Func CleanupAction; + private readonly Func _cleanupAction; public QueueScope(string name, Func cleanupAction) { Name = name; - CleanupAction = cleanupAction; + _cleanupAction = cleanupAction; } - public Task CleanupAsync() => CleanupAction?.Invoke() ?? Task.CompletedTask; + public Task CleanupAsync() => _cleanupAction?.Invoke() ?? Task.CompletedTask; } internal sealed class TopicScope { public readonly string TopicName; public readonly string SubscriptionName; - private readonly Func CleanupAction; + private readonly Func _cleanupAction; public TopicScope(string topicName, string subscriptionName, Func cleanupAction) { TopicName = topicName; SubscriptionName = subscriptionName; - CleanupAction = cleanupAction; + _cleanupAction = cleanupAction; } - public Task CleanupAsync() => CleanupAction?.Invoke() ?? Task.CompletedTask; + public Task CleanupAsync() => _cleanupAction?.Invoke() ?? Task.CompletedTask; } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs index 741c98d2db24..7a8268d44453 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs @@ -414,31 +414,31 @@ public async Task GetSubscriptionRuntimeInfoTest() var msg = await receiver.ReceiveAsync(); await receiver.DeadLetterAsync(msg.SystemProperties.LockToken); - var subscriptionsRI = await client.GetSubscriptionsRuntimeInfoAsync(topicName); - var subscriptionRI = subscriptionsRI.FirstOrDefault(s => subscriptionName.Equals(s.SubscriptionName, StringComparison.OrdinalIgnoreCase)); + var subscriptionsRi = await client.GetSubscriptionsRuntimeInfoAsync(topicName); + var subscriptionRi = subscriptionsRi.FirstOrDefault(s => subscriptionName.Equals(s.SubscriptionName, StringComparison.OrdinalIgnoreCase)); - Assert.Equal(topicName, subscriptionRI.TopicPath); - Assert.Equal(subscriptionName, subscriptionRI.SubscriptionName); + Assert.Equal(topicName, subscriptionRi.TopicPath); + Assert.Equal(subscriptionName, subscriptionRi.SubscriptionName); - Assert.True(subscriptionRI.CreatedAt < subscriptionRI.UpdatedAt); - Assert.True(subscriptionRI.UpdatedAt < subscriptionRI.AccessedAt); + Assert.True(subscriptionRi.CreatedAt < subscriptionRi.UpdatedAt); + Assert.True(subscriptionRi.UpdatedAt < subscriptionRi.AccessedAt); - Assert.Equal(1, subscriptionRI.MessageCountDetails.ActiveMessageCount); - Assert.Equal(1, subscriptionRI.MessageCountDetails.DeadLetterMessageCount); - Assert.Equal(0, subscriptionRI.MessageCountDetails.ScheduledMessageCount); - Assert.Equal(2, subscriptionRI.MessageCount); + Assert.Equal(1, subscriptionRi.MessageCountDetails.ActiveMessageCount); + Assert.Equal(1, subscriptionRi.MessageCountDetails.DeadLetterMessageCount); + Assert.Equal(0, subscriptionRi.MessageCountDetails.ScheduledMessageCount); + Assert.Equal(2, subscriptionRi.MessageCount); - var singleSubscriptionRI = await client.GetSubscriptionRuntimeInfoAsync(topicName, subscriptionName); + var singleSubscriptionRi = await client.GetSubscriptionRuntimeInfoAsync(topicName, subscriptionName); - Assert.Equal(subscriptionRI.CreatedAt, singleSubscriptionRI.CreatedAt); - Assert.Equal(subscriptionRI.AccessedAt, singleSubscriptionRI.AccessedAt); - Assert.Equal(subscriptionRI.UpdatedAt, singleSubscriptionRI.UpdatedAt); - Assert.Equal(subscriptionRI.SubscriptionName, singleSubscriptionRI.SubscriptionName); - Assert.Equal(subscriptionRI.MessageCount, singleSubscriptionRI.MessageCount); - Assert.Equal(subscriptionRI.MessageCountDetails.ActiveMessageCount, singleSubscriptionRI.MessageCountDetails.ActiveMessageCount); - Assert.Equal(subscriptionRI.MessageCountDetails.DeadLetterMessageCount, singleSubscriptionRI.MessageCountDetails.DeadLetterMessageCount); - Assert.Equal(subscriptionRI.MessageCountDetails.ScheduledMessageCount, singleSubscriptionRI.MessageCountDetails.ScheduledMessageCount); - Assert.Equal(subscriptionRI.TopicPath, singleSubscriptionRI.TopicPath); + Assert.Equal(subscriptionRi.CreatedAt, singleSubscriptionRi.CreatedAt); + Assert.Equal(subscriptionRi.AccessedAt, singleSubscriptionRi.AccessedAt); + Assert.Equal(subscriptionRi.UpdatedAt, singleSubscriptionRi.UpdatedAt); + Assert.Equal(subscriptionRi.SubscriptionName, singleSubscriptionRi.SubscriptionName); + Assert.Equal(subscriptionRi.MessageCount, singleSubscriptionRi.MessageCount); + Assert.Equal(subscriptionRi.MessageCountDetails.ActiveMessageCount, singleSubscriptionRi.MessageCountDetails.ActiveMessageCount); + Assert.Equal(subscriptionRi.MessageCountDetails.DeadLetterMessageCount, singleSubscriptionRi.MessageCountDetails.DeadLetterMessageCount); + Assert.Equal(subscriptionRi.MessageCountDetails.ScheduledMessageCount, singleSubscriptionRi.MessageCountDetails.ScheduledMessageCount); + Assert.Equal(subscriptionRi.TopicPath, singleSubscriptionRi.TopicPath); await client.DeleteSubscriptionAsync(topicName, subscriptionName); await client.DeleteTopicAsync(topicName); @@ -482,30 +482,30 @@ public async Task GetTopicRuntimeInfoTest() await sender.SendAsync(new Message() { MessageId = "2" }); await sender.SendAsync(new Message() { MessageId = "3", ScheduledEnqueueTimeUtc = DateTime.UtcNow.AddDays(1) }); - var topicsRI = await client.GetTopicsRuntimeInfoAsync(); - var topicRI = topicsRI.FirstOrDefault(t => topicName.Equals(t.Path, StringComparison.OrdinalIgnoreCase)); + var topicsRi = await client.GetTopicsRuntimeInfoAsync(); + var topicRi = topicsRi.FirstOrDefault(t => topicName.Equals(t.Path, StringComparison.OrdinalIgnoreCase)); - Assert.Equal(topicName, topicRI.Path); + Assert.Equal(topicName, topicRi.Path); - Assert.True(topicRI.CreatedAt < topicRI.UpdatedAt); - Assert.True(topicRI.UpdatedAt < topicRI.AccessedAt); + Assert.True(topicRi.CreatedAt < topicRi.UpdatedAt); + Assert.True(topicRi.UpdatedAt < topicRi.AccessedAt); - Assert.Equal(0, topicRI.MessageCountDetails.ActiveMessageCount); - Assert.Equal(0, topicRI.MessageCountDetails.DeadLetterMessageCount); - Assert.Equal(1, topicRI.MessageCountDetails.ScheduledMessageCount); - Assert.Equal(1, topicRI.SubscriptionCount); - Assert.True(topicRI.SizeInBytes > 0); + Assert.Equal(0, topicRi.MessageCountDetails.ActiveMessageCount); + Assert.Equal(0, topicRi.MessageCountDetails.DeadLetterMessageCount); + Assert.Equal(1, topicRi.MessageCountDetails.ScheduledMessageCount); + Assert.Equal(1, topicRi.SubscriptionCount); + Assert.True(topicRi.SizeInBytes > 0); - var singleTopicRI = await client.GetTopicRuntimeInfoAsync(topicRI.Path); + var singleTopicRi = await client.GetTopicRuntimeInfoAsync(topicRi.Path); - Assert.Equal(topicRI.AccessedAt, singleTopicRI.AccessedAt); - Assert.Equal(topicRI.CreatedAt, singleTopicRI.CreatedAt); - Assert.Equal(topicRI.UpdatedAt, singleTopicRI.UpdatedAt); - Assert.Equal(topicRI.MessageCountDetails.ActiveMessageCount, singleTopicRI.MessageCountDetails.ActiveMessageCount); - Assert.Equal(topicRI.MessageCountDetails.DeadLetterMessageCount, singleTopicRI.MessageCountDetails.DeadLetterMessageCount); - Assert.Equal(topicRI.MessageCountDetails.ScheduledMessageCount, singleTopicRI.MessageCountDetails.ScheduledMessageCount); - Assert.Equal(topicRI.SizeInBytes, singleTopicRI.SizeInBytes); - Assert.Equal(topicRI.SubscriptionCount, singleTopicRI.SubscriptionCount); + Assert.Equal(topicRi.AccessedAt, singleTopicRi.AccessedAt); + Assert.Equal(topicRi.CreatedAt, singleTopicRi.CreatedAt); + Assert.Equal(topicRi.UpdatedAt, singleTopicRi.UpdatedAt); + Assert.Equal(topicRi.MessageCountDetails.ActiveMessageCount, singleTopicRi.MessageCountDetails.ActiveMessageCount); + Assert.Equal(topicRi.MessageCountDetails.DeadLetterMessageCount, singleTopicRi.MessageCountDetails.DeadLetterMessageCount); + Assert.Equal(topicRi.MessageCountDetails.ScheduledMessageCount, singleTopicRi.MessageCountDetails.ScheduledMessageCount); + Assert.Equal(topicRi.SizeInBytes, singleTopicRi.SizeInBytes); + Assert.Equal(topicRi.SubscriptionCount, singleTopicRi.SubscriptionCount); await client.DeleteSubscriptionAsync(topicName, subscriptionName); await client.DeleteTopicAsync(topicName); @@ -664,7 +664,7 @@ await Assert.ThrowsAsync( } } - public static IEnumerable TestData_EntityNameValidationTest => new[] + public static IEnumerable TestDataEntityNameValidationTest => new[] { new object[] {"qq@", true}, new object[] {"qq/", true}, @@ -676,7 +676,7 @@ await Assert.ThrowsAsync( }; [Theory] - [MemberData(nameof(TestData_EntityNameValidationTest))] + [MemberData(nameof(TestDataEntityNameValidationTest))] [LiveTest] [DisplayTestMethodName] public void EntityNameValidationTest(string entityName, bool isPathSeparatorAllowed) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs index 83bee9d03570..86dfc9a9f37e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs @@ -14,21 +14,21 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.MessageInterop public class MessageInteropTests { - private static IDictionary SerializerTestCases = new XmlObjectSerializer[] + private static IDictionary _serializerTestCases = new XmlObjectSerializer[] { new DataContractBinarySerializer(typeof(TestBook)), new DataContractSerializer(typeof(TestBook)) }.ToDictionary(item => item.ToString(), item => item); - public static IEnumerable SerializerTestCaseNames => SerializerTestCases.Select(testCase => new[] { testCase.Key }); + public static IEnumerable SerializerTestCaseNames => _serializerTestCases.Select(testCase => new[] { testCase.Key }); [Theory] [MemberData(nameof(SerializerTestCaseNames))] [DisplayTestMethodName] public void RunSerializerTests(string testCaseName) { - var serializer = SerializerTestCases[testCaseName]; + var serializer = _serializerTestCases[testCaseName]; var book = new TestBook("contoso", 1, 5); var message = GetBrokeredMessage(serializer, book); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageSenderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageSenderTests.cs index 67e7f3040789..d59a49d8ef42 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageSenderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageSenderTests.cs @@ -10,39 +10,39 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class MessageSenderTests { - private MessageSender viaSender; - private MessageSender nonViaSender; + private MessageSender _viaSender; + private MessageSender _nonViaSender; public MessageSenderTests() { var builder = new ServiceBusConnectionStringBuilder("blah.com", "path", "key-name", "key-value"); var connection = new ServiceBusConnection(builder); - viaSender = new MessageSender(connection, "path", "via"); - nonViaSender = new MessageSender(connection, "path"); + _viaSender = new MessageSender(connection, "path", "via"); + _nonViaSender = new MessageSender(connection, "path"); } [Fact] [DisplayTestMethodName] public void Path_reflects_actual_link_destination() { - Assert.Equal("via", viaSender.Path); - Assert.Equal("path", nonViaSender.Path); + Assert.Equal("via", _viaSender.Path); + Assert.Equal("path", _nonViaSender.Path); } [Fact] [DisplayTestMethodName] public void TransferDestinationPath_should_be_final_destination_name() { - Assert.Equal("path", viaSender.TransferDestinationPath); - Assert.Null(nonViaSender.TransferDestinationPath); + Assert.Equal("path", _viaSender.TransferDestinationPath); + Assert.Null(_nonViaSender.TransferDestinationPath); } [Fact] [DisplayTestMethodName] public void ViaEntityPath_should_be_via_entity_name() { - Assert.Equal("via", viaSender.ViaEntityPath); - Assert.Null(nonViaSender.ViaEntityPath); + Assert.Equal("via", _viaSender.ViaEntityPath); + Assert.Null(_nonViaSender.ViaEntityPath); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs index cb48544183b4..5ccb6d6c72fc 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs @@ -16,7 +16,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class RetryTests { - private static IDictionary RetryTestCases = new[] + private static IDictionary _retryTestCases = new[] { new ExceptionRetryData(new ServiceBusCommunicationException(string.Empty), 0, true), new ExceptionRetryData(new ServerBusyException(string.Empty), 0, true), @@ -37,13 +37,13 @@ public class RetryTests }.ToDictionary(item => item.ToString(), item => item); - public static IEnumerable RetryTestCaseNames => RetryTestCases.Select(testCase => new[] { testCase.Key }); + public static IEnumerable RetryTestCaseNames => _retryTestCases.Select(testCase => new[] { testCase.Key }); [Theory] [MemberData(nameof(RetryTestCaseNames))] public void RetryExponentialShouldRetryTest(string retryTestCaseName) { - var testCase = RetryTestCases[retryTestCaseName]; + var testCase = _retryTestCases[retryTestCaseName]; var retry = new RetryExponential(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(20), 5); var remainingTime = Constants.DefaultOperationTimeout; var shouldRetry = retry.ShouldRetry(remainingTime, testCase.RetryCount, testCase.Exception, out var _); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs index 470e4dd4a474..37226c9c09fa 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs @@ -15,7 +15,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class SenderReceiverTests : SenderReceiverClientTestBase { - private static TimeSpan TwoSeconds = TimeSpan.FromSeconds(2); + private static TimeSpan _twoSeconds = TimeSpan.FromSeconds(2); public static IEnumerable TestPermutations => new[] { @@ -169,22 +169,22 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, // The first ReceiveAsync() would initialize the link and block prefetch2 for receiver2 Assert.Equal("prefetch1", (await receiver2.ReceiveAsync().ConfigureAwait(false)).Label); - await Task.Delay(TwoSeconds); + await Task.Delay(_twoSeconds); // Updating prefetch count on receiver1. receiver1.PrefetchCount = 2; - await Task.Delay(TwoSeconds); + await Task.Delay(_twoSeconds); // The next operation should fetch prefetch3 and prefetch4. Assert.Equal("prefetch3", (await receiver1.ReceiveAsync().ConfigureAwait(false)).Label); - await Task.Delay(TwoSeconds); + await Task.Delay(_twoSeconds); Assert.Equal("prefetch2", (await receiver2.ReceiveAsync().ConfigureAwait(false)).Label); - await Task.Delay(TwoSeconds); + await Task.Delay(_twoSeconds); // The next operation should block prefetch6 for receiver2. Assert.Equal("prefetch5", (await receiver2.ReceiveAsync().ConfigureAwait(false)).Label); - await Task.Delay(TwoSeconds); + await Task.Delay(_twoSeconds); // Updates in prefetch count of receiver1 should not affect receiver2. // Receiver2 should continue with 1 prefetch. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs index 3ee9049fbb5a..ec421e318c38 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs @@ -19,12 +19,12 @@ internal class TestSessionHandler private const int NumberOfSessions = 5; private const int MessagesPerSession = 10; - private readonly SessionPumpHost sessionPumpHost; - private readonly ReceiveMode receiveMode; - private readonly MessageSender sender; - private readonly SessionHandlerOptions sessionHandlerOptions; - private ConcurrentDictionary sessionMessageMap; - private int totalMessageCount; + private readonly SessionPumpHost _sessionPumpHost; + private readonly ReceiveMode _receiveMode; + private readonly MessageSender _sender; + private readonly SessionHandlerOptions _sessionHandlerOptions; + private ConcurrentDictionary _sessionMessageMap; + private int _totalMessageCount; public TestSessionHandler( ReceiveMode receiveMode, @@ -32,21 +32,21 @@ public TestSessionHandler( MessageSender sender, SessionPumpHost sessionPumpHost) { - this.receiveMode = receiveMode; - this.sessionHandlerOptions = sessionHandlerOptions; - this.sender = sender; - this.sessionPumpHost = sessionPumpHost; - sessionMessageMap = new ConcurrentDictionary(); + this._receiveMode = receiveMode; + this._sessionHandlerOptions = sessionHandlerOptions; + this._sender = sender; + this._sessionPumpHost = sessionPumpHost; + _sessionMessageMap = new ConcurrentDictionary(); } public void RegisterSessionHandler(SessionHandlerOptions handlerOptions) { - sessionPumpHost.OnSessionHandler(OnSessionHandler, sessionHandlerOptions); + _sessionPumpHost.OnSessionHandler(OnSessionHandler, _sessionHandlerOptions); } public async Task SendSessionMessages() { - await TestUtility.SendSessionMessagesAsync(sender, NumberOfSessions, MessagesPerSession); + await TestUtility.SendSessionMessagesAsync(_sender, NumberOfSessions, MessagesPerSession); } public async Task OnSessionHandler(IMessageSession session, Message message, CancellationToken token) @@ -54,15 +54,15 @@ public async Task OnSessionHandler(IMessageSession session, Message message, Can Assert.NotNull(session); Assert.NotNull(message); - Interlocked.Increment(ref totalMessageCount); + Interlocked.Increment(ref _totalMessageCount); TestUtility.Log($"Received Session: {session.SessionId} message: SequenceNumber: {message.SystemProperties.SequenceNumber}"); - if (receiveMode == ReceiveMode.PeekLock && !sessionHandlerOptions.AutoComplete) + if (_receiveMode == ReceiveMode.PeekLock && !_sessionHandlerOptions.AutoComplete) { await session.CompleteAsync(message.SystemProperties.LockToken); } - sessionMessageMap.AddOrUpdate(session.SessionId, 1, (_, current) => current + 1); + _sessionMessageMap.AddOrUpdate(session.SessionId, 1, (_, current) => current + 1); } public async Task VerifyRun() @@ -71,27 +71,27 @@ public async Task VerifyRun() var stopwatch = Stopwatch.StartNew(); while (stopwatch.Elapsed.TotalSeconds <= 180) { - if (totalMessageCount == MessagesPerSession * NumberOfSessions) + if (_totalMessageCount == MessagesPerSession * NumberOfSessions) { - TestUtility.Log($"All '{totalMessageCount}' messages Received."); + TestUtility.Log($"All '{_totalMessageCount}' messages Received."); break; } await Task.Delay(TimeSpan.FromSeconds(5)); } - foreach (KeyValuePair keyValuePair in sessionMessageMap) + foreach (KeyValuePair keyValuePair in _sessionMessageMap) { TestUtility.Log($"Session: {keyValuePair.Key}, Messages Received in this Session: {keyValuePair.Value}"); } - Assert.True(sessionMessageMap.Keys.Count == NumberOfSessions); - Assert.True(totalMessageCount == MessagesPerSession * NumberOfSessions); + Assert.True(_sessionMessageMap.Keys.Count == NumberOfSessions); + Assert.True(_totalMessageCount == MessagesPerSession * NumberOfSessions); } public void ClearData() { - totalMessageCount = 0; - sessionMessageMap = new ConcurrentDictionary(); + _totalMessageCount = 0; + _sessionMessageMap = new ConcurrentDictionary(); } } } \ No newline at end of file diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs index fe3f5109a524..18d75c9bf60e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs @@ -45,19 +45,19 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, public async Task AzureActiveDirectoryTokenProviderAuthCallbackTest() { var csb = new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString); - string TestToken = @"eyJhbGciOiJIUzI1NiJ9.e30.ZRrHA1JJJW8opsbCGfG_HACGpVUMN_a9IV7pAx_Zmeo"; + string testToken = @"eyJhbGciOiJIUzI1NiJ9.e30.ZRrHA1JJJW8opsbCGfG_HACGpVUMN_a9IV7pAx_Zmeo"; var aadTokenProvider = TokenProvider.CreateAzureActiveDirectoryTokenProvider( (audience, authority, state) => { Assert.Equal(Constants.AadServiceBusAudience, audience); - return Task.FromResult(TestToken); + return Task.FromResult(testToken); }, "https://servicebus.azure.net/MyTenantId"); var token = await aadTokenProvider.GetTokenAsync(csb.Endpoint, TimeSpan.FromSeconds(60)); Assert.Equal(typeof(JsonSecurityToken), token.GetType()); - Assert.Equal(TestToken, token.TokenValue); + Assert.Equal(testToken, token.TokenValue); Assert.Equal(csb.Endpoint, token.Audience); } } From bb6ef2e27996ecd300b7f9ee5ae9192d1d31addd Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:41:40 -0400 Subject: [PATCH 10/82] Cleaned up XML commenting --- .../src/Primitives/ManagedIdentityTokenProvider.cs | 8 ++++++-- .../Microsoft.Azure.ServiceBus/tests/MessageTests.cs | 6 +++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs index 074443803349..309bfd2ce34c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs @@ -14,10 +14,14 @@ public class ManagedIdentityTokenProvider : TokenProvider { private readonly AzureServiceTokenProvider _azureServiceTokenProvider; - /// Initializes new instance of class with default configuration. + /// + /// Initializes new instance of class with default configuration. + /// public ManagedIdentityTokenProvider() : this(new AzureServiceTokenProvider()){} - /// Initializes new instance of class with . + /// + /// Initializes new instance of class with . + /// /// Call that constructore to set with required Managed Identity connection string. public ManagedIdentityTokenProvider(AzureServiceTokenProvider azureServiceTokenProvider) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs index abd7c8b432f5..9f22de8a8922 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs @@ -212,9 +212,9 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, var sender = new MessageSender(TestUtility.NamespaceConnectionString, queueName); var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete); - /// Only following value types are supported: - /// byte, sbyte, char, short, ushort, int, uint, long, ulong, float, double, decimal, - /// bool, Guid, string, Uri, DateTime, DateTimeOffset, TimeSpan + // Only following value types are supported: + // byte, sbyte, char, short, ushort, int, uint, long, ulong, float, double, decimal, + // bool, Guid, string, Uri, DateTime, DateTimeOffset, TimeSpan var msg = new Message(); msg.UserProperties.Add("byte", (byte)2); msg.UserProperties.Add("sbyte", (sbyte)3); From 2f5eb48fcc8b3d6041415d44125ad55ca44d268e Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:42:49 -0400 Subject: [PATCH 11/82] Removed unneeded imports --- .../src/Primitives/ITokenProvider.cs | 3 --- 1 file changed, 3 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ITokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ITokenProvider.cs index 6d887c96f566..05fb8bc78212 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ITokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ITokenProvider.cs @@ -4,9 +4,6 @@ namespace Microsoft.Azure.ServiceBus.Primitives { using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; using System.Threading.Tasks; /// From 6b7a2498058947f45ff0622cf9a4abdd7a96258b Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:44:28 -0400 Subject: [PATCH 12/82] Removed redundant field initializers --- .../src/Management/QueueDescription.cs | 6 +++--- .../src/Management/SubscriptionDescription.cs | 6 +++--- .../src/Management/TopicDescription.cs | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index b5b83f025dc6..5e58fff02ac9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -18,9 +18,9 @@ public class QueueDescription : IEquatable private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; private int _maxDeliveryCount = 10; - private string _forwardTo = null; - private string _forwardDeadLetteredMessagesTo = null; - private string _userMetadata = null; + private string _forwardTo; + private string _forwardDeadLetteredMessagesTo; + private string _userMetadata; /// /// Initializes a new instance of QueueDescription class with the specified relative path. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs index e4ebbe252284..f5deb1014141 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -19,9 +19,9 @@ public class SubscriptionDescription : IEquatable private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; private int _maxDeliveryCount = 10; - private string _forwardTo = null; - private string _forwardDeadLetteredMessagesTo = null; - private string _userMetadata = null; + private string _forwardTo; + private string _forwardDeadLetteredMessagesTo; + private string _userMetadata; /// /// Initializes a new instance of SubscriptionDescription class with the specified name and topic path. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs index ee15b67140ad..c19f8f559b56 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs @@ -15,7 +15,7 @@ public class TopicDescription : IEquatable internal string path; private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; - private string _userMetadata = null; + private string _userMetadata; /// /// Initializes a new instance of TopicDescription class with the specified relative path. From edc41c632a8e9e5ece824422a09eaf80b2a12e95 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:47:47 -0400 Subject: [PATCH 13/82] Removed redundant casts --- .../tests/Management/ManagementClientTests.cs | 4 ++-- .../Microsoft.Azure.ServiceBus/tests/MessageTests.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs index 7a8268d44453..33629f5abdf6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs @@ -248,7 +248,7 @@ await client.CreateSubscriptionAsync( var sqlFilter = new SqlFilter("stringValue = @stringParam AND intValue = @intParam AND longValue = @longParam AND dateValue = @dateParam AND timeSpanValue = @timeSpanParam"); sqlFilter.Parameters.Add("@stringParam", "string"); - sqlFilter.Parameters.Add("@intParam", (int)1); + sqlFilter.Parameters.Add("@intParam", 1); sqlFilter.Parameters.Add("@longParam", (long)12); sqlFilter.Parameters.Add("@dateParam", DateTime.UtcNow); sqlFilter.Parameters.Add("@timeSpanParam", TimeSpan.FromDays(1)); @@ -859,7 +859,7 @@ public async Task SqlFilterParamsTest() { "@intPropertyValue", 3 }, { "@longPropertyValue", 3L }, { "@boolPropertyValue", true }, - { "@doublePropertyValue", (double)3.0 }, + { "@doublePropertyValue", 3.0 }, } }; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs index 9f22de8a8922..89a22b566d31 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs @@ -221,12 +221,12 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, msg.UserProperties.Add("char", 'c'); msg.UserProperties.Add("short", (short)4); msg.UserProperties.Add("ushort", (ushort)5); - msg.UserProperties.Add("int", (int)6); + msg.UserProperties.Add("int", 6); msg.UserProperties.Add("uint", (uint)7); msg.UserProperties.Add("long", (long)8); msg.UserProperties.Add("ulong", (ulong)9); msg.UserProperties.Add("float", (float)10.0); - msg.UserProperties.Add("double", (double)11.0); + msg.UserProperties.Add("double", 11.0); msg.UserProperties.Add("decimal", (decimal)12.0); msg.UserProperties.Add("bool", true); msg.UserProperties.Add("Guid", Guid.NewGuid()); From 6c53a30391798cefff99a94a102b6df907dad6b1 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:48:22 -0400 Subject: [PATCH 14/82] Fixed parameter name in XML comment --- .../tests/Infrastructure/ServiceBusScope.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs index 2f6a93ef6bdf..5f66e06d330d 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs @@ -138,7 +138,7 @@ public static async Task UsingQueueAsync(bool partitioned, /// If true, a session will be required on the subscription. /// The asynchronous operation to be performed; the name of the topic and subscription will be passed to the operation. /// If provided, an action that can override the default properties used for topic creation. - /// If provided, an action that can override the default properties used for topic creation. + /// If provided, an action that can override the default properties used for topic creation. /// The name of the calling method; this is intended to be populated by the runtime. /// /// The task representing the operation being performed From 8687e9038ade53e2cf47e8c70fceff1be9a598e9 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:48:47 -0400 Subject: [PATCH 15/82] Adjusted namespace --- .../tests/Performance/Program.cs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index 16eb10d74d9e..78b69d67124c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -1,16 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -namespace Microsoft.Azure.ServiceBus.Performance +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Azure.ServiceBus.Core; + +namespace Microsoft.Azure.ServiceBus.UnitTests.Performance { - using ServiceBus; - using Core; - using System; - using System.Diagnostics; - using System.Threading; - using System.Threading.Tasks; - - internal class Program + internal class Program { private static readonly Stopwatch _stopwatch = Stopwatch.StartNew(); From 6bfb0c1cc6725756ed858773299495227ba27539 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:52:09 -0400 Subject: [PATCH 16/82] Fixed null reference warnings --- .../src/Amqp/AmqpMessageConverter.cs | 2 +- .../tests/Infrastructure/ServiceBusScope.cs | 2 +- .../tests/Management/ManagementClientTests.cs | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index d85c09060497..f23f2f7a368b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -202,7 +202,7 @@ public static SBMessage AmqpMessageToSBMessage(AmqpMessage amqpMessage, bool isP else if (data.Value is ArraySegment arraySegmentValue) { byte[] byteArray; - if (arraySegmentValue.Count == arraySegmentValue.Array.Length) + if (arraySegmentValue.Count == arraySegmentValue.Array?.Length) { byteArray = arraySegmentValue.Array; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs index 5f66e06d330d..83b57ef0c2ac 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs @@ -126,7 +126,7 @@ public static async Task UsingQueueAsync(bool partitioned, } finally { - await scope?.CleanupAsync(); + await (scope?.CleanupAsync() ?? Task.CompletedTask); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs index 33629f5abdf6..5d33153a8c27 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs @@ -417,10 +417,10 @@ public async Task GetSubscriptionRuntimeInfoTest() var subscriptionsRi = await client.GetSubscriptionsRuntimeInfoAsync(topicName); var subscriptionRi = subscriptionsRi.FirstOrDefault(s => subscriptionName.Equals(s.SubscriptionName, StringComparison.OrdinalIgnoreCase)); - Assert.Equal(topicName, subscriptionRi.TopicPath); - Assert.Equal(subscriptionName, subscriptionRi.SubscriptionName); + Assert.Equal(topicName, subscriptionRi?.TopicPath); + Assert.Equal(subscriptionName, subscriptionRi?.SubscriptionName); - Assert.True(subscriptionRi.CreatedAt < subscriptionRi.UpdatedAt); + Assert.True(subscriptionRi?.CreatedAt < subscriptionRi?.UpdatedAt); Assert.True(subscriptionRi.UpdatedAt < subscriptionRi.AccessedAt); Assert.Equal(1, subscriptionRi.MessageCountDetails.ActiveMessageCount); From c5a8ccf27e908d5a60a53eb35895b562df1d0f12 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:53:32 -0400 Subject: [PATCH 17/82] Refactored Console WriteLine's to TestOutputHelper calls in XUnit tests --- .../Microsoft.Azure.ServiceBus/tests/MessageTests.cs | 12 ++++++++++-- .../tests/TransactionTests.cs | 11 +++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs index 89a22b566d31..8fbd91dd850b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; +using Xunit.Abstractions; namespace Microsoft.Azure.ServiceBus.UnitTests { @@ -15,7 +16,14 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class MessageTests { - [Fact] + private readonly ITestOutputHelper _testOutputHelper; + + public MessageTests(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } + + [Fact] [DisplayTestMethodName] public void TestClone() { @@ -192,7 +200,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, } catch (Exception e) { - Console.WriteLine(e); + _testOutputHelper.WriteLine(e.ToString()); throw; } finally diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs index bb6e341ef6dc..cf0a821ffbd6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; +using Xunit.Abstractions; namespace Microsoft.Azure.ServiceBus.UnitTests { @@ -15,10 +16,16 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class TransactionTests { + private readonly ITestOutputHelper _testOutputHelper; private static readonly string ConnectionString = TestUtility.NamespaceConnectionString; private static readonly TimeSpan ReceiveTimeout = TimeSpan.FromSeconds(5); - public static IEnumerable TestPermutations => new[] + public TransactionTests(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } + + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedQueue, useSessionQueue } new object[] { false, false }, @@ -363,7 +370,7 @@ await Assert.ThrowsAsync( } catch (Exception e) { - Console.WriteLine(e); + _testOutputHelper.WriteLine(e.ToString()); } finally { From 954dd56b74c6dbed5a530838c88f68595125aba8 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:54:00 -0400 Subject: [PATCH 18/82] Removed redundant import --- sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs index 8fbd91dd850b..14b569ef280f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs @@ -7,7 +7,6 @@ namespace Microsoft.Azure.ServiceBus.UnitTests { using System; - using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; From 406541546d36645b46a761bfbd18ddc582cd1f14 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:55:06 -0400 Subject: [PATCH 19/82] Removed unused variable --- .../src/Primitives/TokenProviderAdapter.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs index af8d3a85392c..1904c456f672 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs @@ -26,7 +26,6 @@ public TokenProviderAdapter(ITokenProvider tokenProvider, TimeSpan operationTime public async Task GetTokenAsync(Uri namespaceAddress, string appliesTo, string[] requiredClaims) { - var claim = requiredClaims?.FirstOrDefault(); var securityToken = await _tokenProvider.GetTokenAsync(appliesTo, _operationTimeout).ConfigureAwait(false); return new CbsToken(securityToken.TokenValue, CbsConstants.ServiceBusSasTokenType, securityToken.ExpiresAtUtc); } From dfdc55e96414e6a542e1de69e3f568d30265967c Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:55:19 -0400 Subject: [PATCH 20/82] Removed redundant import --- .../src/Primitives/TokenProviderAdapter.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs index 1904c456f672..3d1336902fbe 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs @@ -5,7 +5,6 @@ namespace Microsoft.Azure.ServiceBus.Primitives { using System.Diagnostics; using System; - using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.Amqp; From 9a231675277bf1caf3ee711d6af8f186dc204045 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:56:06 -0400 Subject: [PATCH 21/82] Removed redundant "this" qualifier --- .../src/Amqp/ActiveClientLinkObject.cs | 2 +- .../src/Amqp/AmqpLinkCreator.cs | 14 +++++++------- .../src/Amqp/AmqpRequestResponseLinkCreator.cs | 2 +- .../src/Amqp/AmqpResponseMessage.cs | 6 +++--- .../src/Amqp/AmqpTransactionEnlistment.cs | 4 ++-- .../src/ClientEntity.cs | 2 +- .../src/Core/MessageReceiver.cs | 2 +- .../src/Management/ManagementClient.cs | 4 ++-- .../src/MessageReceivePump.cs | 10 +++++----- .../AzureActiveDirectoryTokenProvider.cs | 2 +- .../src/Primitives/Fx.cs | 16 ++++++++-------- .../Primitives/ManagedIdentityTokenProvider.cs | 2 +- .../src/Primitives/SecurityToken.cs | 6 +++--- .../SharedAccessSignatureTokenProvider.cs | 8 ++++---- .../src/Primitives/TokenProviderAdapter.cs | 4 ++-- .../src/ServiceBusDiagnosticsSource.cs | 4 ++-- .../src/SessionPumpHost.cs | 2 +- .../src/SessionReceivePump.cs | 12 ++++++------ .../tests/Diagnostics/FakeDiagnosticListener.cs | 8 ++++---- .../tests/TestSessionHandler.cs | 8 ++++---- 20 files changed, 59 insertions(+), 59 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs index b7675e553c8c..33b5d75e147f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs @@ -15,7 +15,7 @@ protected ActiveClientLinkObject(AmqpObject amqpLinkObject, Uri endpointUri, st LinkObject = amqpLinkObject; EndpointUri = endpointUri; Audience = audience; - this._requiredClaims = requiredClaims; + _requiredClaims = requiredClaims; AuthorizationValidUntilUtc = authorizationValidUntilUtc; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs index 57845a7ae082..cbf82406d5c5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs @@ -21,13 +21,13 @@ internal abstract class AmqpLinkCreator protected AmqpLinkCreator(string entityPath, ServiceBusConnection serviceBusConnection, Uri endpointAddress, string[] audience, string[] requiredClaims, ICbsTokenProvider cbsTokenProvider, AmqpLinkSettings amqpLinkSettings, string clientId) { - this._entityPath = entityPath; - this._serviceBusConnection = serviceBusConnection; - this._endpointAddress = endpointAddress; - this._audience = audience; - this._requiredClaims = requiredClaims; - this._cbsTokenProvider = cbsTokenProvider; - this._amqpLinkSettings = amqpLinkSettings; + _entityPath = entityPath; + _serviceBusConnection = serviceBusConnection; + _endpointAddress = endpointAddress; + _audience = audience; + _requiredClaims = requiredClaims; + _cbsTokenProvider = cbsTokenProvider; + _amqpLinkSettings = amqpLinkSettings; ClientId = clientId; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs index a6fd11bd9cea..37a29515396f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs @@ -14,7 +14,7 @@ internal class AmqpRequestResponseLinkCreator : AmqpLinkCreator public AmqpRequestResponseLinkCreator(string entityPath, ServiceBusConnection serviceBusConnection, Uri endpointAddress, string[] audience, string[] requiredClaims, ICbsTokenProvider cbsTokenProvider, AmqpLinkSettings linkSettings, string clientId) : base(entityPath, serviceBusConnection, endpointAddress, audience, requiredClaims, cbsTokenProvider, linkSettings, clientId) { - this._entityPath = entityPath; + _entityPath = entityPath; } protected override AmqpObject OnCreateAmqpLink(AmqpConnection connection, AmqpLinkSettings linkSettings, AmqpSession amqpSession) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs index cb573b90a9e1..36d19a994d9b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs @@ -16,9 +16,9 @@ internal sealed class AmqpResponseMessage private AmqpResponseMessage(AmqpMessage responseMessage) { - this._responseMessage = responseMessage; - StatusCode = this._responseMessage.GetResponseStatusCode(); - if (this._responseMessage.ApplicationProperties.Map.TryGetValue(ManagementConstants.Properties.TrackingId, out var trackingId)) + _responseMessage = responseMessage; + StatusCode = _responseMessage.GetResponseStatusCode(); + if (_responseMessage.ApplicationProperties.Map.TryGetValue(ManagementConstants.Properties.TrackingId, out var trackingId)) { TrackingId = trackingId; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs index fb9459bfa53d..db43e082751e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs @@ -21,8 +21,8 @@ public AmqpTransactionEnlistment( ServiceBusConnection serviceBusConnection) { _transactionId = transaction.TransactionInformation.LocalIdentifier; - this._transactionManager = transactionManager; - this._serviceBusConnection = serviceBusConnection; + _transactionManager = transactionManager; + _serviceBusConnection = serviceBusConnection; } public ArraySegment AmqpTransactionId { get; private set; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs index e1c8cb614b39..7078511a9311 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ClientEntity.cs @@ -22,7 +22,7 @@ public abstract class ClientEntity : IClientEntity protected ClientEntity(string clientTypeName, string postfix, RetryPolicy retryPolicy) { - this._clientTypeName = clientTypeName; + _clientTypeName = clientTypeName; ClientId = GenerateClientId(clientTypeName, postfix); RetryPolicy = retryPolicy ?? RetryPolicy.Default; _syncLock = new object(); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index 230c75f548b7..91659aab7d77 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -186,7 +186,7 @@ internal MessageReceiver( } SessionIdInternal = sessionId; - this._isSessionReceiver = isSessionReceiver; + _isSessionReceiver = isSessionReceiver; ReceiveLinkManager = new FaultTolerantAmqpObject(CreateLinkAsync, CloseSession); RequestResponseLinkManager = new FaultTolerantAmqpObject(CreateRequestResponseLinkAsync, CloseRequestResponseSession); _requestResponseLockedMessages = new ConcurrentExpiringSet(); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs index f92c3f6cbc6d..e9d2b185b864 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs @@ -51,11 +51,11 @@ public ManagementClient(ServiceBusConnectionStringBuilder connectionStringBuilde { _httpClient = new HttpClient { Timeout = connectionStringBuilder.OperationTimeout }; _endpointFqdn = connectionStringBuilder.Endpoint; - this._tokenProvider = tokenProvider ?? CreateTokenProvider(connectionStringBuilder); + _tokenProvider = tokenProvider ?? CreateTokenProvider(connectionStringBuilder); _port = GetPort(connectionStringBuilder.Endpoint); _clientId = nameof(ManagementClient) + Guid.NewGuid().ToString("N").Substring(0, 6); - MessagingEventSource.Log.ManagementClientCreated(_clientId, _httpClient.Timeout.TotalSeconds, this._tokenProvider.ToString()); + MessagingEventSource.Log.ManagementClientCreated(_clientId, _httpClient.Timeout.TotalSeconds, _tokenProvider.ToString()); } public static HttpRequestMessage CloneRequest(HttpRequestMessage req) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs index 95ab6b1ae0ac..34d853458ad5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs @@ -26,12 +26,12 @@ public MessageReceivePump(IMessageReceiver messageReceiver, Uri endpoint, CancellationToken pumpCancellationToken) { - this._messageReceiver = messageReceiver ?? throw new ArgumentNullException(nameof(messageReceiver)); - this._registerHandlerOptions = registerHandlerOptions; + _messageReceiver = messageReceiver ?? throw new ArgumentNullException(nameof(messageReceiver)); + _registerHandlerOptions = registerHandlerOptions; _onMessageCallback = callback; - this._endpoint = endpoint.Authority; - this._pumpCancellationToken = pumpCancellationToken; - _maxConcurrentCallsSemaphoreSlim = new SemaphoreSlim(this._registerHandlerOptions.MaxConcurrentCalls); + _endpoint = endpoint.Authority; + _pumpCancellationToken = pumpCancellationToken; + _maxConcurrentCallsSemaphoreSlim = new SemaphoreSlim(_registerHandlerOptions.MaxConcurrentCalls); _diagnosticSource = new ServiceBusDiagnosticSource(messageReceiver.Path, endpoint); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs index 46b4862ea979..6876c6b28833 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs @@ -20,7 +20,7 @@ public class AzureActiveDirectoryTokenProvider : TokenProvider public AzureActiveDirectoryTokenProvider(AuthenticationCallback authenticationCallback, string authority, object state) { AuthCallback = authenticationCallback ?? throw Fx.Exception.ArgumentNull(nameof(authenticationCallback)); - this._authority = authority ?? throw Fx.Exception.ArgumentNull(nameof(authority)); + _authority = authority ?? throw Fx.Exception.ArgumentNull(nameof(authority)); _authCallbackState = state; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs index 5bd0c5b9a510..e71ef5a48d82 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs @@ -108,8 +108,8 @@ public sealed class ExternalResourceAttribute : Attribute public ExternalResourceAttribute(Location location, string description) { - this._location = location; - this._description = description; + _location = location; + _description = description; } public Location Location => _location; @@ -135,8 +135,8 @@ public CacheAttribute(Type elementType, CacheAttrition cacheAttrition) throw Exception.ArgumentNull(nameof(elementType)); } - this._elementType = elementType; - this._cacheAttrition = cacheAttrition; + _elementType = elementType; + _cacheAttrition = cacheAttrition; } public Type ElementType => _elementType; @@ -166,7 +166,7 @@ public QueueAttribute(Type elementType) throw Exception.ArgumentNull(nameof(elementType)); } - this._elementType = elementType; + _elementType = elementType; } public Type ElementType => _elementType; @@ -208,7 +208,7 @@ public sealed class SynchronizationPrimitiveAttribute : Attribute public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing) { - this._blocksUsing = blocksUsing; + _blocksUsing = blocksUsing; } public BlocksUsing BlocksUsing => _blocksUsing; @@ -267,8 +267,8 @@ public ThrowsAttribute(Type exceptionType, string diagnosis) throw new ArgumentNullException(nameof(diagnosis)); } - this._exceptionType = exceptionType; - this._diagnosis = diagnosis; + _exceptionType = exceptionType; + _diagnosis = diagnosis; } public Type ExceptionType => _exceptionType; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs index 309bfd2ce34c..4968133e4894 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs @@ -25,7 +25,7 @@ public ManagedIdentityTokenProvider() : this(new AzureServiceTokenProvider()){} /// Call that constructore to set with required Managed Identity connection string. public ManagedIdentityTokenProvider(AzureServiceTokenProvider azureServiceTokenProvider) { - this._azureServiceTokenProvider = azureServiceTokenProvider; + _azureServiceTokenProvider = azureServiceTokenProvider; } /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs index 440cf3bcb8b4..fa8a6d7e84ef 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SecurityToken.cs @@ -50,9 +50,9 @@ public SecurityToken(string tokenString, DateTime expiresAtUtc, string audience, } _token = tokenString; - this._expiresAtUtc = expiresAtUtc; - this._audience = audience; - this._tokenType = tokenType; + _expiresAtUtc = expiresAtUtc; + _audience = audience; + _tokenType = tokenType; } /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs index 0ec95aaf3559..f34545641952 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs @@ -29,7 +29,7 @@ public class SharedAccessSignatureTokenProvider : TokenProvider internal SharedAccessSignatureTokenProvider(string sharedAccessSignature) { SharedAccessSignatureToken.Validate(sharedAccessSignature); - this._sharedAccessSignature = sharedAccessSignature; + _sharedAccessSignature = sharedAccessSignature; } internal SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TokenScope tokenScope = TokenScope.Entity) @@ -74,12 +74,12 @@ protected SharedAccessSignatureTokenProvider(string keyName, string sharedAccess Resources.ArgumentStringTooBig.FormatForUser(nameof(sharedAccessKey), SharedAccessSignatureToken.MaxKeyLength)); } - this._keyName = keyName; - this._tokenTimeToLive = tokenTimeToLive; + _keyName = keyName; + _tokenTimeToLive = tokenTimeToLive; _encodedSharedAccessKey = customKeyEncoder != null ? customKeyEncoder(sharedAccessKey) : MessagingTokenProviderKeyEncoder(sharedAccessKey); - this._tokenScope = tokenScope; + _tokenScope = tokenScope; } /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs index 3d1336902fbe..7537771207c1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs @@ -19,8 +19,8 @@ internal sealed class TokenProviderAdapter : ICbsTokenProvider public TokenProviderAdapter(ITokenProvider tokenProvider, TimeSpan operationTimeout) { Debug.Assert(tokenProvider != null, "tokenProvider cannot be null"); - this._tokenProvider = tokenProvider; - this._operationTimeout = operationTimeout; + _tokenProvider = tokenProvider; + _operationTimeout = operationTimeout; } public async Task GetTokenAsync(Uri namespaceAddress, string appliesTo, string[] requiredClaims) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs index 00b266ec6b00..e312bd21f7ba 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs @@ -32,8 +32,8 @@ internal class ServiceBusDiagnosticSource public ServiceBusDiagnosticSource(string entityPath, Uri endpoint) { - this._entityPath = entityPath; - this._endpoint = endpoint; + _entityPath = entityPath; + _endpoint = endpoint; } public static bool IsEnabled() diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs index e770ef03b53a..6f5b7be060c7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs @@ -20,7 +20,7 @@ public SessionPumpHost(string clientId, ReceiveMode receiveMode, ISessionClient ClientId = clientId; ReceiveMode = receiveMode; SessionClient = sessionClient; - this._endpoint = endpoint; + _endpoint = endpoint; } private ReceiveMode ReceiveMode { get; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs index a930fc505cdc..13b2b721f90b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs @@ -30,16 +30,16 @@ public SessionReceivePump(string clientId, Uri endpoint, CancellationToken token) { - this._client = client ?? throw new ArgumentException(nameof(client)); - this._clientId = clientId; + _client = client ?? throw new ArgumentException(nameof(client)); + _clientId = clientId; ReceiveMode = receiveMode; - this._sessionHandlerOptions = sessionHandlerOptions; + _sessionHandlerOptions = sessionHandlerOptions; _userOnSessionCallback = callback; - this._endpoint = endpoint.Authority; + _endpoint = endpoint.Authority; _entityPath = client.EntityPath; _pumpCancellationToken = token; - _maxConcurrentSessionsSemaphoreSlim = new SemaphoreSlim(this._sessionHandlerOptions.MaxConcurrentSessions); - _maxPendingAcceptSessionsSemaphoreSlim = new SemaphoreSlim(this._sessionHandlerOptions.MaxConcurrentAcceptSessionCalls); + _maxConcurrentSessionsSemaphoreSlim = new SemaphoreSlim(_sessionHandlerOptions.MaxConcurrentSessions); + _maxPendingAcceptSessionsSemaphoreSlim = new SemaphoreSlim(_sessionHandlerOptions.MaxConcurrentAcceptSessionCalls); _diagnosticSource = new ServiceBusDiagnosticSource(client.EntityPath, endpoint); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs index 49285de9fb40..4a3fd52e440c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs @@ -16,7 +16,7 @@ private class FakeDiagnosticSourceWriteObserver : IObserver> writeCallback) { - this._writeCallback = writeCallback; + _writeCallback = writeCallback; } public void OnCompleted() @@ -39,7 +39,7 @@ public void OnNext(KeyValuePair value) public FakeDiagnosticListener(Action> writeCallback) { - this._writeCallback = writeCallback; + _writeCallback = writeCallback; } public void OnCompleted() @@ -65,12 +65,12 @@ public void Enable() public void Enable(Func writeObserverEnabled) { - this._writeObserverEnabled = (name, arg1, arg2) => writeObserverEnabled(name); + _writeObserverEnabled = (name, arg1, arg2) => writeObserverEnabled(name); } public void Enable(Func writeObserverEnabled) { - this._writeObserverEnabled = (name, arg1, arg2) => writeObserverEnabled(name, arg1, arg2); + _writeObserverEnabled = (name, arg1, arg2) => writeObserverEnabled(name, arg1, arg2); } public void Disable() diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs index ec421e318c38..62f19a06d6b7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs @@ -32,10 +32,10 @@ public TestSessionHandler( MessageSender sender, SessionPumpHost sessionPumpHost) { - this._receiveMode = receiveMode; - this._sessionHandlerOptions = sessionHandlerOptions; - this._sender = sender; - this._sessionPumpHost = sessionPumpHost; + _receiveMode = receiveMode; + _sessionHandlerOptions = sessionHandlerOptions; + _sender = sender; + _sessionPumpHost = sessionPumpHost; _sessionMessageMap = new ConcurrentDictionary(); } From c342da5e5701068c8bc69b7605e8c9ab5eeb27f5 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:56:47 -0400 Subject: [PATCH 22/82] Removed redundant semicolon --- .../tests/MessageInterop/MessageInterOpTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs index 86dfc9a9f37e..e9d60a3ecac0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs @@ -45,7 +45,7 @@ private Message GetBrokeredMessage(XmlObjectSerializer serializer, TestBook book memoryStream.Flush(); memoryStream.Position = 0; payload = memoryStream.ToArray(); - }; + } return new Message(payload); } From af9f2b48dac56834e869e7e2c407169d87bbc5ac Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:57:28 -0400 Subject: [PATCH 23/82] Removed unused values --- .../src/Primitives/SharedAccessSignatureToken.cs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs index 0ebac7391ebf..468a8db5ab51 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs @@ -45,26 +45,22 @@ internal static void Validate(string sharedAccessSignature) IDictionary parsedFields = ExtractFieldValues(sharedAccessSignature); - string signature; - if (!parsedFields.TryGetValue(Signature, out signature)) + if (!parsedFields.TryGetValue(Signature, out _)) { throw new ArgumentNullException(Signature); } - string expiry; - if (!parsedFields.TryGetValue(SignedExpiry, out expiry)) + if (!parsedFields.TryGetValue(SignedExpiry, out _)) { throw new ArgumentNullException(SignedExpiry); } - string keyName; - if (!parsedFields.TryGetValue(SignedKeyName, out keyName)) + if (!parsedFields.TryGetValue(SignedKeyName, out _)) { throw new ArgumentNullException(SignedKeyName); } - string encodedAudience; - if (!parsedFields.TryGetValue(SignedResource, out encodedAudience)) + if (!parsedFields.TryGetValue(SignedResource, out _)) { throw new ArgumentNullException(SignedResource); } From d79feb2b09712e973875906267c3432792c953df Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:58:07 -0400 Subject: [PATCH 24/82] Used var throughout system --- .../src/Amqp/ActiveClientLinkManager.cs | 2 +- .../src/Amqp/AmqpExceptionHelper.cs | 6 +-- .../src/Amqp/AmqpLinkCreator.cs | 2 +- .../src/Amqp/AmqpMessageConverter.cs | 6 +-- .../src/Amqp/AmqpTransactionEnlistment.cs | 4 +- .../src/Amqp/AmqpTransactionManager.cs | 2 +- .../src/Core/MessageReceiver.cs | 50 +++++++++---------- .../src/Core/MessageSender.cs | 24 ++++----- .../src/EntityNameHelper.cs | 2 +- .../MessageDiagnosticsExtensions.cs | 10 ++-- .../src/Filters/CorrelationFilter.cs | 6 +-- .../src/Filters/RuleDescription.cs | 2 +- .../src/Filters/RuleDescriptionExtensions.cs | 2 +- .../src/Filters/XmlObjectConvertor.cs | 2 +- .../src/Management/AuthorizationRules.cs | 6 +-- .../src/Management/ManagementClient.cs | 10 ++-- .../SharedAccessAuthorizationRule.cs | 12 ++--- .../src/Management/SubscriptionDescription.cs | 2 +- .../Management/TopicDescriptionExtensions.cs | 2 +- .../src/MessageReceivePump.cs | 2 +- .../src/MessageSession.cs | 6 +-- .../ManagedIdentityTokenProvider.cs | 2 +- .../Primitives/SharedAccessSignatureToken.cs | 18 +++---- .../SharedAccessSignatureTokenProvider.cs | 16 +++--- .../src/RetryExponential.cs | 4 +- .../src/ServiceBusDiagnosticsSource.cs | 10 ++-- .../src/SessionClient.cs | 4 +- .../src/SessionReceivePump.cs | 4 +- .../src/SubscriptionClient.cs | 12 ++--- .../tests/Diagnostics/DiagnosticsTests.cs | 10 ++-- .../QueueClientDiagnosticsTests.cs | 12 ++--- .../Diagnostics/SessionDiagnosticsTests.cs | 2 +- .../tests/Management/ManagementClientTests.cs | 2 +- .../MessageInteropEnd2EndTests.cs | 2 +- .../tests/SenderReceiverTests.cs | 6 +-- .../tests/TestSessionHandler.cs | 2 +- .../tests/TokenProviderTests.cs | 2 +- .../tests/TransactionTests.cs | 26 +++++----- 38 files changed, 147 insertions(+), 147 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs index b2926251c878..fad2c72c579c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs @@ -83,7 +83,7 @@ private async Task RenewCbsTokenAsync(ActiveClientLinkObject activeClientLinkObj try { var cbsLink = activeClientLinkObject.Connection.Extensions.Find() ?? new AmqpCbsLink(activeClientLinkObject.Connection); - DateTime cbsTokenExpiresAtUtc = DateTime.MaxValue; + var cbsTokenExpiresAtUtc = DateTime.MaxValue; foreach (var resource in activeClientLinkObject.Audience) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs index 140438b7cdce..6219c82a8567 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpExceptionHelper.cs @@ -42,7 +42,7 @@ internal static class AmqpExceptionHelper public static AmqpSymbol GetResponseErrorCondition(AmqpMessage response, AmqpResponseStatusCode statusCode) { - object condition = response.ApplicationProperties.Map[ManagementConstants.Response.ErrorCondition]; + var condition = response.ApplicationProperties.Map[ManagementConstants.Response.ErrorCondition]; if (condition != null) { return (AmqpSymbol)condition; @@ -63,7 +63,7 @@ public static AmqpSymbol GetResponseErrorCondition(AmqpMessage response, AmqpRes public static AmqpResponseStatusCode GetResponseStatusCode(this AmqpMessage responseMessage) { var amqpResponseStatusCode = AmqpResponseStatusCode.Unused; - object statusCodeValue = responseMessage?.ApplicationProperties.Map[ManagementConstants.Response.StatusCode]; + var statusCodeValue = responseMessage?.ApplicationProperties.Map[ManagementConstants.Response.StatusCode]; if (statusCodeValue is int && Enum.IsDefined(typeof(AmqpResponseStatusCode), statusCodeValue)) { amqpResponseStatusCode = (AmqpResponseStatusCode)statusCodeValue; @@ -74,7 +74,7 @@ public static AmqpResponseStatusCode GetResponseStatusCode(this AmqpMessage resp public static Exception ToMessagingContractException(this AmqpMessage responseMessage, AmqpResponseStatusCode statusCode) { - AmqpSymbol errorCondition = GetResponseErrorCondition(responseMessage, statusCode); + var errorCondition = GetResponseErrorCondition(responseMessage, statusCode); var statusDescription = responseMessage.ApplicationProperties.Map[ManagementConstants.Response.StatusDescription] as string ?? errorCondition.Value; return ToMessagingContractException(errorCondition.Value, statusDescription); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs index cbf82406d5c5..49937e4def93 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs @@ -43,7 +43,7 @@ public async Task> CreateAndOpenAmqpLinkAsync() // Authenticate over CBS var cbsLink = amqpConnection.Extensions.Find(); - DateTime cbsTokenExpiresAtUtc = DateTime.MaxValue; + var cbsTokenExpiresAtUtc = DateTime.MaxValue; foreach (var resource in _audience) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index f23f2f7a368b..968eb4e77267 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -569,7 +569,7 @@ private static bool TryGetNetObjectFromAmqpObject(object amqpObject, MappingType } else if (amqpObject is ArraySegment amqpObjectAsArraySegment) { - ArraySegment binValue = amqpObjectAsArraySegment; + var binValue = amqpObjectAsArraySegment; if (binValue.Count == binValue.Array.Length) { netObject = binValue.Array; @@ -645,9 +645,9 @@ private static ArraySegment StreamToBytes(Stream stream) private static Data ToData(AmqpMessage message) { - ArraySegment[] payload = message.GetPayload(); + var payload = message.GetPayload(); var buffer = new BufferListStream(payload); - ArraySegment value = buffer.ReadBytes((int)buffer.Length); + var value = buffer.ReadBytes((int)buffer.Length); return new Data { Value = value }; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs index db43e082751e..8d8b8077e82d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs @@ -73,7 +73,7 @@ private async Task SinglePhaseCommitAsync(SinglePhaseEnlistment singlePhaseEnlis } catch (Exception e) { - Exception exception = AmqpExceptionHelper.GetClientException(e); + var exception = AmqpExceptionHelper.GetClientException(e); MessagingEventSource.Log.AmqpTransactionDischargeException(_transactionId, AmqpTransactionId, exception); singlePhaseEnlistment.InDoubt(exception); } @@ -98,7 +98,7 @@ private async Task RollbackAsync(SinglePhaseEnlistment singlePhaseEnlistment) } catch (Exception e) { - Exception exception = AmqpExceptionHelper.GetClientException(e); + var exception = AmqpExceptionHelper.GetClientException(e); MessagingEventSource.Log.AmqpTransactionDischargeException(_transactionId, AmqpTransactionId, exception); singlePhaseEnlistment.Aborted(exception); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs index 8bce689fa5c4..1565aa5bdb3d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionManager.cs @@ -24,7 +24,7 @@ public async Task> EnlistAsync( throw new InvalidOperationException($"The only supported IsolationLevel is {nameof(IsolationLevel.Serializable)}"); } - string transactionId = transaction.TransactionInformation.LocalIdentifier; + var transactionId = transaction.TransactionInformation.LocalIdentifier; AmqpTransactionEnlistment transactionEnlistment; lock (_syncRoot) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index 91659aab7d77..f11f430a4018 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -362,8 +362,8 @@ public async Task> ReceiveAsync(int maxMessageCount, TimeSpan ope MessagingEventSource.Log.MessageReceiveStart(ClientId, maxMessageCount); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.ReceiveStart(maxMessageCount) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.ReceiveStart(maxMessageCount) : null; Task receiveTask = null; IList unprocessedMessageList = null; @@ -445,8 +445,8 @@ public async Task> ReceiveDeferredMessageAsync(IEnumerable MessagingEventSource.Log.MessageReceiveDeferredMessageStart(ClientId, sequenceNumberList.Length, sequenceNumberList); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.ReceiveDeferredStart(sequenceNumberList) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.ReceiveDeferredStart(sequenceNumberList) : null; Task receiveTask = null; IList messages = null; @@ -516,8 +516,8 @@ public async Task CompleteAsync(IEnumerable lockTokens) } MessagingEventSource.Log.MessageCompleteStart(ClientId, lockTokenList.Count, lockTokenList); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.CompleteStart(lockTokenList) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.CompleteStart(lockTokenList) : null; Task completeTask = null; try @@ -561,8 +561,8 @@ public async Task AbandonAsync(string lockToken, IDictionary pro ThrowIfNotPeekLockMode(); MessagingEventSource.Log.MessageAbandonStart(ClientId, 1, lockToken); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("Abandon", lockToken) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("Abandon", lockToken) : null; Task abandonTask = null; try @@ -607,8 +607,8 @@ public async Task DeferAsync(string lockToken, IDictionary prope ThrowIfNotPeekLockMode(); MessagingEventSource.Log.MessageDeferStart(ClientId, 1, lockToken); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("Defer", lockToken) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("Defer", lockToken) : null; Task deferTask = null; try @@ -652,8 +652,8 @@ public async Task DeadLetterAsync(string lockToken, IDictionary ThrowIfNotPeekLockMode(); MessagingEventSource.Log.MessageDeadLetterStart(ClientId, 1, lockToken); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; Task deadLetterTask = null; try @@ -698,8 +698,8 @@ public async Task DeadLetterAsync(string lockToken, string deadLetterReason, str ThrowIfNotPeekLockMode(); MessagingEventSource.Log.MessageDeadLetterStart(ClientId, 1, lockToken); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; Task deadLetterTask = null; try @@ -759,8 +759,8 @@ public async Task RenewLockAsync(string lockToken) ThrowIfNotPeekLockMode(); MessagingEventSource.Log.MessageRenewLockStart(ClientId, 1, lockToken); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.RenewLockStart(lockToken) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.RenewLockStart(lockToken) : null; Task renewTask = null; var lockedUntilUtc = DateTime.MinValue; @@ -842,8 +842,8 @@ public async Task> PeekBySequenceNumberAsync(long fromSequenceNum IList messages = null; MessagingEventSource.Log.MessagePeekStart(ClientId, fromSequenceNumber, messageCount); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.PeekStart(fromSequenceNumber, messageCount) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.PeekStart(fromSequenceNumber, messageCount) : null; Task peekTask = null; try @@ -973,7 +973,7 @@ internal async Task ExecuteRequestResponseAsync(AmqpRequest var timeoutHelper = new TimeoutHelper(OperationTimeout, true); - ArraySegment transactionId = AmqpConstants.NullBinary; + var transactionId = AmqpConstants.NullBinary; var ambientTransaction = Transaction.Current; if (ambientTransaction != null) { @@ -1099,7 +1099,7 @@ protected virtual async Task> OnPeekAsync(long fromSequenceNumber { Message message = null; var messageList = amqpResponseMessage.GetListValue(ManagementConstants.Properties.Messages); - foreach (AmqpMap entry in messageList) + foreach (var entry in messageList) { var payload = (ArraySegment)entry[ManagementConstants.Properties.Message]; var amqpMessage = AmqpMessage.CreateAmqpStreamMessage(new BufferListStream(new[] { payload }), true); @@ -1363,12 +1363,12 @@ private async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome ou } var timeoutHelper = new TimeoutHelper(OperationTimeout, true); - List> deliveryTags = ConvertLockTokensToDeliveryTags(lockTokens); + var deliveryTags = ConvertLockTokensToDeliveryTags(lockTokens); ReceivingAmqpLink receiveLink = null; try { - ArraySegment transactionId = AmqpConstants.NullBinary; + var transactionId = AmqpConstants.NullBinary; var ambientTransaction = Transaction.Current; if (ambientTransaction != null) { @@ -1383,7 +1383,7 @@ private async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome ou var disposeMessageTasks = new Task[deliveryTags.Count]; var i = 0; - foreach (ArraySegment deliveryTag in deliveryTags) + foreach (var deliveryTag in deliveryTags) { disposeMessageTasks[i++] = Task.Factory.FromAsync( (c, s) => receiveLink.BeginDisposeMessage(deliveryTag, transactionId, outcome, true, timeoutHelper.RemainingTime(), c, s), @@ -1533,7 +1533,7 @@ private async Task CreateLinkAsync(TimeSpan timeout) amqpLinkSettings, ClientId); - Tuple linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); + var linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); var receivingAmqpLink = (ReceivingAmqpLink) linkDetails.Item1; var activeSendReceiveClientLink = new ActiveSendReceiveClientLink( @@ -1635,7 +1635,7 @@ private Outcome GetDeferOutcome(IDictionary propertiesToModify) private Outcome GetModifiedOutcome(IDictionary propertiesToModify, bool undeliverableHere) { - Modified modified = new Modified(); + var modified = new Modified(); if (undeliverableHere) { modified.UndeliverableHere = true; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs index 8e9910753e30..affb91d54218 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs @@ -253,8 +253,8 @@ public async Task SendAsync(IList messageList) MessagingEventSource.Log.MessageSendStart(ClientId, count); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.SendStart(messageList) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.SendStart(messageList) : null; Task sendTask = null; try @@ -314,8 +314,8 @@ public async Task ScheduleMessageAsync(Message message, DateTimeOffset sch MessagingEventSource.Log.ScheduleMessageStart(ClientId, scheduleEnqueueTimeUtc); long result = 0; - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.ScheduleStart(message, scheduleEnqueueTimeUtc) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.ScheduleStart(message, scheduleEnqueueTimeUtc) : null; Task scheduleTask = null; try @@ -362,8 +362,8 @@ public async Task CancelScheduledMessageAsync(long sequenceNumber) MessagingEventSource.Log.CancelScheduledMessageStart(ClientId, sequenceNumber); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.CancelStart(sequenceNumber) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.CancelStart(sequenceNumber) : null; Task cancelTask = null; try @@ -431,7 +431,7 @@ internal async Task ExecuteRequestResponseAsync(AmqpRequest var amqpMessage = amqpRequestMessage.AmqpMessage; var timeoutHelper = new TimeoutHelper(OperationTimeout, true); - ArraySegment transactionId = AmqpConstants.NullBinary; + var transactionId = AmqpConstants.NullBinary; var ambientTransaction = Transaction.Current; if (ambientTransaction != null) { @@ -543,7 +543,7 @@ private async Task OnSendAsync(IList messageList) SendingAmqpLink amqpLink = null; try { - ArraySegment transactionId = AmqpConstants.NullBinary; + var transactionId = AmqpConstants.NullBinary; var ambientTransaction = Transaction.Current; if (ambientTransaction != null) { @@ -596,9 +596,9 @@ private async Task OnScheduleMessageAsync(Message message) request.AmqpMessage.ApplicationProperties.Map[ManagementConstants.Request.AssociatedLinkName] = sendLink.Name; } - ArraySegment[] payload = amqpMessage.GetPayload(); + var payload = amqpMessage.GetPayload(); var buffer = new BufferListStream(payload); - ArraySegment value = buffer.ReadBytes((int)buffer.Length); + var value = buffer.ReadBytes((int)buffer.Length); var entry = new AmqpMap(); { @@ -711,7 +711,7 @@ private async Task CreateLinkAsync(TimeSpan timeout) string[] claims = {ClaimConstants.Send}; var amqpSendReceiveLinkCreator = new AmqpSendReceiveLinkCreator(SendingLinkDestination, ServiceBusConnection, endpointUri, audience, claims, CbsTokenProvider, amqpLinkSettings, ClientId); - Tuple linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); + var linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); var sendingAmqpLink = (SendingAmqpLink) linkDetails.Item1; var activeSendReceiveClientLink = new ActiveSendReceiveClientLink( @@ -758,7 +758,7 @@ private async Task CreateRequestResponseLinkAsync(TimeS amqpLinkSettings, ClientId); - Tuple linkDetails = + var linkDetails = await amqpRequestResponseLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); var requestResponseAmqpLink = (RequestResponseAmqpLink) linkDetails.Item1; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/EntityNameHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/EntityNameHelper.cs index 551d19beba86..a40991e0d6b2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/EntityNameHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/EntityNameHelper.cs @@ -134,7 +134,7 @@ private static string GetPathWithoutBaseUri(string entityName) // To ensure relative queue paths are correctly rejected on these platforms, // an additional check using IsWellFormedOriginalString() is made here. // See https://github.com/dotnet/corefx/issues/22098 for more information. - if (Uri.TryCreate(entityName, UriKind.Absolute, out Uri uriValue) && + if (Uri.TryCreate(entityName, UriKind.Absolute, out var uriValue) && uriValue.IsWellFormedOriginalString()) { entityName = uriValue.PathAndQuery; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageDiagnosticsExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageDiagnosticsExtensions.cs index 951fd8c2247e..76110bbbbff5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageDiagnosticsExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageDiagnosticsExtensions.cs @@ -75,7 +75,7 @@ public static Activity ExtractActivity(this Message message, string activityName var activity = new Activity(activityName); - if (TryExtractId(message, out string id)) + if (TryExtractId(message, out var id)) { activity.SetParentId(id); @@ -95,7 +95,7 @@ internal static bool TryExtractId(this Message message, out string id) { id = null; if (message.UserProperties.TryGetValue(ServiceBusDiagnosticSource.ActivityIdPropertyName, - out object requestId)) + out var requestId)) { var tmp = requestId as string; if (tmp != null && tmp.Trim().Length > 0) @@ -114,9 +114,9 @@ internal static bool TryExtractContext(this Message message, out IList>(); - foreach (string item in ctxList) + foreach (var item in ctxList) { var kvp = item.Split('='); if (kvp.Length == 2) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs index 6d12ca7e5a2a..428cb8718a9f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs @@ -173,8 +173,8 @@ public override string ToString() foreach (var pair in Properties) { - string propertyName = pair.Key; - object propertyValue = pair.Value; + var propertyName = pair.Key; + var propertyValue = pair.Value; AppendPropertyExpression(ref isFirstExpression, stringBuilder, propertyName, propertyValue); } @@ -201,7 +201,7 @@ private void AppendPropertyExpression(ref bool firstExpression, StringBuilder bu public override int GetHashCode() { - int hash = 13; + var hash = 13; unchecked { hash = (hash * 7) + CorrelationId?.GetHashCode() ?? 0; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs index 53cba0255190..95afde0bb467 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs @@ -101,7 +101,7 @@ internal DateTime CreatedAt public override int GetHashCode() { - int hash = 13; + var hash = 13; unchecked { hash = (hash * 7) + _filter?.GetHashCode() ?? 0; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs index 348df2c358bb..f0b20ec742ef 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs @@ -131,7 +131,7 @@ private static RuleDescription ParseFromEntryElement(XElement xEntry) public static XDocument Serialize(this RuleDescription description) { - XDocument doc = new XDocument( + var doc = new XDocument( new XElement(XName.Get("entry", ManagementClientConstants.AtomNamespace), new XElement(XName.Get("content", ManagementClientConstants.AtomNamespace), new XAttribute("type", "application/xml"), diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/XmlObjectConvertor.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/XmlObjectConvertor.cs index 22b465809bdb..236f63aec441 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/XmlObjectConvertor.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/XmlObjectConvertor.cs @@ -56,7 +56,7 @@ internal static object ParseValueObject(XElement element) internal static XElement SerializeObject(object value) { var prefix = "l28"; - string type = prefix + ':'; + var type = prefix + ':'; if (value is string) { type += "string"; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs index d506bc4e2c0e..bc4195c3d127 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs @@ -29,7 +29,7 @@ internal static AuthorizationRules ParseFromXElement(XElement xElement) public override int GetHashCode() { - int hash = 7; + var hash = 7; unchecked { foreach (var rule in this) @@ -55,12 +55,12 @@ public bool Equals(AuthorizationRules other) } var cnt = new Dictionary(); - foreach (AuthorizationRule rule in this) + foreach (var rule in this) { cnt[rule.KeyName] = rule; } - foreach (AuthorizationRule otherRule in other) + foreach (var otherRule in other) { if (!cnt.TryGetValue(otherRule.KeyName, out var rule) || !rule.Equals(otherRule)) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs index e9d2b185b864..bf3e5fe6635a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs @@ -60,17 +60,17 @@ public ManagementClient(ServiceBusConnectionStringBuilder connectionStringBuilde public static HttpRequestMessage CloneRequest(HttpRequestMessage req) { - HttpRequestMessage clone = new HttpRequestMessage(req.Method, req.RequestUri); + var clone = new HttpRequestMessage(req.Method, req.RequestUri); clone.Content = req.Content; clone.Version = req.Version; - foreach (KeyValuePair prop in req.Properties) + foreach (var prop in req.Properties) { clone.Properties.Add(prop); } - foreach (KeyValuePair> header in req.Headers) + foreach (var header in req.Headers) { clone.Headers.TryAddWithoutValidation(header.Key, header.Value); } @@ -1128,7 +1128,7 @@ private async Task GetEntity(string path, string query, bool enrich, Can }.Uri; var request = new HttpRequestMessage(HttpMethod.Get, uri); - HttpResponseMessage response = await SendHttpRequest(request, cancellationToken).ConfigureAwait(false); + var response = await SendHttpRequest(request, cancellationToken).ConfigureAwait(false); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); MessagingEventSource.Log.ManagementOperationEnd(_clientId, nameof(GetEntity), $"path:{path},query:{query},enrich:{enrich}"); @@ -1171,7 +1171,7 @@ private async Task PutEntity(string path, string requestBody, bool isUpd request.Headers.Add(ManagementClientConstants.ServiceBusDlqSupplementaryAuthorizationHeaderName, token); } - HttpResponseMessage response = await SendHttpRequest(request, cancellationToken).ConfigureAwait(false); + var response = await SendHttpRequest(request, cancellationToken).ConfigureAwait(false); var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); MessagingEventSource.Log.ManagementOperationEnd(_clientId, nameof(PutEntity), $"path:{path},isUpdate:{isUpdate}"); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs index a21d94f6d34e..c6afeb1489cd 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs @@ -153,7 +153,7 @@ public override List Rights throw new ArgumentException($"Rights cannot be null, empty or greater than {ManagementClientConstants.SupportedClaimsCount}"); } - HashSet dedupedAccessRights = new HashSet(value); + var dedupedAccessRights = new HashSet(value); if (value.Count != dedupedAccessRights.Count) { throw new ArgumentException("Access rights on an authorization rule must be unique"); @@ -171,7 +171,7 @@ public override List Rights /// Returns the hash code for this instance. public override int GetHashCode() { - int hash = 13; + var hash = 13; unchecked { hash = (hash * 7) + KeyName?.GetHashCode() ?? 0; @@ -199,7 +199,7 @@ public override bool Equals(AuthorizationRule other) return false; } - SharedAccessAuthorizationRule comparand = (SharedAccessAuthorizationRule)other; + var comparand = (SharedAccessAuthorizationRule)other; if (!string.Equals(KeyName, comparand.KeyName, StringComparison.OrdinalIgnoreCase) || !string.Equals(PrimaryKey, comparand.PrimaryKey, StringComparison.Ordinal) || !string.Equals(SecondaryKey, comparand.SecondaryKey, StringComparison.Ordinal)) @@ -215,7 +215,7 @@ public override bool Equals(AuthorizationRule other) if (Rights != null && comparand.Rights != null) { - HashSet thisRights = new HashSet(Rights); + var thisRights = new HashSet(Rights); if (comparand.Rights.Count != thisRights.Count) { return false; @@ -250,7 +250,7 @@ public override bool Equals(AuthorizationRule other) /// Generates the random key for the authorization rule. private static string GenerateRandomKey() { - byte[] key256 = new byte[32]; + var key256 = new byte[32]; using (var rngCryptoServiceProvider = new RNGCryptoServiceProvider()) { rngCryptoServiceProvider.GetBytes(key256); @@ -311,7 +311,7 @@ private static bool CheckBase64(string base64EncodedString) internal override XElement Serialize() { - XElement rule = new XElement( + var rule = new XElement( XName.Get("AuthorizationRule", ManagementClientConstants.ServiceBusNamespace), new XAttribute(XName.Get("type", ManagementClientConstants.XmlSchemaInstanceNamespace), nameof(SharedAccessAuthorizationRule)), new XElement(XName.Get("ClaimType", ManagementClientConstants.ServiceBusNamespace), ClaimType), diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs index f5deb1014141..8aa9385b0b9a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -261,7 +261,7 @@ public string UserMetadata public override int GetHashCode() { - int hash = 7; + var hash = 7; unchecked { hash = (hash * 7) + TopicPath?.GetHashCode() ?? 0; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs index 2aca66feca67..53f09cc15770 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs @@ -159,7 +159,7 @@ public static XDocument Serialize(this TopicDescription description) topicDescriptionElements.AddRange(description.UnknownProperties); } - XDocument doc = new XDocument( + var doc = new XDocument( new XElement(XName.Get("entry", ManagementClientConstants.AtomNamespace), new XElement(XName.Get("content", ManagementClientConstants.AtomNamespace), new XAttribute("type", "application/xml"), diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs index 34d853458ad5..c3a046a32ff5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs @@ -126,7 +126,7 @@ private async Task MessagePumpTaskAsync() private async Task MessageDispatchTaskInstrumented(Message message) { - Activity activity = _diagnosticSource.ProcessStart(message); + var activity = _diagnosticSource.ProcessStart(message); Task processTask = null; try { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs index 2b153ac6987a..1f8b86827fa1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs @@ -187,7 +187,7 @@ protected override void ThrowIfClosed() private async Task OnGetStateInstrumentedAsync() { - Activity activity = _diagnosticSource.GetSessionStateStart(SessionId); + var activity = _diagnosticSource.GetSessionStateStart(SessionId); Task getStateTask = null; byte[] state = null; @@ -210,7 +210,7 @@ private async Task OnGetStateInstrumentedAsync() private async Task OnSetStateInstrumentedAsync(byte[] sessionState) { - Activity activity = _diagnosticSource.SetSessionStateStart(SessionId, sessionState); + var activity = _diagnosticSource.SetSessionStateStart(SessionId, sessionState); Task setStateTask = null; try @@ -231,7 +231,7 @@ private async Task OnSetStateInstrumentedAsync(byte[] sessionState) private async Task OnRenewSessionLockInstrumentedAsync() { - Activity activity = _diagnosticSource.RenewSessionLockStart(SessionId); + var activity = _diagnosticSource.RenewSessionLockStart(SessionId); Task renewTask = null; try diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs index 4968133e4894..32e636b3c8d1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs @@ -36,7 +36,7 @@ public ManagedIdentityTokenProvider(AzureServiceTokenProvider azureServiceTokenP /// public async override Task GetTokenAsync(string appliesTo, TimeSpan timeout) { - string accessToken = await _azureServiceTokenProvider.GetAccessTokenAsync(Constants.AadServiceBusAudience).ConfigureAwait(false); + var accessToken = await _azureServiceTokenProvider.GetAccessTokenAsync(Constants.AadServiceBusAudience).ConfigureAwait(false); return new JsonSecurityToken(accessToken, appliesTo); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs index 468a8db5ab51..98b0898d83c6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs @@ -43,7 +43,7 @@ internal static void Validate(string sharedAccessSignature) throw new ArgumentNullException(nameof(sharedAccessSignature)); } - IDictionary parsedFields = ExtractFieldValues(sharedAccessSignature); + var parsedFields = ExtractFieldValues(sharedAccessSignature); if (!parsedFields.TryGetValue(Signature, out _)) { @@ -68,7 +68,7 @@ internal static void Validate(string sharedAccessSignature) private static IDictionary ExtractFieldValues(string sharedAccessSignature) { - string[] tokenLines = sharedAccessSignature.Split(); + var tokenLines = sharedAccessSignature.Split(); if (!string.Equals(tokenLines[0].Trim(), SharedAccessSignature, StringComparison.OrdinalIgnoreCase) || tokenLines.Length != 2) { @@ -76,13 +76,13 @@ private static IDictionary ExtractFieldValues(string sharedAcces } IDictionary parsedFields = new Dictionary(StringComparer.OrdinalIgnoreCase); - string[] tokenFields = tokenLines[1].Trim().Split(new[] { SasPairSeparator }, StringSplitOptions.None); + var tokenFields = tokenLines[1].Trim().Split(new[] { SasPairSeparator }, StringSplitOptions.None); - foreach (string tokenField in tokenFields) + foreach (var tokenField in tokenFields) { if (tokenField != string.Empty) { - string[] fieldParts = tokenField.Split(new[] { SasKeyValueSeparator }, StringSplitOptions.None); + var fieldParts = tokenField.Split(new[] { SasKeyValueSeparator }, StringSplitOptions.None); if (string.Equals(fieldParts[0], SignedResource, StringComparison.OrdinalIgnoreCase)) { // We need to preserve the casing of the escape characters in the audience, @@ -101,7 +101,7 @@ private static IDictionary ExtractFieldValues(string sharedAcces private static string GetAudienceFromToken(string token) { - IDictionary decodedToken = Decode(token, Decoder, Decoder, SasKeyValueSeparator, SasPairSeparator); + var decodedToken = Decode(token, Decoder, Decoder, SasKeyValueSeparator, SasPairSeparator); if (!decodedToken.TryGetValue(SignedResourceFullFieldName, out var audience)) { throw new FormatException(Resources.TokenMissingAudience); @@ -112,7 +112,7 @@ private static string GetAudienceFromToken(string token) private static DateTime GetExpirationDateTimeUtcFromToken(string token) { - IDictionary decodedToken = Decode(token, Decoder, Decoder, SasKeyValueSeparator, SasPairSeparator); + var decodedToken = Decode(token, Decoder, Decoder, SasKeyValueSeparator, SasPairSeparator); if (!decodedToken.TryGetValue(SignedExpiry, out var expiresIn)) { throw new FormatException(Resources.TokenMissingExpiresOn); @@ -127,9 +127,9 @@ private static IDictionary Decode(string encodedString, Func dictionary = new Dictionary(); IEnumerable valueEncodedPairs = encodedString.Split(new[] { pairSeparator }, StringSplitOptions.None); - foreach (string valueEncodedPair in valueEncodedPairs) + foreach (var valueEncodedPair in valueEncodedPairs) { - string[] pair = valueEncodedPair.Split(new[] { keyValueSeparator }, StringSplitOptions.None); + var pair = valueEncodedPair.Split(new[] { keyValueSeparator }, StringSplitOptions.None); if (pair.Length != 2) { throw new FormatException(Resources.InvalidEncoding); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs index f34545641952..de202fcecd5f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs @@ -96,7 +96,7 @@ public override Task GetTokenAsync(string appliesTo, TimeSpan tim { TimeoutHelper.ThrowIfNegativeArgument(timeout); appliesTo = NormalizeAppliesTo(appliesTo); - string tokenString = BuildSignature(appliesTo); + var tokenString = BuildSignature(appliesTo); var securityToken = new SharedAccessSignatureToken(tokenString); return Task.FromResult(securityToken); } @@ -131,14 +131,14 @@ public static string BuildSignature( { // Note that target URI is not normalized because in IoT scenario it // is case sensitive. - string expiresOn = BuildExpiresOn(timeToLive); - string audienceUri = WebUtility.UrlEncode(targetUri); - List fields = new List { audienceUri, expiresOn }; + var expiresOn = BuildExpiresOn(timeToLive); + var audienceUri = WebUtility.UrlEncode(targetUri); + var fields = new List { audienceUri, expiresOn }; // Example string to be signed: // http://mynamespace.servicebus.windows.net/a/b/c?myvalue1=a // - string signature = Sign(string.Join("\n", fields), encodedSharedAccessKey); + var signature = Sign(string.Join("\n", fields), encodedSharedAccessKey); // Example returned string: // SharedAccessKeySignature @@ -154,9 +154,9 @@ public static string BuildSignature( private static string BuildExpiresOn(TimeSpan timeToLive) { - DateTime expiresOn = DateTime.UtcNow.Add(timeToLive); - TimeSpan secondsFromBaseTime = expiresOn.Subtract(Constants.EpochTime); - long seconds = Convert.ToInt64(secondsFromBaseTime.TotalSeconds, CultureInfo.InvariantCulture); + var expiresOn = DateTime.UtcNow.Add(timeToLive); + var secondsFromBaseTime = expiresOn.Subtract(Constants.EpochTime); + var seconds = Convert.ToInt64(secondsFromBaseTime.TotalSeconds, CultureInfo.InvariantCulture); return Convert.ToString(seconds, CultureInfo.InvariantCulture); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryExponential.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryExponential.cs index 34f22db9b25a..a03784128216 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryExponential.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryExponential.cs @@ -89,8 +89,8 @@ protected override bool OnShouldRetry(TimeSpan remainingTime, int currentRetryCo // - then get the interval in terms of sleep time (between min and max sleep time) // - if interval to large to fit inside remainingTime, we quit. var randomizedInterval = ConcurrentRandom.Next((int)(DeltaBackoff.TotalMilliseconds * 0.8), (int)(DeltaBackoff.TotalMilliseconds * 1.2)); - double increment = (Math.Pow(2, currentRetryCount) - 1) * randomizedInterval; - double timeToSleepMsec = Math.Min(MinimalBackoff.TotalMilliseconds + increment, MaximumBackoff.TotalMilliseconds); + var increment = (Math.Pow(2, currentRetryCount) - 1) * randomizedInterval; + var timeToSleepMsec = Math.Min(MinimalBackoff.TotalMilliseconds + increment, MaximumBackoff.TotalMilliseconds); retryInterval = TimeSpan.FromMilliseconds(timeToSleepMsec); return true; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs index e312bd21f7ba..667b4a864e1e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusDiagnosticsSource.cs @@ -46,7 +46,7 @@ public static bool IsEnabled() internal Activity SendStart(IList messageList) { - Activity activity = Start("Send", () => new + var activity = Start("Send", () => new { Messages = messageList, Entity = _entityPath, @@ -143,7 +143,7 @@ internal void ProcessSessionStop(Activity activity, IMessageSession session, Mes internal Activity ScheduleStart(Message message, DateTimeOffset scheduleEnqueueTimeUtc) { - Activity activity = Start("Schedule", () => new + var activity = Start("Schedule", () => new { Message = message, ScheduleEnqueueTimeUtc = scheduleEnqueueTimeUtc, @@ -629,7 +629,7 @@ internal void ReportException(Exception ex) private Activity Start(string operationName, Func getPayload, Action setTags) { Activity activity = null; - string activityName = BaseActivityName + operationName; + var activityName = BaseActivityName + operationName; if (DiagnosticListener.IsEnabled(activityName, _entityPath)) { activity = new Activity(activityName); @@ -699,7 +699,7 @@ private void SetRelatedOperations(Activity activity, IList messageList) var relatedTo = new List(); foreach (var message in messageList) { - if (message.TryExtractId(out string id)) + if (message.TryExtractId(out var id)) { relatedTo.Add(id); } @@ -715,7 +715,7 @@ private void SetRelatedOperations(Activity activity, IList messageList) private Activity ProcessStart(string operationName, Message message, Func getPayload, Action setTags) { Activity activity = null; - string activityName = BaseActivityName + operationName; + var activityName = BaseActivityName + operationName; if (message != null && DiagnosticListener.IsEnabled(activityName, _entityPath)) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs index 689060d99fd9..af8e1908e262 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs @@ -296,8 +296,8 @@ public async Task AcceptMessageSessionAsync(string sessionId, T PrefetchCount, sessionId); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.AcceptMessageSessionStart(sessionId) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.AcceptMessageSessionStart(sessionId) : null; Task acceptMessageSessionTask = null; var session = new MessageSession( diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs index 13b2b721f90b..2143ca858617 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs @@ -217,8 +217,8 @@ private async Task MessagePumpTaskAsync(IMessageSession session) break; } - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.ProcessSessionStart(session, message) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.ProcessSessionStart(session, message) : null; Task processTask = null; try diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs index fa0bc91c6ed4..39d3bd1757df 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs @@ -491,8 +491,8 @@ public async Task AddRuleAsync(RuleDescription description) EntityNameHelper.CheckValidRuleName(description.Name); MessagingEventSource.Log.AddRuleStart(ClientId, description.Name); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.AddRuleStart(description) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.AddRuleStart(description) : null; Task addRuleTask = null; try @@ -532,8 +532,8 @@ public async Task RemoveRuleAsync(string ruleName) } MessagingEventSource.Log.RemoveRuleStart(ClientId, ruleName); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.RemoveRuleStart(ruleName) : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.RemoveRuleStart(ruleName) : null; Task removeRuleTask = null; try @@ -568,8 +568,8 @@ public async Task> GetRulesAsync() ThrowIfClosed(); MessagingEventSource.Log.GetRulesStart(ClientId); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? _diagnosticSource.GetRulesStart() : null; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.GetRulesStart() : null; Task> getRulesTask = null; var skip = 0; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs index 938ef63d67d8..e88e7038771a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs @@ -435,7 +435,7 @@ protected void AssertTags(IList messageList, Activity activity) { Assert.Contains("MessageId", activity.Tags.Select(t => t.Key)); - string messageIdTag = activity.Tags.Single(t => t.Key == "MessageId").Value; + var messageIdTag = activity.Tags.Single(t => t.Key == "MessageId").Value; foreach (var m in messagesWithId) { Assert.Contains(m.MessageId, messageIdTag); @@ -447,7 +447,7 @@ protected void AssertTags(IList messageList, Activity activity) { Assert.Contains("SessionId", activity.Tags.Select(t => t.Key)); - string sessionIdTag = activity.Tags.Single(t => t.Key == "SessionId").Value; + var sessionIdTag = activity.Tags.Single(t => t.Key == "SessionId").Value; foreach (var m in messagesWithSessionId) { Assert.Contains(m.SessionId, sessionIdTag); @@ -501,11 +501,11 @@ protected void AssertCommonStopPayloadProperties(string entityName, object event protected T GetPropertyValueFromAnonymousTypeInstance(object obj, string propertyName, bool canValueBeNull = false) { - Type t = obj.GetType(); + var t = obj.GetType(); - PropertyInfo p = t.GetRuntimeProperty(propertyName); + var p = t.GetRuntimeProperty(propertyName); - object propertyValue = p.GetValue(obj); + var propertyValue = p.GetValue(obj); if (!canValueBeNull) { Assert.NotNull(propertyValue); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs index ca3f1f1698ba..24474419f13e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs @@ -67,7 +67,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, // message is processed, but complete happens after that // let's wat until Complete starts and ends and Process ends - int wait = 0; + var wait = 0; while (wait++ < MaxWaitSec && eventQueue.Count < 3) { await Task.Delay(TimeSpan.FromSeconds(1)); @@ -140,7 +140,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, // message is processed, but abandon happens after that // let's spin until Complete call starts and ends - int wait = 0; + var wait = 0; while (wait++ < MaxWaitSec && eventQueue.Count < 3) { await Task.Delay(TimeSpan.FromSeconds(1)); @@ -247,7 +247,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, await queueClient.InnerReceiver.ReceiveAsync(2, TimeSpan.FromSeconds(5)); - int receivedStopCount = 0; + var receivedStopCount = 0; Assert.Equal(2, eventQueue.Count); while (eventQueue.TryDequeue(out var receiveStart)) { @@ -300,8 +300,8 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, Assert.True(eventQueue.TryDequeue(out var sendStop2)); AssertSendStop(queueName, sendStop2.eventName, sendStop2.payload, sendStop2.activity, sendStop2.activity, 3); - int receivedStopCount = 0; - string relatedTo = ""; + var receivedStopCount = 0; + var relatedTo = ""; while (eventQueue.TryDequeue(out var receiveStart)) { var startCount = AssertReceiveStart(queueName, receiveStart.eventName, receiveStart.payload, receiveStart.activity, -1); @@ -532,7 +532,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, using (var listener = CreateEventListener(queueName, eventQueue)) using (SubscribeToEvents(listener)) { - Activity parentActivity = new Activity("test"); + var parentActivity = new Activity("test"); listener.Enable((name, queue, arg) => name.Contains("Schedule") || name.Contains("Cancel")); parentActivity.Start(); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs index 8743a71fd6a5..ed1000c41eaa 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs @@ -158,7 +158,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, Assert.True(eventQueue.TryDequeue(out var processStart)); AssertProcessSessionStart(queueName, processStart.eventName, processStart.payload, processStart.activity, sendStart.activity); - int wait = 0; + var wait = 0; while (wait++ < MaxWaitSec && eventQueue.Count < 1) { await Task.Delay(TimeSpan.FromSeconds(1)); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs index 5d33153a8c27..66fd9d4fda5d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs @@ -845,7 +845,7 @@ public async Task SqlFilterParamsTest() await client.CreateTopicAsync(topicName); await client.CreateSubscriptionAsync(topicName, subscriptionName); - SqlFilter sqlFilter = new SqlFilter( + var sqlFilter = new SqlFilter( "PROPERTY(@propertyName) = @stringPropertyValue " + "AND PROPERTY(intProperty) = @intPropertyValue " + "AND PROPERTY(longProperty) = @longPropertyValue " + diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs index 272c7c68689c..172362c837cb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs @@ -102,7 +102,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, internal static string GetSbConnectionString(TransportType transportType) { // Override and Create a new ConnectionString with SbmpConnection Endpoint scheme - string[] parts = TestUtility.NamespaceConnectionString.Split(':'); + var parts = TestUtility.NamespaceConnectionString.Split(':'); var sbConnectionString = "Endpoint=sb:" + parts[1]; if (transportType == TransportType.Amqp) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs index 37226c9c09fa..1131dd264874 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs @@ -244,7 +244,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, } TestUtility.Log("Waiting for maximum 10 Secs"); - bool receiverReturnedInTime = false; + var receiverReturnedInTime = false; using (var timeoutCancellationTokenSource = new CancellationTokenSource()) { @@ -329,7 +329,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, Assert.True(message.UserProperties.ContainsKey("key")); Assert.Equal("value1", message.UserProperties["key"]); - long sequenceNumber = message.SystemProperties.SequenceNumber; + var sequenceNumber = message.SystemProperties.SequenceNumber; await receiver.DeferAsync(message.SystemProperties.LockToken, new Dictionary { {"key", "value2"} @@ -456,7 +456,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: true, sessionEnabled: false, { EntityPath = queueName }; - ServiceBusConnection connection = new ServiceBusConnection(csb); + var connection = new ServiceBusConnection(csb); sender = new MessageSender(connection, queueName); messageBody = Encoding.UTF8.GetBytes("Message 2"); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs index 62f19a06d6b7..9c2be5108a9d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs @@ -79,7 +79,7 @@ public async Task VerifyRun() await Task.Delay(TimeSpan.FromSeconds(5)); } - foreach (KeyValuePair keyValuePair in _sessionMessageMap) + foreach (var keyValuePair in _sessionMessageMap) { TestUtility.Log($"Session: {keyValuePair.Key}, Messages Received in this Session: {keyValuePair.Value}"); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs index 18d75c9bf60e..38650e277ae2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs @@ -45,7 +45,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, public async Task AzureActiveDirectoryTokenProviderAuthCallbackTest() { var csb = new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString); - string testToken = @"eyJhbGciOiJIUzI1NiJ9.e30.ZRrHA1JJJW8opsbCGfG_HACGpVUMN_a9IV7pAx_Zmeo"; + var testToken = @"eyJhbGciOiJIUzI1NiJ9.e30.ZRrHA1JJJW8opsbCGfG_HACGpVUMN_a9IV7pAx_Zmeo"; var aadTokenProvider = TokenProvider.CreateAzureActiveDirectoryTokenProvider( (audience, authority, state) => diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs index cf0a821ffbd6..0b6652eca617 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs @@ -52,7 +52,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - string body = Guid.NewGuid().ToString("N"); + var body = Guid.NewGuid().ToString("N"); var message = new Message(body.GetBytes()) {PartitionKey = "pk"}; using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { @@ -87,7 +87,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - string body = Guid.NewGuid().ToString("N"); + var body = Guid.NewGuid().ToString("N"); var message = new Message(body.GetBytes()) { PartitionKey = "pk" }; using (new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { @@ -122,7 +122,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - string body = Guid.NewGuid().ToString("N"); + var body = Guid.NewGuid().ToString("N"); var message = new Message(body.GetBytes()); await sender.SendAsync(message).ConfigureAwait(false); @@ -163,7 +163,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - string body = Guid.NewGuid().ToString("N"); + var body = Guid.NewGuid().ToString("N"); var message = new Message(body.GetBytes()); await sender.SendAsync(message).ConfigureAwait(false); @@ -204,7 +204,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - string body = Guid.NewGuid().ToString("N"); + var body = Guid.NewGuid().ToString("N"); var message = new Message(body.GetBytes()) { SessionId = body @@ -260,7 +260,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - string body = Guid.NewGuid().ToString("N"); + var body = Guid.NewGuid().ToString("N"); var message = new Message(body.GetBytes()); await sender.SendAsync(message).ConfigureAwait(false); @@ -313,7 +313,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { - string body = Guid.NewGuid().ToString("N"); + var body = Guid.NewGuid().ToString("N"); var message1 = new Message((body + "1").GetBytes()) { PartitionKey = "1" @@ -325,7 +325,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, // Two send operations to different partitions. var transaction = new CommittableTransaction(); - using (TransactionScope ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)) + using (var ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)) { await sender.SendAsync(message1); @@ -350,7 +350,7 @@ await Assert.ThrowsAsync( Assert.NotNull(receivedMessage2); transaction = new CommittableTransaction(); - using (TransactionScope ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)) + using (var ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)) { await receiver.CompleteAsync(receivedMessage1.SystemProperties.LockToken); @@ -393,8 +393,8 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { - string body1 = Guid.NewGuid().ToString("N"); - string body2 = Guid.NewGuid().ToString("N"); + var body1 = Guid.NewGuid().ToString("N"); + var body2 = Guid.NewGuid().ToString("N"); var message = new Message(body1.GetBytes()); var message2 = new Message(body2.GetBytes()); await sender.SendAsync(message).ConfigureAwait(false); @@ -445,8 +445,8 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { - string body1 = Guid.NewGuid().ToString("N"); - string body2 = Guid.NewGuid().ToString("N"); + var body1 = Guid.NewGuid().ToString("N"); + var body2 = Guid.NewGuid().ToString("N"); var message = new Message(body1.GetBytes()); var message2 = new Message(body2.GetBytes()); await sender.SendAsync(message).ConfigureAwait(false); From a1157381b77912cd1c418b57cc1e8d519d9d5a5b Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 19:59:15 -0400 Subject: [PATCH 25/82] Set instantiated value to unused variable --- .../tests/Management/ManagementClientTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs index 66fd9d4fda5d..59454c2c6783 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs @@ -893,7 +893,7 @@ public async Task CorrelationFilterPropertiesTest() await client.CreateTopicAsync(topicName); await client.CreateSubscriptionAsync(topicName, subscriptionName); - new SubscriptionClient(TestUtility.NamespaceConnectionString, topicName, subscriptionName); + var _ = new SubscriptionClient(TestUtility.NamespaceConnectionString, topicName, subscriptionName); var filter = new CorrelationFilter(); filter.Properties.Add("stringKey", "stringVal"); filter.Properties.Add("intKey", 5); From 7498a30c06dac9978b36b92163cf222c38e2c9cc Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:00:48 -0400 Subject: [PATCH 26/82] Removed unnecessary imports --- .../src/Amqp/AmqpRequestResponseLinkCreator.cs | 1 - .../src/Amqp/AmqpSendReceiveLinkCreator.cs | 1 - .../Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs | 1 - .../Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs | 1 - .../Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs | 1 - sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs | 1 - .../src/Primitives/JsonSecurityToken.cs | 2 -- sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs | 1 - .../Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs | 1 - .../Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs | 1 - 10 files changed, 11 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs index 37a29515396f..65c7f145d590 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs @@ -5,7 +5,6 @@ namespace Microsoft.Azure.ServiceBus.Amqp { using System; using Microsoft.Azure.Amqp; - using Primitives; internal class AmqpRequestResponseLinkCreator : AmqpLinkCreator { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs index 2f63cd56c6f3..4b89e89d24e6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs @@ -5,7 +5,6 @@ namespace Microsoft.Azure.ServiceBus.Amqp { using System; using Microsoft.Azure.Amqp; - using Primitives; internal class AmqpSendReceiveLinkCreator : AmqpLinkCreator { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index f11f430a4018..7e6cc5129ada 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -5,7 +5,6 @@ namespace Microsoft.Azure.ServiceBus.Core { using System; using System.Collections.Generic; - using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs index affb91d54218..bfc8658e814d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs @@ -5,7 +5,6 @@ namespace Microsoft.Azure.ServiceBus.Core { using System; using System.Collections.Generic; - using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs index c3a046a32ff5..21ce043d0f0f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs @@ -4,7 +4,6 @@ namespace Microsoft.Azure.ServiceBus { using System; - using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Core; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs index 1f8b86827fa1..2ac4e4dbe6ff 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageSession.cs @@ -4,7 +4,6 @@ namespace Microsoft.Azure.ServiceBus { using System; - using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Amqp; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/JsonSecurityToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/JsonSecurityToken.cs index 8effe4ef0395..87c04931f821 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/JsonSecurityToken.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/JsonSecurityToken.cs @@ -4,8 +4,6 @@ namespace Microsoft.Azure.ServiceBus.Primitives { using System; - using System.Collections.ObjectModel; - using System.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs index af8e1908e262..4c71bbb97ad9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionClient.cs @@ -5,7 +5,6 @@ namespace Microsoft.Azure.ServiceBus { using System; using System.Collections.Generic; - using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Amqp; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs index 2143ca858617..86b126af0ffb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs @@ -4,7 +4,6 @@ namespace Microsoft.Azure.ServiceBus { using System; - using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Primitives; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs index 39d3bd1757df..823ef302add4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs @@ -7,7 +7,6 @@ namespace Microsoft.Azure.ServiceBus { using System; using System.Collections.Generic; - using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Amqp; From 17be779a12ba4bbab3f780cb39031d3738f52e86 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:01:41 -0400 Subject: [PATCH 27/82] Removed redundant constructor --- sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs index 9ba3db482f81..b0e8f4f2a6b4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs @@ -27,10 +27,6 @@ public abstract class RetryPolicy // This is a volatile copy of IsServerBusy. IsServerBusy is synchronized with a lock, whereas encounteredServerBusy is kept volatile for performance reasons. private volatile bool _encounteredServerBusy; - protected RetryPolicy() - { - } - /// /// Returns the default retry policy, . /// From f1690a150b1016495e5d08ecd668de746bc3fb78 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:03:37 -0400 Subject: [PATCH 28/82] Fixed redundant type check --- .../src/Management/SubscriptionDescription.cs | 37 +++++++++---------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs index 8aa9385b0b9a..727a7e5a576a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -279,26 +279,23 @@ public override bool Equals(object obj) public bool Equals(SubscriptionDescription otherDescription) { - if (otherDescription is SubscriptionDescription other - && SubscriptionName.Equals(other.SubscriptionName, StringComparison.OrdinalIgnoreCase) - && TopicPath.Equals(other.TopicPath, StringComparison.OrdinalIgnoreCase) - && AutoDeleteOnIdle.Equals(other.AutoDeleteOnIdle) - && DefaultMessageTimeToLive.Equals(other.DefaultMessageTimeToLive) - && EnableBatchedOperations == other.EnableBatchedOperations - && EnableDeadLetteringOnMessageExpiration == other.EnableDeadLetteringOnMessageExpiration - && EnableDeadLetteringOnFilterEvaluationExceptions == other.EnableDeadLetteringOnFilterEvaluationExceptions - && string.Equals(ForwardDeadLetteredMessagesTo, other.ForwardDeadLetteredMessagesTo, StringComparison.OrdinalIgnoreCase) - && string.Equals(ForwardTo, other.ForwardTo, StringComparison.OrdinalIgnoreCase) - && LockDuration.Equals(other.LockDuration) - && MaxDeliveryCount == other.MaxDeliveryCount - && RequiresSession.Equals(other.RequiresSession) - && Status.Equals(other.Status) - && string.Equals(_userMetadata, other._userMetadata, StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - return false; + return otherDescription != null + && SubscriptionName.Equals(otherDescription.SubscriptionName, StringComparison.OrdinalIgnoreCase) + && TopicPath.Equals(otherDescription.TopicPath, StringComparison.OrdinalIgnoreCase) + && AutoDeleteOnIdle.Equals(otherDescription.AutoDeleteOnIdle) + && DefaultMessageTimeToLive.Equals(otherDescription.DefaultMessageTimeToLive) + && EnableBatchedOperations == otherDescription.EnableBatchedOperations + && EnableDeadLetteringOnMessageExpiration == otherDescription.EnableDeadLetteringOnMessageExpiration + && EnableDeadLetteringOnFilterEvaluationExceptions == + otherDescription.EnableDeadLetteringOnFilterEvaluationExceptions + && string.Equals(ForwardDeadLetteredMessagesTo, otherDescription.ForwardDeadLetteredMessagesTo, + StringComparison.OrdinalIgnoreCase) + && string.Equals(ForwardTo, otherDescription.ForwardTo, StringComparison.OrdinalIgnoreCase) + && LockDuration.Equals(otherDescription.LockDuration) + && MaxDeliveryCount == otherDescription.MaxDeliveryCount + && RequiresSession.Equals(otherDescription.RequiresSession) + && Status.Equals(otherDescription.Status) + && string.Equals(_userMetadata, otherDescription._userMetadata, StringComparison.OrdinalIgnoreCase); } public static bool operator ==(SubscriptionDescription o1, SubscriptionDescription o2) From dddf1069127dc9a2372f00164169435d670450a6 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:04:39 -0400 Subject: [PATCH 29/82] Fixed backward parameters in ArgumentException construction --- .../src/Management/SharedAccessAuthorizationRule.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs index c6afeb1489cd..d5fca167f08c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs @@ -161,7 +161,8 @@ public override List Rights if (value.Contains(AccessRights.Manage) && value.Count != 3) { - throw new ArgumentException(nameof(Rights), "Manage permission should also include Send and Listen"); + throw new ArgumentException(@"Manage permission should also include Send and Listen", + nameof(Rights)); } _internalRights = value; From 1097d6b123f57e8188a897e5893be05d14a9daec Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:05:08 -0400 Subject: [PATCH 30/82] Removed unneeded constant --- .../Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index 968eb4e77267..668b382c4801 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -24,7 +24,6 @@ internal static class AmqpMessageConverter private const string SequenceNumberName = "x-opt-sequence-number"; private const string EnqueueSequenceNumberName = "x-opt-enqueue-sequence-number"; private const string LockedUntilName = "x-opt-locked-until"; - private const string PublisherName = "x-opt-publisher"; private const string PartitionKeyName = "x-opt-partition-key"; private const string PartitionIdName = "x-opt-partition-id"; private const string ViaPartitionKeyName = "x-opt-via-partition-key"; From 103d3e490bba0e3a257e4da0791ba15326e56603 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:05:30 -0400 Subject: [PATCH 31/82] Removed unused method --- .../tests/QueueSessionTests.cs | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs index 46f7270f375f..71e5ec1b010b 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/QueueSessionTests.cs @@ -240,25 +240,6 @@ await Assert.ThrowsAsync(async () => }); } - private async Task AcceptAndCompleteSessionsAsync(SessionClient sessionClient, string sessionId, string messageId) - { - var sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId); - if (sessionId != null) - { - Assert.True(sessionReceiver.SessionId == sessionId); - } - - var message = await sessionReceiver.ReceiveAsync(); - Assert.True(message.MessageId == messageId); - TestUtility.Log($"Received Message: {message.MessageId} from Session: {sessionReceiver.SessionId}"); - - await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken); - await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken); - TestUtility.Log($"Completed Message: {message.MessageId} for Session: {sessionReceiver.SessionId}"); - - await sessionReceiver.CloseAsync(); - } - private async Task PeekAndDeleteMessageAsync(SessionClient sessionClient, string sessionId, string messageId) { var sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId); From e911f32a994b238141f25bd31a0182a291ab8716 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:05:50 -0400 Subject: [PATCH 32/82] Removed redundant semicolon --- .../Microsoft.Azure.ServiceBus/tests/TransactionTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs index 0b6652eca617..0c73aeff5d46 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs @@ -586,7 +586,7 @@ private Task SafeCloseAllAsync(params IClientEntity[] clientEntities) async Task closeEntity(IClientEntity entity) { try { await entity.CloseAsync(); } catch {} - }; + } return Task.WhenAll(clientEntities.Select(entity => closeEntity(entity))); } From fd7b1bed47c08381326f0b4c166450b7ac7c3750 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:06:27 -0400 Subject: [PATCH 33/82] Fixed access modifier of Main method --- .../Microsoft.Azure.ServiceBus/tests/Performance/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index 78b69d67124c..4dff6f5d7459 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -17,7 +17,7 @@ internal class Program private static long _messages; - private static async Task Main(string[] args) + internal static async Task Main(string[] args) { var maxInflight = (args.Length >= 1 ? int.Parse(args[0]) : 1); Log($"Maximum inflight messages: {maxInflight}"); From 22258fa4c3ec7e7b2a29751d27ab81748315ef2b Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:07:36 -0400 Subject: [PATCH 34/82] Commented acknowledging disregarded catch --- .../Microsoft.Azure.ServiceBus/tests/TransactionTests.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs index 0c73aeff5d46..b89b870bc072 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs @@ -585,7 +585,14 @@ private Task SafeCloseAllAsync(params IClientEntity[] clientEntities) { async Task closeEntity(IClientEntity entity) { - try { await entity.CloseAsync(); } catch {} + try + { + await entity.CloseAsync(); + } + catch + { + // Ignored + } } return Task.WhenAll(clientEntities.Select(entity => closeEntity(entity))); From bc96feb8804a28462f1e59c6f2f95d59e942e853 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:08:16 -0400 Subject: [PATCH 35/82] Refactored lambda to be method group call --- .../Microsoft.Azure.ServiceBus/tests/TransactionTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs index b89b870bc072..d0e82c93938f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs @@ -595,7 +595,7 @@ async Task closeEntity(IClientEntity entity) } } - return Task.WhenAll(clientEntities.Select(entity => closeEntity(entity))); + return Task.WhenAll(clientEntities.Select(closeEntity)); } } } From 7b36bc5347145b955143182de7498ec1153af907 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:09:00 -0400 Subject: [PATCH 36/82] Removed redundant ToString calls --- .../src/Amqp/AmqpSendReceiveLinkCreator.cs | 2 +- .../tests/MessageInterop/MessageInteropEnd2EndTests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs index 4b89e89d24e6..6abd58edc68d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSendReceiveLinkCreator.cs @@ -24,7 +24,7 @@ protected override AmqpObject OnCreateAmqpLink(AmqpConnection connection, AmqpLi { amqpLink = new SendingAmqpLink(linkSettings); } - linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{amqpSession.Identifier}:{amqpLink.Identifier}:{linkSettings.Source.ToString()}:{ClientId}"; + linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{amqpSession.Identifier}:{amqpLink.Identifier}:{linkSettings.Source}:{ClientId}"; amqpLink.AttachTo(amqpSession); return amqpLink; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs index 172362c837cb..3c7c4130379b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs @@ -107,7 +107,7 @@ internal static string GetSbConnectionString(TransportType transportType) if (transportType == TransportType.Amqp) { - sbConnectionString += ';' + nameof(TransportType) + '=' + TransportType.Amqp.ToString(); + sbConnectionString += ';' + nameof(TransportType) + '=' + TransportType.Amqp; } return sbConnectionString; From ce7081ea231abe579b5f79136ef33e54af691771 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:09:15 -0400 Subject: [PATCH 37/82] Removed redundant import --- .../Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs index 9c2be5108a9d..ae50d65f337c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs @@ -7,7 +7,6 @@ namespace Microsoft.Azure.ServiceBus.UnitTests { using System; using System.Collections.Concurrent; - using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; From fddba5caa1614d4b5c3fa76a3b272f5f10717a34 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:09:46 -0400 Subject: [PATCH 38/82] Fixed null reference warnings --- .../tests/Management/ManagementClientTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs index 59454c2c6783..646b9ab775cb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs @@ -485,9 +485,9 @@ public async Task GetTopicRuntimeInfoTest() var topicsRi = await client.GetTopicsRuntimeInfoAsync(); var topicRi = topicsRi.FirstOrDefault(t => topicName.Equals(t.Path, StringComparison.OrdinalIgnoreCase)); - Assert.Equal(topicName, topicRi.Path); + Assert.Equal(topicName, topicRi?.Path); - Assert.True(topicRi.CreatedAt < topicRi.UpdatedAt); + Assert.True(topicRi?.CreatedAt < topicRi?.UpdatedAt); Assert.True(topicRi.UpdatedAt < topicRi.AccessedAt); Assert.Equal(0, topicRi.MessageCountDetails.ActiveMessageCount); From 8b6bcefa0f19d74ade246ac410b37087b2c43c48 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:10:33 -0400 Subject: [PATCH 39/82] Removed redundant parenthesis --- .../src/Amqp/AmqpMessageConverter.cs | 6 +++--- .../src/Core/MessageReceiver.cs | 6 +++--- .../src/Filters/CorrelationFilter.cs | 10 +++++----- .../src/Filters/RuleDescription.cs | 4 ++-- .../src/Filters/SqlFilter.cs | 4 ++-- .../src/Filters/SqlRuleAction.cs | 4 ++-- .../src/Management/AuthorizationRules.cs | 2 +- .../src/Management/SharedAccessAuthorizationRule.cs | 12 ++++++------ .../src/Management/SubscriptionDescription.cs | 4 ++-- .../src/Primitives/SharedAccessSignatureToken.cs | 2 +- .../src/Primitives/TimeoutHelper.cs | 4 ++-- .../tests/ExpectedMessagingExceptionTests.cs | 2 +- .../tests/Infrastructure/ServiceBusScope.cs | 4 ++-- .../Microsoft.Azure.ServiceBus/tests/MessageTests.cs | 2 +- .../tests/Performance/Program.cs | 6 +++--- .../tests/SenderReceiverClientTestBase.cs | 2 +- 16 files changed, 37 insertions(+), 37 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index 668b382c4801..de8be81f589d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -127,7 +127,7 @@ public static AmqpMessage SBMessageToAmqpMessage(SBMessage sbMessage) } } - if ((sbMessage.ScheduledEnqueueTimeUtc != null) && sbMessage.ScheduledEnqueueTimeUtc > DateTime.MinValue) + if (sbMessage.ScheduledEnqueueTimeUtc != null && sbMessage.ScheduledEnqueueTimeUtc > DateTime.MinValue) { amqpMessage.MessageAnnotations.Map.Add(ScheduledEnqueueTimeUtcName, sbMessage.ScheduledEnqueueTimeUtc); } @@ -230,7 +230,7 @@ public static SBMessage AmqpMessageToSBMessage(AmqpMessage amqpMessage, bool isP if (amqpMessage.Header.DeliveryCount != null) { - sbMessage.SystemProperties.DeliveryCount = isPeeked ? (int)(amqpMessage.Header.DeliveryCount.Value) : (int)(amqpMessage.Header.DeliveryCount.Value + 1); + sbMessage.SystemProperties.DeliveryCount = isPeeked ? (int)amqpMessage.Header.DeliveryCount.Value : (int)(amqpMessage.Header.DeliveryCount.Value + 1); } } @@ -564,7 +564,7 @@ private static bool TryGetNetObjectFromAmqpObject(object amqpObject, MappingType case PropertyValueType.Unknown: if (amqpObject is AmqpSymbol amqpObjectAsAmqpSymbol) { - netObject = (amqpObjectAsAmqpSymbol).Value; + netObject = amqpObjectAsAmqpSymbol.Value; } else if (amqpObject is ArraySegment amqpObjectAsArraySegment) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index 7e6cc5129ada..14ff4e6a5714 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -1115,7 +1115,7 @@ protected virtual async Task> OnPeekAsync(long fromSequenceNumber } if (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.NoContent || - (amqpResponseMessage.StatusCode == AmqpResponseStatusCode.NotFound && Equals(AmqpClientConstants.MessageNotFoundError, amqpResponseMessage.GetResponseErrorCondition()))) + amqpResponseMessage.StatusCode == AmqpResponseStatusCode.NotFound && Equals(AmqpClientConstants.MessageNotFoundError, amqpResponseMessage.GetResponseErrorCondition())) { return messages; } @@ -1394,7 +1394,7 @@ private async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome ou Error error = null; foreach (var item in outcomes) { - var disposedOutcome = item.DescriptorCode == Rejected.Code && ((error = ((Rejected)item).Error) != null) ? item : null; + var disposedOutcome = item.DescriptorCode == Rejected.Code && (error = ((Rejected)item).Error) != null ? item : null; if (disposedOutcome != null) { if (error.Condition.Equals(AmqpErrorCode.NotFound)) @@ -1510,7 +1510,7 @@ private async Task CreateLinkAsync(TimeSpan timeout) TotalLinkCredit = (uint)PrefetchCount, AutoSendFlow = PrefetchCount > 0, Source = new Source { Address = Path, FilterSet = filterMap }, - SettleType = (ReceiveMode == ReceiveMode.PeekLock) ? SettleMode.SettleOnDispose : SettleMode.SettleOnSend + SettleType = ReceiveMode == ReceiveMode.PeekLock ? SettleMode.SettleOnDispose : SettleMode.SettleOnSend }; if (EntityType != null) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs index 428cb8718a9f..03434478572d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs @@ -204,9 +204,9 @@ public override int GetHashCode() var hash = 13; unchecked { - hash = (hash * 7) + CorrelationId?.GetHashCode() ?? 0; - hash = (hash * 7) + MessageId?.GetHashCode() ?? 0; - hash = (hash * 7) + SessionId?.GetHashCode() ?? 0; + hash = hash * 7 + CorrelationId?.GetHashCode() ?? 0; + hash = hash * 7 + MessageId?.GetHashCode() ?? 0; + hash = hash * 7 + SessionId?.GetHashCode() ?? 0; } return hash; @@ -243,8 +243,8 @@ public override bool Equals(Filter other) foreach (var param in properties) { if (!correlationFilter.properties.TryGetValue(param.Key, out var otherParamValue) || - (param.Value == null ^ otherParamValue == null) || - (param.Value != null && !param.Value.Equals(otherParamValue))) + param.Value == null ^ otherParamValue == null || + param.Value != null && !param.Value.Equals(otherParamValue)) { return false; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs index 95afde0bb467..c01d5c31f0fc 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs @@ -104,8 +104,8 @@ public override int GetHashCode() var hash = 13; unchecked { - hash = (hash * 7) + _filter?.GetHashCode() ?? 0; - hash = (hash * 7) + Action?.GetHashCode() ?? 0; + hash = hash * 7 + _filter?.GetHashCode() ?? 0; + hash = hash * 7 + Action?.GetHashCode() ?? 0; } return hash; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs index 52d34031fb37..4e571d291f3b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs @@ -97,8 +97,8 @@ public override bool Equals(Filter other) foreach (var param in parameters) { if (!sqlFilter.parameters.TryGetValue(param.Key, out var otherParamValue) || - (param.Value == null ^ otherParamValue == null) || - (param.Value != null && !param.Value.Equals(otherParamValue))) + param.Value == null ^ otherParamValue == null || + param.Value != null && !param.Value.Equals(otherParamValue)) { return false; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs index 0e5d349f6eb1..07a137a6a616 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs @@ -90,8 +90,8 @@ public override bool Equals(RuleAction other) foreach (var param in parameters) { if (!sqlAction.parameters.TryGetValue(param.Key, out var otherParamValue) || - (param.Value == null ^ otherParamValue == null) || - (param.Value != null && !param.Value.Equals(otherParamValue))) + param.Value == null ^ otherParamValue == null || + param.Value != null && !param.Value.Equals(otherParamValue)) { return false; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs index bc4195c3d127..0f0e9ce2402f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs @@ -34,7 +34,7 @@ public override int GetHashCode() { foreach (var rule in this) { - hash = (hash * 7) + rule.GetHashCode(); + hash = hash * 7 + rule.GetHashCode(); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs index d5fca167f08c..bb7928e4a582 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs @@ -175,10 +175,10 @@ public override int GetHashCode() var hash = 13; unchecked { - hash = (hash * 7) + KeyName?.GetHashCode() ?? 0; - hash = (hash * 7) + PrimaryKey?.GetHashCode() ?? 0; - hash = (hash * 7) + SecondaryKey?.GetHashCode() ?? 0; - hash = (hash * 7) + Rights.GetHashCode(); + hash = hash * 7 + KeyName?.GetHashCode() ?? 0; + hash = hash * 7 + PrimaryKey?.GetHashCode() ?? 0; + hash = hash * 7 + SecondaryKey?.GetHashCode() ?? 0; + hash = hash * 7 + Rights.GetHashCode(); } return hash; @@ -208,8 +208,8 @@ public override bool Equals(AuthorizationRule other) return false; } - if ((Rights != null && comparand.Rights == null) || - (Rights == null && comparand.Rights != null)) + if (Rights != null && comparand.Rights == null || + Rights == null && comparand.Rights != null) { return false; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs index 727a7e5a576a..2e3e27697e12 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -264,8 +264,8 @@ public override int GetHashCode() var hash = 7; unchecked { - hash = (hash * 7) + TopicPath?.GetHashCode() ?? 0; - hash = (hash * 7) + SubscriptionName?.GetHashCode() ?? 0; + hash = hash * 7 + TopicPath?.GetHashCode() ?? 0; + hash = hash * 7 + SubscriptionName?.GetHashCode() ?? 0; } return hash; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs index 98b0898d83c6..c388ee526169 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureToken.cs @@ -118,7 +118,7 @@ private static DateTime GetExpirationDateTimeUtcFromToken(string token) throw new FormatException(Resources.TokenMissingExpiresOn); } - var expiresOn = (Constants.EpochTime + TimeSpan.FromSeconds(double.Parse(expiresIn, CultureInfo.InvariantCulture))); + var expiresOn = Constants.EpochTime + TimeSpan.FromSeconds(double.Parse(expiresIn, CultureInfo.InvariantCulture)); return expiresOn; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs index a50827bcb9e9..5ed0f08fc5b5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs @@ -19,7 +19,7 @@ public TimeoutHelper(TimeSpan timeout, bool startTimeout) _originalTimeout = timeout; _deadline = DateTime.MaxValue; - _deadlineSet = (timeout == TimeSpan.MaxValue); + _deadlineSet = timeout == TimeSpan.MaxValue; if (startTimeout && !_deadlineSet) { @@ -52,7 +52,7 @@ public static TimeSpan Divide(TimeSpan timeout, int factor) return TimeSpan.MaxValue; } - return Ticks.ToTimeSpan((Ticks.FromTimeSpan(timeout) / factor) + 1); + return Ticks.ToTimeSpan(Ticks.FromTimeSpan(timeout) / factor + 1); } public static TimeSpan Min(TimeSpan time1, TimeSpan time2) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs index 83c77bd9b78b..943f7fd83eb1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs @@ -107,7 +107,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: true, // Let the Session expire with some buffer time TestUtility.Log($"Waiting for session lock to time out..."); - await Task.Delay((sessionReceiver.LockedUntilUtc - DateTime.UtcNow) + TimeSpan.FromSeconds(10)); + await Task.Delay(sessionReceiver.LockedUntilUtc - DateTime.UtcNow + TimeSpan.FromSeconds(10)); await Assert.ThrowsAsync(async () => await sessionReceiver.ReceiveAsync()); await Assert.ThrowsAsync(async () => await sessionReceiver.RenewSessionLockAsync()); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs index 83b57ef0c2ac..b16f7cc2fbab 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs @@ -71,7 +71,7 @@ public static async Task CreateTopicAsync(bool partitioned, [CallerMemberName] string caller = "") { var topicName = $"{ caller }-{ Guid.NewGuid().ToString("D").Substring(0, 8) }"; - var subscripionName = (sessionEnabled) ? TestConstants.SessionSubscriptionName : TestConstants.SubscriptionName; + var subscripionName = sessionEnabled ? TestConstants.SessionSubscriptionName : TestConstants.SubscriptionName; var topicDescription = BuildTopicDescription(topicName, partitioned); var subscriptionDescription = BuildSubscriptionDescription(subscripionName, topicName, sessionEnabled); @@ -181,7 +181,7 @@ private static IAsyncPolicy CreateRetryPolicy(int maxRetryAttempts = TestConstan .WaitAndRetryAsync(maxRetryAttempts, attempt => CalculateRetryDelay(attempt, exponentialBackoffSeconds, baseJitterSeconds)); private static TimeSpan CalculateRetryDelay(int attempt, double exponentialBackoffSeconds, double baseJitterSeconds) => - TimeSpan.FromSeconds((Math.Pow(2, attempt) * exponentialBackoffSeconds) + (Rng.Value.NextDouble() * baseJitterSeconds)); + TimeSpan.FromSeconds(Math.Pow(2, attempt) * exponentialBackoffSeconds + Rng.Value.NextDouble() * baseJitterSeconds); private static QueueDescription BuildQueueDescription(string name, bool partitioned, bool sessionEnabled) => new QueueDescription(name) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs index 14b569ef280f..b5153643c28c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs @@ -148,7 +148,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { - var maxMessageSize = (256 * 1024) - 77; // 77 bytes is the current serialization hit. + var maxMessageSize = 256 * 1024 - 77; // 77 bytes is the current serialization hit. var maxPayload = Enumerable.Repeat(0x20, maxMessageSize).ToArray(); var maxSizeMessage = new Message(maxPayload); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index 4dff6f5d7459..c378c0060ae6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -19,10 +19,10 @@ internal class Program internal static async Task Main(string[] args) { - var maxInflight = (args.Length >= 1 ? int.Parse(args[0]) : 1); + var maxInflight = args.Length >= 1 ? int.Parse(args[0]) : 1; Log($"Maximum inflight messages: {maxInflight}"); - var messages = (args.Length >= 2 ? long.Parse(args[1]) : 10); + var messages = args.Length >= 2 ? long.Parse(args[1]) : 10; var connectionString = Environment.GetEnvironmentVariable("SERVICE_BUS_CONNECTION_STRING"); var entityPath = Environment.GetEnvironmentVariable("SERVICE_BUS_QUEUE_NAME"); @@ -78,7 +78,7 @@ private static async Task WriteResults(long messages) var currentElapsed = elapsed - lastElapsed; lastElapsed = elapsed; - if ((currentMessages / currentElapsed.TotalSeconds) > (maxMessages / maxElapsed.TotalSeconds)) { + if (currentMessages / currentElapsed.TotalSeconds > maxMessages / maxElapsed.TotalSeconds) { maxMessages = currentMessages; maxElapsed = currentElapsed; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverClientTestBase.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverClientTestBase.cs index c2bdc45ffd5d..9d7cb977148d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverClientTestBase.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverClientTestBase.cs @@ -229,7 +229,7 @@ internal async Task CancelScheduledMessagesAsyncTestCase(IMessageSender messageS // Sending a dummy message so that ReceiveAsync(2) returns immediately after getting 1 message // instead of waiting for connection timeout on a single message. - await messageSender.SendAsync(new Message(Encoding.UTF8.GetBytes(("Dummy"))) { MessageId = "Dummy" }); + await messageSender.SendAsync(new Message(Encoding.UTF8.GetBytes("Dummy")) { MessageId = "Dummy" }); IList messages = null; var retryCount = 5; while (messages == null && --retryCount > 0) From 86a63deeb5cdcc8281b32bd25b85934bbb5fff60 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:12:59 -0400 Subject: [PATCH 40/82] Fixed null reference warning --- .../src/Amqp/AmqpMessageConverter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index de8be81f589d..cb18938e9584 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -566,9 +566,9 @@ private static bool TryGetNetObjectFromAmqpObject(object amqpObject, MappingType { netObject = amqpObjectAsAmqpSymbol.Value; } - else if (amqpObject is ArraySegment amqpObjectAsArraySegment) + else if (amqpObject is ArraySegment binValue && + binValue.Array != null) { - var binValue = amqpObjectAsArraySegment; if (binValue.Count == binValue.Array.Length) { netObject = binValue.Array; From 42ad7ad8c6bf2c2ac293be41509c5d14245b181e Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:13:58 -0400 Subject: [PATCH 41/82] Refactored property name from "parameters" to "properties" on SqlRuleAction --- .../src/Filters/RuleActionExtensions.cs | 2 +- .../src/Filters/SqlRuleAction.cs | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs index ddd758001928..562d37fb8416 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleActionExtensions.cs @@ -63,7 +63,7 @@ public static XElement Serialize(this RuleAction action) if (action is SqlRuleAction sqlRuleAction) { XElement parameterElement = null; - if (sqlRuleAction.parameters != null) + if (sqlRuleAction.Properties != null) { parameterElement = new XElement(XName.Get("Parameters", ManagementClientConstants.ServiceBusNamespace)); foreach (var param in sqlRuleAction.Parameters) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs index 07a137a6a616..06930a156f5f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs @@ -13,7 +13,7 @@ namespace Microsoft.Azure.ServiceBus.Filters /// public sealed class SqlRuleAction : RuleAction { - internal PropertyDictionary parameters; + internal PropertyDictionary Properties; /// /// Initializes a new instance of the class with the specified SQL expression. @@ -50,7 +50,7 @@ public SqlRuleAction(string sqlExpression) /// Sets the value of a rule action. /// /// The value of a rule action. - public IDictionary Parameters => parameters ?? (parameters = new PropertyDictionary()); + public IDictionary Parameters => Properties ?? (Properties = new PropertyDictionary()); /// /// Returns a string representation of . @@ -77,19 +77,19 @@ public override bool Equals(RuleAction other) if (other is SqlRuleAction sqlAction) { if (string.Equals(SqlExpression, sqlAction.SqlExpression, StringComparison.OrdinalIgnoreCase) - && (parameters != null && sqlAction.parameters != null - || parameters == null && sqlAction.parameters == null)) + && (Properties != null && sqlAction.Properties != null + || Properties == null && sqlAction.Properties == null)) { - if (parameters != null) + if (Properties != null) { - if (parameters.Count != sqlAction.parameters.Count) + if (Properties.Count != sqlAction.Properties.Count) { return false; } - foreach (var param in parameters) + foreach (var param in Properties) { - if (!sqlAction.parameters.TryGetValue(param.Key, out var otherParamValue) || + if (!sqlAction.Properties.TryGetValue(param.Key, out var otherParamValue) || param.Value == null ^ otherParamValue == null || param.Value != null && !param.Value.Equals(otherParamValue)) { From 78952e22a740e0d547c776270951fc2330e606a3 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:14:31 -0400 Subject: [PATCH 42/82] Fixed null reference warning --- .../Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs index 06930a156f5f..987bfb0ad7ba 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs @@ -82,7 +82,7 @@ public override bool Equals(RuleAction other) { if (Properties != null) { - if (Properties.Count != sqlAction.Properties.Count) + if (Properties.Count != sqlAction.Properties?.Count) { return false; } From ed3081db3a7ab1fd764dfede2b6d9d009241673d Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:15:32 -0400 Subject: [PATCH 43/82] Refactored exception to better exception type --- .../tests/Diagnostics/QueueClientDiagnosticsTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs index 24474419f13e..b50433acd729 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/QueueClientDiagnosticsTests.cs @@ -437,7 +437,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, try { using (var listener = CreateEventListener(queueName, eventQueue)) - using (SubscribeToEvents(listener) ?? throw new ArgumentNullException("SubscribeToEvents(listener)")) + using (SubscribeToEvents(listener) ?? throw new InvalidOperationException("SubscribeToEvents(listener)")) { await TestUtility.SendMessagesAsync(queueClient.InnerSender, 1); var messages = await TestUtility.ReceiveMessagesAsync(queueClient.InnerReceiver, 1); From b9e6dd700c753c91e8e5ff538ccebea6a02e8119 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:16:09 -0400 Subject: [PATCH 44/82] Fixed null reference warning --- .../src/Amqp/AmqpMessageConverter.cs | 42 ++++++++++--------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index cb18938e9584..592ef270acd8 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -74,25 +74,29 @@ public static AmqpMessage BatchSBMessagesAsAmqpMessage(IEnumerable sb amqpMessage = AmqpMessage.Create(dataList); amqpMessage.MessageFormat = AmqpConstants.AmqpBatchedMessageFormat; - if (firstMessage.MessageId != null) - { - amqpMessage.Properties.MessageId = firstMessage.MessageId; - } - if (firstMessage.SessionId != null) - { - amqpMessage.Properties.GroupId = firstMessage.SessionId; - } - - if (firstMessage.PartitionKey != null) - { - amqpMessage.MessageAnnotations.Map[PartitionKeyName] = - firstMessage.PartitionKey; - } - - if (firstMessage.ViaPartitionKey != null) - { - amqpMessage.MessageAnnotations.Map[ViaPartitionKeyName] = - firstMessage.ViaPartitionKey; + if (firstMessage != null) + { + if (firstMessage.MessageId != null) + { + amqpMessage.Properties.MessageId = firstMessage.MessageId; + } + + if (firstMessage.SessionId != null) + { + amqpMessage.Properties.GroupId = firstMessage.SessionId; + } + + if (firstMessage.PartitionKey != null) + { + amqpMessage.MessageAnnotations.Map[PartitionKeyName] = + firstMessage.PartitionKey; + } + + if (firstMessage.ViaPartitionKey != null) + { + amqpMessage.MessageAnnotations.Map[ViaPartitionKeyName] = + firstMessage.ViaPartitionKey; + } } amqpMessage.Batchable = true; From 743d1f113072d31e0d0cd9a175fd98dd884d4356 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:16:32 -0400 Subject: [PATCH 45/82] Removed redundant check --- .../Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index 592ef270acd8..68509a2710ca 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -131,7 +131,7 @@ public static AmqpMessage SBMessageToAmqpMessage(SBMessage sbMessage) } } - if (sbMessage.ScheduledEnqueueTimeUtc != null && sbMessage.ScheduledEnqueueTimeUtc > DateTime.MinValue) + if (sbMessage.ScheduledEnqueueTimeUtc > DateTime.MinValue) { amqpMessage.MessageAnnotations.Map.Add(ScheduledEnqueueTimeUtcName, sbMessage.ScheduledEnqueueTimeUtc); } From e7e8979c5ac94e173f2409ada858fa8b32323359 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:17:31 -0400 Subject: [PATCH 46/82] Refactored property from "properties" to "FilterProperties" in CorrelationFilter --- .../src/Filters/CorrelationFilter.cs | 16 ++++++++-------- .../src/Filters/CorrelationFilterExtensions.cs | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs index 03434478572d..87727893800e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs @@ -30,7 +30,7 @@ namespace Microsoft.Azure.ServiceBus.Filters /// public sealed class CorrelationFilter : Filter { - internal PropertyDictionary properties; + internal PropertyDictionary FilterProperties; /// /// Initializes a new instance of the class with default values. @@ -148,7 +148,7 @@ public string ContentType /// bool, Guid, string, Uri, DateTime, DateTimeOffset, TimeSpan, Stream, byte[], /// and IList / IDictionary of supported types /// - public IDictionary Properties => properties ?? (properties = new PropertyDictionary()); + public IDictionary Properties => FilterProperties ?? (FilterProperties = new PropertyDictionary()); /// /// Converts the value of the current instance to its equivalent string representation. @@ -230,19 +230,19 @@ public override bool Equals(Filter other) && string.Equals(SessionId, correlationFilter.SessionId, StringComparison.OrdinalIgnoreCase) && string.Equals(ReplyToSessionId, correlationFilter.ReplyToSessionId, StringComparison.OrdinalIgnoreCase) && string.Equals(ContentType, correlationFilter.ContentType, StringComparison.OrdinalIgnoreCase) - && (properties != null && correlationFilter.properties != null - || properties == null && correlationFilter.properties == null)) + && (FilterProperties != null && correlationFilter.FilterProperties != null + || FilterProperties == null && correlationFilter.FilterProperties == null)) { - if (properties != null) + if (FilterProperties != null) { - if (properties.Count != correlationFilter.properties.Count) + if (FilterProperties.Count != correlationFilter.FilterProperties.Count) { return false; } - foreach (var param in properties) + foreach (var param in FilterProperties) { - if (!correlationFilter.properties.TryGetValue(param.Key, out var otherParamValue) || + if (!correlationFilter.FilterProperties.TryGetValue(param.Key, out var otherParamValue) || param.Value == null ^ otherParamValue == null || param.Value != null && !param.Value.Equals(otherParamValue)) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs index cf922fe8f0eb..0a13f649a8f7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs @@ -61,10 +61,10 @@ public static Filter ParseFromXElement(XElement xElement) public static XElement Serialize(this CorrelationFilter filter) { XElement parameterElement = null; - if (filter.properties != null) + if (filter.FilterProperties != null) { parameterElement = new XElement(XName.Get("Properties", ManagementClientConstants.ServiceBusNamespace)); - foreach (var param in filter.properties) + foreach (var param in filter.FilterProperties) { parameterElement.Add( new XElement(XName.Get("KeyValueOfstringanyType", ManagementClientConstants.ServiceBusNamespace), From 8c06c0f2ea1337cc4fefd56335c8503481fd57f1 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:18:35 -0400 Subject: [PATCH 47/82] Fixed localizable string warning --- .../src/Management/QueueDescription.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index 5e58fff02ac9..b1b398ccf598 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -261,7 +261,7 @@ public string UserMetadata { if (value == null) { - throw new ArgumentNullException(nameof(UserMetadata), $"Value cannot be null"); + throw new ArgumentNullException(nameof(UserMetadata), @"Value cannot be null"); } if (value.Length > ManagementClientConstants.MaxUserMetadataLength) From d69947158069440dfd060c3281366522f7aefd23 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:19:38 -0400 Subject: [PATCH 48/82] Fixed naming of field --- .../src/Primitives/ConcurrentExpiringSet.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs index 99500a4e717d..4fbd9fa1bf70 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs @@ -8,16 +8,16 @@ namespace Microsoft.Azure.ServiceBus.Primitives using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; - + internal sealed class ConcurrentExpiringSet { + private static readonly TimeSpan DelayBetweenCleanups = TimeSpan.FromSeconds(30); private readonly ConcurrentDictionary _dictionary; private readonly ICollection> _dictionaryAsCollection; private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource(); private volatile TaskCompletionSource _cleanupTaskCompletionSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); private int _closeSignaled; private bool _closed; - private static readonly TimeSpan delayBetweenCleanups = TimeSpan.FromSeconds(30); public ConcurrentExpiringSet() { @@ -63,7 +63,7 @@ private async Task CollectExpiredEntriesAsync(CancellationToken token) try { await _cleanupTaskCompletionSource.Task.ConfigureAwait(false); - await Task.Delay(delayBetweenCleanups, token).ConfigureAwait(false); + await Task.Delay(DelayBetweenCleanups, token).ConfigureAwait(false); } catch (OperationCanceledException) { From 75e6c80cce33f9d5c969348ca33b7fd33c06d800 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:21:26 -0400 Subject: [PATCH 49/82] Removed redundant type check --- .../src/Management/TopicDescription.cs | 34 ++++++++----------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs index c19f8f559b56..1bddae474d5b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs @@ -191,25 +191,21 @@ public override bool Equals(object obj) public bool Equals(TopicDescription otherDescription) { - if (otherDescription is TopicDescription other - && Path.Equals(other.Path, StringComparison.OrdinalIgnoreCase) - && AutoDeleteOnIdle.Equals(other.AutoDeleteOnIdle) - && DefaultMessageTimeToLive.Equals(other.DefaultMessageTimeToLive) - && (!RequiresDuplicateDetection || DuplicateDetectionHistoryTimeWindow.Equals(other.DuplicateDetectionHistoryTimeWindow)) - && EnableBatchedOperations == other.EnableBatchedOperations - && EnablePartitioning == other.EnablePartitioning - && MaxSizeInMB == other.MaxSizeInMB - && RequiresDuplicateDetection.Equals(other.RequiresDuplicateDetection) - && Status.Equals(other.Status) - && string.Equals(_userMetadata, other._userMetadata, StringComparison.OrdinalIgnoreCase) - && (AuthorizationRules != null && other.AuthorizationRules != null - || AuthorizationRules == null && other.AuthorizationRules == null) - && (AuthorizationRules == null || AuthorizationRules.Equals(other.AuthorizationRules))) - { - return true; - } - - return false; + return otherDescription != null + && Path.Equals(otherDescription.Path, StringComparison.OrdinalIgnoreCase) + && AutoDeleteOnIdle.Equals(otherDescription.AutoDeleteOnIdle) + && DefaultMessageTimeToLive.Equals(otherDescription.DefaultMessageTimeToLive) + && (!RequiresDuplicateDetection || + DuplicateDetectionHistoryTimeWindow.Equals(otherDescription.DuplicateDetectionHistoryTimeWindow)) + && EnableBatchedOperations == otherDescription.EnableBatchedOperations + && EnablePartitioning == otherDescription.EnablePartitioning + && MaxSizeInMB == otherDescription.MaxSizeInMB + && RequiresDuplicateDetection.Equals(otherDescription.RequiresDuplicateDetection) + && Status.Equals(otherDescription.Status) + && string.Equals(_userMetadata, otherDescription._userMetadata, StringComparison.OrdinalIgnoreCase) + && (AuthorizationRules != null && otherDescription.AuthorizationRules != null + || AuthorizationRules == null && otherDescription.AuthorizationRules == null) + && (AuthorizationRules == null || AuthorizationRules.Equals(otherDescription.AuthorizationRules)); } public static bool operator ==(TopicDescription o1, TopicDescription o2) From 2554309b228c09ed74e8b7c308c4561b09afddc2 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:22:27 -0400 Subject: [PATCH 50/82] Removed redundant type check --- .../src/Management/QueueDescription.cs | 47 +++++++++---------- 1 file changed, 22 insertions(+), 25 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index b1b398ccf598..984033c7d307 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -292,31 +292,28 @@ public override bool Equals(object obj) public bool Equals(QueueDescription otherDescription) { - if (otherDescription is QueueDescription other - && Path.Equals(other.Path, StringComparison.OrdinalIgnoreCase) - && AutoDeleteOnIdle.Equals(other.AutoDeleteOnIdle) - && DefaultMessageTimeToLive.Equals(other.DefaultMessageTimeToLive) - && (!RequiresDuplicateDetection || DuplicateDetectionHistoryTimeWindow.Equals(other.DuplicateDetectionHistoryTimeWindow)) - && EnableBatchedOperations == other.EnableBatchedOperations - && EnableDeadLetteringOnMessageExpiration == other.EnableDeadLetteringOnMessageExpiration - && EnablePartitioning == other.EnablePartitioning - && string.Equals(ForwardDeadLetteredMessagesTo, other.ForwardDeadLetteredMessagesTo, StringComparison.OrdinalIgnoreCase) - && string.Equals(ForwardTo, other.ForwardTo, StringComparison.OrdinalIgnoreCase) - && LockDuration.Equals(other.LockDuration) - && MaxDeliveryCount == other.MaxDeliveryCount - && MaxSizeInMB == other.MaxSizeInMB - && RequiresDuplicateDetection.Equals(other.RequiresDuplicateDetection) - && RequiresSession.Equals(other.RequiresSession) - && Status.Equals(other.Status) - && string.Equals(_userMetadata, other._userMetadata, StringComparison.OrdinalIgnoreCase) - && (AuthorizationRules != null && other.AuthorizationRules != null - || AuthorizationRules == null && other.AuthorizationRules == null) - && (AuthorizationRules == null || AuthorizationRules.Equals(other.AuthorizationRules))) - { - return true; - } - - return false; + return otherDescription != null + && Path.Equals(otherDescription.Path, StringComparison.OrdinalIgnoreCase) + && AutoDeleteOnIdle.Equals(otherDescription.AutoDeleteOnIdle) + && DefaultMessageTimeToLive.Equals(otherDescription.DefaultMessageTimeToLive) + && (!RequiresDuplicateDetection || + DuplicateDetectionHistoryTimeWindow.Equals(otherDescription.DuplicateDetectionHistoryTimeWindow)) + && EnableBatchedOperations == otherDescription.EnableBatchedOperations + && EnableDeadLetteringOnMessageExpiration == otherDescription.EnableDeadLetteringOnMessageExpiration + && EnablePartitioning == otherDescription.EnablePartitioning + && string.Equals(ForwardDeadLetteredMessagesTo, otherDescription.ForwardDeadLetteredMessagesTo, + StringComparison.OrdinalIgnoreCase) + && string.Equals(ForwardTo, otherDescription.ForwardTo, StringComparison.OrdinalIgnoreCase) + && LockDuration.Equals(otherDescription.LockDuration) + && MaxDeliveryCount == otherDescription.MaxDeliveryCount + && MaxSizeInMB == otherDescription.MaxSizeInMB + && RequiresDuplicateDetection.Equals(otherDescription.RequiresDuplicateDetection) + && RequiresSession.Equals(otherDescription.RequiresSession) + && Status.Equals(otherDescription.Status) + && string.Equals(_userMetadata, otherDescription._userMetadata, StringComparison.OrdinalIgnoreCase) + && (AuthorizationRules != null && otherDescription.AuthorizationRules != null + || AuthorizationRules == null && otherDescription.AuthorizationRules == null) + && (AuthorizationRules == null || AuthorizationRules.Equals(otherDescription.AuthorizationRules)); } public static bool operator ==(QueueDescription o1, QueueDescription o2) From a057c988408bbbdfd8d9abddf2775aa0b907ecb8 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:23:17 -0400 Subject: [PATCH 51/82] Refactored log statement to use string formatter --- .../Microsoft.Azure.ServiceBus/tests/Performance/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index c378c0060ae6..7a01a53279cd 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -100,7 +100,7 @@ private static void WriteResult(long totalMessages, TimeSpan totalElapsed, private static void Log(string message) { - Console.WriteLine($"[{DateTime.Now.ToString("hh:mm:ss.fff")}] {message}"); + Console.WriteLine($@"[{DateTime.Now:hh:mm:ss.fff}] {message}"); } } } From 070be5af8afb269168c14fd96b30c1fe2ceff3d4 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:23:38 -0400 Subject: [PATCH 52/82] Removed redundant initializer --- .../tests/MessageInterop/MessageInterOpTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs index e9d60a3ecac0..8827a9e774bd 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs @@ -38,7 +38,7 @@ public void RunSerializerTests(string testCaseName) private Message GetBrokeredMessage(XmlObjectSerializer serializer, TestBook book) { - byte[] payload = null; + byte[] payload; using (var memoryStream = new MemoryStream(10)) { serializer.WriteObject(memoryStream, book); From ae122b35d7123590b059530bb062030b6c570580 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:24:06 -0400 Subject: [PATCH 53/82] Adjusted namespace to match directory --- .../Microsoft.Azure.ServiceBus/tests/Performance/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index 7a01a53279cd..99b9038e21b9 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; using Microsoft.Azure.ServiceBus.Core; -namespace Microsoft.Azure.ServiceBus.UnitTests.Performance +namespace Microsoft.Azure.ServiceBus.Performance { internal class Program { From 2e1dc4938436bf1b60a09f50c147e23e7629cc6e Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:24:48 -0400 Subject: [PATCH 54/82] Fixed naming of fields --- .../tests/Performance/Program.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index 99b9038e21b9..c9130cdbc29f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -11,9 +11,8 @@ namespace Microsoft.Azure.ServiceBus.Performance { internal class Program { - private static readonly Stopwatch _stopwatch = Stopwatch.StartNew(); - - private static readonly byte[] _payload = new byte[1024]; + private static readonly Stopwatch Stopwatch = Stopwatch.StartNew(); + private static readonly byte[] Payload = new byte[1024]; private static long _messages; @@ -52,7 +51,7 @@ private static async Task ExecuteSendsAsync(MessageSender sender, long messages) { while (Interlocked.Increment(ref _messages) <= messages) { - await sender.SendAsync(new Message(_payload)); + await sender.SendAsync(new Message(Payload)); } // Undo last increment, since a message was never sent on the final loop iteration @@ -74,7 +73,7 @@ private static async Task WriteResults(long messages) var currentMessages = sentMessages - lastMessages; lastMessages = sentMessages; - var elapsed = _stopwatch.Elapsed; + var elapsed = Stopwatch.Elapsed; var currentElapsed = elapsed - lastElapsed; lastElapsed = elapsed; From 95dd35d9a4f96cc751a11546a9348dc421d33d1c Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:26:07 -0400 Subject: [PATCH 55/82] Simplified method names in converter --- .../src/Amqp/AmqpMessageConverter.cs | 8 ++++---- .../src/Core/MessageReceiver.cs | 6 +++--- .../src/Core/MessageSender.cs | 4 ++-- .../tests/AmqpConverterTests.cs | 18 +++++++++--------- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index 68509a2710ca..7d727241fbdc 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -33,7 +33,7 @@ internal static class AmqpMessageConverter private const string DateTimeOffsetName = AmqpConstants.Vendor + ":datetime-offset"; private const int GuidSize = 16; - public static AmqpMessage BatchSBMessagesAsAmqpMessage(IEnumerable sbMessages) + public static AmqpMessage Convert(IEnumerable sbMessages) { if (sbMessages == null) { @@ -49,7 +49,7 @@ public static AmqpMessage BatchSBMessagesAsAmqpMessage(IEnumerable sb { messageCount++; - amqpMessage = SBMessageToAmqpMessage(sbMessage); + amqpMessage = Convert(sbMessage); if (firstAmqpMessage == null) { firstAmqpMessage = amqpMessage; @@ -103,7 +103,7 @@ public static AmqpMessage BatchSBMessagesAsAmqpMessage(IEnumerable sb return amqpMessage; } - public static AmqpMessage SBMessageToAmqpMessage(SBMessage sbMessage) + public static AmqpMessage Convert(SBMessage sbMessage) { var amqpMessage = sbMessage.Body == null ? AmqpMessage.Create() : AmqpMessage.Create(new Data { Value = new ArraySegment(sbMessage.Body) }); @@ -169,7 +169,7 @@ public static AmqpMessage SBMessageToAmqpMessage(SBMessage sbMessage) return amqpMessage; } - public static SBMessage AmqpMessageToSBMessage(AmqpMessage amqpMessage, bool isPeeked = false) + public static SBMessage Convert(AmqpMessage amqpMessage, bool isPeeked = false) { if (amqpMessage == null) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index 14ff4e6a5714..a0355cd9a6d7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -1051,7 +1051,7 @@ protected virtual async Task> OnReceiveAsync(int maxMessageCount, receiveLink.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome); } - var message = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); + var message = AmqpMessageConverter.Convert(amqpMessage); if (brokeredMessages == null) { brokeredMessages = new List(); @@ -1102,7 +1102,7 @@ protected virtual async Task> OnPeekAsync(long fromSequenceNumber { var payload = (ArraySegment)entry[ManagementConstants.Properties.Message]; var amqpMessage = AmqpMessage.CreateAmqpStreamMessage(new BufferListStream(new[] { payload }), true); - message = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage, true); + message = AmqpMessageConverter.Convert(amqpMessage, true); messages.Add(message); } @@ -1155,7 +1155,7 @@ protected virtual async Task> OnReceiveDeferredMessageAsync(long[ { var payload = (ArraySegment)entry[ManagementConstants.Properties.Message]; var amqpMessage = AmqpMessage.CreateAmqpStreamMessage(new BufferListStream(new[] { payload }), true); - var message = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); + var message = AmqpMessageConverter.Convert(amqpMessage); if (entry.TryGetValue(ManagementConstants.Properties.LockToken, out var lockToken)) { message.SystemProperties.LockTokenGuid = lockToken; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs index bfc8658e814d..84d9a11ec0fd 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs @@ -537,7 +537,7 @@ private async Task> ProcessMessages(IList messageList) private async Task OnSendAsync(IList messageList) { var timeoutHelper = new TimeoutHelper(OperationTimeout, true); - using (var amqpMessage = AmqpMessageConverter.BatchSBMessagesAsAmqpMessage(messageList)) + using (var amqpMessage = AmqpMessageConverter.Convert(messageList)) { SendingAmqpLink amqpLink = null; try @@ -579,7 +579,7 @@ private async Task OnSendAsync(IList messageList) private async Task OnScheduleMessageAsync(Message message) { - using (var amqpMessage = AmqpMessageConverter.SBMessageToAmqpMessage(message)) + using (var amqpMessage = AmqpMessageConverter.Convert(message)) { var request = AmqpRequestMessage.CreateRequest( ManagementConstants.Operations.ScheduleMessageOperation, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs index 95c98761d100..aa08bcd1da14 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs @@ -25,7 +25,7 @@ public void Convert_Amqp_message_with_Amqp_value_array_segment_to_SB_message() amqpValue.Value = new ArraySegment(messageBody); var amqpMessage = AmqpMessage.Create(amqpValue); - var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); + var sbMessage = AmqpMessageConverter.Convert(amqpMessage); Assert.Equal(messageBody, sbMessage.GetBody()); } @@ -39,7 +39,7 @@ public void Convert_Amqp_message_with_Amqp_value_byte_array_to_SB_message() amqpValue.Value = messageBody; var amqpMessage = AmqpMessage.Create(amqpValue); - var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); + var sbMessage = AmqpMessageConverter.Convert(amqpMessage); Assert.Equal(messageBody, sbMessage.GetBody()); } @@ -53,7 +53,7 @@ public void Convert_Amqp_message_with_data_value_array_segment_to_SB_message() data.Value = new ArraySegment(messageBody); var amqpMessage = AmqpMessage.Create(data); - var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); + var sbMessage = AmqpMessageConverter.Convert(amqpMessage); Assert.Equal(messageBody, sbMessage.Body); } @@ -67,7 +67,7 @@ public void Convert_Amqp_message_with_data_value_byte_array_to_SB_message() data.Value = messageBody; var amqpMessage = AmqpMessage.Create(data); - var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); + var sbMessage = AmqpMessageConverter.Convert(amqpMessage); Assert.Equal(messageBody, sbMessage.Body); } @@ -104,8 +104,8 @@ public void Convert_SB_message_to_Amqp_message_and_back() }; sbMessage.UserProperties.Add("UserProperty", "SomeUserProperty"); - var amqpMessage = AmqpMessageConverter.SBMessageToAmqpMessage(sbMessage); - var convertedSbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); + var amqpMessage = AmqpMessageConverter.Convert(sbMessage); + var convertedSbMessage = AmqpMessageConverter.Convert(amqpMessage); Assert.Equal("SomeUserProperty", convertedSbMessage.UserProperties["UserProperty"]); Assert.Equal(messageBody, convertedSbMessage.Body); @@ -128,7 +128,7 @@ public void SB_message_with_no_TTL_results_in_empty_Ampq_TTL() { var sbMessage = new Message(); - var amqpMessage = AmqpMessageConverter.SBMessageToAmqpMessage(sbMessage); + var amqpMessage = AmqpMessageConverter.Convert(sbMessage); Assert.Null(amqpMessage.Header.Ttl); } @@ -144,7 +144,7 @@ public void When_message_is_peeked_should_have_delivery_count_set_to_zero() var amqpMessage = AmqpMessage.Create(amqpValue); amqpMessage.Header.DeliveryCount = 2; - var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage, isPeeked: true); + var sbMessage = AmqpMessageConverter.Convert(amqpMessage, isPeeked: true); sbMessage.SystemProperties.SequenceNumber = 1L; Assert.Equal(2, sbMessage.SystemProperties.DeliveryCount); @@ -161,7 +161,7 @@ public void When_message_is_received_should_have_delivery_count_increased() var amqpMessage = AmqpMessage.Create(amqpValue); amqpMessage.Header.DeliveryCount = 2; - var sbMessage = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage, isPeeked: false); + var sbMessage = AmqpMessageConverter.Convert(amqpMessage, isPeeked: false); sbMessage.SystemProperties.SequenceNumber = 1L; Assert.Equal(3, sbMessage.SystemProperties.DeliveryCount); From 4c541cb546cafabdfdf9f190deae8f43d69a483b Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:28:18 -0400 Subject: [PATCH 56/82] Converter "if" statements to pattern matching "switch" --- .../src/Amqp/AmqpMessageConverter.cs | 113 ++++++++++-------- 1 file changed, 60 insertions(+), 53 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs index 7d727241fbdc..e3598b0b21df 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpMessageConverter.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Linq; using Microsoft.Azure.ServiceBus.Filters; namespace Microsoft.Azure.ServiceBus.Amqp @@ -566,60 +567,66 @@ private static bool TryGetNetObjectFromAmqpObject(object amqpObject, MappingType netObject = amqpObject; break; case PropertyValueType.Unknown: - if (amqpObject is AmqpSymbol amqpObjectAsAmqpSymbol) + switch (amqpObject) { - netObject = amqpObjectAsAmqpSymbol.Value; - } - else if (amqpObject is ArraySegment binValue && - binValue.Array != null) - { - if (binValue.Count == binValue.Array.Length) - { - netObject = binValue.Array; - } - else - { - var buffer = new byte[binValue.Count]; - Buffer.BlockCopy(binValue.Array, binValue.Offset, buffer, 0, binValue.Count); - netObject = buffer; - } - } - else if (amqpObject is DescribedType amqpObjectAsDescribedType) - { - if (amqpObjectAsDescribedType.Descriptor is AmqpSymbol) - { - var amqpSymbol = (AmqpSymbol)amqpObjectAsDescribedType.Descriptor; - if (amqpSymbol.Equals((AmqpSymbol)UriName)) - { - netObject = new Uri((string)amqpObjectAsDescribedType.Value); - } - else if (amqpSymbol.Equals((AmqpSymbol)TimeSpanName)) - { - netObject = new TimeSpan((long)amqpObjectAsDescribedType.Value); - } - else if (amqpSymbol.Equals((AmqpSymbol)DateTimeOffsetName)) - { - netObject = new DateTimeOffset(new DateTime((long)amqpObjectAsDescribedType.Value, DateTimeKind.Utc)); - } - } - } - else if (mappingType == MappingType.ApplicationProperty) - { - throw Fx.Exception.AsError(new SerializationException(Resources.FailedToSerializeUnsupportedType.FormatForUser(amqpObject.GetType().FullName))); - } - else if (amqpObject is AmqpMap map) - { - var dictionary = new Dictionary(); - foreach (var pair in map) - { - dictionary.Add(pair.Key.ToString(), pair.Value); - } - - netObject = dictionary; - } - else - { - netObject = amqpObject; + case AmqpSymbol amqpObjectAsAmqpSymbol: + netObject = amqpObjectAsAmqpSymbol.Value; + break; + case ArraySegment binValue when binValue.Array != null: + { + if (binValue.Count == binValue.Array.Length) + { + netObject = binValue.Array; + } + else + { + var buffer = new byte[binValue.Count]; + Buffer.BlockCopy(binValue.Array, binValue.Offset, buffer, 0, binValue.Count); + netObject = buffer; + } + + break; + } + case DescribedType amqpObjectAsDescribedType: + { + if (amqpObjectAsDescribedType.Descriptor is AmqpSymbol amqpSymbol) + { + if (amqpSymbol.Equals((AmqpSymbol)UriName)) + { + netObject = new Uri((string)amqpObjectAsDescribedType.Value); + } + else if (amqpSymbol.Equals((AmqpSymbol)TimeSpanName)) + { + netObject = new TimeSpan((long)amqpObjectAsDescribedType.Value); + } + else if (amqpSymbol.Equals((AmqpSymbol)DateTimeOffsetName)) + { + netObject = new DateTimeOffset(new DateTime((long)amqpObjectAsDescribedType.Value, DateTimeKind.Utc)); + } + } + + break; + } + default: + { + if (mappingType == MappingType.ApplicationProperty) + { + throw Fx.Exception.AsError(new SerializationException(Resources.FailedToSerializeUnsupportedType.FormatForUser(amqpObject.GetType().FullName))); + } + + if (amqpObject is AmqpMap map) + { + var dictionary = map.ToDictionary(pair => pair.Key.ToString(), pair => pair.Value); + + netObject = dictionary; + } + else + { + netObject = amqpObject; + } + + break; + } } break; } From 28eb14a940f12e5fcd6ef97030c77e49d6eca27f Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:29:05 -0400 Subject: [PATCH 57/82] Removed redundant type check --- .../src/Filters/RuleDescription.cs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs index c01d5c31f0fc..f5b04cad0ca1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs @@ -118,15 +118,10 @@ public override bool Equals(object obj) public bool Equals(RuleDescription otherRule) { - if (otherRule is RuleDescription other - && string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase) - && (Filter == null || Filter.Equals(other.Filter)) - && (Action == null || Action.Equals(other.Action))) - { - return true; - } - - return false; + return otherRule != null + && string.Equals(Name, otherRule.Name, StringComparison.OrdinalIgnoreCase) + && (Filter == null || Filter.Equals(otherRule.Filter)) + && (Action == null || Action.Equals(otherRule.Action)); } public static bool operator ==(RuleDescription o1, RuleDescription o2) From 68fb27e7766460ef9ad93fda0f43bc9961bab8d8 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:31:52 -0400 Subject: [PATCH 58/82] Assigned instantiated value to ignored variable --- .../tests/ServiceBusConnectionStringBuilderTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs index eaf5f08a57c7..65b20fb24c4d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs @@ -212,7 +212,7 @@ public void ManagementIdentityTokenProviderFromConnectionStringTest(string conne { var builder = new ServiceBusConnectionStringBuilder(connectionString); var connection = new ServiceBusConnection(builder); - new ManagementClient(builder); // Will throw without a valid TokenProvider + var _ = new ManagementClient(builder); // Will throw without a valid TokenProvider Assert.Equal(typeof(ManagedIdentityTokenProvider), connection.TokenProvider.GetType()); } From 04f3f7d77b1acca76b42596b5cd106d3e8a1353c Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:32:14 -0400 Subject: [PATCH 59/82] Fixed constant name --- .../src/Management/ManagementClient.cs | 6 +++--- .../src/Management/ManagementClientConstants.cs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs index bf3e5fe6635a..8ae86abfecad 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs @@ -1114,7 +1114,7 @@ private async Task GetEntity(string path, string query, bool enrich, Can { MessagingEventSource.Log.ManagementOperationStart(_clientId, nameof(GetEntity), $"path:{path},query:{query},enrich:{enrich}"); - var queryString = $"{ManagementClientConstants.apiVersionQuery}&enrich={enrich}"; + var queryString = $"{ManagementClientConstants.ApiVersionQuery}&enrich={enrich}"; if (query != null) { queryString = queryString + "&" + query; @@ -1144,7 +1144,7 @@ private async Task PutEntity(string path, string requestBody, bool isUpd Path = path, Port = _port, Scheme = Uri.UriSchemeHttps, - Query = $"{ManagementClientConstants.apiVersionQuery}" + Query = $"{ManagementClientConstants.ApiVersionQuery}" }.Uri; var request = new HttpRequestMessage(HttpMethod.Put, uri); @@ -1187,7 +1187,7 @@ private async Task DeleteEntity(string path, CancellationToken cancellationToken Path = path, Scheme = Uri.UriSchemeHttps, Port = _port, - Query = ManagementClientConstants.apiVersionQuery + Query = ManagementClientConstants.ApiVersionQuery }.Uri; var request = new HttpRequestMessage(HttpMethod.Delete, uri); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs index 9c37b5fc6082..88b7b6db52cf 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs @@ -18,7 +18,7 @@ internal class ManagementClientConstants public const string XmlSchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/"; public const string AtomContentType = "application/atom+xml"; - public const string apiVersionQuery = "api-version=" + ApiVersion; + public const string ApiVersionQuery = "api-version=" + ApiVersion; public const string ApiVersion = "2017-04"; public const string ServiceBusSupplementartyAuthorizationHeaderName = "ServiceBusSupplementaryAuthorization"; From 00f921db8e3302ae478a2dd6d1a63e32aa70454a Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:32:44 -0400 Subject: [PATCH 60/82] Fixed spelling mistake in constant name --- .../src/Management/ManagementClient.cs | 2 +- .../src/Management/ManagementClientConstants.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs index 8ae86abfecad..39dcec56a87a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClient.cs @@ -1162,7 +1162,7 @@ private async Task PutEntity(string path, string requestBody, bool isUpd if (!string.IsNullOrWhiteSpace(forwardTo)) { var token = await GetToken(forwardTo).ConfigureAwait(false); - request.Headers.Add(ManagementClientConstants.ServiceBusSupplementartyAuthorizationHeaderName, token); + request.Headers.Add(ManagementClientConstants.ServiceBusSupplementaryAuthorizationHeaderName, token); } if (!string.IsNullOrWhiteSpace(fwdDeadLetterTo)) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs index 88b7b6db52cf..f9305ab7ef1d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs @@ -21,7 +21,7 @@ internal class ManagementClientConstants public const string ApiVersionQuery = "api-version=" + ApiVersion; public const string ApiVersion = "2017-04"; - public const string ServiceBusSupplementartyAuthorizationHeaderName = "ServiceBusSupplementaryAuthorization"; + public const string ServiceBusSupplementaryAuthorizationHeaderName = "ServiceBusSupplementaryAuthorization"; public const string ServiceBusDlqSupplementaryAuthorizationHeaderName = "ServiceBusDlqSupplementaryAuthorization"; public const string HttpErrorSubCodeFormatString = "SubCode={0}"; public static string ConflictOperationInProgressSubCode = From 706e68d459e99141a639b8cfa95846bae36de108 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:33:30 -0400 Subject: [PATCH 61/82] Refactored fields to readonly/const where available --- .../Management/ManagementClientConstants.cs | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs index f9305ab7ef1d..99f49b123e5f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs @@ -22,12 +22,17 @@ internal class ManagementClientConstants public const string ApiVersion = "2017-04"; public const string ServiceBusSupplementaryAuthorizationHeaderName = "ServiceBusSupplementaryAuthorization"; - public const string ServiceBusDlqSupplementaryAuthorizationHeaderName = "ServiceBusDlqSupplementaryAuthorization"; + + public const string ServiceBusDlqSupplementaryAuthorizationHeaderName = + "ServiceBusDlqSupplementaryAuthorization"; + public const string HttpErrorSubCodeFormatString = "SubCode={0}"; - public static string ConflictOperationInProgressSubCode = - string.Format(HttpErrorSubCodeFormatString, ExceptionErrorCodes.ConflictOperationInProgress.ToString("D")); - public static string ForbiddenInvalidOperationSubCode = - string.Format(HttpErrorSubCodeFormatString, ExceptionErrorCodes.ForbiddenInvalidOperation.ToString("D")); + + public static readonly string ConflictOperationInProgressSubCode = + string.Format(HttpErrorSubCodeFormatString, ExceptionErrorCodes.ConflictOperationInProgress.ToString("D")); + + public static readonly string ForbiddenInvalidOperationSubCode = + string.Format(HttpErrorSubCodeFormatString, ExceptionErrorCodes.ForbiddenInvalidOperation.ToString("D")); public static readonly TimeSpan MinimumAllowedTimeToLive = TimeSpan.FromSeconds(1); public static readonly TimeSpan MaximumAllowedTimeToLive = TimeSpan.MaxValue; @@ -36,13 +41,13 @@ internal class ManagementClientConstants public static readonly TimeSpan MinimumAllowedAutoDeleteOnIdle = TimeSpan.FromMinutes(5); public static readonly TimeSpan MaximumDuplicateDetectionHistoryTimeWindow = TimeSpan.FromDays(7); public static readonly TimeSpan MinimumDuplicateDetectionHistoryTimeWindow = TimeSpan.FromSeconds(20); - public static readonly int MinAllowedMaxDeliveryCount = 1; - public static readonly int MaxUserMetadataLength = 1024; + public const int MinAllowedMaxDeliveryCount = 1; + public const int MaxUserMetadataLength = 1024; - public static char[] InvalidEntityPathCharacters = { '@', '?', '#', '*' }; + public static readonly char[] InvalidEntityPathCharacters = { '@', '?', '#', '*' }; // Authorization constants - public static readonly int SupportedClaimsCount = 3; + public const int SupportedClaimsCount = 3; /// Specifies the error codes of the exceptions. public enum ExceptionErrorCodes From 2f2692634ace0d6c14831230863e495dd0fca79e Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:34:08 -0400 Subject: [PATCH 62/82] Removed redundant property initialization --- .../Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs | 4 ++-- .../tests/Infrastructure/LiveTestAttribute.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs index e71ef5a48d82..983231a25e5a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs @@ -200,7 +200,7 @@ public SynchronizationObjectAttribute() public SynchronizationKind Kind { get; set; } } - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)] + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)] [Conditional("CODE_ANALYSIS")] public sealed class SynchronizationPrimitiveAttribute : Attribute { @@ -289,7 +289,7 @@ public sealed class InheritThrowsAttribute : Attribute AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | - AttributeTargets.Delegate, AllowMultiple = false, + AttributeTargets.Delegate, Inherited = false)] [Conditional("CODE_ANALYSIS")] public sealed class SecurityNoteAttribute : Attribute diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs index 4f4051ee972d..eda6b210f799 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs @@ -7,7 +7,7 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure { [TraitDiscoverer("Xunit.Sdk.TraitDiscoverer", "xunit.core")] - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class LiveTestAttribute : Attribute, ITraitAttribute { public LiveTestAttribute(string name = "TestCategory", string value = "Live") {} From c9bf232704ab322b5179f45588b6a4341fd4332f Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:34:47 -0400 Subject: [PATCH 63/82] Refactored namespace to match directory --- .../Microsoft.Azure.ServiceBus/tests/Performance/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index c9130cdbc29f..6b799c037f58 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; using Microsoft.Azure.ServiceBus.Core; -namespace Microsoft.Azure.ServiceBus.Performance +namespace Microsoft.Azure.ServiceBus.UnitTests.Performance { internal class Program { From d4bf4fe1612b0843a71977e0a3ddcdd95b1ab4ba Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:35:29 -0400 Subject: [PATCH 64/82] Fixed string localization warning --- .../src/Management/SubscriptionDescription.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs index 2e3e27697e12..cc48db8b921f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -239,7 +239,7 @@ public string UserMetadata { if (value == null) { - throw new ArgumentNullException(nameof(UserMetadata), $"Value cannot be null"); + throw new ArgumentNullException(nameof(UserMetadata), @"Value cannot be null"); } if (value.Length > ManagementClientConstants.MaxUserMetadataLength) From 925f0d8c1f6c618fc41016b87adf6268d35a95ea Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:36:43 -0400 Subject: [PATCH 65/82] Fixed type reference --- .../Microsoft.Azure.ServiceBus/src/Primitives/TokenProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProvider.cs index f27b5aa699c0..8dc9e86a877d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProvider.cs @@ -76,7 +76,7 @@ public static TokenProvider CreateSharedAccessSignatureTokenProvider(string keyN /// The user defined authentication delegate to provide access token. /// URL of the Azure Active Directory instance to issue token. /// Custom parameters that may be passed into the authentication delegate. - /// The for returning Json web token. + /// The for returning Json web token. public static TokenProvider CreateAzureActiveDirectoryTokenProvider( AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback, string authority, From de9aed95eb17087646b8277d8bc9294fa05732e3 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:37:22 -0400 Subject: [PATCH 66/82] Assigned value to unused variable to satisfy warnings --- .../src/Management/SharedAccessAuthorizationRule.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs index bb7928e4a582..503f9aa15166 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs @@ -264,7 +264,8 @@ private static bool CheckBase64(string base64EncodedString) { try { - Convert.FromBase64String(base64EncodedString); + var _ = Convert.FromBase64String(base64EncodedString); + return true; } catch (Exception) From 3b3dca167b91ba911641ebf4b269cf7bf514a512 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:40:50 -0400 Subject: [PATCH 67/82] Sealed properties to prevent virtual calls in constructors --- .../Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs | 2 +- .../Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs | 2 +- sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs | 2 +- .../Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs | 4 ++-- sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index a0355cd9a6d7..43b6f34ca70c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs @@ -275,7 +275,7 @@ public override TimeSpan OperationTimeout { /// /// Connection object to the service bus namespace. /// - public override ServiceBusConnection ServiceBusConnection { get; } + public sealed override ServiceBusConnection ServiceBusConnection { get; } /// /// Gets the DateTime that the current receiver is locked until. This is only applicable when Sessions are used. diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs index 84d9a11ec0fd..09d7a38508eb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageSender.cs @@ -216,7 +216,7 @@ public override TimeSpan OperationTimeout /// /// Connection object to the service bus namespace. /// - public override ServiceBusConnection ServiceBusConnection { get; } + public sealed override ServiceBusConnection ServiceBusConnection { get; } internal MessagingEntityType? EntityType { get; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs index a4b60cdd8b38..76f0522d1a3c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/QueueClient.cs @@ -223,7 +223,7 @@ public int PrefetchCount /// /// Connection object to the service bus namespace. /// - public override ServiceBusConnection ServiceBusConnection { get; } + public sealed override ServiceBusConnection ServiceBusConnection { get; } internal MessageSender InnerSender { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs index 823ef302add4..417a14fda9b1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs @@ -166,7 +166,7 @@ public SubscriptionClient(ServiceBusConnection serviceBusConnection, string topi /// Gets the formatted path of the subscription client. /// /// - public override string Path { get; } + public sealed override string Path { get; } /// /// Gets the name of the subscription. @@ -230,7 +230,7 @@ public int PrefetchCount /// /// Connection object to the service bus namespace. /// - public override ServiceBusConnection ServiceBusConnection { get; } + public sealed override ServiceBusConnection ServiceBusConnection { get; } internal IInnerSubscriptionClient InnerSubscriptionClient { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs index 309a5c415693..c3dfbf635825 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/TopicClient.cs @@ -138,7 +138,7 @@ public override TimeSpan OperationTimeout /// /// Connection object to the service bus namespace. /// - public override ServiceBusConnection ServiceBusConnection { get; } + public sealed override ServiceBusConnection ServiceBusConnection { get; } internal MessageSender InnerSender { From a506fd3f64a974208805cc609e0128ce54a53bba Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:41:49 -0400 Subject: [PATCH 68/82] Removed redundant constructor parameters --- .../tests/Infrastructure/LiveTestAttribute.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs index eda6b210f799..160d72bdd0ca 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs @@ -10,6 +10,5 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class LiveTestAttribute : Attribute, ITraitAttribute { - public LiveTestAttribute(string name = "TestCategory", string value = "Live") {} } } From 3d2bce710731709438c0d33135a48f42d54b83a2 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:42:20 -0400 Subject: [PATCH 69/82] Sealed property to prevent virtual call in constructor --- .../src/Management/SharedAccessAuthorizationRule.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs index 503f9aa15166..c16957e77af5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs @@ -143,7 +143,7 @@ public string SecondaryKey } } - public override List Rights + public sealed override List Rights { get => _internalRights; set From 5a516615268e3ac3111182f7ba51cd95355e6d9d Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:46:12 -0400 Subject: [PATCH 70/82] Reverted changes to namespace for Program --- .../Microsoft.Azure.ServiceBus/tests/Performance/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index 6b799c037f58..c9130cdbc29f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; using Microsoft.Azure.ServiceBus.Core; -namespace Microsoft.Azure.ServiceBus.UnitTests.Performance +namespace Microsoft.Azure.ServiceBus.Performance { internal class Program { From 4997d8fd92d7ff60fb9d8878102aed78bdadf217 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:46:38 -0400 Subject: [PATCH 71/82] Fixed string localization warning --- .../src/Management/TopicDescription.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs index 1bddae474d5b..26bd2d9945c6 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs @@ -160,7 +160,7 @@ public string UserMetadata { if (value == null) { - throw new ArgumentNullException(nameof(UserMetadata), $"Value cannot be null"); + throw new ArgumentNullException(nameof(UserMetadata), @"Value cannot be null"); } if (value.Length > ManagementClientConstants.MaxUserMetadataLength) From 61d97c27010c3f887a8ebb2c8e92f8ba11c4711b Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:48:11 -0400 Subject: [PATCH 72/82] Fixed XML see reference --- .../src/ServiceBusConnection.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs index dea70305c105..5e7d2379ccb7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs @@ -46,7 +46,7 @@ public ServiceBusConnection(string namespaceConnectionString) /// Creates a new connection to service bus. /// /// Namespace connection string. - /// Retry policy for operations. Defaults to + /// Retry policy for operations. Defaults to /// It is the responsibility of the user to close the connection after use through public ServiceBusConnection(string namespaceConnectionString, RetryPolicy retryPolicy = null) : this(retryPolicy) @@ -70,7 +70,7 @@ public ServiceBusConnection(string namespaceConnectionString, RetryPolicy retryP /// /// Namespace connection string. /// Duration after which individual operations will timeout. - /// Retry policy for operations. Defaults to + /// Retry policy for operations. Defaults to /// It is the responsibility of the user to close the connection after use through [Obsolete("This constructor is obsolete. Use ServiceBusConnection(string namespaceConnectionString, RetryPolicy retryPolicy) constructor instead, providing operationTimeout in the connection string.")] public ServiceBusConnection(string namespaceConnectionString, TimeSpan operationTimeout, RetryPolicy retryPolicy = null) @@ -97,7 +97,7 @@ public ServiceBusConnection(string namespaceConnectionString, TimeSpan operation /// /// Fully qualified domain name for Service Bus. Most likely, {yournamespace}.servicebus.windows.net /// Transport type. - /// Retry policy for operations. Defaults to + /// Retry policy for operations. Defaults to public ServiceBusConnection(string endpoint, TransportType transportType, RetryPolicy retryPolicy = null) : this(retryPolicy) { @@ -135,7 +135,7 @@ internal ServiceBusConnection(RetryPolicy retryPolicy = null) /// /// Retry policy for operations performed on the connection. /// - /// Defaults to + /// Defaults to public RetryPolicy RetryPolicy { get; set; } /// From 3ccfb2a0be3b5a1869d96d05cdf48c9d2cff3ef7 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:58:42 -0400 Subject: [PATCH 73/82] Fixed XML see reference --- .../src/Management/NamespaceInfo.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/NamespaceInfo.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/NamespaceInfo.cs index 15c1631ad7af..7fa308d2ad04 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/NamespaceInfo.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/NamespaceInfo.cs @@ -31,13 +31,13 @@ public class NamespaceInfo public DateTime ModifiedTime { get; set; } /// - /// The SKU/tier of the namespace. Valid only for + /// The SKU/tier of the namespace. Valid only for /// public MessagingSku MessagingSku { get; set; } /// /// Number of messaging units allocated for namespace. - /// Valid only for and + /// Valid only for and /// public int MessagingUnits { get; set; } From 565dde651b6a8c8d2a95f5f9d6027889605460e5 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 20:59:14 -0400 Subject: [PATCH 74/82] Fixed null reference warning --- .../Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs index 87727893800e..9be25a8f64c3 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilter.cs @@ -235,7 +235,7 @@ public override bool Equals(Filter other) { if (FilterProperties != null) { - if (FilterProperties.Count != correlationFilter.FilterProperties.Count) + if (FilterProperties.Count != correlationFilter.FilterProperties?.Count) { return false; } From d205dbd1cfab51e16c2d1fe2b8015f0dac3baef4 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 21:03:15 -0400 Subject: [PATCH 75/82] Fixed field naming --- .../src/Management/QueueDescription.cs | 16 ++++++++-------- .../src/Management/QueueDescriptionExtensions.cs | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index 984033c7d307..5a8070b1da9b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -12,8 +12,8 @@ namespace Microsoft.Azure.ServiceBus.Management /// public class QueueDescription : IEquatable { - internal TimeSpan duplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1); - internal string path; + private TimeSpan _duplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1); + private string _path; private TimeSpan _lockDuration = TimeSpan.FromSeconds(60); private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; @@ -38,11 +38,11 @@ public QueueDescription(string path) /// Cannot have restricted characters: '@','?','#','*' public string Path { - get => path; + get => _path; set { EntityNameHelper.CheckValidQueueName(value, nameof(Path)); - path = value; + _path = value; } } @@ -141,7 +141,7 @@ public TimeSpan AutoDeleteOnIdle /// public TimeSpan DuplicateDetectionHistoryTimeWindow { - get => duplicateDetectionHistoryTimeWindow; + get => _duplicateDetectionHistoryTimeWindow; set { if (value < ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow || value > ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow) @@ -150,7 +150,7 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow $@"The value must be between {ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow} and {ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow}"); } - duplicateDetectionHistoryTimeWindow = value; + _duplicateDetectionHistoryTimeWindow = value; } } @@ -209,7 +209,7 @@ public string ForwardTo } EntityNameHelper.CheckValidQueueName(value, nameof(ForwardTo)); - if (path.Equals(value, StringComparison.CurrentCultureIgnoreCase)) + if (Path.Equals(value, StringComparison.CurrentCultureIgnoreCase)) { throw new InvalidOperationException("Entity cannot have auto-forwarding policy to itself"); } @@ -235,7 +235,7 @@ public string ForwardDeadLetteredMessagesTo } EntityNameHelper.CheckValidQueueName(value, nameof(ForwardDeadLetteredMessagesTo)); - if (path.Equals(value, StringComparison.CurrentCultureIgnoreCase)) + if (Path.Equals(value, StringComparison.CurrentCultureIgnoreCase)) { throw new InvalidOperationException("Entity cannot have auto-forwarding policy to itself"); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescriptionExtensions.cs index 84dcb77acedc..d2e2a1b29d6f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescriptionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescriptionExtensions.cs @@ -98,7 +98,7 @@ private static QueueDescription ParseFromEntryElement(XElement xEntry) qd.EnableDeadLetteringOnMessageExpiration = Boolean.Parse(element.Value); break; case "DuplicateDetectionHistoryTimeWindow": - qd.duplicateDetectionHistoryTimeWindow = XmlConvert.ToTimeSpan(element.Value); + qd.DuplicateDetectionHistoryTimeWindow = XmlConvert.ToTimeSpan(element.Value); break; case "LockDuration": qd.LockDuration = XmlConvert.ToTimeSpan(element.Value); From 8a5cfc6ad453955e6b9f29aab7e644b8daeafa77 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 21:03:48 -0400 Subject: [PATCH 76/82] Removed redundant property initializations --- .../src/Management/QueueDescription.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index 5a8070b1da9b..ee17d928c4f4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -73,7 +73,7 @@ public TimeSpan LockDuration /// will be discarded. /// /// Defaults to false. - public bool RequiresDuplicateDetection { get; set; } = false; + public bool RequiresDuplicateDetection { get; set; } /// /// This indicates whether the queue supports the concept of session. Sessionful-messages follow FIFO ordering. @@ -82,7 +82,7 @@ public TimeSpan LockDuration /// If true, the receiver can only receive messages using . /// Defaults to false. /// - public bool RequiresSession { get; set; } = false; + public bool RequiresSession { get; set; } /// /// The default time to live value for the messages. This is the duration after which the message expires, starting from when @@ -131,7 +131,7 @@ public TimeSpan AutoDeleteOnIdle /// Indicates whether this queue has dead letter support when a message expires. /// /// If true, the expired messages are moved to dead-letter sub-queue. Default value is false. - public bool EnableDeadLetteringOnMessageExpiration { get; set; } = false; + public bool EnableDeadLetteringOnMessageExpiration { get; set; } /// /// The duration of duplicate detection history that is maintained by the service. @@ -248,7 +248,7 @@ public string ForwardDeadLetteredMessagesTo /// Indicates whether the queue is to be partitioned across multiple message brokers. /// /// Defaults to false. - public bool EnablePartitioning { get; set; } = false; + public bool EnablePartitioning { get; set; } /// /// Custom metdata that user can associate with the description. From 8428c9db5ee119c84f8b8f11477bead682e74163 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 21:04:07 -0400 Subject: [PATCH 77/82] Fixed spelling type in comment --- .../src/Management/QueueDescription.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index ee17d928c4f4..e8f374aefe1a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -251,7 +251,7 @@ public string ForwardDeadLetteredMessagesTo public bool EnablePartitioning { get; set; } /// - /// Custom metdata that user can associate with the description. + /// Custom metadata that user can associate with the description. /// /// Cannot be null. Max length is 1024 chars. public string UserMetadata From 065914b0c84d21040906fd6012c8a73eeb71230b Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 21:05:30 -0400 Subject: [PATCH 78/82] Fixed field naming --- .../src/Management/TopicDescription.cs | 12 ++++++------ .../src/Management/TopicDescriptionExtensions.cs | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs index 26bd2d9945c6..94e422360a69 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs @@ -11,8 +11,8 @@ namespace Microsoft.Azure.ServiceBus.Management /// public class TopicDescription : IEquatable { - internal TimeSpan duplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1); - internal string path; + private TimeSpan _duplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1); + private string _path; private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; private string _userMetadata; @@ -91,7 +91,7 @@ public TimeSpan AutoDeleteOnIdle /// public TimeSpan DuplicateDetectionHistoryTimeWindow { - get => duplicateDetectionHistoryTimeWindow; + get => _duplicateDetectionHistoryTimeWindow; set { if (value < ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow || value > ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow) @@ -100,7 +100,7 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow $@"The value must be between {ManagementClientConstants.MinimumDuplicateDetectionHistoryTimeWindow} and {ManagementClientConstants.MaximumDuplicateDetectionHistoryTimeWindow}"); } - duplicateDetectionHistoryTimeWindow = value; + _duplicateDetectionHistoryTimeWindow = value; } } @@ -111,11 +111,11 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow /// Cannot have restricted characters: '@','?','#','*' public string Path { - get => path; + get => _path; set { EntityNameHelper.CheckValidTopicName(value, nameof(Path)); - path = value; + _path = value; } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs index 53f09cc15770..693b791388d5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs @@ -84,7 +84,7 @@ private static TopicDescription ParseFromEntryElement(XElement xEntry) topicDesc.RequiresDuplicateDetection = bool.Parse(element.Value); break; case "DuplicateDetectionHistoryTimeWindow": - topicDesc.duplicateDetectionHistoryTimeWindow = XmlConvert.ToTimeSpan(element.Value); + topicDesc.DuplicateDetectionHistoryTimeWindow = XmlConvert.ToTimeSpan(element.Value); break; case "DefaultMessageTimeToLive": topicDesc.DefaultMessageTimeToLive = XmlConvert.ToTimeSpan(element.Value); From 7516adc87aca5409d62264119876701580d01a91 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 21:05:51 -0400 Subject: [PATCH 79/82] Added conditional access modifier --- .../src/Management/TopicDescriptionExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs index 693b791388d5..2754703aa801 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs @@ -62,7 +62,7 @@ public static IList ParseCollectionFromContent(string xml) private static TopicDescription ParseFromEntryElement(XElement xEntry) { - var name = xEntry.Element(XName.Get("title", ManagementClientConstants.AtomNamespace)).Value; + var name = xEntry.Element(XName.Get("title", ManagementClientConstants.AtomNamespace))?.Value; var topicDesc = new TopicDescription(name); var qdXml = xEntry.Element(XName.Get("content", ManagementClientConstants.AtomNamespace))? From baf7d56dbe63526b3beb2f772061656b022f183e Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 21:11:02 -0400 Subject: [PATCH 80/82] Simplified property accessor --- .../src/Filters/SqlFilter.cs | 53 +++++++++---------- .../src/Filters/SqlFilterExtensions.cs | 2 +- 2 files changed, 25 insertions(+), 30 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs index 4e571d291f3b..b805585977a8 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs @@ -20,9 +20,7 @@ namespace Microsoft.Azure.ServiceBus.Filters /// public class SqlFilter : Filter { - internal PropertyDictionary parameters; - - /// + /// /// Initializes a new instance of the class using the specified SQL expression. /// /// Max allowed length of sql expression is 1024 chars. @@ -57,7 +55,7 @@ public SqlFilter(string sqlExpression) /// Allowed types: string, int, long, bool, double /// /// The value of a filter expression. - public IDictionary Parameters => parameters ?? (parameters = new PropertyDictionary()); + public IDictionary Parameters { get; } = new PropertyDictionary(); /// /// Returns a string representation of . @@ -81,32 +79,29 @@ public override bool Equals(object obj) public override bool Equals(Filter other) { - if (other is SqlFilter sqlFilter) + if (!(other is SqlFilter sqlFilter)) + { + return false; + } + + if (!string.Equals(SqlExpression, sqlFilter.SqlExpression, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + if (Parameters.Count != sqlFilter.Parameters.Count) + { + return false; + } + + foreach (var param in Parameters) { - if (string.Equals(SqlExpression, sqlFilter.SqlExpression, StringComparison.OrdinalIgnoreCase) - && (parameters != null && sqlFilter.parameters != null - || parameters == null && sqlFilter.parameters == null)) - { - if (parameters != null) - { - if (parameters.Count != sqlFilter.parameters.Count) - { - return false; - } - - foreach (var param in parameters) - { - if (!sqlFilter.parameters.TryGetValue(param.Key, out var otherParamValue) || - param.Value == null ^ otherParamValue == null || - param.Value != null && !param.Value.Equals(otherParamValue)) - { - return false; - } - } - } - - return true; - } + if (!sqlFilter.Parameters.TryGetValue(param.Key, out var otherParamValue) || + param.Value == null ^ otherParamValue == null || + param.Value != null && !param.Value.Equals(otherParamValue)) + { + return false; + } } return false; diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs index 7ed688c65e03..cfa4a2eeb6e0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilterExtensions.cs @@ -35,7 +35,7 @@ public static Filter ParseFromXElement(XElement xElement) public static XElement Serialize(this SqlFilter filter, string filterName) { XElement parameterElement = null; - if (filter.parameters != null) + if (filter.Parameters.Count > 0) { parameterElement = new XElement(XName.Get("Parameters", ManagementClientConstants.ServiceBusNamespace)); foreach (var param in filter.Parameters) From b389d6094cbe133a5256dfa3631a3714368f8f24 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 21:17:16 -0400 Subject: [PATCH 81/82] Rolled back some changes --- .../tests/MessageInterop/MessageInteropEnd2EndTests.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs index 3c7c4130379b..f1645119e20a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs @@ -1,9 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -using Microsoft.Azure.ServiceBus.Extensions; -using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; - #if FullNetFx namespace Microsoft.Azure.ServiceBus.UnitTests.MessageInterop { @@ -13,13 +10,14 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.MessageInterop using System.Text; using System.Threading.Tasks; using Xunit; + using InteropExtensions; public class MessageInteropEnd2EndTests { public static IEnumerable TestEnd2EndEntityPermutations => new[] { - new object[] { TransportType.NetMessaging, MessageInteropEnd2EndTests.GetSbConnectionString(TransportType.NetMessaging) }, - new object[] { TransportType.Amqp, MessageInteropEnd2EndTests.GetSbConnectionString(TransportType.Amqp) } + new object[] { TransportType.NetMessaging, GetSbConnectionString(TransportType.NetMessaging) }, + new object[] { TransportType.Amqp, GetSbConnectionString(TransportType.Amqp) } }; [Theory] From 0abba6a94894b14130ea88e8854a090699a532c8 Mon Sep 17 00:00:00 2001 From: "Timothy M. Stepanski" Date: Mon, 27 Apr 2020 21:29:57 -0400 Subject: [PATCH 82/82] Fixed broken tests --- .../tests/MessageInterop/MessageInteropEnd2EndTests.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs index f1645119e20a..ea3dfddb2daa 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs @@ -1,6 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using Microsoft.Azure.ServiceBus.Extensions; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + #if FullNetFx namespace Microsoft.Azure.ServiceBus.UnitTests.MessageInterop { @@ -10,7 +13,6 @@ namespace Microsoft.Azure.ServiceBus.UnitTests.MessageInterop using System.Text; using System.Threading.Tasks; using Xunit; - using InteropExtensions; public class MessageInteropEnd2EndTests {