diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs index 9278dd9d3ce7..fad2c72c579c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkManager.cs @@ -9,121 +9,121 @@ 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) { - 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) + private 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); } } - static async void OnRenewSendReceiveCbsToken(object state) + 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); } - static async void OnRenewRequestResponseCbsToken(object state) + 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); } - async Task RenewCbsTokenAsync(ActiveClientLinkObject activeClientLinkObject) + private async Task RenewCbsTokenAsync(ActiveClientLinkObject activeClientLinkObject) { 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) { 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) + private void OnRequestResponseLinkClosed(object sender, EventArgs e) { - this.ChangeRenewTimer(this.activeRequestResponseClientLink, Timeout.InfiniteTimeSpan); + ChangeRenewTimer(_activeRequestResponseClientLink, Timeout.InfiniteTimeSpan); } - void SetRenewCbsTokenTimer(ActiveClientLinkObject activeClientLinkObject) + private void SetRenewCbsTokenTimer(ActiveClientLinkObject activeClientLinkObject) { var utcNow = DateTime.UtcNow; if (activeClientLinkObject.AuthorizationValidUntilUtc < utcNow) @@ -131,24 +131,27 @@ void SetRenewCbsTokenTimer(ActiveClientLinkObject activeClientLinkObject) return; } - var interval = activeClientLinkObject.AuthorizationValidUntilUtc.Subtract(utcNow) - ActiveClientLinkManager.TokenRefreshBuffer; - if (interval < ActiveClientLinkManager.TokenRefreshBuffer) - interval = TimeSpan.Zero; + 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) + private 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..33b5d75e147f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveClientLinkObject.cs @@ -6,17 +6,17 @@ 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) { - this.LinkObject = amqpLinkObject; - this.EndpointUri = endpointUri; - this.Audience = audience; - this.requiredClaims = requiredClaims; - this.AuthorizationValidUntilUtc = authorizationValidUntilUtc; + LinkObject = amqpLinkObject; + EndpointUri = endpointUri; + Audience = audience; + _requiredClaims = requiredClaims; + 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..e8fe42f8a003 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveRequestResponseLink.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveRequestResponseLink.cs @@ -6,16 +6,16 @@ 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) { - 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..655de0cf03e0 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveSendReceiveClientLink.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/ActiveSendReceiveClientLink.cs @@ -6,16 +6,16 @@ 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) { - 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/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 d6d7d11d0246..b7aea66d328e 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpConnectionHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpConnectionHelper.cs @@ -8,11 +8,11 @@ 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 { - const string CbsSaslMechanismName = "MSSBCBS"; + private const string CbsSaslMechanismName = "MSSBCBS"; public static AmqpSettings CreateAmqpSettings( Version amqpVersion, @@ -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..6219c82a8567 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 }, @@ -42,7 +42,7 @@ 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,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); + var 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) @@ -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 848e6a7c4219..49937e4def93 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpLinkCreator.cs @@ -7,50 +7,50 @@ 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 { - 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) { - this.entityPath = entityPath; - this.serviceBusConnection = serviceBusConnection; - this.endpointAddress = endpointAddress; - this.audience = audience; - this.requiredClaims = requiredClaims; - this.cbsTokenProvider = cbsTokenProvider; - this.amqpLinkSettings = amqpLinkSettings; - this.ClientId = clientId; + _entityPath = entityPath; + _serviceBusConnection = serviceBusConnection; + _endpointAddress = endpointAddress; + _audience = audience; + _requiredClaims = requiredClaims; + _cbsTokenProvider = cbsTokenProvider; + _amqpLinkSettings = amqpLinkSettings; + 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; + var 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..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,9 @@ // 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 { using System; @@ -15,24 +18,23 @@ 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; - - public static AmqpMessage BatchSBMessagesAsAmqpMessage(IEnumerable sbMessages) + 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 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 Convert(IEnumerable sbMessages) { if (sbMessages == null) { @@ -48,7 +50,7 @@ public static AmqpMessage BatchSBMessagesAsAmqpMessage(IEnumerable sb { messageCount++; - amqpMessage = AmqpMessageConverter.SBMessageToAmqpMessage(sbMessage); + amqpMessage = Convert(sbMessage); if (firstAmqpMessage == null) { firstAmqpMessage = amqpMessage; @@ -73,32 +75,36 @@ 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) + if (firstMessage != null) { - amqpMessage.Properties.GroupId = firstMessage.SessionId; - } + if (firstMessage.MessageId != null) + { + amqpMessage.Properties.MessageId = firstMessage.MessageId; + } - if (firstMessage.PartitionKey != null) - { - amqpMessage.MessageAnnotations.Map[AmqpMessageConverter.PartitionKeyName] = - firstMessage.PartitionKey; - } + if (firstMessage.SessionId != null) + { + amqpMessage.Properties.GroupId = firstMessage.SessionId; + } - if (firstMessage.ViaPartitionKey != null) - { - amqpMessage.MessageAnnotations.Map[AmqpMessageConverter.ViaPartitionKeyName] = - firstMessage.ViaPartitionKey; + if (firstMessage.PartitionKey != null) + { + amqpMessage.MessageAnnotations.Map[PartitionKeyName] = + firstMessage.PartitionKey; + } + + if (firstMessage.ViaPartitionKey != null) + { + amqpMessage.MessageAnnotations.Map[ViaPartitionKeyName] = + firstMessage.ViaPartitionKey; + } } amqpMessage.Batchable = true; 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) }); @@ -126,7 +132,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); } @@ -164,7 +170,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) { @@ -200,7 +206,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; } @@ -229,7 +235,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); } } @@ -435,7 +441,7 @@ public static Filter GetFilter(AmqpFilterCodec amqpFilter) return filter; } - static RuleAction GetRuleAction(AmqpRuleActionCodec amqpAction) + private static RuleAction GetRuleAction(AmqpRuleActionCodec amqpAction) { RuleAction action; @@ -532,7 +538,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) @@ -561,60 +567,66 @@ static bool TryGetNetObjectFromAmqpObject(object amqpObject, MappingType mapping netObject = amqpObject; break; case PropertyValueType.Unknown: - if (amqpObject is AmqpSymbol amqpObjectAsAmqpSymbol) - { - netObject = (amqpObjectAsAmqpSymbol).Value; - } - else if (amqpObject is ArraySegment amqpObjectAsArraySegment) - { - ArraySegment binValue = amqpObjectAsArraySegment; - 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 + switch (amqpObject) { - 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; } @@ -622,7 +634,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) @@ -643,13 +655,13 @@ 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 }; } - static AmqpMap GetSqlFilterMap(SqlFilter sqlFilter) + private static AmqpMap GetSqlFilterMap(SqlFilter sqlFilter) { var amqpFilterMap = new AmqpMap { @@ -658,7 +670,7 @@ static AmqpMap GetSqlFilterMap(SqlFilter sqlFilter) return amqpFilterMap; } - static AmqpMap GetCorrelationFilterMap(CorrelationFilter correlationFilter) + private static AmqpMap GetCorrelationFilterMap(CorrelationFilter correlationFilter) { var correlationFilterMap = new AmqpMap { @@ -683,7 +695,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 62176d7b0210..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 { - readonly AmqpMessage requestMessage; + private readonly AmqpMessage _requestMessage; - AmqpRequestMessage(string operation, TimeSpan timeout, string trackingId) + private 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..65c7f145d590 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpRequestResponseLinkCreator.cs @@ -5,22 +5,21 @@ namespace Microsoft.Azure.ServiceBus.Amqp { using System; using Microsoft.Azure.Amqp; - using Microsoft.Azure.ServiceBus.Primitives; 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) { - this.entityPath = entityPath; + _entityPath = entityPath; } 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..36d19a994d9b 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpResponseMessage.cs @@ -12,24 +12,24 @@ 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; - this.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)) { - 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..6abd58edc68d 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 Microsoft.Azure.ServiceBus.Primitives; internal class AmqpSendReceiveLinkCreator : AmqpLinkCreator { @@ -25,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()}:{this.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/src/Amqp/AmqpSubscriptionClient.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpSubscriptionClient.cs index 38e3d1029be9..c7e080748979 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; @@ -14,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() { @@ -37,38 +39,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,34 +80,34 @@ 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; } } } - 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() { - return this.innerReceiver?.CloseAsync(); + return _innerReceiver?.CloseAsync(); } public async Task OnAddRuleAsync(RuleDescription description) @@ -114,13 +116,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 +142,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 +166,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..8d8b8077e82d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/AmqpTransactionEnlistment.cs @@ -7,22 +7,22 @@ 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 + 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, AmqpTransactionManager transactionManager, ServiceBusConnection serviceBusConnection) { - this.transactionId = transaction.TransactionInformation.LocalIdentifier; - this.transactionManager = transactionManager; - this.serviceBusConnection = serviceBusConnection; + _transactionId = transaction.TransactionInformation.LocalIdentifier; + _transactionManager = transactionManager; + _serviceBusConnection = serviceBusConnection; } public ArraySegment AmqpTransactionId { get; private set; } @@ -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) + private 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); + var exception = AmqpExceptionHelper.GetClientException(e); + 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) + private 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); + 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 0cbf94031d65..1565aa5bdb3d 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(); @@ -24,19 +24,19 @@ 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 (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..e58db1bd9f2c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Amqp/Framing/AmqpCorrelationFilterCodec.cs @@ -7,17 +7,17 @@ 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) { - 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/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 0b0be07f8eff..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) { } @@ -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..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) { } @@ -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..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) { } @@ -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/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 14cf1234374f..7078511a9311 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 { - 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) { - this.clientTypeName = clientTypeName; - this.ClientId = GenerateClientId(clientTypeName, postfix); - this.RetryPolicy = retryPolicy ?? RetryPolicy.Default; - this.syncLock = new object(); + _clientTypeName = clientTypeName; + ClientId = GenerateClientId(clientTypeName, postfix); + RetryPolicy = retryPolicy ?? RetryPolicy.Default; + _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,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); } } } @@ -126,7 +126,7 @@ public async Task CloseAsync() protected static long GetNextId() { - return Interlocked.Increment(ref nextId); + return Interlocked.Increment(ref _nextId); } /// @@ -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/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/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/Core/MessageReceiver.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Core/MessageReceiver.cs index a55266d092c4..43b6f34ca70c 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; @@ -13,8 +12,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. @@ -45,16 +44,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 . @@ -98,7 +97,7 @@ public MessageReceiver( throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -123,7 +122,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 +143,7 @@ public MessageReceiver( int prefetchCount = Constants.DefaultClientPrefetchCount) : this(entityPath, null, receiveMode, serviceBusConnection, null, retryPolicy, prefetchCount) { - this.OwnsConnection = false; + OwnsConnection = false; } internal MessageReceiver( @@ -166,35 +165,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; - 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); + SessionIdInternal = sessionId; + _isSessionReceiver = isSessionReceiver; + 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 +228,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 +248,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,14 +268,14 @@ 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; } /// /// 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. @@ -290,13 +289,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. @@ -305,7 +304,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 +319,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 +336,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 +352,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; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +381,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 +411,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 +429,8 @@ public async Task ReceiveDeferredMessageAsync(long sequenceNumber) /// public async Task> ReceiveDeferredMessageAsync(IEnumerable sequenceNumbers) { - this.ThrowIfClosed(); - this.ThrowIfNotPeekLockMode(); + ThrowIfClosed(); + ThrowIfNotPeekLockMode(); if (sequenceNumbers == null) { @@ -443,37 +442,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; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +488,7 @@ public async Task> ReceiveDeferredMessageAsync(IEnumerable /// public Task CompleteAsync(string lockToken) { - return this.CompleteAsync(new[] { lockToken }); + return CompleteAsync(new[] { lockToken }); } /// @@ -503,8 +502,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 +514,34 @@ public async Task CompleteAsync(IEnumerable lockTokens) throw Fx.Exception.Argument(nameof(lockTokens), Resources.ListOfLockTokensCannotBeEmpty); } - MessagingEventSource.Log.MessageCompleteStart(this.ClientId, lockTokenList.Count, lockTokenList); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.CompleteStart(lockTokenList) : null; + MessagingEventSource.Log.MessageCompleteStart(ClientId, lockTokenList.Count, lockTokenList); + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +556,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); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("Abandon", lockToken) : null; + MessagingEventSource.Log.MessageAbandonStart(ClientId, 1, lockToken); + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +602,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); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("Defer", lockToken) : null; + MessagingEventSource.Log.MessageDeferStart(ClientId, 1, lockToken); + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +647,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); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; + MessagingEventSource.Log.MessageDeadLetterStart(ClientId, 1, lockToken); + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +693,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); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.DisposeStart("DeadLetter", lockToken) : null; + MessagingEventSource.Log.MessageDeadLetterStart(ClientId, 1, lockToken); + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +754,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); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.RenewLockStart(lockToken) : null; + MessagingEventSource.Log.MessageRenewLockStart(ClientId, 1, lockToken); + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +802,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 +817,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 +827,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 +837,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); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.PeekStart(fromSequenceNumber, messageCount) : null; + MessagingEventSource.Log.MessagePeekStart(ClientId, fromSequenceNumber, messageCount); + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +859,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 +882,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 +894,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 +903,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 +921,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 +930,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 +955,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 +965,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 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 +995,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,12 +1046,12 @@ 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); } - var message = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage); + var message = AmqpMessageConverter.Convert(amqpMessage); if (brokeredMessages == null) { brokeredMessages = new List(); @@ -1076,10 +1075,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,36 +1086,36 @@ 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; 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); - message = AmqpMessageConverter.AmqpMessageToSBMessage(amqpMessage, true); + message = AmqpMessageConverter.Convert(amqpMessage, true); messages.Add(message); } if (message != null) { - this.LastPeekedSequenceNumber = message.SystemProperties.SequenceNumber; + LastPeekedSequenceNumber = message.SystemProperties.SequenceNumber; } return messages; } 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; } @@ -1134,20 +1133,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) { @@ -1156,11 +1155,11 @@ 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; - this.requestResponseLockedMessages.AddOrUpdate(lockToken, message.SystemProperties.LockedUntilUtc); + _requestResponseLockedMessages.AddOrUpdate(lockToken, message.SystemProperties.LockedUntilUtc); } messages.Add(message); @@ -1182,52 +1181,52 @@ 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) { if (deadLetterReason != null && deadLetterReason.Length > 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) }; - if (lockTokens.Any(lt => 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 +1235,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,56 +1268,56 @@ 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) + 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 this.RegisteredPlugins) + foreach (var plugin in RegisteredPlugins) { try { @@ -1338,9 +1337,9 @@ async Task ProcessMessage(Message message) return processedMessage; } - async Task> ProcessMessages(IList messageList) + private async Task> ProcessMessages(IList messageList) { - if (this.RegisteredPlugins.Count < 1) + if (RegisteredPlugins.Count < 1) { return messageList; } @@ -1348,42 +1347,42 @@ 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); } return processedMessageList; } - async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome outcome) + private 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); + var deliveryTags = ConvertLockTokensToDeliveryTags(lockTokens); ReceivingAmqpLink receiveLink = null; try { - ArraySegment transactionId = AmqpConstants.NullBinary; + var 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.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]; 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), @@ -1395,12 +1394,12 @@ async Task DisposeMessagesAsync(IEnumerable lockTokens, Outcome outcome) 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)) { - if (this.isSessionReceiver) + if (_isSessionReceiver) { throw new SessionLockLostException(Resources.SessionLockExpiredOnMessageSession); } @@ -1418,8 +1417,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); } @@ -1431,14 +1430,14 @@ 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 { // 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 +1476,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(); @@ -1494,82 +1493,82 @@ async Task DisposeMessageRequestResponseAsync(Guid[] lockTokens, DispositionStat } } - async Task CreateLinkAsync(TimeSpan timeout) + private 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 }, + new[] { endpointUri.AbsoluteUri }, claims, - this.CbsTokenProvider, + CbsTokenProvider, amqpLinkSettings, - this.ClientId); + ClientId); - Tuple linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); + var linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); var receivingAmqpLink = (ReceivingAmqpLink) linkDetails.Item1; var activeSendReceiveClientLink = new ActiveSendReceiveClientLink( receivingAmqpLink, endpointUri, - new string[] { endpointUri.AbsoluteUri }, + new[] { endpointUri.AbsoluteUri }, claims, linkDetails.Item2); - this.clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); + _clientLinkManager.SetActiveSendReceiveLink(activeSendReceiveClientLink); - MessagingEventSource.Log.AmqpReceiveLinkCreateStop(this.ClientId); + MessagingEventSource.Log.AmqpReceiveLinkCreateStop(ClientId); return receivingAmqpLink; } // TODO: Consolidate the link creation paths - async Task CreateRequestResponseLinkAsync(TimeSpan timeout) + private 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 }, + new[] { endpointUri.AbsoluteUri }, claims, - this.CbsTokenProvider, + CbsTokenProvider, amqpLinkSettings, - this.ClientId); + ClientId); var linkDetails = await amqpRequestResponseLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); @@ -1577,16 +1576,16 @@ async Task CreateRequestResponseLinkAsync(TimeSpan time var activeRequestResponseClientLink = new ActiveRequestResponseLink( requestResponseAmqpLink, endpointUri, - new string[] { endpointUri.AbsoluteUri }, + new[] { endpointUri.AbsoluteUri }, claims, linkDetails.Item2); - this.clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); + _clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); - MessagingEventSource.Log.AmqpReceiveLinkCreateStop(this.ClientId); + MessagingEventSource.Log.AmqpReceiveLinkCreateStop(ClientId); return requestResponseAmqpLink; } - void OnSessionReceiverLinkClosed(object sender, EventArgs e) + private void OnSessionReceiverLinkClosed(object sender, EventArgs e) { var receivingAmqpLink = (ReceivingAmqpLink)sender; if (receivingAmqpLink != null) @@ -1597,45 +1596,45 @@ 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); } } - List> ConvertLockTokensToDeliveryTags(IEnumerable lockTokens) + private List> ConvertLockTokensToDeliveryTags(IEnumerable lockTokens) { return lockTokens.Select(lockToken => new ArraySegment(lockToken.ToByteArray())).ToList(); } - void ThrowIfNotPeekLockMode() + private 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.")); } } - void ThrowIfSessionLockLost() + private void ThrowIfSessionLockLost() { - if (this.LinkException != null) + if (LinkException != null) { - throw this.LinkException; + throw LinkException; } } - Outcome GetAbandonOutcome(IDictionary propertiesToModify) + private Outcome GetAbandonOutcome(IDictionary propertiesToModify) { - return this.GetModifiedOutcome(propertiesToModify, false); + return GetModifiedOutcome(propertiesToModify, false); } - Outcome GetDeferOutcome(IDictionary propertiesToModify) + private Outcome GetDeferOutcome(IDictionary propertiesToModify) { - return this.GetModifiedOutcome(propertiesToModify, true); + return GetModifiedOutcome(propertiesToModify, true); } - Outcome GetModifiedOutcome(IDictionary propertiesToModify, bool undeliverableHere) + private Outcome GetModifiedOutcome(IDictionary propertiesToModify, bool undeliverableHere) { - Modified modified = new Modified(); + var modified = new Modified(); if (undeliverableHere) { modified.UndeliverableHere = true; @@ -1660,7 +1659,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 18d22681cc86..09d7a38508eb 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; @@ -13,8 +12,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. @@ -36,10 +35,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. @@ -72,7 +71,7 @@ public MessageSender( throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -92,7 +91,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 +106,7 @@ public MessageSender( RetryPolicy retryPolicy = null) : this(entityPath, null, null, serviceBusConnection, null, retryPolicy) { - this.OwnsConnection = false; + OwnsConnection = false; } /// @@ -130,7 +129,7 @@ public MessageSender( RetryPolicy retryPolicy = null) :this(viaEntityPath, entityPath, null, serviceBusConnection, null, retryPolicy) { - this.OwnsConnection = false; + OwnsConnection = false; } internal MessageSender( @@ -149,38 +148,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,31 +209,31 @@ internal MessageSender( /// public override TimeSpan OperationTimeout { - get => this.ServiceBusConnection.OperationTimeout; - set => this.ServiceBusConnection.OperationTimeout = value; + get => ServiceBusConnection.OperationTimeout; + set => ServiceBusConnection.OperationTimeout = value; } /// /// Connection object to the service bus namespace. /// - public override ServiceBusConnection ServiceBusConnection { get; } + public sealed override ServiceBusConnection ServiceBusConnection { get; } internal MessagingEntityType? EntityType { get; } 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 . /// public Task SendAsync(Message message) { - return this.SendAsync(new[] { message }); + return SendAsync(new[] { message }); } /// @@ -243,43 +242,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; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +289,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 +303,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; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +353,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; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +394,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 +413,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 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,12 +453,12 @@ 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) + private static int ValidateMessages(IList messageList) { var count = 0; if (messageList == null) @@ -476,7 +475,7 @@ static int ValidateMessages(IList messageList) return count; } - static void ValidateMessage(Message message) + private static void ValidateMessage(Message message) { if (message.SystemProperties.IsLockTokenSet) { @@ -484,21 +483,21 @@ 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 this.RegisteredPlugins) + foreach (var plugin in RegisteredPlugins) { try { @@ -518,9 +517,9 @@ async Task ProcessMessage(Message message) return processedMessage; } - async Task> ProcessMessages(IList messageList) + private async Task> ProcessMessages(IList messageList) { - if (this.RegisteredPlugins.Count < 1) + if (RegisteredPlugins.Count < 1) { return messageList; } @@ -528,31 +527,31 @@ 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); } return processedMessageList; } - async Task OnSendAsync(IList messageList) + private async Task OnSendAsync(IList messageList) { - var timeoutHelper = new TimeoutHelper(this.OperationTimeout, true); - using (var amqpMessage = AmqpMessageConverter.BatchSBMessagesAsAmqpMessage(messageList)) + var timeoutHelper = new TimeoutHelper(OperationTimeout, true); + using (var amqpMessage = AmqpMessageConverter.Convert(messageList)) { SendingAmqpLink amqpLink = null; try { - ArraySegment transactionId = AmqpConstants.NullBinary; + var 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.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 +562,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) { @@ -578,27 +577,27 @@ async Task OnSendAsync(IList messageList) } } - async Task OnScheduleMessageAsync(Message message) + 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, - 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; } - 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(); { @@ -623,7 +622,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); @@ -647,26 +646,26 @@ async Task OnScheduleMessageAsync(Message message) } } - async Task OnCancelScheduledMessageAsync(long sequenceNumber) + private 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) { @@ -679,39 +678,39 @@ async Task OnCancelScheduledMessageAsync(long sequenceNumber) } } - async Task CreateLinkAsync(TimeSpan timeout) + private 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); - audience = new string[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; - amqpLinkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, this.TransferDestinationPath); + var transferDestinationEndpointUri = new Uri(ServiceBusConnection.Endpoint, TransferDestinationPath); + 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}; - var amqpSendReceiveLinkCreator = new AmqpSendReceiveLinkCreator(this.SendingLinkDestination, this.ServiceBusConnection, endpointUri, audience, claims, this.CbsTokenProvider, amqpLinkSettings, this.ClientId); - Tuple linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); + var amqpSendReceiveLinkCreator = new AmqpSendReceiveLinkCreator(SendingLinkDestination, ServiceBusConnection, endpointUri, audience, claims, CbsTokenProvider, amqpLinkSettings, ClientId); + var linkDetails = await amqpSendReceiveLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); var sendingAmqpLink = (SendingAmqpLink) linkDetails.Item1; var activeSendReceiveClientLink = new ActiveSendReceiveClientLink( @@ -721,44 +720,44 @@ 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) + private 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); - audience = new string[] { endpointUri.AbsoluteUri, transferDestinationEndpointUri.AbsoluteUri }; - amqpLinkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, this.TransferDestinationPath); + var transferDestinationEndpointUri = new Uri(ServiceBusConnection.Endpoint, TransferDestinationPath); + 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 }; var amqpRequestResponseLinkCreator = new AmqpRequestResponseLinkCreator( entityPath, - this.ServiceBusConnection, + ServiceBusConnection, endpointUri, audience, claims, - this.CbsTokenProvider, + CbsTokenProvider, amqpLinkSettings, - this.ClientId); + ClientId); - Tuple linkDetails = + var linkDetails = await amqpRequestResponseLinkCreator.CreateAndOpenAmqpLinkAsync().ConfigureAwait(false); var requestResponseAmqpLink = (RequestResponseAmqpLink) linkDetails.Item1; @@ -768,14 +767,14 @@ async Task CreateRequestResponseLinkAsync(TimeSpan time audience, claims, linkDetails.Item2); - this.clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); + _clientLinkManager.SetActiveRequestResponseLink(activeRequestResponseClientLink); return requestResponseAmqpLink; } - ArraySegment GetNextDeliveryTag() + private 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..a40991e0d6b2 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); } /// @@ -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/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..39cc8baea125 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/DataContractBinarySerializer.cs @@ -1,29 +1,29 @@ // 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 /// instead of text. /// - sealed class DataContractBinarySerializer : XmlObjectSerializer + internal sealed class DataContractBinarySerializer : XmlObjectSerializer { - readonly DataContractSerializer dataContractSerializer; + private readonly DataContractSerializer _dataContractSerializer; /// /// Initializes a new DataContractBinarySerializer instance /// 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/Extensions/MessageDiagnosticsExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Extensions/MessageDiagnosticsExtensions.cs index a7547c2641f0..76110bbbbff5 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 @@ -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/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 4e0000eb36cd..9be25a8f64c3 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. /// /// @@ -30,7 +30,7 @@ namespace Microsoft.Azure.ServiceBus /// public sealed class CorrelationFilter : Filter { - internal PropertyDictionary properties; + internal PropertyDictionary FilterProperties; /// /// Initializes a new instance of the class with default values. @@ -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 => FilterProperties ?? (FilterProperties = new PropertyDictionary()); /// /// Converts the value of the current instance to its equivalent string representation. @@ -162,27 +162,27 @@ 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; + var propertyName = pair.Key; + var propertyValue = pair.Value; - this.AppendPropertyExpression(ref isFirstExpression, stringBuilder, propertyName, propertyValue); + AppendPropertyExpression(ref isFirstExpression, stringBuilder, propertyName, propertyValue); } 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) { @@ -201,12 +201,12 @@ void AppendPropertyExpression(ref bool firstExpression, StringBuilder builder, s public override int GetHashCode() { - int hash = 13; + var 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,36 +215,36 @@ 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) + && (FilterProperties != null && correlationFilter.FilterProperties != null + || FilterProperties == null && correlationFilter.FilterProperties == null)) { - if (this.properties != null) + if (FilterProperties != null) { - if (this.properties.Count != correlationFilter.properties.Count) + if (FilterProperties.Count != correlationFilter.FilterProperties?.Count) { return false; } - foreach (var param in this.properties) + foreach (var param in FilterProperties) { - if (!correlationFilter.properties.TryGetValue(param.Key, out var otherParamValue) || - (param.Value == null ^ otherParamValue == null) || - (param.Value != null && !param.Value.Equals(otherParamValue))) + if (!correlationFilter.FilterProperties.TryGetValue(param.Key, out var 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/CorrelationFilterExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/CorrelationFilterExtensions.cs index eb4d58f6b511..0a13f649a8f7 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 Microsoft.Azure.ServiceBus.Filters; - using Microsoft.Azure.ServiceBus.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) { @@ -62,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), 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 00cd64744835..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 Microsoft.Azure.ServiceBus.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 54b67505feb3..562d37fb8416 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 Microsoft.Azure.ServiceBus.Filters; - using Microsoft.Azure.ServiceBus.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) { @@ -35,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)) @@ -64,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/RuleDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescription.cs index a7de9bbaa032..f5b04cad0ca1 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 Microsoft.Azure.ServiceBus.Management; - using Microsoft.Azure.ServiceBus.Primitives; +using System; +using Microsoft.Azure.ServiceBus.Primitives; - /// +namespace Microsoft.Azure.ServiceBus.Filters +{ + /// /// Represents a description of a rule. /// public sealed class RuleDescription : IEquatable @@ -21,14 +20,14 @@ 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. /// public RuleDescription() - : this(RuleDescription.DefaultRuleName, TrueFilter.Default) + : this(DefaultRuleName, TrueFilter.Default) { } @@ -47,7 +46,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 +55,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 +66,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 +84,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; } } @@ -102,11 +101,11 @@ internal DateTime CreatedAt public override int GetHashCode() { - int hash = 13; + var 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,20 +113,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))) - { - 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) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/RuleDescriptionExtensions.cs index b5c5d044b85d..f0b20ec742ef 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 Microsoft.Azure.ServiceBus.Management; - using Microsoft.Azure.ServiceBus.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) { @@ -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))? @@ -132,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/SqlFilter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlFilter.cs index 7b07e1ea556c..b805585977a8 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. /// /// @@ -20,9 +20,7 @@ namespace Microsoft.Azure.ServiceBus /// 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. @@ -42,7 +40,7 @@ public SqlFilter(string sqlExpression) Constants.MaximumSqlFilterStatementLength)); } - this.SqlExpression = sqlExpression; + SqlExpression = sqlExpression; } /// @@ -57,7 +55,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 { get; } = new PropertyDictionary(); /// /// Returns a string representation of . @@ -65,48 +63,45 @@ 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 (!(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(this.SqlExpression, sqlFilter.SqlExpression, StringComparison.OrdinalIgnoreCase) - && (this.parameters != null && sqlFilter.parameters != null - || this.parameters == null && sqlFilter.parameters == null)) - { - if (this.parameters != null) - { - if (this.parameters.Count != sqlFilter.parameters.Count) - { - return false; - } - - foreach (var param in this.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 179d6b153f3c..cfa4a2eeb6e0 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 Microsoft.Azure.ServiceBus.Filters; - using Microsoft.Azure.ServiceBus.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) { @@ -36,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) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs index 38195cf15d33..987bfb0ad7ba 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/SqlRuleAction.cs @@ -1,19 +1,19 @@ // 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 { - internal PropertyDictionary parameters; + internal PropertyDictionary Properties; /// /// Initializes a new instance of the class with the specified SQL expression. @@ -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 => Properties ?? (Properties = new PropertyDictionary()); /// /// Returns a string representation of . @@ -58,40 +58,40 @@ 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) + && (Properties != null && sqlAction.Properties != null + || Properties == null && sqlAction.Properties == null)) { - if (this.parameters != null) + if (Properties != null) { - if (this.parameters.Count != sqlAction.parameters.Count) + if (Properties.Count != sqlAction.Properties?.Count) { return false; } - foreach (var param in this.parameters) + foreach (var param in Properties) { - if (!sqlAction.parameters.TryGetValue(param.Key, out var otherParamValue) || - (param.Value == null ^ otherParamValue == null) || - (param.Value != null && !param.Value.Equals(otherParamValue))) + if (!sqlAction.Properties.TryGetValue(param.Key, out var 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/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/Filters/XmlObjectConvertor.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Filters/XmlObjectConvertor.cs index 194c16b2ed63..236f63aec441 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 { @@ -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/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/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/AuthorizationRules.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/AuthorizationRules.cs index 5756c30e7a22..0f0e9ce2402f 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 => this.Count > 0; - - internal XElement Serialize() + internal XElement Serialize() { var rules = new XElement( XName.Get("AuthorizationRules", ManagementClientConstants.ServiceBusNamespace), @@ -31,12 +29,12 @@ internal static AuthorizationRules ParseFromXElement(XElement xElement) public override int GetHashCode() { - int hash = 7; + var hash = 7; unchecked { foreach (var rule in this) { - hash = (hash * 7) + rule.GetHashCode(); + hash = hash * 7 + rule.GetHashCode(); } } @@ -46,23 +44,23 @@ 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; } 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 4af36b22c91e..39dcec56a87a 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; @@ -11,15 +13,15 @@ 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 { - 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. @@ -47,28 +49,28 @@ 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; - this.tokenProvider = tokenProvider ?? CreateTokenProvider(connectionStringBuilder); - this.port = GetPort(connectionStringBuilder.Endpoint); - this.clientId = nameof(ManagementClient) + Guid.NewGuid().ToString("N").Substring(0, 6); + _httpClient = new HttpClient { Timeout = connectionStringBuilder.OperationTimeout }; + _endpointFqdn = connectionStringBuilder.Endpoint; + _tokenProvider = tokenProvider ?? CreateTokenProvider(connectionStringBuilder); + _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, _tokenProvider.ToString()); } 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); } @@ -362,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); @@ -391,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); @@ -422,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); @@ -457,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); @@ -489,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); @@ -518,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); @@ -549,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); @@ -582,7 +584,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 +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(this.endpointFQDN); + queueDescription.NormalizeDescription(_endpointFqdn); var atomRequest = queueDescription.Serialize().ToString(); var content = await PutEntity( queueDescription.Path, @@ -631,7 +633,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 +680,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 +702,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 +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(this.endpointFQDN); + subscriptionDescription.NormalizeDescription(_endpointFqdn); subscriptionDescription.DefaultRuleDescription = defaultRule; var atomRequest = subscriptionDescription.Serialize().ToString(); var content = await PutEntity( @@ -787,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(this.endpointFQDN); + queueDescription.NormalizeDescription(_endpointFqdn); var atomRequest = queueDescription.Serialize().ToString(); @@ -841,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(this.endpointFQDN); + subscriptionDescription.NormalizeDescription(_endpointFqdn); var atomRequest = subscriptionDescription.Serialize().ToString(); var content = await PutEntity( EntityNameHelper.FormatSubscriptionPath(subscriptionDescription.TopicPath, subscriptionDescription.SubscriptionName), @@ -905,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) { @@ -933,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) { @@ -963,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) { @@ -976,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; } @@ -1099,50 +1101,50 @@ 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}"; + 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; 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(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}" + Query = $"{ManagementClientConstants.ApiVersionQuery}" }.Uri; var request = new HttpRequestMessage(HttpMethod.Put, uri); @@ -1159,38 +1161,38 @@ private async Task PutEntity(string path, string requestBody, bool isUpd if (!string.IsNullOrWhiteSpace(forwardTo)) { - var token = await this.GetToken(forwardTo).ConfigureAwait(false); - request.Headers.Add(ManagementClientConstants.ServiceBusSupplementartyAuthorizationHeaderName, token); + var token = await GetToken(forwardTo).ConfigureAwait(false); + request.Headers.Add(ManagementClientConstants.ServiceBusSupplementaryAuthorizationHeaderName, 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 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, - Query = ManagementClientConstants.apiVersionQuery + 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 +1200,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 +1213,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 +1228,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/ManagementClientConstants.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs index 9c37b5fc6082..99f49b123e5f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/ManagementClientConstants.cs @@ -18,16 +18,21 @@ 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"; - public const string ServiceBusDlqSupplementaryAuthorizationHeaderName = "ServiceBusDlqSupplementaryAuthorization"; + public const string ServiceBusSupplementaryAuthorizationHeaderName = "ServiceBusSupplementaryAuthorization"; + + 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 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; } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs index be5fd4badea5..e8f374aefe1a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/QueueDescription.cs @@ -5,22 +5,22 @@ 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. /// 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 _duplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1); + private 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; + private string _forwardDeadLetteredMessagesTo; + private string _userMetadata; /// /// Initializes a new instance of QueueDescription class with the specified relative path. @@ -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; } } @@ -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 @@ -95,16 +95,16 @@ public TimeSpan LockDuration /// public TimeSpan DefaultMessageTimeToLive { - get => this.defaultMessageTimeToLive; + get => _defaultMessageTimeToLive; set { 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}"); } - this.defaultMessageTimeToLive = value; + _defaultMessageTimeToLive = value; } } @@ -114,16 +114,16 @@ 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) { throw new ArgumentOutOfRangeException(nameof(AutoDeleteOnIdle), - $"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); + $@"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } - this.autoDeleteOnIdle = value; + _autoDeleteOnIdle = value; } } @@ -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. @@ -141,16 +141,16 @@ public TimeSpan AutoDeleteOnIdle /// public TimeSpan DuplicateDetectionHistoryTimeWindow { - get => this.duplicateDetectionHistoryTimeWindow; + get => _duplicateDetectionHistoryTimeWindow; set { 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}"); } - this.duplicateDetectionHistoryTimeWindow = value; + _duplicateDetectionHistoryTimeWindow = value; } } @@ -162,16 +162,16 @@ public TimeSpan DuplicateDetectionHistoryTimeWindow /// Default value is 10. Minimum value is 1. public int MaxDeliveryCount { - get => this.maxDeliveryCount; + get => _maxDeliveryCount; set { 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}"); } - 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; } } @@ -248,28 +248,28 @@ 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. + /// Custom metadata that user can associate with the description. /// /// Cannot be null. Max length is 1024 chars. public string UserMetadata { - get => this.userMetadata; + get => _userMetadata; set { 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) { - throw new ArgumentOutOfRangeException(nameof(UserMetadata), $"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); + throw new ArgumentOutOfRangeException(nameof(UserMetadata), $@"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } - this.userMetadata = value; + _userMetadata = value; } } @@ -281,42 +281,39 @@ 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))) - { - 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) 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); 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..c16957e77af5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SharedAccessAuthorizationRule.cs @@ -11,20 +11,20 @@ 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. /// 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; - private string internalSecondaryKey; - private List internalRights; + private string _internalKeyName; + private string _internalPrimaryKey; + private string _internalSecondaryKey; + private List _internalRights; internal SharedAccessAuthorizationRule() { @@ -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)) @@ -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))) @@ -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)) @@ -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)) @@ -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)) @@ -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)) @@ -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 + public sealed override List Rights { - get => this.internalRights; + get => _internalRights; set { if (value == null || value.Count < 0 || value.Count > ManagementClientConstants.SupportedClaimsCount) @@ -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"); @@ -161,23 +161,24 @@ 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)); } - this.internalRights = value; + _internalRights = value; } } /// Returns the hash code for this instance. public override int GetHashCode() { - int hash = 13; + var 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 +187,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. @@ -199,23 +200,23 @@ public override bool Equals(AuthorizationRule other) return false; } - 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)) + 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)) { 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); + var thisRights = new HashSet(Rights); if (comparand.Rights.Count != thisRights.Count) { return false; @@ -250,7 +251,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); @@ -263,7 +264,8 @@ private static bool CheckBase64(string base64EncodedString) { try { - Convert.FromBase64String(base64EncodedString); + var _ = Convert.FromBase64String(base64EncodedString); + return true; } catch (Exception) @@ -311,16 +313,16 @@ 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), 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..cc48db8b921f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescription.cs @@ -1,25 +1,27 @@ // 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; using System.Collections.Generic; - using Microsoft.Azure.ServiceBus.Primitives; + using Primitives; /// /// Represents the metadata description of the subscription. /// 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; + private string _forwardDeadLetteredMessagesTo; + private string _userMetadata; /// /// Initializes a new instance of SubscriptionDescription class with the specified name and topic path. @@ -28,8 +30,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 +41,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,16 +69,16 @@ public TimeSpan LockDuration /// public TimeSpan DefaultMessageTimeToLive { - get => this.defaultMessageTimeToLive; + get => _defaultMessageTimeToLive; set { 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}"); } - this.defaultMessageTimeToLive = value; + _defaultMessageTimeToLive = value; } } @@ -86,16 +88,16 @@ 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) { throw new ArgumentOutOfRangeException(nameof(AutoDeleteOnIdle), - $"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); + $@"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } - this.autoDeleteOnIdle = value; + _autoDeleteOnIdle = value; } } @@ -118,11 +120,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 +135,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,16 +151,16 @@ public string SubscriptionName /// Default value is 10. Minimum value is 1. public int MaxDeliveryCount { - get => this.maxDeliveryCount; + get => _maxDeliveryCount; set { 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}"); } - this.maxDeliveryCount = value; + _maxDeliveryCount = value; } } @@ -175,22 +177,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 +203,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,20 +234,20 @@ public string ForwardDeadLetteredMessagesTo /// Cannot be null. Max length is 1024 chars. public string UserMetadata { - get => this.userMetadata; + get => _userMetadata; set { 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) { - throw new ArgumentOutOfRangeException(nameof(UserMetadata), $"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); + throw new ArgumentOutOfRangeException(nameof(UserMetadata), $@"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } - this.userMetadata = value; + _userMetadata = value; } } @@ -259,11 +261,11 @@ public string UserMetadata public override int GetHashCode() { - int hash = 7; + var 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,31 +274,28 @@ 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)) - { - 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) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/SubscriptionDescriptionExtensions.cs index 40ac2ad514cc..7b9e21690724 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; @@ -23,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/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..94e422360a69 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescription.cs @@ -11,11 +11,11 @@ namespace Microsoft.Azure.ServiceBus.Management /// 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 _duplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1); + private string _path; + private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; + private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; + private string _userMetadata; /// /// Initializes a new instance of TopicDescription class with the specified relative path. @@ -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,16 +37,16 @@ public TopicDescription(string path) /// public TimeSpan DefaultMessageTimeToLive { - get => this.defaultMessageTimeToLive; + get => _defaultMessageTimeToLive; set { 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}"); } - this.defaultMessageTimeToLive = value; + _defaultMessageTimeToLive = value; } } @@ -56,16 +56,16 @@ 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) { throw new ArgumentOutOfRangeException(nameof(AutoDeleteOnIdle), - $"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); + $@"The value must be greater than {ManagementClientConstants.MinimumAllowedAutoDeleteOnIdle}"); } - this.autoDeleteOnIdle = value; + _autoDeleteOnIdle = value; } } @@ -91,16 +91,16 @@ public TimeSpan AutoDeleteOnIdle /// public TimeSpan DuplicateDetectionHistoryTimeWindow { - get => this.duplicateDetectionHistoryTimeWindow; + get => _duplicateDetectionHistoryTimeWindow; set { 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}"); } - 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,20 +155,20 @@ public string Path /// Cannot be null. Max length is 1024 chars. public string UserMetadata { - get => this.userMetadata; + get => _userMetadata; set { 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) { - throw new ArgumentOutOfRangeException(nameof(UserMetadata), $"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); + throw new ArgumentOutOfRangeException(nameof(UserMetadata), $@"Length cannot cross {ManagementClientConstants.MaxUserMetadataLength} characters"); } - this.userMetadata = value; + _userMetadata = value; } } @@ -180,36 +180,32 @@ 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))) - { - 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) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Management/TopicDescriptionExtensions.cs index 2aca66feca67..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))? @@ -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); @@ -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/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/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 3d04fcfb1eb9..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 @@ -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; @@ -343,20 +343,20 @@ 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. /// /// 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 @@ -508,9 +508,9 @@ internal object BodyObject set; } - void ThrowIfNotReceived() + private 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..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 { - int maxConcurrentCalls; - TimeSpan maxAutoRenewDuration; + private int _maxConcurrentCalls; + private TimeSpan _maxAutoRenewDuration; /// Initializes a new instance of the class. /// Default Values: @@ -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..21ce043d0f0f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessageReceivePump.cs @@ -4,21 +4,20 @@ namespace Microsoft.Azure.ServiceBus { using System; - using System.Diagnostics; using System.Threading; using System.Threading.Tasks; 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, @@ -26,107 +25,107 @@ public MessageReceivePump(IMessageReceiver messageReceiver, Uri endpoint, CancellationToken pumpCancellationToken) { - this.messageReceiver = messageReceiver ?? throw new ArgumentNullException(nameof(messageReceiver)); - this.registerHandlerOptions = registerHandlerOptions; - this.onMessageCallback = callback; - this.endpoint = endpoint.Authority; - this.pumpCancellationToken = pumpCancellationToken; - this.maxConcurrentCallsSemaphoreSlim = new SemaphoreSlim(this.registerHandlerOptions.MaxConcurrentCalls); - this.diagnosticSource = new ServiceBusDiagnosticSource(messageReceiver.Path, endpoint); + _messageReceiver = messageReceiver ?? throw new ArgumentNullException(nameof(messageReceiver)); + _registerHandlerOptions = registerHandlerOptions; + _onMessageCallback = callback; + _endpoint = endpoint.Authority; + _pumpCancellationToken = pumpCancellationToken; + _maxConcurrentCallsSemaphoreSlim = new SemaphoreSlim(_registerHandlerOptions.MaxConcurrentCalls); + _diagnosticSource = new ServiceBusDiagnosticSource(messageReceiver.Path, endpoint); } public void StartPump() { - TaskExtensionHelper.Schedule(() => this.MessagePumpTaskAsync()); + TaskExtensionHelper.Schedule(() => MessagePumpTaskAsync()); } - bool ShouldRenewLock() + private bool ShouldRenewLock() { return - this.messageReceiver.ReceiveMode == ReceiveMode.PeekLock && - this.registerHandlerOptions.AutoRenewLock; + _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, 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() + private 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); } }); } } - 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(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); } } }); } - 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(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) + private async Task MessageDispatchTaskInstrumented(Message message) { - Activity activity = this.diagnosticSource.ProcessStart(message); + var activity = _diagnosticSource.ProcessStart(message); Task processTask = null; try { @@ -135,55 +134,55 @@ 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); } } - async Task MessageDispatchTask(Message message) + private 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,13 +194,13 @@ 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) + private void CancelAutoRenewLock(object state) { var renewLockCancellationTokenSource = (CancellationTokenSource)state; try @@ -214,46 +213,46 @@ void CancelAutoRenewLock(object state) } } - async Task AbandonMessageIfNeededAsync(Message message) + private 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); } } - async Task CompleteMessageIfNeededAsync(Message message) + private 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) + private 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 +264,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 +277,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..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; @@ -14,7 +13,7 @@ namespace Microsoft.Azure.ServiceBus internal class MessageSession : MessageReceiver, IMessageSession { - private readonly ServiceBusDiagnosticSource diagnosticSource; + private readonly ServiceBusDiagnosticSource _diagnosticSource; public MessageSession( string entityPath, @@ -28,7 +27,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 +35,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 +76,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 +112,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 +131,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 +147,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 +178,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); + var 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); + var 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); + var 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..e974aec49cd0 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private void MessageReceiveDeferredMessageException(string clientId, string exception) { - this.WriteEvent(30, clientId, exception); + WriteEvent(30, clientId, exception); } // Unused - 31;32;33 @@ -355,785 +355,785 @@ 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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()); } } [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); } @@ -1141,14 +1141,14 @@ 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()); } } [Event(99, Level = EventLevel.Error, Message = "ExceptionReceivedHandler threw exception. Exception:{0}")] - void ExceptionReceivedHandlerThrewException(string exception) + private void ExceptionReceivedHandlerThrewException(string exception) { WriteEvent(99, exception); } @@ -1156,14 +1156,14 @@ 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()); } } [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); } @@ -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,47 +1180,47 @@ 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) + private 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); } } [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); } @@ -1228,14 +1228,14 @@ 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); } } [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); } @@ -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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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) + private 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/MessagingUtilities.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingUtilities.cs index 8012b05d6544..0e9a06e02bf1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingUtilities.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/MessagingUtilities.cs @@ -5,7 +5,7 @@ namespace Microsoft.Azure.ServiceBus { using System; - static class MessagingUtilities + internal static class MessagingUtilities { public static TimeSpan CalculateRenewAfterDuration(DateTime lockedUntilUtc) { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs index b94a7c746eb0..6876c6b28833 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/AzureActiveDirectoryTokenProvider.cs @@ -11,17 +11,17 @@ namespace Microsoft.Azure.ServiceBus.Primitives /// 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); public AzureActiveDirectoryTokenProvider(AuthenticationCallback authenticationCallback, string authority, object state) { - this.AuthCallback = authenticationCallback ?? throw Fx.Exception.ArgumentNull(nameof(authenticationCallback)); - this.authority = authority ?? throw Fx.Exception.ArgumentNull(nameof(authority)); - this.authCallbackState = state; + AuthCallback = authenticationCallback ?? throw Fx.Exception.ArgumentNull(nameof(authenticationCallback)); + _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 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/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 16da8f9c4607..4fbd9fa1bf70 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ConcurrentExpiringSet.cs @@ -8,62 +8,62 @@ namespace Microsoft.Azure.ServiceBus.Primitives using System.Collections.Concurrent; 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 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; public ConcurrentExpiringSet() { - this.dictionary = new ConcurrentDictionary(); - this.dictionaryAsCollection = dictionary; - _ = CollectExpiredEntriesAsync(tokenSource.Token); + _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) + private async Task CollectExpiredEntriesAsync(CancellationToken token) { while (!token.IsCancellationRequested) { try { - await this.cleanupTaskCompletionSource.Task.ConfigureAwait(false); - await Task.Delay(delayBetweenCleanups, token).ConfigureAwait(false); + await _cleanupTaskCompletionSource.Task.ConfigureAwait(false); + await Task.Delay(DelayBetweenCleanups, token).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -72,26 +72,26 @@ 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); } } } - void ThrowIfClosed() + 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 3c47b0d23f12..7a5adb1ed855 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,9 +28,9 @@ public static long NextPositiveLong() return Math.Abs(ulongValue); } - static Random GetThreadLocalRandom() + private static Random GetThreadLocalRandom() { - if (threadLocalRandom == null) + if (_threadLocalRandom == null) { int seed; lock (SeedGenerator) @@ -40,10 +38,10 @@ 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/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 515f090432d9..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) { @@ -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..983231a25e5a 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/Fx.cs @@ -6,20 +6,20 @@ 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 { get { - if (exceptionUtility == null) + if (_exceptionUtility == null) { - exceptionUtility = new ExceptionUtility(); + _exceptionUtility = new ExceptionUtility(); } - return exceptionUtility; + return _exceptionUtility; } } @@ -103,45 +103,45 @@ 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) { - this.location = location; - this.description = description; + _location = location; + _description = description; } - public Location Location => this.location; + public Location Location => _location; - public string Description => this.description; + public string Description => _description; } [AttributeUsage(AttributeTargets.Field)] [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) { - 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; + _elementType = elementType; + _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; } @@ -154,22 +154,22 @@ 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) { - 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; + _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; } @@ -200,18 +200,18 @@ 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 { - readonly BlocksUsing blocksUsing; + private readonly BlocksUsing _blocksUsing; public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing) { - this.blocksUsing = blocksUsing; + _blocksUsing = blocksUsing; } - public BlocksUsing BlocksUsing => this.blocksUsing; + public BlocksUsing BlocksUsing => _blocksUsing; public bool SupportsAsync { get; set; } @@ -252,14 +252,14 @@ 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) { if (exceptionType == null) { - throw Fx.Exception.ArgumentNull(nameof(exceptionType)); + throw Exception.ArgumentNull(nameof(exceptionType)); } if (string.IsNullOrEmpty(diagnosis)) { @@ -267,13 +267,13 @@ public ThrowsAttribute(Type exceptionType, string diagnosis) throw new ArgumentNullException(nameof(diagnosis)); } - this.exceptionType = exceptionType; - this.diagnosis = diagnosis; + _exceptionType = exceptionType; + _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)] @@ -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/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; /// diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/JsonSecurityToken.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/JsonSecurityToken.cs index b4c04ce491da..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; /// @@ -23,7 +21,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/ManagedIdentityTokenProvider.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs index e6aecfbb0d28..32e636b3c8d1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/ManagedIdentityTokenProvider.cs @@ -5,23 +5,27 @@ 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. /// public class ManagedIdentityTokenProvider : TokenProvider { - private readonly AzureServiceTokenProvider azureServiceTokenProvider; + 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) { - this.azureServiceTokenProvider = azureServiceTokenProvider; + _azureServiceTokenProvider = azureServiceTokenProvider; } /// @@ -32,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/PropertyDictionary.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs index f2371c41f766..1c576e8b8cdd 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/PropertyDictionary.cs @@ -6,102 +6,102 @@ 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 + internal sealed class PropertyDictionary : IDictionary { - readonly IDictionary inner; + private readonly IDictionary _inner; 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) + 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 ade1c588341c..fa8a6d7e84ef 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. @@ -49,30 +49,30 @@ public SecurityToken(string tokenString, DateTime expiresAtUtc, string audience, throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(audience)); } - this.token = tokenString; - this.expiresAtUtc = expiresAtUtc; - this.audience = audience; - this.tokenType = tokenType; + _token = tokenString; + _expiresAtUtc = expiresAtUtc; + _audience = audience; + _tokenType = tokenType; } /// /// 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/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..c388ee526169 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. @@ -43,36 +43,32 @@ internal static void Validate(string sharedAccessSignature) throw new ArgumentNullException(nameof(sharedAccessSignature)); } - IDictionary parsedFields = ExtractFieldValues(sharedAccessSignature); + var 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); } } - static IDictionary ExtractFieldValues(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) { @@ -80,13 +76,13 @@ static IDictionary ExtractFieldValues(string sharedAccessSignatu } 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, @@ -103,9 +99,9 @@ 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); + var decodedToken = Decode(token, Decoder, Decoder, SasKeyValueSeparator, SasPairSeparator); if (!decodedToken.TryGetValue(SignedResourceFullFieldName, out var audience)) { throw new FormatException(Resources.TokenMissingAudience); @@ -114,26 +110,26 @@ 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); + var decodedToken = Decode(token, Decoder, Decoder, SasKeyValueSeparator, SasPairSeparator); if (!decodedToken.TryGetValue(SignedExpiry, out var expiresIn)) { 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; } - 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); - 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 7a4af3b5ccec..de202fcecd5f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/SharedAccessSignatureTokenProvider.cs @@ -17,21 +17,19 @@ namespace Microsoft.Azure.ServiceBus.Primitives /// public class SharedAccessSignatureTokenProvider : TokenProvider { - const TokenScope DefaultTokenScope = TokenScope.Entity; + internal static readonly TimeSpan DefaultTokenTTL = TimeSpan.FromMinutes(60); - 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) { SharedAccessSignatureToken.Validate(sharedAccessSignature); - this.sharedAccessSignature = sharedAccessSignature; + _sharedAccessSignature = sharedAccessSignature; } internal SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TokenScope tokenScope = TokenScope.Entity) @@ -76,12 +74,12 @@ protected SharedAccessSignatureTokenProvider(string keyName, string sharedAccess Resources.ArgumentStringTooBig.FormatForUser(nameof(sharedAccessKey), SharedAccessSignatureToken.MaxKeyLength)); } - this.keyName = keyName; - this.tokenTimeToLive = tokenTimeToLive; - this.encodedSharedAccessKey = customKeyEncoder != null ? + _keyName = keyName; + _tokenTimeToLive = tokenTimeToLive; + _encodedSharedAccessKey = customKeyEncoder != null ? customKeyEncoder(sharedAccessKey) : MessagingTokenProviderKeyEncoder(sharedAccessKey); - this.tokenScope = tokenScope; + _tokenScope = tokenScope; } /// @@ -98,7 +96,7 @@ public override Task GetTokenAsync(string appliesTo, TimeSpan tim { TimeoutHelper.ThrowIfNegativeArgument(timeout); appliesTo = NormalizeAppliesTo(appliesTo); - string tokenString = this.BuildSignature(appliesTo); + var tokenString = BuildSignature(appliesTo); var securityToken = new SharedAccessSignatureToken(tokenString); return Task.FromResult(securityToken); } @@ -108,21 +106,21 @@ 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) + private 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 + private static class SharedAccessSignatureBuilder { [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "Uris are normalized to lowercase")] public static string BuildSignature( @@ -133,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,15 +152,15 @@ 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); - 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); } - 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 367641a8d583..5ed0f08fc5b5 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TimeoutHelper.cs @@ -7,23 +7,23 @@ 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) { 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(); } } @@ -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) @@ -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() + private 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/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, diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs index ed35e15d9310..7537771207c1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/Primitives/TokenProviderAdapter.cs @@ -5,29 +5,27 @@ namespace Microsoft.Azure.ServiceBus.Primitives { using System.Diagnostics; using System; - using System.Linq; using System.Threading.Tasks; using Microsoft.Azure.Amqp; /// /// 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) { 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) { - 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..76f0522d1a3c 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. @@ -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. @@ -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,35 +218,35 @@ 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. /// - public override ServiceBusConnection ServiceBusConnection { get; } + public sealed override ServiceBusConnection ServiceBusConnection { get; } 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,33 +310,33 @@ 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; } } - - ICbsTokenProvider CbsTokenProvider { get; } + + private ICbsTokenProvider CbsTokenProvider { get; } /// /// Sends a message to Service Bus. /// 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..a03784128216 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)); - double increment = (Math.Pow(2, currentRetryCount) - 1) * randomizedInterval; - double timeToSleepMsec = Math.Min(this.MinimalBackoff.TotalMilliseconds + increment, this.MaximumBackoff.TotalMilliseconds); + var randomizedInterval = ConcurrentRandom.Next((int)(DeltaBackoff.TotalMilliseconds * 0.8), (int)(DeltaBackoff.TotalMilliseconds * 1.2)); + 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/RetryPolicy.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs index e8e41231b781..b0e8f4f2a6b4 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/RetryPolicy.cs @@ -18,18 +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; - - protected RetryPolicy() - { - } + private volatile bool _encounteredServerBusy; /// /// Returns the default retry policy, . @@ -62,19 +58,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 +78,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 +90,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 +131,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 +146,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 +166,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 +186,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..5e7d2379ccb7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusConnection.cs @@ -10,17 +10,17 @@ 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 /// 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. @@ -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) @@ -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); } /// @@ -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) @@ -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; } /// @@ -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) { @@ -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(); } /// @@ -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; } /// @@ -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; } } } @@ -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,58 +191,58 @@ 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) + private 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) + 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 = this.Endpoint.Host; + var hostName = Endpoint.Host; var timeoutHelper = new TimeoutHelper(timeout, true); var amqpSettings = AmqpConnectionHelper.CreateAmqpSettings( @@ -272,10 +272,10 @@ 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 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,18 +296,18 @@ 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; } return controller; } - TransportSettings CreateTransportSettings() + private 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..634f7ec78182 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 { @@ -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,15 +333,15 @@ 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) + private void ParseConnectionString(string connectionString) { // First split based on ';' var keyValuePairs = connectionString.Split(new[] { KeyValuePairDelimiter }, StringSplitOptions.RemoveEmptyEntries); @@ -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..667b4a864e1e 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 Microsoft.Azure.ServiceBus.Diagnostics; - internal class ServiceBusDiagnosticSource { public const string DiagnosticListenerName = "Microsoft.Azure.ServiceBus"; @@ -26,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; + _entityPath = entityPath; + _endpoint = endpoint; } public static bool IsEnabled() @@ -45,11 +46,11 @@ public static bool IsEnabled() internal Activity SendStart(IList messageList) { - Activity activity = Start("Send", () => new + var activity = Start("Send", () => new { Messages = messageList, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = _entityPath, + Endpoint = _endpoint }, a => SetTags(a, messageList) ); @@ -66,8 +67,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 +84,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 +97,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 +115,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 +129,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 }); } @@ -142,12 +143,12 @@ 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, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = _entityPath, + Endpoint = _endpoint }, a => SetTags(a, message)); @@ -164,8 +165,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 +183,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 +196,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 +213,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 +228,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 +247,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 +264,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 +282,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 +298,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 +316,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 +329,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 +346,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 +359,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 +376,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 +389,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 +407,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 +420,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 +437,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 +450,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 +466,8 @@ internal Activity GetRulesStart() { return Start("GetRules", () => new { - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = _entityPath, + Endpoint = _endpoint }, null); } @@ -478,8 +479,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 +496,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 +510,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 +527,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 +540,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 +559,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 +573,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 +590,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 +603,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 +620,8 @@ internal void ReportException(Exception ex) new { Exception = ex, - Entity = this.entityPath, - Endpoint = this.endpoint + Entity = _entityPath, + Endpoint = _endpoint }); } } @@ -628,8 +629,8 @@ internal void ReportException(Exception ex) private Activity Start(string operationName, Func getPayload, Action setTags) { Activity activity = null; - string activityName = BaseActivityName + operationName; - if (DiagnosticListener.IsEnabled(activityName, this.entityPath)) + var activityName = BaseActivityName + operationName; + if (DiagnosticListener.IsEnabled(activityName, _entityPath)) { activity = new Activity(activityName); setTags?.Invoke(activity); @@ -698,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); } @@ -714,14 +715,14 @@ 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)) + if (message != null && DiagnosticListener.IsEnabled(activityName, _entityPath)) { var tmpActivity = message.ExtractActivity(activityName); setTags?.Invoke(tmpActivity); - if (DiagnosticListener.IsEnabled(activityName, entityPath, tmpActivity)) + if (DiagnosticListener.IsEnabled(activityName, _entityPath, tmpActivity)) { activity = tmpActivity; if (DiagnosticListener.IsEnabled(activityName + ".Start")) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusException.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusException.cs index 2d0eb40ca332..c1787c6c7aa3 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusException.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/ServiceBusException.cs @@ -17,7 +17,7 @@ public class ServiceBusException : Exception /// Specifies 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..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; @@ -44,8 +43,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 @@ -96,7 +95,7 @@ public SessionClient( throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -129,7 +128,7 @@ public SessionClient( retryPolicy, null) { - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -157,7 +156,7 @@ public SessionClient( retryPolicy, null) { - this.OwnsConnection = false; + OwnsConnection = false; } internal SessionClient( @@ -177,39 +176,39 @@ 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); } } } - 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. @@ -219,15 +218,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; } /// @@ -235,11 +234,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. @@ -253,7 +252,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 +263,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 +274,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 +286,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; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +321,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 +334,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 +358,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 +377,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 +387,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..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 { - int maxConcurrentSessions; - TimeSpan messageWaitTimeout; - TimeSpan maxAutoRenewDuration; + private int _maxConcurrentSessions; + private TimeSpan _messageWaitTimeout; + private TimeSpan _maxAutoRenewDuration; /// Initializes a new instance of the class. /// Default Values: @@ -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..6f5b7be060c7 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionPumpHost.cs @@ -9,33 +9,33 @@ 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) { - this.syncLock = new object(); - this.ClientId = clientId; - this.ReceiveMode = receiveMode; - this.SessionClient = sessionClient; - this.endpoint = endpoint; + _syncLock = new object(); + ClientId = clientId; + ReceiveMode = receiveMode; + SessionClient = sessionClient; + _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() { - 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..86b126af0ffb 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SessionReceivePump.cs @@ -4,23 +4,22 @@ namespace Microsoft.Azure.ServiceBus { using System; - using System.Diagnostics; using System.Threading; 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 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,31 +29,31 @@ public SessionReceivePump(string clientId, Uri endpoint, CancellationToken token) { - this.client = client ?? throw new ArgumentException(nameof(client)); - this.clientId = clientId; - this.ReceiveMode = receiveMode; - this.sessionHandlerOptions = sessionHandlerOptions; - this.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); + _client = client ?? throw new ArgumentException(nameof(client)); + _clientId = clientId; + ReceiveMode = receiveMode; + _sessionHandlerOptions = sessionHandlerOptions; + _userOnSessionCallback = callback; + _endpoint = endpoint.Authority; + _entityPath = client.EntityPath; + _pumpCancellationToken = token; + _maxConcurrentSessionsSemaphoreSlim = new SemaphoreSlim(_sessionHandlerOptions.MaxConcurrentSessions); + _maxPendingAcceptSessionsSemaphoreSlim = new SemaphoreSlim(_sessionHandlerOptions.MaxConcurrentAcceptSessionCalls); + _diagnosticSource = new ServiceBusDiagnosticSource(client.EntityPath, endpoint); } - ReceiveMode ReceiveMode { get; } + private ReceiveMode ReceiveMode { get; } 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); } } - static void CancelAutoRenewLock(object state) + private static void CancelAutoRenewLock(object state) { var renewCancellationTokenSource = (CancellationTokenSource)state; @@ -68,36 +67,36 @@ static void CancelAutoRenewLock(object state) } } - bool ShouldRenewSessionLock() + private bool ShouldRenewSessionLock() { return - this.ReceiveMode == ReceiveMode.PeekLock && - this.sessionHandlerOptions.AutoRenewLock; + ReceiveMode == ReceiveMode.PeekLock && + _sessionHandlerOptions.AutoRenewLock; } - Task RaiseExceptionReceived(Exception e, string action) + private 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) + private 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); } } - async Task AbandonMessageIfNeededAsync(IMessageSession session, Message message) + private async Task AbandonMessageIfNeededAsync(IMessageSession session, Message message) { try { @@ -108,66 +107,66 @@ 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() + private 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(); } } } - async Task MessagePumpTaskAsync(IMessageSession session) + private async Task MessagePumpTaskAsync(IMessageSession session) { if (session == null) { @@ -175,9 +174,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 +187,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; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +253,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 +263,7 @@ async Task MessagePumpTaskAsync(IMessageSession session) } finally { - this.diagnosticSource.ProcessSessionStop(activity, session, message, processTask?.Status); + _diagnosticSource.ProcessSessionStop(activity, session, message, processTask?.Status); } } } @@ -274,45 +273,45 @@ 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(); } } - async Task CloseSessionIfNeededAsync(IMessageSession session) + private async Task CloseSessionIfNeededAsync(IMessageSession session) { if (!session.IsClosedOrClosing) { 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) + private 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 +320,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..417a14fda9b1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/src/SubscriptionClient.cs @@ -1,17 +1,18 @@ // 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; using System.Collections.Generic; - using System.Diagnostics; 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. @@ -50,13 +51,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. @@ -85,7 +86,7 @@ public SubscriptionClient(string connectionString, string topicPath, string subs throw Fx.Exception.ArgumentNullOrWhiteSpace(connectionString); } - this.OwnsConnection = true; + OwnsConnection = true; } /// @@ -109,7 +110,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 +135,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); } /// @@ -165,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. @@ -182,8 +183,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 +208,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; } } } @@ -229,27 +230,27 @@ public int PrefetchCount /// /// Connection object to the service bus namespace. /// - public override ServiceBusConnection ServiceBusConnection { get; } + public sealed override ServiceBusConnection ServiceBusConnection { get; } 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 +258,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,26 +286,26 @@ 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; } } - ICbsTokenProvider CbsTokenProvider { get; } + private ICbsTokenProvider CbsTokenProvider { get; } /// /// Completes a using its lock token. This will delete the message from the subscription. @@ -317,8 +318,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 +334,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 +351,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 +369,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 +388,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 +403,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 +416,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 +433,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 +446,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 +464,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 +480,7 @@ public Task AddRuleAsync(string ruleName, Filter filter) /// public async Task AddRuleAsync(RuleDescription description) { - this.ThrowIfClosed(); + ThrowIfClosed(); if (description == null) { @@ -487,33 +488,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; + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +523,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); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.RemoveRuleStart(ruleName) : null; + MessagingEventSource.Log.RemoveRuleStart(ClientId, ruleName); + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var 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 +564,11 @@ public async Task RemoveRuleAsync(string ruleName) /// public async Task> GetRulesAsync() { - this.ThrowIfClosed(); + ThrowIfClosed(); - MessagingEventSource.Log.GetRulesStart(this.ClientId); - bool isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); - Activity activity = isDiagnosticSourceEnabled ? this.diagnosticSource.GetRulesStart() : null; + MessagingEventSource.Log.GetRulesStart(ClientId); + var isDiagnosticSourceEnabled = ServiceBusDiagnosticSource.IsEnabled(); + var activity = isDiagnosticSourceEnabled ? _diagnosticSource.GetRulesStart() : null; Task> getRulesTask = null; var skip = 0; @@ -576,33 +577,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 +611,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 +621,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..c3dfbf635825 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. @@ -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. @@ -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,53 +126,53 @@ 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. /// - public override ServiceBusConnection ServiceBusConnection { get; } + public sealed override ServiceBusConnection ServiceBusConnection { get; } 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; } } - - ICbsTokenProvider CbsTokenProvider { get; } + + private ICbsTokenProvider CbsTokenProvider { get; } /// /// Sends a message to Service Bus. /// 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/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/AmqpConverterTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs index f6579f86657d..aa08bcd1da14 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/AmqpConverterTests.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. +using Microsoft.Azure.ServiceBus.Extensions; +using Microsoft.Azure.ServiceBus.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; using System.Text; using Azure.Amqp.Framing; using Microsoft.Azure.Amqp; - using Microsoft.Azure.ServiceBus.Amqp; - using InteropExtensions; + using Amqp; using Xunit; public class AmqpConverterTests @@ -23,8 +25,8 @@ 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); - Assert.Equal(messageBody, sbMessage.GetBody(null)); + var sbMessage = AmqpMessageConverter.Convert(amqpMessage); + Assert.Equal(messageBody, sbMessage.GetBody()); } [Fact] @@ -37,8 +39,8 @@ 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); - Assert.Equal(messageBody, sbMessage.GetBody(null)); + var sbMessage = AmqpMessageConverter.Convert(amqpMessage); + Assert.Equal(messageBody, sbMessage.GetBody()); } [Fact] @@ -51,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); } @@ -65,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); } @@ -84,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) @@ -103,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); @@ -127,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); } @@ -143,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); @@ -160,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); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/DiagnosticsTests.cs index 904a83616b4f..e88e7038771a 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; @@ -33,7 +35,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)) { @@ -433,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); @@ -445,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); @@ -499,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/ExtractActivityTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs index 931346e02833..c506017acd28 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/ExtractActivityTests.cs @@ -1,17 +1,19 @@ // 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 { [Fact] [DisplayTestMethodName] - void ValidIdAndContextAreExtracted() + private void ValidIdAndContextAreExtracted() { var message = new Message(); message.UserProperties["Diagnostic-Id"] = "diagnostic-id"; @@ -32,7 +34,7 @@ void ValidIdAndContextAreExtracted() [Fact] [DisplayTestMethodName] - void ValidIdAndMultipleContextAreExtracted() + private void ValidIdAndMultipleContextAreExtracted() { var message = new Message(); message.UserProperties["Diagnostic-Id"] = "diagnostic-id"; @@ -57,7 +59,7 @@ void ValidIdAndMultipleContextAreExtracted() [Fact] [DisplayTestMethodName] - void ActivityNameCouldBeChanged() + private void ActivityNameCouldBeChanged() { var message = new Message(); message.UserProperties["Diagnostic-Id"] = "diagnostic-id"; @@ -69,7 +71,7 @@ void ActivityNameCouldBeChanged() [Fact] [DisplayTestMethodName] - void ValidIdAndNoContextAreExtracted() + private void ValidIdAndNoContextAreExtracted() { var message = new Message(); message.UserProperties["Diagnostic-Id"] = "diagnostic-id"; @@ -90,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"; @@ -110,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/Diagnostics/FakeDiagnosticListener.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/FakeDiagnosticListener.cs index 09072d025927..4a3fd52e440c 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; + _writeCallback = writeCallback; } public void OnCompleted() @@ -29,17 +29,17 @@ public void OnError(Exception error) public void OnNext(KeyValuePair value) { - this.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; + _writeCallback = writeCallback; } public void OnCompleted() @@ -54,37 +54,37 @@ 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) { - 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() { - 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..b50433acd729 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; @@ -19,71 +21,71 @@ 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 queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + 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 + var 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 @@ -100,76 +102,76 @@ 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 queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + 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 + var 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 @@ -186,37 +188,37 @@ 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 queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + 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 @@ -234,28 +236,29 @@ 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 (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)); + + var 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 @@ -273,49 +276,49 @@ 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 (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); + var receivedStopCount = 0; + var 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 @@ -332,37 +335,37 @@ 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 queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + 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 @@ -379,39 +382,39 @@ 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 queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + 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 @@ -428,30 +431,30 @@ 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 queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + using (SubscribeToEvents(listener) ?? throw new InvalidOperationException("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 @@ -468,43 +471,43 @@ 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 queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName); + var eventQueue = CreateEventQueue(); try { - using (var listener = this.CreateEventListener(queueName, eventQueue)) - using (var subscription = this.SubscribeToEvents(listener)) + using (var listener = CreateEventListener(queueName, eventQueue)) + 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 @@ -522,36 +525,36 @@ 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 (SubscribeToEvents(listener)) { - Activity parentActivity = new Activity("test"); - listener.Enable((name, queue, arg) => name.Contains("Schedule") || name.Contains("Cancel")); + var 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 135f0385096f..ed1000c41eaa 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Diagnostics/SessionDiagnosticsTests.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.UnitTests.Infrastructure; + namespace Microsoft.Azure.ServiceBus.UnitTests.Diagnostics { using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Xunit; [Collection(nameof(DiagnosticsTests))] @@ -23,67 +25,67 @@ 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 (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 @@ -104,7 +106,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,73 +115,73 @@ 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 (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); + + var 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 @@ -192,9 +194,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 +206,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 +218,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 +230,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 +243,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 +256,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 +269,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 +281,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) { @@ -309,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 deb6fb589f3e..eca8a4e15df8 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; @@ -20,40 +23,40 @@ 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 (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/ExpectedMessagingExceptionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs index 220b6e7af1cc..943f7fd83eb1 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ExpectedMessagingExceptionTests.cs @@ -1,12 +1,14 @@ // 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; using System.Text; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Xunit; public class ExpectedMessagingExceptionTests @@ -105,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.Tests/FakeDiagnosticsListenerTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/FakeDiagnosticsListenerTests.cs index c97db0086372..fd5fac872506 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 Microsoft.Azure.ServiceBus.Core; - using Xunit; - - [Collection(nameof(DiagnosticsTests))] + [Collection(nameof(DiagnosticsTests))] public class FakeDiagnosticsListenerTests : DiagnosticsTests { [Fact] @@ -19,22 +21,22 @@ 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 (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 @@ -52,32 +54,32 @@ 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 (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 @@ -95,33 +97,33 @@ 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 (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 @@ -141,30 +143,30 @@ 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 (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 @@ -185,34 +187,34 @@ 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 (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/Infrastructure.Tests/TaskExtensionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure.Tests/TaskExtensionTests.cs index 86fb0d0e0145..d5bd0e46fba2 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 { @@ -12,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); } @@ -32,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."); } @@ -40,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); } @@ -59,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); @@ -74,7 +73,7 @@ public async Task WithTimeoutDoesNotThrowWhenATimeoutDoesNotOccur() try { - await Task.Delay(TinyDelay).WithTimeout(LongDelay); + await Task.Delay(_tinyDelay).WithTimeout(_longDelay); } catch (TimeoutException) { @@ -91,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) { @@ -105,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); } @@ -115,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); } @@ -123,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); } @@ -134,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); } @@ -147,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); } @@ -158,7 +157,7 @@ public async Task WithTimeoutInvokesTheCancellationTokenWhenATimeoutOccurs() try { - await Task.Delay(LongDelay).WithTimeout(TinyDelay, token); + await Task.Delay(_longDelay).WithTimeout(_tinyDelay, token); } catch (TimeoutException) @@ -176,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/DisplayTestMethodNameAttribute.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/DisplayTestMethodNameAttribute.cs index 68d20fe1356a..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 Microsoft.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..160d72bdd0ca 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/LiveTestAttribute.cs @@ -1,15 +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.UnitTests -{ - using System; - using Xunit.Sdk; +using System; +using Xunit.Sdk; - [TraitDiscoverer("Xunit.Sdk.TraitDiscoverer", "xunit.core")] - [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] +namespace Microsoft.Azure.ServiceBus.UnitTests.Infrastructure +{ + [TraitDiscoverer("Xunit.Sdk.TraitDiscoverer", "xunit.core")] + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class LiveTestAttribute : Attribute, ITraitAttribute { - public LiveTestAttribute(string name = "TestCategory", string value = "Live") {} } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs index 5811a54e30b7..b16f7cc2fbab 100755 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Infrastructure/ServiceBusScope.cs @@ -1,20 +1,20 @@ // 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; + 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); /// @@ -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); @@ -126,7 +126,7 @@ public static async Task UsingQueueAsync(bool partitioned, } finally { - await scope?.CleanupAsync(); + await (scope?.CleanupAsync() ?? Task.CompletedTask); } } @@ -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 @@ -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) @@ -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/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..81024a2a066a 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 +{ + 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 fe7f2a41231d..3676ee63a9a5 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 + 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/Management/ManagementClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Management/ManagementClientTests.cs index c00570ac93b1..646b9ab775cb 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; @@ -8,7 +11,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; @@ -245,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)); @@ -325,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 @@ -411,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); @@ -479,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); @@ -661,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}, @@ -673,7 +676,7 @@ await Assert.ThrowsAsync( }; [Theory] - [MemberData(nameof(TestData_EntityNameValidationTest))] + [MemberData(nameof(TestDataEntityNameValidationTest))] [LiveTest] [DisplayTestMethodName] public void EntityNameValidationTest(string entityName, bool isPathSeparatorAllowed) @@ -706,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" }); @@ -842,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 " + @@ -856,7 +859,7 @@ public async Task SqlFilterParamsTest() { "@intPropertyValue", 3 }, { "@longPropertyValue", 3L }, { "@boolPropertyValue", true }, - { "@doublePropertyValue", (double)3.0 }, + { "@doublePropertyValue", 3.0 }, } }; @@ -890,7 +893,7 @@ public async Task CorrelationFilterPropertiesTest() await client.CreateTopicAsync(topicName); await client.CreateSubscriptionAsync(topicName, subscriptionName); - var sClient = 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); 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..8827a9e774bd 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInterOpTests.cs @@ -1,32 +1,34 @@ // 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 { - 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); @@ -36,14 +38,14 @@ 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); memoryStream.Flush(); memoryStream.Position = 0; payload = memoryStream.ToArray(); - }; + } return new Message(payload); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageInterop/MessageInteropEnd2EndTests.cs index 182111f0d4ac..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,14 +13,13 @@ 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 object[][] + 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] @@ -100,12 +102,12 @@ 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) { - sbConnectionString += ';' + nameof(TransportType) + '=' + TransportType.Amqp.ToString(); + sbConnectionString += ';' + nameof(TransportType) + '=' + TransportType.Amqp; } return sbConnectionString; 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/MessageSenderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageSenderTests.cs index 0e02d4145522..d59a49d8ef42 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; @@ -8,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/MessageTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs index 1b79ea90b71b..b5153643c28c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/MessageTests.cs @@ -1,19 +1,28 @@ // 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; +using Xunit.Abstractions; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; - using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Xunit; public class MessageTests { - [Fact] + private readonly ITestOutputHelper _testOutputHelper; + + public MessageTests(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } + + [Fact] [DisplayTestMethodName] public void TestClone() { @@ -28,8 +37,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) { @@ -112,7 +119,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 { @@ -137,11 +144,11 @@ 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 { - 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); @@ -182,7 +189,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 { @@ -192,7 +199,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned: false, sessionEnabled: false, } catch (Exception e) { - Console.WriteLine(e); + _testOutputHelper.WriteLine(e.ToString()); throw; } finally @@ -212,21 +219,21 @@ 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); 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()); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/OnMessageQueueTests.cs index ede0b52db34b..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; @@ -11,7 +13,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 }, @@ -26,7 +28,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 +37,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 +46,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 +60,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 +122,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..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; @@ -9,7 +11,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 }, @@ -22,7 +24,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 +33,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 +51,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..ed09de4f6d7f 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; @@ -11,7 +13,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 +22,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 }, @@ -33,7 +35,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 +44,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 +53,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] @@ -63,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 161836250b28..112697a09944 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; @@ -11,7 +13,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 }, @@ -26,7 +28,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 +37,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] @@ -50,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 => { @@ -102,8 +103,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN var subscriptionClient = new SubscriptionClient( TestUtility.NamespaceConnectionString, topicClient.TopicName, - subscriptionName, - ReceiveMode.PeekLock); + subscriptionName); try { diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs index c83252486c50..c9130cdbc29f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/Performance/Program.cs @@ -1,29 +1,27 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Azure.ServiceBus.Core; + namespace Microsoft.Azure.ServiceBus.Performance { - using Microsoft.Azure.ServiceBus; - using Microsoft.Azure.ServiceBus.Core; - using System; - using System.Diagnostics; - using System.Threading; - using System.Threading.Tasks; - - class Program + 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; - static async Task Main(string[] args) + 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"); @@ -53,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 @@ -75,11 +73,11 @@ 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; - if ((currentMessages / currentElapsed.TotalSeconds) > (maxMessages / maxElapsed.TotalSeconds)) { + if (currentMessages / currentElapsed.TotalSeconds > maxMessages / maxElapsed.TotalSeconds) { maxMessages = currentMessages; maxElapsed = currentElapsed; } @@ -101,7 +99,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}"); } } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/PluginTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/PluginTests.cs index 0d72210690e7..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; @@ -8,7 +10,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 +297,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 +306,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..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; @@ -10,7 +12,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 }, @@ -28,7 +30,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 +104,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 +124,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 +149,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { await - this.PeekLockWithDeadLetterTestCase( + PeekLockWithDeadLetterTestCase( queueClient.InnerSender, queueClient.InnerReceiver, deadLetterQueueClient.InnerReceiver, @@ -172,7 +174,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 +194,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 +214,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..71e5ec1b010b 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; @@ -12,7 +14,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 }, @@ -162,10 +164,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 { @@ -238,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); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryPolicyTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryPolicyTests.cs index a620caa36c8a..22b21bfb56a9 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; @@ -37,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/RetryTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/RetryTests.cs index 3ead6d7056f5..5ccb6d6c72fc 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; @@ -14,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), @@ -35,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 _); @@ -200,9 +202,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/SenderReceiverClientTestBase.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverClientTestBase.cs index 2430b0d7b18c..9d7cb977148d 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; @@ -227,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) diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SenderReceiverTests.cs index fe69daeb0886..1131dd264874 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; @@ -13,9 +15,9 @@ 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 object[][] + public static IEnumerable TestPermutations => new[] { // Expected structure: { usePartitionedQueue, useSessionQueue } new object[] { false, false }, @@ -35,7 +37,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - await this.PeekLockTestCase(sender, receiver, messageCount); + await PeekLockTestCase(sender, receiver, messageCount); } finally { @@ -59,7 +61,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { await - this.PeekLockDeferTestCase(sender, receiver, messageCount); + PeekLockDeferTestCase(sender, receiver, messageCount); } finally { @@ -82,7 +84,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - await this.PeekAsyncTestCase(sender, receiver, messageCount); + await PeekAsyncTestCase(sender, receiver, messageCount); } finally { @@ -105,7 +107,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - await this.ReceiveShouldReturnNoLaterThanServerWaitTimeTestCase(sender, receiver, messageCount); + await ReceiveShouldReturnNoLaterThanServerWaitTimeTestCase(sender, receiver, messageCount); } finally { @@ -127,7 +129,7 @@ await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueNa try { - await this.ReceiveShouldThrowForServerTimeoutZero(receiver); + await ReceiveShouldThrowForServerTimeoutZero(receiver); } finally { @@ -167,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. @@ -242,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()) { @@ -327,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"} @@ -454,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/ServiceBusConnectionStringBuilderTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs index 4d0eaf130d79..65b20fb24c4d 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/ServiceBusConnectionStringBuilderTests.cs @@ -1,12 +1,14 @@ // 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; 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; @@ -188,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(); }); @@ -210,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()); } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SubscriptionClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/SubscriptionClientTests.cs index 1baf29cdae42..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; @@ -11,7 +14,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/TestSessionHandler.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs index 99b76a09c8d2..ae50d65f337c 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TestSessionHandler.cs @@ -1,28 +1,29 @@ // 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; using System.Collections.Concurrent; - using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; 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, @@ -30,21 +31,21 @@ public TestSessionHandler( MessageSender sender, SessionPumpHost sessionPumpHost) { - this.receiveMode = receiveMode; - this.sessionHandlerOptions = sessionHandlerOptions; - this.sender = sender; - this.sessionPumpHost = sessionPumpHost; - this.sessionMessageMap = new ConcurrentDictionary(); + _receiveMode = receiveMode; + _sessionHandlerOptions = sessionHandlerOptions; + _sender = sender; + _sessionPumpHost = sessionPumpHost; + _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 +53,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 +70,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 (var 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..38650e277ae2 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TokenProviderTests.cs @@ -1,11 +1,13 @@ // 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; using System.Threading.Tasks; - using Microsoft.Azure.ServiceBus.Core; + using Core; using Microsoft.Azure.ServiceBus.Primitives; using Xunit; @@ -28,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 { @@ -43,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"; + var 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); } } diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TopicClientTests.cs index 5326ab039aea..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; @@ -9,7 +11,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 }, @@ -32,7 +34,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { - await this.PeekLockTestCase( + await PeekLockTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); @@ -62,7 +64,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { await - this.ReceiveDeleteTestCase( + ReceiveDeleteTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); @@ -91,7 +93,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { await - this.PeekLockWithAbandonTestCase( + PeekLockWithAbandonTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); @@ -128,7 +130,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { await - this.PeekLockWithDeadLetterTestCase( + PeekLockWithDeadLetterTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, deadLetterSubscriptionClient.InnerSubscriptionClient.InnerReceiver, @@ -158,7 +160,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN subscriptionName); try { - await this.RenewLockTestCase( + await RenewLockTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); @@ -188,7 +190,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { await - this.ScheduleMessagesAppearAfterScheduledTimeAsyncTestCase( + ScheduleMessagesAppearAfterScheduledTimeAsyncTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); @@ -218,7 +220,7 @@ await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicN try { await - this.CancelScheduledMessagesAsyncTestCase( + CancelScheduledMessagesAsyncTestCase( topicClient.InnerSender, subscriptionClient.InnerSubscriptionClient.InnerReceiver, messageCount); diff --git a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs index dfa87e34e344..d0e82c93938f 100644 --- a/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.cs +++ b/sdk/servicebus/Microsoft.Azure.ServiceBus/tests/TransactionTests.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.UnitTests.Infrastructure; +using Xunit.Abstractions; + namespace Microsoft.Azure.ServiceBus.UnitTests { using System; @@ -13,17 +16,23 @@ namespace Microsoft.Azure.ServiceBus.UnitTests public class TransactionTests { - static readonly string ConnectionString = TestUtility.NamespaceConnectionString; - static readonly TimeSpan ReceiveTimeout = TimeSpan.FromSeconds(5); + private readonly ITestOutputHelper _testOutputHelper; + private static readonly string ConnectionString = TestUtility.NamespaceConnectionString; + private static readonly TimeSpan ReceiveTimeout = TimeSpan.FromSeconds(5); + + public TransactionTests(ITestOutputHelper testOutputHelper) + { + _testOutputHelper = testOutputHelper; + } - 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 }, @@ -43,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)) { @@ -78,11 +87,11 @@ 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)) + 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. @@ -113,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); @@ -154,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); @@ -162,9 +171,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. @@ -195,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 @@ -208,9 +217,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. @@ -251,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); @@ -263,9 +272,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. @@ -304,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" @@ -316,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); @@ -341,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); @@ -361,7 +370,7 @@ await Assert.ThrowsAsync( } catch (Exception e) { - Console.WriteLine(e); + _testOutputHelper.WriteLine(e.ToString()); } finally { @@ -384,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); @@ -436,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); @@ -446,10 +455,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. @@ -576,10 +585,17 @@ 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))); + return Task.WhenAll(clientEntities.Select(closeEntity)); } } } 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;