From f4cbb5c5659b949de1d3cb9d82e02220003848d2 Mon Sep 17 00:00:00 2001 From: Pavel Krymets Date: Mon, 23 Nov 2020 16:52:03 -0800 Subject: [PATCH] Update FxCop analyzers (#17157) --- .../Stress/Azure.Test.Stress/StressMetrics.cs | 4 +- eng/Directory.Build.Data.props | 4 + eng/Packages.Data.props | 4 +- .../src/AddTasksWorkflowManager.cs | 38 ++-- .../Microsoft.Azure.Batch/src/BatchClient.cs | 14 +- .../src/ConcurrentChangeTrackedList.cs | 24 +-- .../src/FileStaging/FileStagingUtils.cs | 2 +- .../Microsoft.Azure.Batch/src/ODATAMonitor.cs | 10 +- .../src/PagedEnumeratorBase.cs | 2 +- .../src/PoolOperations.cs | 184 +++++++++--------- .../FileUploadUtilities.cs | 20 +- .../ThreadSafeRefreshableAccessTokenCache.cs | 2 +- sdk/core/Azure.Core.Amqp/src/AmqpAddress.cs | 10 - sdk/core/Azure.Core.Amqp/src/AmqpMessageId.cs | 10 - .../src/Pipeline/HttpClientTransport.cs | 7 +- .../src/Shared/ClientDiagnostics.cs | 2 + .../src/Shared/HttpMessageSanitizer.cs | 4 +- .../Shared/Multipart/BufferedReadStream.cs | 6 +- .../src/Shared/Multipart/MemoryResponse.cs | 2 +- .../src/Shared/RequestRequestContent.cs | 2 +- .../Azure.Core/src/Shared/RetriableStream.cs | 2 +- .../Customized/DigitalTwinModelsRestClient.cs | 2 +- .../src/Customized/DigitalTwinsRestClient.cs | 2 +- .../src/Customized/Models/GetModelsOptions.cs | 2 +- .../src/Customized/QueryRestClient.cs | 2 +- .../src/Models/BasicDigitalTwin.cs | 2 + .../src/Models/BasicDigitalTwinComponent.cs | 4 + .../src/Models/BasicRelationship.cs | 2 + .../src/Models/DigitalTwinMetadata.cs | 2 + .../src/EventProcessorClientOptions.cs | 4 +- .../src/Amqp/AmqpClient.cs | 2 +- .../src/Amqp/AmqpConnectionScope.cs | 2 +- .../src/Amqp/AmqpConsumer.cs | 2 +- .../src/Amqp/AmqpEventBatch.cs | 4 +- .../src/Amqp/AmqpProducer.cs | 4 +- .../src/Azure.Messaging.EventHubs.csproj | 4 + .../src/Consumer/EventHubConsumerClient.cs | 4 +- .../src/Consumer/ReadEventOptions.cs | 4 +- .../src/EventHubConnectionOptions.cs | 2 +- .../src/Primitives/EventProcessorOptions.cs | 2 +- .../src/Primitives/PartitionReceiver.cs | 2 +- .../Primitives/PartitionReceiverOptions.cs | 2 +- .../src/Producer/CreateBatchOptions.cs | 2 +- .../src/Producer/EventDataBatch.cs | 2 +- .../src/Producer/EventHubProducerClient.cs | 2 +- .../src/Listeners/EventHubListener.cs | 10 +- .../src/Processor/EventProcessorHost.cs | 2 +- .../src/AzureKeyVaultConfigurationProvider.cs | 1 + .../src/AzureBlobXmlRepository.cs | 2 +- .../src/ClientDiagnostics.cs | 2 + .../src/FormTrainingClient.cs | 12 +- .../src/RecognizeBusinessCardsOptions.cs | 4 +- .../src/RecognizeContentOptions.cs | 2 +- .../src/RecognizeCustomFormsOptions.cs | 4 +- .../src/RecognizeInvoicesOptions.cs | 4 +- .../src/RecognizeReceiptsOptions.cs | 4 +- .../Azure.Identity/src/AsyncLockWithValue.cs | 2 +- .../src/DefaultAzureCredentialOptions.cs | 12 +- .../src/DeviceCodeCredentialOptions.cs | 2 +- .../InteractiveBrowserCredentialOptions.cs | 2 +- .../src/SharedTokenCacheCredentialOptions.cs | 2 +- .../src/VisualStudioCodeCredentialOptions.cs | 2 +- .../src/VisualStudioCredentialOptions.cs | 2 +- .../src/WindowsNativeMethods.cs | 2 + .../tests/CredentialTestHelpers.cs | 4 +- .../Azure.Iot.Hub.Service/src/JobsClient.cs | 4 +- .../src/StatisticsClient.cs | 2 +- .../src/Cryptography/SignatureAlgorithm.cs | 2 +- .../src/KeyCurveName.cs | 4 +- .../src/ChallengeBasedAuthenticationPolicy.cs | 2 +- .../src/ClientDiagnostics.cs | 6 +- .../src/KeyVaultPipeline.cs | 2 + .../keyvaultproxy/src/KeyVaultProxy.cs | 2 +- ...nomaliesForDetectionConfigurationFilter.cs | 2 + ...cidentsForDetectionConfigurationOptions.cs | 2 + .../src/GetMetricSeriesDefinitionsOptions.cs | 2 + .../AnomalyDetectionConfiguration.cs | 4 + .../src/Models/DataFeed/DataFeed.cs | 4 + .../Models/DataFeed/DataFeedRollupSettings.cs | 2 + .../src/Models/DataFeed/DataFeedSchema.cs | 2 + .../NotificationHook/WebNotificationHook.cs | 2 + ...OpenTelemetry.Exporter.AzureMonitor.csproj | 19 +- .../src/TelemetryPartA.cs | 4 +- .../src/Batching/ChannelExtensions.cs | 2 +- .../src/Batching/ManualRetryDelay.cs | 2 +- .../src/Batching/Publisher{T}.cs | 2 +- .../SearchIndexingBufferedSenderOptions{T}.cs | 2 +- .../SearchIndexingBufferedSender{T}.cs | 8 +- .../src/Indexes/Models/IndexingParameters.cs | 2 + .../src/Indexes/Models/SearchIndex.cs | 2 + .../src/Options/IndexDocumentsOptions.cs | 2 +- .../src/SearchClient.cs | 2 +- .../src/SearchDocument/SearchDocument.Core.cs | 2 +- .../src/SearchFilter.cs | 4 +- .../src/Spatial/SpatialFormatter.cs | 10 +- ...ClientDiagnostics.ExtractFailureContent.cs | 6 +- .../src/Utilities/SearchExtensions.cs | 2 +- .../src/Administration/ClientDiagnostics.cs | 2 + .../src/Administration/CreateQueueOptions.cs | 14 +- .../CreateSubscriptionOptions.cs | 10 +- .../src/Administration/CreateTopicOptions.cs | 8 +- .../src/Administration/QueueProperties.cs | 14 +- .../Administration/SubscriptionProperties.cs | 10 +- .../src/Administration/TopicProperties.cs | 18 +- .../src/Amqp/AmqpClient.cs | 2 +- .../src/Amqp/AmqpMessageBatch.cs | 4 +- .../src/Amqp/AmqpReceiver.cs | 4 +- .../src/Amqp/AmqpRuleManager.cs | 2 +- .../src/Amqp/AmqpSender.cs | 4 +- .../src/Azure.Messaging.ServiceBus.csproj | 4 + .../src/Client/ServiceBusClient.cs | 2 +- .../src/Client/ServiceBusClientOptions.cs | 2 +- .../src/Processor/ServiceBusProcessor.cs | 4 +- .../Processor/ServiceBusProcessorOptions.cs | 2 +- .../ServiceBusSessionProcessorOptions.cs | 2 +- .../src/Processor/SessionReceiverManager.cs | 2 +- .../src/Receiver/ServiceBusReceiver.cs | 2 +- .../src/Receiver/ServiceBusReceiverOptions.cs | 2 +- .../ServiceBusSessionReceiverOptions.cs | 2 +- .../src/RuleManager/ServiceBusRuleManager.cs | 2 +- .../src/Sender/CreateMessageBatchOptions.cs | 2 +- .../src/Sender/ServiceBusMessageBatch.cs | 2 +- .../src/Sender/ServiceBusSender.cs | 2 +- .../src/BlobBatch.cs | 4 +- .../src/DelayedResponse.cs | 2 +- .../src/MemoryResponse.cs | 2 +- .../src/Multipart.cs | 4 +- .../src/RemoveVersionHeaderPolicy.cs | 2 +- .../src/Shared/BufferedReadStream.cs | 5 +- .../src/LazyLoadingBlobStream.cs | 8 +- .../src/BlobQuickQueryStream.cs | 4 + .../Azure.Storage.Blobs/src/BlobUriBuilder.cs | 16 +- .../src/Generated/BlobRestClient.cs | 2 + .../src/Models/AppendBlobCreateOptions.cs | 4 + .../src/Models/BlobCopyFromUriOptions.cs | 4 + .../src/Models/BlobUploadOptions.cs | 4 + .../src/Models/BlockBlobOpenWriteOptions.cs | 4 + .../src/Models/CommitBlockListOptions.cs | 4 + .../src/Models/PageBlobCreateOptions.cs | 4 + .../src/Shared/LazyLoadingReadOnlyStream.cs | 1 + .../src/Shared/NonDisposingStream.cs | 2 - .../src/Shared/PooledMemoryStream.cs | 1 + .../src/Shared/ProgressIncrementingStream.cs | 6 +- .../src/Shared/StorageMemoryPool.cs | 2 +- .../src/Shared/StreamPartition.cs | 6 +- .../src/Shared/WindowStream.cs | 2 +- .../tests/CommonTestBase.cs | 2 +- .../src/DataLakePathClient.cs | 10 +- .../src/DataLakeUriBuilder.cs | 12 +- .../src/Models/DataLakeFileUploadOptions.cs | 2 + .../src/Models/PathAccessControlItem.cs | 4 +- .../src/Models/PathPermissions.cs | 4 +- .../src/Models/RemovePathAccessControlItem.cs | 2 +- .../src/Generated/FileRestClient.cs | 2 + .../src/Models/NtfsFileAttributes.cs | 2 +- .../src/Models/ShareCreateOptions.cs | 2 + .../src/ShareClient.cs | 2 +- .../src/ShareUriBuilder.cs | 12 +- .../src/AvroReader.cs | 2 +- .../src/StreamWithPosition.cs | 4 +- .../src/Generated/QueueRestClient.cs | 2 + .../src/QueueUriBuilder.cs | 8 +- .../src/BlobPathSource.cs | 2 +- .../src/Listeners/PollLogsStrategy.cs | 2 +- .../ScanBlobScanLogHybridPollingStrategy.cs | 2 +- .../src/Listeners/ScanContainersStrategy.cs | 2 +- .../src/ParameterizedBlobPathSource.cs | 2 +- .../src/Shared/Queues/QueueListener.cs | 4 +- .../src/Shared/StorageClientProvider.cs | 2 +- .../Timers/RecurrentTaskSeriesCommand.cs | 2 +- .../src/Shared/Timers/TaskSeriesTimer.cs | 2 +- .../UpdateQueueMessageVisibilityCommand.cs | 2 +- .../src/Queryable/WebConvert.cs | 4 +- .../src/Queryable/XmlConstants.cs | 2 +- .../src/TableTransactionalBatch.cs | 6 +- .../src/ClientDiagnostics.cs | 2 + .../src/DocumentHealthcareResult.cs | 2 +- .../src/TextAnalyticsClient.cs | 8 +- 178 files changed, 515 insertions(+), 427 deletions(-) diff --git a/common/Stress/Azure.Test.Stress/StressMetrics.cs b/common/Stress/Azure.Test.Stress/StressMetrics.cs index 4259c80917949..07fcb99468944 100644 --- a/common/Stress/Azure.Test.Stress/StressMetrics.cs +++ b/common/Stress/Azure.Test.Stress/StressMetrics.cs @@ -225,10 +225,10 @@ private static string FormatTable(IEnumerable<(string Key, object Value)> data) foreach (var kvp in data) { sb.Append(kvp.Key); - sb.Append(":"); + sb.Append(':'); for (var i = kvp.Key.Length + 1; i < longestKeyLength + padding + 1; i++) { - sb.Append(" "); + sb.Append(' '); } sb.Append(kvp.Value); sb.AppendLine(); diff --git a/eng/Directory.Build.Data.props b/eng/Directory.Build.Data.props index e2bd1717b305b..6f8e8e2cff383 100644 --- a/eng/Directory.Build.Data.props +++ b/eng/Directory.Build.Data.props @@ -25,6 +25,10 @@ CA2231; CA2225; CA1714; + CA1062; + CA1031; + CA2000; + CA2012; true diff --git a/eng/Packages.Data.props b/eng/Packages.Data.props index c19daafa72e65..00d3d5c506f0e 100644 --- a/eng/Packages.Data.props +++ b/eng/Packages.Data.props @@ -9,7 +9,7 @@ - + @@ -63,7 +63,7 @@ - + diff --git a/sdk/batch/Microsoft.Azure.Batch/src/AddTasksWorkflowManager.cs b/sdk/batch/Microsoft.Azure.Batch/src/AddTasksWorkflowManager.cs index 62d4338561dec..116e1d05ffcc4 100644 --- a/sdk/batch/Microsoft.Azure.Batch/src/AddTasksWorkflowManager.cs +++ b/sdk/batch/Microsoft.Azure.Batch/src/AddTasksWorkflowManager.cs @@ -42,7 +42,7 @@ internal class AddTasksWorkflowManager /// File staging artifacts associated with this operation. If the customer does not set this, it is unviewable by them. /// The behavior manager. internal AddTasksWorkflowManager( - JobOperations jobOperations, + JobOperations jobOperations, string jobId, BatchClientParallelOptions parallelOptions, ConcurrentBag> fileStagingArtifacts, @@ -55,7 +55,7 @@ internal AddTasksWorkflowManager( { parallelOptions = new BatchClientParallelOptions(); } - + // // Set up the data structures associated with this workflow // @@ -69,7 +69,7 @@ internal AddTasksWorkflowManager( this._behaviorManager = bhMgr; this._maxTasks = Constants.MaxTasksInSingleAddTaskCollectionRequest; this._hasRun = HasNotRun; //Has not run by default - + //Read the behavior manager and populate the collection List behaviorList = this._behaviorManager.GetBehaviors(); foreach (AddTaskCollectionResultHandler handler in behaviorList) @@ -96,7 +96,7 @@ public async System.Threading.Tasks.Task AddTasksAsync(IEnumerable ta { throw new RunOnceException(string.Format(CultureInfo.InvariantCulture, BatchErrorMessages.CanOnlyBeRunOnceFailure, this.GetType().Name)); } - + //Determine what time to timeout at if (timeout != null) { @@ -131,12 +131,12 @@ public async System.Threading.Tasks.Task AddTasksAsync(IEnumerable ta { throw new ArgumentNullException(nameof(tasksToAdd), BatchErrorMessages.CollectionMustNotContainNull); } - + if (cloudTask.BindingState == BindingState.Bound) { throw UtilitiesInternal.OperationForbiddenOnBoundObjects; } - + this._remainingTasksToAdd.Enqueue(new TrackedCloudTask(this._jobId, this._jobOperations, cloudTask)); } @@ -149,12 +149,12 @@ public async System.Threading.Tasks.Task AddTasksAsync(IEnumerable ta //1. We have no free request slots //2. We have no more tasks to add and there are ongoing pending operations which could result in task add retries (causing us to get more tasks to add) bool noFreeSlots = this._pendingAsyncOperations.Count >= this._parallelOptions.MaxDegreeOfParallelism; - bool noTasksToAddButSomePendingLegsRemain = this._remainingTasksToAdd.Count == 0 && this._pendingAsyncOperations.Count > 0; + bool noTasksToAddButSomePendingLegsRemain = this._remainingTasksToAdd.IsEmpty && this._pendingAsyncOperations.Count > 0; if (noFreeSlots || noTasksToAddButSomePendingLegsRemain) { await this.ProcessPendingOperationResults().ConfigureAwait(continueOnCapturedContext: false); } - + //If we get here, we are starting a single new leg. Another iteration of this loop will get to any tasks which do not fit in this leg. //Add any tasks (up to max count in 1 request) which are remaining since we have an open parallel slot @@ -193,7 +193,7 @@ private void CheckForCancellationOrTimeoutAndThrow() { //We always throw when cancelation is requested this._parallelOptions.CancellationToken.ThrowIfCancellationRequested(); - + DateTime currentTime = DateTime.UtcNow; @@ -209,7 +209,7 @@ private void CheckForCancellationOrTimeoutAndThrow() /// True if the workflow has successfully completed, false if it has not. private bool IsWorkflowDone() { - return !(this._remainingTasksToAdd.Count > 0 || this._pendingAsyncOperations.Count > 0); + return !(!this._remainingTasksToAdd.IsEmpty || this._pendingAsyncOperations.Count > 0); } /// @@ -254,7 +254,7 @@ private async Task StageFilesAndAddTasks( // wait for file staging async task await fileStagingTask.ConfigureAwait(continueOnCapturedContext: false); - + // now update each non-finalized Task with its new ResourceFiles foreach (TrackedCloudTask taskToAdd in tasksToAdd.Values) { @@ -279,7 +279,7 @@ private async Task StageFilesAndAddTasks( } } } - + //Mark the file staging collection as read only just incase there's another reference to it ConcurrentChangeTrackedList filesToStageListImpl = taskToAdd.Task.FilesToStage as ConcurrentChangeTrackedList; @@ -353,13 +353,13 @@ private void ProcessProtocolAddTaskResults( { string taskId = protoAddTaskResult.TaskId; TrackedCloudTask trackedTask = taskMap[taskId]; - + AddTaskResult omResult = new AddTaskResult(trackedTask.Task, trackedTask.RetryCount, protoAddTaskResult); - + //We know that there must be at least one AddTaskResultHandler so the below ForEach will always be called //at least once. AddTaskResultStatus status = AddTaskResultStatus.Success; //The default is success to avoid infinite retry - + //Call the customer defined result handler foreach (var resultHandlerFunction in this._addTaskResultHandlerCollection) { @@ -385,7 +385,7 @@ private void ProcessProtocolAddTaskResults( private async Task ProcessPendingOperationResults() { //Wait for any task to complete - Task completedTask = await Task.WhenAny(this._pendingAsyncOperations).ConfigureAwait(continueOnCapturedContext: false); + Task completedTask = await Task.WhenAny(this._pendingAsyncOperations).ConfigureAwait(continueOnCapturedContext: false); //Check for a task failure -- if there is one, we a-wait for all remaining tasks to complete (this will throw an exception since at least one of them failed). if (completedTask.IsFaulted) @@ -395,7 +395,7 @@ private async Task ProcessPendingOperationResults() else { await completedTask.ConfigureAwait(continueOnCapturedContext: false); //This await should finish immediately and will not fail since the task has not faulted - + //Remove the task which completed this._pendingAsyncOperations.Remove(completedTask); } @@ -421,7 +421,7 @@ private static async Task WaitForTasksAndThrowParallelOperationsExceptionAsync(L #endregion #region Private classes - + /// /// Internal task wrapper which tracks a tasks retry count and holds a reference to the protocol object and CloudTask. /// @@ -444,7 +444,7 @@ internal TrackedCloudTask( this.JobOperations = jobOperations; // matt-c: do we really need one of these in every instance? Even when they were wiMgrs couldnt something outside keep a reference? this.RetryCount = 0; } - + public void IncrementRetryCount() { this.RetryCount++; diff --git a/sdk/batch/Microsoft.Azure.Batch/src/BatchClient.cs b/sdk/batch/Microsoft.Azure.Batch/src/BatchClient.cs index 96ee5ea843c83..4d284be2811a8 100644 --- a/sdk/batch/Microsoft.Azure.Batch/src/BatchClient.cs +++ b/sdk/batch/Microsoft.Azure.Batch/src/BatchClient.cs @@ -12,9 +12,9 @@ namespace Microsoft.Azure.Batch /// /// The dispose pattern sets all references to null. /// Put all references into this box. - /// + /// /// ONLY ACCESS VIA GetStateThrowIfNotOpen() method! - /// + /// /// internal class BatchClientDisposableStateBox { @@ -56,7 +56,7 @@ public BatchClientDisposableStateBox(BatchClient parentBatchClient) public class BatchClient : IDisposable { private BatchClientDisposableStateBox _disposableStateBox; // null state box signals that the instance is closed - private bool _disposed = false; // used for dispose pattern + private bool _disposed; // used for dispose pattern private readonly object _closeLocker = new object(); #region // constructors @@ -103,7 +103,7 @@ internal BatchClient(IProtocolLayer protocolLayer) } #endregion Constructors - + #region IInheritedBehaviors /// @@ -275,13 +275,13 @@ internal BatchClientDisposableStateBox GetStateThrowIfNotOpen() /// /// Holds the protocol layer to be used for this client instance. /// This enables "mock"ing the protocol layer for testing. - /// + /// /// Since 100% of all calls indirect through this property, it /// provides a single place to immediately stop all (new) call attempts /// when the underlying BatchClient is closed. /// - internal IProtocolLayer ProtocolLayer - { + internal IProtocolLayer ProtocolLayer + { get { IProtocolLayer localProto = GetStateThrowIfNotOpen().ProtocolLayer; diff --git a/sdk/batch/Microsoft.Azure.Batch/src/ConcurrentChangeTrackedList.cs b/sdk/batch/Microsoft.Azure.Batch/src/ConcurrentChangeTrackedList.cs index d5435053589c9..fce19c1ae6aa4 100644 --- a/sdk/batch/Microsoft.Azure.Batch/src/ConcurrentChangeTrackedList.cs +++ b/sdk/batch/Microsoft.Azure.Batch/src/ConcurrentChangeTrackedList.cs @@ -12,9 +12,9 @@ internal class ConcurrentChangeTrackedList : IList, IPropertyMetadata, IRe { protected readonly IList _list; protected readonly object _listLock = new object(); - - protected bool _hasBeenModified = false; - + + protected bool _hasBeenModified; + public ConcurrentChangeTrackedList() { this._list = new List(); @@ -24,7 +24,7 @@ public ConcurrentChangeTrackedList() public ConcurrentChangeTrackedList(IEnumerable other, bool isReadOnly = false) { this._list = new List(); - + foreach (T item in other) { this._list.Add(item); @@ -73,11 +73,11 @@ IEnumerator IEnumerable.GetEnumerator() #endregion #region IList - + public void Add(T item) { this.ThrowOnReadOnly(); - + lock (this._listLock) { this._list.Add(item); @@ -125,8 +125,8 @@ public bool Remove(T item) } } - public int Count - { + public int Count + { get { lock (this._listLock) @@ -170,8 +170,8 @@ public void RemoveAt(int index) public T this[int index] { - get - { + get + { lock (this._listLock) { T result = this._list[index]; @@ -179,7 +179,7 @@ public T this[int index] } } - set + set { this.ThrowOnReadOnly(); @@ -208,7 +208,7 @@ public void AddRange(IEnumerable items) public IReadOnlyList AsReadOnly() { - //As per http://msdn.microsoft.com/en-us/library/ms132474%28v=vs.110%29.aspx this is a wrapper around the collection, which will disallow modification but + //As per http://msdn.microsoft.com/en-us/library/ms132474%28v=vs.110%29.aspx this is a wrapper around the collection, which will disallow modification but //will reflect any changes made to the underlying list return new ReadOnlyCollection(this._list); } diff --git a/sdk/batch/Microsoft.Azure.Batch/src/FileStaging/FileStagingUtils.cs b/sdk/batch/Microsoft.Azure.Batch/src/FileStaging/FileStagingUtils.cs index d5aebb053879c..1043bfcda7ce9 100644 --- a/sdk/batch/Microsoft.Azure.Batch/src/FileStaging/FileStagingUtils.cs +++ b/sdk/batch/Microsoft.Azure.Batch/src/FileStaging/FileStagingUtils.cs @@ -55,7 +55,7 @@ internal static async Task StageFilesAsync(List filesToSta throw new ArgumentNullException(nameof(allFileStagingArtifacts)); } - if (allFileStagingArtifacts.Count > 0) + if (!allFileStagingArtifacts.IsEmpty) { throw new ArgumentOutOfRangeException(nameof(allFileStagingArtifacts)); } diff --git a/sdk/batch/Microsoft.Azure.Batch/src/ODATAMonitor.cs b/sdk/batch/Microsoft.Azure.Batch/src/ODATAMonitor.cs index d3178f56f2cdc..aa79e739c44fb 100644 --- a/sdk/batch/Microsoft.Azure.Batch/src/ODATAMonitor.cs +++ b/sdk/batch/Microsoft.Azure.Batch/src/ODATAMonitor.cs @@ -35,7 +35,7 @@ public TimeSpan DelayBetweenDataFetch { value = _lowerBoundDelayBetweenRefresh; } - + _delayBetweenDataFetch = value; } } @@ -52,7 +52,7 @@ public TimeSpan DelayBetweenDataFetch /// /// internal delegate IPagedEnumerable ListDelegate(); - + /// /// A class that leverages OData predicates to poll the states of instances. /// @@ -179,7 +179,7 @@ internal RefreshViaODATAFilterList( // queue that holds the instances that have been refreshed and failed the condition... // to be refreshed again on the next pass public Queue> NextPassQueue = new Queue>(); - + public CancellationToken CancellationToken { get; private set; } /// @@ -206,7 +206,7 @@ internal RefreshViaODATAFilterList( private readonly StringBuilder _odataFilterSB = new StringBuilder(); private const string IdPrefix = "id eq '"; - private const string IdPostfix = "'"; + private const char IdPostfix = '\''; private const string OrOperator = " or "; internal async Task ProcessOneInstance(MonitorLastCall nextInstance, Func getName) @@ -322,7 +322,7 @@ internal async Task CallListAndProcessResults() return; } - // update the detail level + // update the detail level _odataDetailLevel.FilterClause = predicate; // get the enumerable to refresh the instances diff --git a/sdk/batch/Microsoft.Azure.Batch/src/PagedEnumeratorBase.cs b/sdk/batch/Microsoft.Azure.Batch/src/PagedEnumeratorBase.cs index 72546a7a11cb8..c2296638773d2 100644 --- a/sdk/batch/Microsoft.Azure.Batch/src/PagedEnumeratorBase.cs +++ b/sdk/batch/Microsoft.Azure.Batch/src/PagedEnumeratorBase.cs @@ -132,7 +132,7 @@ public void Dispose() internal class SkipTokenHandler { private string _skipToken; - private bool _hasBeenCalled = false; + private bool _hasBeenCalled; public bool AtLeastOneCallMade { get { return _hasBeenCalled; } set { _hasBeenCalled = value; } } diff --git a/sdk/batch/Microsoft.Azure.Batch/src/PoolOperations.cs b/sdk/batch/Microsoft.Azure.Batch/src/PoolOperations.cs index 638b1bfb57ce8..642adead41862 100644 --- a/sdk/batch/Microsoft.Azure.Batch/src/PoolOperations.cs +++ b/sdk/batch/Microsoft.Azure.Batch/src/PoolOperations.cs @@ -206,12 +206,12 @@ public CloudPool CreatePool() /// The for the pool. /// /// The desired number of dedicated compute nodes in the pool. - /// If and are omitted, + /// If and are omitted, /// you must set the and properties. /// /// /// The desired number of low-priority compute nodes in the pool. - /// If and are omitted, + /// If and are omitted, /// you must set the and properties. /// /// A representing a new pool that has not been added to the Batch service. @@ -242,18 +242,18 @@ public CloudPool CreatePool( /// Creates an instance of CloudPool that is unbound and does not have a consistency relationship to any pool in the Batch service. /// /// The id of the pool. - /// The size of virtual machines in the pool. + /// The size of virtual machines in the pool. /// See https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/ for windows sizes and https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/ for linux sizes. /// /// The for the pool. /// /// The desired number of dedicated compute nodes in the pool. - /// If and are omitted, + /// If and are omitted, /// you must set the and properties. /// /// /// The desired number of low-priority compute nodes in the pool. - /// If and are omitted, + /// If and are omitted, /// you must set the and properties. /// /// A representing a new pool that has not been added to the Batch service. @@ -489,7 +489,7 @@ public IPagedEnumerable ListComputeNodes(string poolId, DetailLevel { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); - + // get enumerable IPagedEnumerable enumerable = ListComputeNodesImpl(poolId, bhMgr, detailLevel); @@ -499,7 +499,7 @@ public IPagedEnumerable ListComputeNodes(string poolId, DetailLevel internal async System.Threading.Tasks.Task GetComputeNodeAsyncImpl( string poolId, - string computeNodeId, + string computeNodeId, BehaviorManager bhMgr, CancellationToken cancellationToken) { @@ -524,9 +524,9 @@ internal async System.Threading.Tasks.Task GetComputeNodeAsyncImpl( /// A containing information about the specified compute node. /// The get node operation runs asynchronously. public System.Threading.Tasks.Task GetComputeNodeAsync( - string poolId, + string poolId, string computeNodeId, - DetailLevel detailLevel = null, + DetailLevel detailLevel = null, IEnumerable additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { @@ -548,8 +548,8 @@ public System.Threading.Tasks.Task GetComputeNodeAsync( /// A containing information about the specified compute node. /// This is a blocking operation. For a non-blocking equivalent, see . public ComputeNode GetComputeNode( - string poolId, - string computeNodeId, + string poolId, + string computeNodeId, DetailLevel detailLevel = null, IEnumerable additionalBehaviors = null) { @@ -567,7 +567,7 @@ public ComputeNode GetComputeNode( /// A that represents the asynchronous operation. /// This operation runs asynchronously. public System.Threading.Tasks.Task EnableComputeNodeSchedulingAsync( - string poolId, + string poolId, string computeNodeId, IEnumerable additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) @@ -588,7 +588,7 @@ public System.Threading.Tasks.Task EnableComputeNodeSchedulingAsync( /// A collection of instances that are applied to the Batch service request after the . /// This is a blocking operation. For a non-blocking equivalent, see . public void EnableComputeNodeScheduling( - string poolId, + string poolId, string computeNodeId, IEnumerable additionalBehaviors = null) { @@ -640,7 +640,7 @@ public void DisableComputeNodeScheduling( } internal async System.Threading.Tasks.Task EnableAutoScaleAsyncImpl( - string poolId, + string poolId, string autoscaleFormula, TimeSpan? autoscaleEvaluationInterval, BehaviorManager bhMgr, @@ -672,7 +672,7 @@ internal async System.Threading.Tasks.Task EnableAutoScaleAsyncImpl( /// The enable autoscale operation runs asynchronously. /// public async System.Threading.Tasks.Task EnableAutoScaleAsync( - string poolId, + string poolId, string autoscaleFormula = null, TimeSpan? autoscaleEvaluationInterval = null, IEnumerable additionalBehaviors = null, @@ -700,7 +700,7 @@ public async System.Threading.Tasks.Task EnableAutoScaleAsync( /// This is a blocking operation. For a non-blocking equivalent, see . /// public void EnableAutoScale( - string poolId, + string poolId, string autoscaleFormula = null, TimeSpan? autoscaleEvaluationInterval = null, IEnumerable additionalBehaviors = null) @@ -772,7 +772,7 @@ internal async System.Threading.Tasks.Task EvaluateAutoScaleAsyncI } /// - /// Gets the result of evaluating an automatic scaling formula on the specified pool. This + /// Gets the result of evaluating an automatic scaling formula on the specified pool. This /// is primarily for validating an autoscale formula, as it simply returns the result /// without applying the formula to the pool. /// @@ -798,7 +798,7 @@ public async System.Threading.Tasks.Task EvaluateAutoScaleAsync( // start call System.Threading.Tasks.Task asyncTask = EvaluateAutoScaleAsyncImpl( poolId, - autoscaleFormula, + autoscaleFormula, bhMgr, cancellationToken); @@ -808,7 +808,7 @@ public async System.Threading.Tasks.Task EvaluateAutoScaleAsync( } /// - /// Gets the result of evaluating an automatic scaling formula on the specified pool. This + /// Gets the result of evaluating an automatic scaling formula on the specified pool. This /// is primarily for validating an autoscale formula, as it simply returns the result /// without applying the formula to the pool. /// @@ -900,11 +900,11 @@ internal System.Threading.Tasks.Task RemoveFromPoolAsyncImpl( { // start call System.Threading.Tasks.Task asyncTask = this._parentBatchClient.ProtocolLayer.RemovePoolComputeNodes( - poolId, - computeNodeIds, - deallocationOption, - resizeTimeout, - bhMgr, + poolId, + computeNodeIds, + deallocationOption, + resizeTimeout, + bhMgr, cancellationToken); return asyncTask; @@ -940,10 +940,10 @@ public System.Threading.Tasks.Task RemoveFromPoolAsync( // start call System.Threading.Tasks.Task asyncTask = RemoveFromPoolAsyncImpl( - poolId, - computeNodeIds, + poolId, + computeNodeIds, deallocationOption, - resizeTimeout, + resizeTimeout, bhMgr, cancellationToken); @@ -1053,10 +1053,10 @@ internal System.Threading.Tasks.Task RemoveFromPoolAsyncImpl( // start call System.Threading.Tasks.Task asyncTask = RemoveFromPoolAsyncImpl( - poolId, - computeNodeIds, + poolId, + computeNodeIds, deallocationOption, - resizeTimeout, + resizeTimeout, bhMgr, cancellationToken); @@ -1093,10 +1093,10 @@ public async System.Threading.Tasks.Task RemoveFromPoolAsync( // start call System.Threading.Tasks.Task asyncTask = RemoveFromPoolAsyncImpl( - poolId, - computeNodes, + poolId, + computeNodes, deallocationOption, - resizeTimeout, + resizeTimeout, bhMgr, cancellationToken); @@ -1158,9 +1158,9 @@ public ComputeNodeUser CreateComputeNodeUser(string poolId, string computeNodeId /// The delete operation runs asynchronously. /// public System.Threading.Tasks.Task DeleteComputeNodeUserAsync( - string poolId, + string poolId, string computeNodeId, - string userName, + string userName, IEnumerable additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { @@ -1169,8 +1169,8 @@ public System.Threading.Tasks.Task DeleteComputeNodeUserAsync( System.Threading.Tasks.Task asyncTask = _parentBatchClient.ProtocolLayer.DeleteComputeNodeUser( poolId, - computeNodeId, - userName, + computeNodeId, + userName, bhMgr, cancellationToken); @@ -1208,13 +1208,13 @@ public void DeleteComputeNodeUser(string poolId, string computeNodeId, string us /// This method does not close the stream, and it does not reset the position after writing. /// It is the caller's responsibility to close the stream, or to reset the position if required. /// The get RDP file operation runs asynchronously. - /// This method can be invoked only if the pool is created with a property. - /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). + /// This method can be invoked only if the pool is created with a property. + /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). /// For pools with property, the new method must be used. /// public System.Threading.Tasks.Task GetRDPFileAsync( - string poolId, - string computeNodeId, + string poolId, + string computeNodeId, Stream rdpStream, IEnumerable additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) @@ -1224,8 +1224,8 @@ public System.Threading.Tasks.Task GetRDPFileAsync( System.Threading.Tasks.Task asyncTask = _parentBatchClient.ProtocolLayer.GetComputeNodeRDPFile( poolId, - computeNodeId, - rdpStream, + computeNodeId, + rdpStream, bhMgr, cancellationToken); @@ -1244,8 +1244,8 @@ public System.Threading.Tasks.Task GetRDPFileAsync( /// This method does not close the stream, and it does not reset the position after writing. /// It is the caller's responsibility to close the stream, or to reset the position if required. /// This is a blocking operation. For a non-blocking equivalent, see . - /// This method can be invoked only if the pool is created with a property. - /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). + /// This method can be invoked only if the pool is created with a property. + /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). /// For pools with property, the new method must be used. /// public void GetRDPFile(string poolId, string computeNodeId, Stream rdpStream, @@ -1256,9 +1256,9 @@ public void GetRDPFile(string poolId, string computeNodeId, Stream rdpStream, } internal async System.Threading.Tasks.Task GetRDPFileViaFileNameAsyncImpl( - string poolId, + string poolId, string computeNodeId, - string rdpFileNameToCreate, + string rdpFileNameToCreate, BehaviorManager bhMgr, CancellationToken cancellationToken) { @@ -1271,7 +1271,7 @@ internal async System.Threading.Tasks.Task GetRDPFileViaFileNameAsyncImpl( await asyncTask.ConfigureAwait(continueOnCapturedContext: false); // stream has rdp contents, flush - await rdpStream.FlushAsync().ConfigureAwait(continueOnCapturedContext: false); + await rdpStream.FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } @@ -1287,14 +1287,14 @@ internal async System.Threading.Tasks.Task GetRDPFileViaFileNameAsyncImpl( /// /// If the file specified by already exists, it is overwritten. /// The get RDP file operation runs asynchronously. - /// This method can be invoked only if the pool is created with a property. - /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). + /// This method can be invoked only if the pool is created with a property. + /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). /// For pools with property, the new method must be used. /// public System.Threading.Tasks.Task GetRDPFileAsync( - string poolId, + string poolId, string computeNodeId, - string rdpFileNameToCreate, + string rdpFileNameToCreate, IEnumerable additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { @@ -1302,9 +1302,9 @@ public System.Threading.Tasks.Task GetRDPFileAsync( BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); System.Threading.Tasks.Task asyncTask = GetRDPFileViaFileNameAsyncImpl( - poolId, + poolId, computeNodeId, - rdpFileNameToCreate, + rdpFileNameToCreate, bhMgr, cancellationToken); @@ -1321,8 +1321,8 @@ public System.Threading.Tasks.Task GetRDPFileAsync( /// /// If the file specified by already exists, it is overwritten. /// This is a blocking operation. For a non-blocking equivalent, see . - /// This method can be invoked only if the pool is created with a property. - /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). + /// This method can be invoked only if the pool is created with a property. + /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). /// For pools with property, the new method must be used. /// public void GetRDPFile(string poolId, string computeNodeId, string rdpFileNameToCreate, @@ -1337,9 +1337,9 @@ internal async System.Threading.Tasks.Task GetRemoteLoginSe var asyncTask = _parentBatchClient.ProtocolLayer.GetRemoteLoginSettings(poolId, computeNodeId, bhMgr, cancellationToken); var response = await asyncTask.ConfigureAwait(continueOnCapturedContext: false); - + Models.ComputeNodeGetRemoteLoginSettingsResult rlSettings = response.Body; - + RemoteLoginSettings rls = new RemoteLoginSettings(rlSettings); return rls; @@ -1355,12 +1355,12 @@ internal async System.Threading.Tasks.Task GetRemoteLoginSe /// A that represents the asynchronous operation. /// /// The get remote login settings operation runs asynchronously. - /// This method can be invoked only if the pool is created with a property. - /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). + /// This method can be invoked only if the pool is created with a property. + /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). /// For pools with a property, one of the GetRDPFileAsync/GetRDPFile methods must be used. /// public System.Threading.Tasks.Task GetRemoteLoginSettingsAsync( - string poolId, + string poolId, string computeNodeId, IEnumerable additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) @@ -1385,13 +1385,13 @@ public System.Threading.Tasks.Task GetRemoteLoginSettingsAs /// A collection of instances that are applied to the Batch service request after the . /// /// This is a blocking operation. For a non-blocking equivalent, see . - /// This method can be invoked only if the pool is created with a property. - /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). + /// This method can be invoked only if the pool is created with a property. + /// If this method is invoked on pools created with , then Batch service returns 409 (Conflict). /// For pools with a property, one of the GetRDPFileAsync/GetRDPFile methods must be used. /// public RemoteLoginSettings GetRemoteLoginSettings( - string poolId, - string computeNodeId, + string poolId, + string computeNodeId, IEnumerable additionalBehaviors = null) { Task asyncTask = GetRemoteLoginSettingsAsync(poolId, computeNodeId, additionalBehaviors); @@ -1413,10 +1413,10 @@ public RemoteLoginSettings GetRemoteLoginSettings( /// You can reboot a compute node only when it is in the or state. /// The reboot operation runs asynchronously. /// - public System.Threading.Tasks.Task RebootAsync(string poolId, + public System.Threading.Tasks.Task RebootAsync(string poolId, string computeNodeId, Common.ComputeNodeRebootOption? rebootOption = null, - IEnumerable additionalBehaviors = null, + IEnumerable additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager @@ -1424,8 +1424,8 @@ public System.Threading.Tasks.Task RebootAsync(string poolId, System.Threading.Tasks.Task asyncTask = _parentBatchClient.ProtocolLayer.RebootComputeNode( poolId, - computeNodeId, - rebootOption, + computeNodeId, + rebootOption, bhMgr, cancellationToken); @@ -1464,7 +1464,7 @@ public void Reboot(string poolId, string computeNodeId, Common.ComputeNodeReboot /// The reimage operation runs asynchronously. /// public System.Threading.Tasks.Task ReimageAsync( - string poolId, + string poolId, string computeNodeId, Common.ComputeNodeReimageOption? reimageOption = null, IEnumerable additionalBehaviors = null, @@ -1504,12 +1504,12 @@ internal async System.Threading.Tasks.Task GetNodeFileAsyncImpl( CancellationToken cancellationToken) { var getNodeFilePropertiesTask = await this.ParentBatchClient.ProtocolLayer.GetNodeFilePropertiesByNode( - poolId, - computeNodeId, - filePath, + poolId, + computeNodeId, + filePath, bhMgr, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); - + Models.NodeFile file = getNodeFilePropertiesTask.Body; // wrap protocol object @@ -1529,9 +1529,9 @@ internal async System.Threading.Tasks.Task GetNodeFileAsyncImpl( /// A containing information about the file, and which can be used to download the file (see ). /// The get file operation runs asynchronously. public System.Threading.Tasks.Task GetNodeFileAsync( - string poolId, + string poolId, string computeNodeId, - string filePath, + string filePath, IEnumerable additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { @@ -1539,8 +1539,8 @@ public System.Threading.Tasks.Task GetNodeFileAsync( BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); System.Threading.Tasks.Task asyncTask = this.GetNodeFileAsyncImpl( - poolId, - computeNodeId, + poolId, + computeNodeId, filePath, bhMgr, cancellationToken); @@ -1756,8 +1756,8 @@ public IPagedEnumerable ListNodeFiles( /// The id of the compute node. /// The path of the file to delete. /// - /// If the file-path parameter represents a directory instead of a file, you can set the optional - /// recursive parameter to true to delete the directory and all of the files and subdirectories in it. If recursive is false + /// If the file-path parameter represents a directory instead of a file, you can set the optional + /// recursive parameter to true to delete the directory and all of the files and subdirectories in it. If recursive is false /// then the directory must be empty or deletion will fail. /// /// A collection of instances that are applied to the Batch service request after the . @@ -1765,8 +1765,8 @@ public IPagedEnumerable ListNodeFiles( /// A that represents the asynchronous operation. /// The delete operation runs asynchronously. public System.Threading.Tasks.Task DeleteNodeFileAsync( - string poolId, - string computeNodeId, + string poolId, + string computeNodeId, string filePath, bool? recursive = null, IEnumerable additionalBehaviors = null, @@ -1777,8 +1777,8 @@ public System.Threading.Tasks.Task DeleteNodeFileAsync( System.Threading.Tasks.Task asyncTask = _parentBatchClient.ProtocolLayer.DeleteNodeFileByNode( poolId, - computeNodeId, - filePath, + computeNodeId, + filePath, recursive, bhMgr, cancellationToken); @@ -1793,15 +1793,15 @@ public System.Threading.Tasks.Task DeleteNodeFileAsync( /// The id of the compute node. /// The path of the file to delete. /// - /// If the file-path parameter represents a directory instead of a file, you can set the optional - /// recursive parameter to true to delete the directory and all of the files and subdirectories in it. If recursive is false + /// If the file-path parameter represents a directory instead of a file, you can set the optional + /// recursive parameter to true to delete the directory and all of the files and subdirectories in it. If recursive is false /// then the directory must be empty or deletion will fail. /// /// A collection of instances that are applied to the Batch service request after the . /// This is a blocking operation. For a non-blocking equivalent, see . public void DeleteNodeFile( - string poolId, - string computeNodeId, + string poolId, + string computeNodeId, string filePath, bool? recursive = null, IEnumerable additionalBehaviors = null) @@ -1825,7 +1825,7 @@ public void DeleteNodeFile( // craft the behavior manager for this call BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); - System.Threading.Tasks.Task> asyncTask = + System.Threading.Tasks.Task> asyncTask = this.ParentBatchClient.ProtocolLayer.GetAllPoolLifetimeStats(bhMgr, cancellationToken); var response = await asyncTask.ConfigureAwait(continueOnCapturedContext: false); @@ -1836,7 +1836,7 @@ public void DeleteNodeFile( } /// - /// Gets lifetime summary statistics for all of the pools in the current account. + /// Gets lifetime summary statistics for all of the pools in the current account. /// Statistics are aggregated across all pools that have ever existed in the account, from account creation to the last update time of the statistics. The statistics may not be immediately available. The /// Batch service performs periodic roll-up of statistics. The typical delay is about 30 minutes. /// @@ -1882,7 +1882,7 @@ public IPagedEnumerable ListPoolUsageMetrics(DateTime? startTi } /// - /// Enumerates the node agent Sku values supported by Batch Service. + /// Enumerates the node agent Sku values supported by Batch Service. /// /// A used for filtering the list and for controlling which properties are retrieved from the service. /// A collection of instances that are applied to the Batch service request after the and . @@ -1925,7 +1925,7 @@ internal async System.Threading.Tasks.Task UploadC cancellationToken); var result = await task.ConfigureAwait(false); - + return new UploadBatchServiceLogsResult(result.Body); } diff --git a/sdk/batch/Microsoft.Azure.Batch/tests/IntegrationTests/IntegrationTestUtilities/FileUploadUtilities.cs b/sdk/batch/Microsoft.Azure.Batch/tests/IntegrationTests/IntegrationTestUtilities/FileUploadUtilities.cs index 8a05cd5feeecb..600275127bdf4 100644 --- a/sdk/batch/Microsoft.Azure.Batch/tests/IntegrationTests/IntegrationTestUtilities/FileUploadUtilities.cs +++ b/sdk/batch/Microsoft.Azure.Batch/tests/IntegrationTests/IntegrationTestUtilities/FileUploadUtilities.cs @@ -147,12 +147,12 @@ private FileToStage() } /// - /// Specifies that a local file should be staged to blob storage. + /// Specifies that a local file should be staged to blob storage. /// The specified account will be charged for storage costs. /// /// The name of the local file. /// The storage credentials to be used when creating the default container. - /// Optional name to be given to the file on the compute node. If this parameter is null or missing + /// Optional name to be given to the file on the compute node. If this parameter is null or missing /// the name on the compute node will be set to the value of localFileToStage stripped of all path information. public FileToStage(string localFileToStage, StagingStorageAccount storageCredentials, string nodeFileName = null) { @@ -233,7 +233,7 @@ private static string ConstructBlobSource(string container, string blob) if (index != -1) { - //SAS + //SAS string containerAbsoluteUrl = container.Substring(0, index); return containerAbsoluteUrl + "/" + blob + container.Substring(index); } @@ -273,7 +273,7 @@ private static async Task CreateContainerWithPolicySASIfNotExistAsync(st Permissions = permissions, StartsOn = start, ExpiresOn = end, - + }, }; @@ -395,7 +395,7 @@ private static async Task StageFilesInternalAsync(List fil } /// - /// Stages all files in the queue + /// Stages all files in the queue /// private async static Task StageFilesAsync(List filesToStage, SequentialFileStagingArtifact seqArtifacts) { @@ -466,16 +466,16 @@ private async static Task StageOneFileAsync(FileToStage stageThisFile, Sequentia public sealed class SequentialFileStagingArtifact : IFileStagingArtifact { /// - /// The name of any blob container created. - /// - /// A blob container is created if there is at least one file + /// The name of any blob container created. + /// + /// A blob container is created if there is at least one file /// to be uploaded that does not have an explicit container specified. /// public string BlobContainerCreated { get; internal set; } /// /// Optionally set by caller. Optionally used by implementation. A name fragment that can be used when constructing default names. - /// + /// /// Can only be set once. /// public string NamingFragment { get; set; } @@ -497,7 +497,7 @@ private static string MakeDefaultNamePlusNamingFragment(string namingFragment) if (!string.IsNullOrWhiteSpace(namingFragment)) { newNameBuilder.Append(namingFragment); - newNameBuilder.Append("-"); + newNameBuilder.Append('-'); } string newName = newNameBuilder.ToString(); diff --git a/sdk/communication/Azure.Communication.Common/src/Identity/ThreadSafeRefreshableAccessTokenCache.cs b/sdk/communication/Azure.Communication.Common/src/Identity/ThreadSafeRefreshableAccessTokenCache.cs index 007410361ddc7..7c30dede8734c 100644 --- a/sdk/communication/Azure.Communication.Common/src/Identity/ThreadSafeRefreshableAccessTokenCache.cs +++ b/sdk/communication/Azure.Communication.Common/src/Identity/ThreadSafeRefreshableAccessTokenCache.cs @@ -23,7 +23,7 @@ internal sealed class ThreadSafeRefreshableAccessTokenCache : IDisposable internal const int OnDemandRefreshIntervalInMinutes = 2; private readonly object _syncLock = new object(); - private bool _someThreadIsRefreshing = false; + private bool _someThreadIsRefreshing; private AccessToken _currentToken; private bool _valueIsInitialized; diff --git a/sdk/core/Azure.Core.Amqp/src/AmqpAddress.cs b/sdk/core/Azure.Core.Amqp/src/AmqpAddress.cs index a48f681fe4919..aab938ac9d458 100644 --- a/sdk/core/Azure.Core.Amqp/src/AmqpAddress.cs +++ b/sdk/core/Azure.Core.Amqp/src/AmqpAddress.cs @@ -89,16 +89,6 @@ public bool Equals(string other) => /// public static bool operator ==(AmqpAddress left, AmqpAddress right) { - if (ReferenceEquals(left, right)) - { - return true; - } - - if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) - { - return false; - } - return left.Equals(right); } diff --git a/sdk/core/Azure.Core.Amqp/src/AmqpMessageId.cs b/sdk/core/Azure.Core.Amqp/src/AmqpMessageId.cs index 4c5c0105b14e4..0604fdd2627da 100644 --- a/sdk/core/Azure.Core.Amqp/src/AmqpMessageId.cs +++ b/sdk/core/Azure.Core.Amqp/src/AmqpMessageId.cs @@ -90,16 +90,6 @@ public bool Equals(string other) => /// public static bool operator ==(AmqpMessageId left, AmqpMessageId right) { - if (ReferenceEquals(left, right)) - { - return true; - } - - if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) - { - return false; - } - return left.Equals(right); } diff --git a/sdk/core/Azure.Core/src/Pipeline/HttpClientTransport.cs b/sdk/core/Azure.Core/src/Pipeline/HttpClientTransport.cs index e9727c4e98971..0aa9ee4d86e9b 100644 --- a/sdk/core/Azure.Core/src/Pipeline/HttpClientTransport.cs +++ b/sdk/core/Azure.Core/src/Pipeline/HttpClientTransport.cs @@ -59,7 +59,7 @@ public sealed override Request CreateRequest() public override void Process(HttpMessage message) { // Intentionally blocking here - ProcessAsync(message).GetAwaiter().GetResult(); + ProcessAsync(message).AsTask().GetAwaiter().GetResult(); } /// @@ -184,7 +184,7 @@ private static string JoinHeaderValues(IEnumerable values) private sealed class PipelineRequest : Request { - private bool _wasSent = false; + private bool _wasSent; private readonly HttpRequestMessage _requestMessage; private PipelineContentAdapter? _requestContent; @@ -280,6 +280,7 @@ public HttpRequestMessage BuildRequestMessage(CancellationToken cancellation) public override void Dispose() { Content?.Dispose(); + _requestContent?.Dispose(); _requestMessage.Dispose(); } @@ -366,7 +367,9 @@ private sealed class PipelineResponse : Response private readonly HttpContent _responseContent; +#pragma warning disable CA2213 // Content stream is intentionally not disposed private Stream? _contentStream; +#pragma warning restore CA2213 public PipelineResponse(string requestId, HttpResponseMessage responseMessage, Stream? contentStream) { diff --git a/sdk/core/Azure.Core/src/Shared/ClientDiagnostics.cs b/sdk/core/Azure.Core/src/Shared/ClientDiagnostics.cs index fff0f60ae9674..f9ec7a52bf392 100644 --- a/sdk/core/Azure.Core/src/Shared/ClientDiagnostics.cs +++ b/sdk/core/Azure.Core/src/Shared/ClientDiagnostics.cs @@ -39,11 +39,13 @@ public ClientDiagnostics(ClientOptions options) : base( /// The error message. /// The error code. /// Additional error details. +#pragma warning disable CA1822 // Member can be static partial void ExtractFailureContent( string? content, ref string? message, ref string? errorCode, ref IDictionary? additionalInfo); +#pragma warning restore CA1822 public async ValueTask CreateRequestFailedExceptionAsync(Response response, string? message = null, string? errorCode = null, IDictionary? additionalInfo = null, Exception? innerException = null) { diff --git a/sdk/core/Azure.Core/src/Shared/HttpMessageSanitizer.cs b/sdk/core/Azure.Core/src/Shared/HttpMessageSanitizer.cs index a8b705f3f6b53..7c09035089d69 100644 --- a/sdk/core/Azure.Core/src/Shared/HttpMessageSanitizer.cs +++ b/sdk/core/Azure.Core/src/Shared/HttpMessageSanitizer.cs @@ -115,11 +115,11 @@ public string SanitizeUrl(string url) else { stringBuilder.Append(query, queryIndex, nameLength); - stringBuilder.Append("="); + stringBuilder.Append('='); stringBuilder.Append(_redactedPlaceholder); if (query[endOfParameterValue - 1] == '&') { - stringBuilder.Append("&"); + stringBuilder.Append('&'); } } } diff --git a/sdk/core/Azure.Core/src/Shared/Multipart/BufferedReadStream.cs b/sdk/core/Azure.Core/src/Shared/Multipart/BufferedReadStream.cs index e01da8bee65cb..59d603a6f5ebd 100644 --- a/sdk/core/Azure.Core/src/Shared/Multipart/BufferedReadStream.cs +++ b/sdk/core/Azure.Core/src/Shared/Multipart/BufferedReadStream.cs @@ -31,8 +31,8 @@ internal class BufferedReadStream : Stream private readonly Stream _inner; private readonly byte[] _buffer; private readonly ArrayPool _bytePool; - private int _bufferOffset = 0; - private int _bufferCount = 0; + private int _bufferOffset; + private int _bufferCount; private bool _disposed; /// @@ -172,6 +172,8 @@ public override void SetLength(long value) /// protected override void Dispose(bool disposing) { + base.Dispose(disposing); + if (!_disposed) { _disposed = true; diff --git a/sdk/core/Azure.Core/src/Shared/Multipart/MemoryResponse.cs b/sdk/core/Azure.Core/src/Shared/Multipart/MemoryResponse.cs index b63f440ece2e8..7179356a4ead9 100644 --- a/sdk/core/Azure.Core/src/Shared/Multipart/MemoryResponse.cs +++ b/sdk/core/Azure.Core/src/Shared/Multipart/MemoryResponse.cs @@ -28,7 +28,7 @@ internal class MemoryResponse : Response /// /// The Response . /// - private string _reasonPhrase = null; + private string _reasonPhrase; /// /// The . diff --git a/sdk/core/Azure.Core/src/Shared/RequestRequestContent.cs b/sdk/core/Azure.Core/src/Shared/RequestRequestContent.cs index 5ab190bd68468..bdff96d4c9b1f 100644 --- a/sdk/core/Azure.Core/src/Shared/RequestRequestContent.cs +++ b/sdk/core/Azure.Core/src/Shared/RequestRequestContent.cs @@ -60,7 +60,7 @@ public override async Task WriteToAsync(Stream stream, CancellationToken cancell Argument.AssertNotNull(stream, nameof(stream)); byte[] header = SerializeHeader(); - await stream.WriteAsync(header, 0, header.Length).ConfigureAwait(false); + await stream.WriteAsync(header, 0, header.Length, cancellationToken).ConfigureAwait(false); if (_request.Content != null) { diff --git a/sdk/core/Azure.Core/src/Shared/RetriableStream.cs b/sdk/core/Azure.Core/src/Shared/RetriableStream.cs index 925fe8184352d..ae015290eb558 100644 --- a/sdk/core/Azure.Core/src/Shared/RetriableStream.cs +++ b/sdk/core/Azure.Core/src/Shared/RetriableStream.cs @@ -152,7 +152,7 @@ public override int Read(byte[] buffer, int offset, int count) } public override bool CanRead => _currentStream.CanRead; - public override bool CanSeek { get; } = false; + public override bool CanSeek { get; } public override long Length { get diff --git a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/DigitalTwinModelsRestClient.cs b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/DigitalTwinModelsRestClient.cs index 563e8af2f4bac..69af707455d29 100644 --- a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/DigitalTwinModelsRestClient.cs +++ b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/DigitalTwinModelsRestClient.cs @@ -219,7 +219,7 @@ private HttpMessage CreateUpdateRequest(string id, IEnumerable modelUpda // As such, these methods are declared here and made private, while the public method is declared above, too. // These methods should never be called. -#pragma warning disable CA1801, IDE0051, IDE0060 // Remove unused parameter +#pragma warning disable CA1801, IDE0051, IDE0060, CA1822 // Remove unused parameter // Original return type is Task>>. Changing to object to allow returning null. private object AddAsync(IEnumerable models = null, CancellationToken cancellationToken = default) => null; diff --git a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/DigitalTwinsRestClient.cs b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/DigitalTwinsRestClient.cs index 38747df7ab62f..1722cf40477de 100644 --- a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/DigitalTwinsRestClient.cs +++ b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/DigitalTwinsRestClient.cs @@ -945,7 +945,7 @@ private HttpMessage CreateSendComponentTelemetryRequest( // As such, these methods are declared here and made private, while the public method is declared above, too. // These methods should never be called. -#pragma warning disable CA1801, IDE0051, IDE0060 // Remove unused parameter +#pragma warning disable CA1801, IDE0051, IDE0060, CA1822 // Remove unused parameter // Original return type is Task>. Changing to object to allow returning null. private object AddAsync(string id, object twin, CreateOrReplaceDigitalTwinOptions digitalTwinsAddOptions = null, CancellationToken cancellationToken = default) => null; diff --git a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/Models/GetModelsOptions.cs b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/Models/GetModelsOptions.cs index 4b9afdcb06bc2..5452d7bb88cb3 100644 --- a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/Models/GetModelsOptions.cs +++ b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/Models/GetModelsOptions.cs @@ -23,7 +23,7 @@ public partial class GetModelsOptions /// /// Whether to include the model definition in the result. If false, only the model metadata will be returned. /// - public bool IncludeModelDefinition { get; set; } = false; + public bool IncludeModelDefinition { get; set; } // This class contains two properties (TraceParent ,TraceState, MaxItemsPerPage) that are not intended to be used by the Track 2 SDKs. // Marking these properties as internal. diff --git a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/QueryRestClient.cs b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/QueryRestClient.cs index f6188ebdbd381..d7f30515b2ef8 100644 --- a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/QueryRestClient.cs +++ b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Customized/QueryRestClient.cs @@ -82,7 +82,7 @@ internal ResponseWithHeaders, QueryQueryTwinsHeaders> QueryTwins< // For methods that we need to override, when the parameter list is the same, autorest knows not to generate them again. // These methods should never be called. -#pragma warning disable CA1801, IDE0051, IDE0060 // Remove unused parameter +#pragma warning disable CA1801, IDE0051, IDE0060, CA1822 // Remove unused parameter private Task> QueryTwinsAsync(QuerySpecification querySpecification, QueryOptions queryTwinsOptions = null, CancellationToken cancellationToken = default) => null; diff --git a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicDigitalTwin.cs b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicDigitalTwin.cs index 77c3a2deb9ccc..39fe8e42ec63e 100644 --- a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicDigitalTwin.cs +++ b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicDigitalTwin.cs @@ -99,7 +99,9 @@ public class BasicDigitalTwin /// /// This field will contain properties and components as defined in the contents section of the DTDL definition of the twin. /// +#pragma warning disable CA2227 // Collection properties should be readonly [JsonExtensionData] public IDictionary Contents { get; set; } = new Dictionary(); +#pragma warning restore CA2227 // Collection properties should be readonly } } diff --git a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicDigitalTwinComponent.cs b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicDigitalTwinComponent.cs index 3f2c5a6e9c2b0..93e6c3e1676a5 100644 --- a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicDigitalTwinComponent.cs +++ b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicDigitalTwinComponent.cs @@ -22,12 +22,16 @@ public class BasicDigitalTwinComponent /// The metadata property, required on a component to identify as one. /// [JsonPropertyName(DigitalTwinsJsonPropertyNames.DigitalTwinMetadata)] +#pragma warning disable CA2227 // Collection properties should be readonly public IDictionary Metadata { get; set; } = new Dictionary(); +#pragma warning restore CA2227 // Collection properties should be readonly /// /// This field will contain properties and components as defined in the contents section of the DTDL definition of the twin. /// [JsonExtensionData] +#pragma warning disable CA2227 // Collection properties should be readonly public IDictionary Contents { get; set; } = new Dictionary(); +#pragma warning restore CA2227 // Collection properties should be readonly } } diff --git a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicRelationship.cs b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicRelationship.cs index e4097ff49539e..1733c6defc5ed 100644 --- a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicRelationship.cs +++ b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/BasicRelationship.cs @@ -96,6 +96,8 @@ public class BasicRelationship /// This property will contain any relationship properties that are not already defined in this class. /// [JsonExtensionData] +#pragma warning disable CA2227 // Collection properties should be readonly public IDictionary Properties { get; set; } = new Dictionary(); +#pragma warning restore CA2227 // Collection properties should be readonly } } diff --git a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/DigitalTwinMetadata.cs b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/DigitalTwinMetadata.cs index 3bbebd03b10da..aa6991ca1099c 100644 --- a/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/DigitalTwinMetadata.cs +++ b/sdk/digitaltwins/Azure.DigitalTwins.Core/src/Models/DigitalTwinMetadata.cs @@ -26,6 +26,8 @@ public class DigitalTwinMetadata /// This field will contain metadata about changes on properties on the digital twin. /// The key will be the property name, and the value is the metadata. /// +#pragma warning disable CA2227 // Collection properties should be readonly public IDictionary PropertyMetadata { get; set; } = new Dictionary(); +#pragma warning restore CA2227 // Collection properties should be readonly } } diff --git a/sdk/eventhub/Azure.Messaging.EventHubs.Processor/src/EventProcessorClientOptions.cs b/sdk/eventhub/Azure.Messaging.EventHubs.Processor/src/EventProcessorClientOptions.cs index c9b3ab1c4dd2a..8da27c0cec623 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs.Processor/src/EventProcessorClientOptions.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs.Processor/src/EventProcessorClientOptions.cs @@ -17,7 +17,7 @@ namespace Azure.Messaging.EventHubs public class EventProcessorClientOptions { /// The maximum amount of time to wait for an event to become available before emitting an null value. - private TimeSpan? _maximumWaitTime = null; + private TimeSpan? _maximumWaitTime; /// The event catch count to use when reading events. private int _cacheEventCount = 100; @@ -26,7 +26,7 @@ public class EventProcessorClientOptions private int _prefetchCount = 300; /// The prefetch size limit to use for the partition receiver. - private long? _prefetchSizeInBytes = default; + private long? _prefetchSizeInBytes; /// The desired amount of time to allow between load balancing verification attempts. private TimeSpan _loadBalancingUpdateInterval = TimeSpan.FromSeconds(10); diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpClient.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpClient.cs index d8fee6bf35638..4980496925345 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpClient.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpClient.cs @@ -35,7 +35,7 @@ internal class AmqpClient : TransportClient private static TimeSpan CredentialRefreshBuffer { get; } = TimeSpan.FromMinutes(5); /// Indicates whether or not this instance has been closed. - private volatile bool _closed = false; + private volatile bool _closed; /// The currently active token to use for authorization with the Event Hubs service. private AccessToken _accessToken; diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpConnectionScope.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpConnectionScope.cs index 0a08e061f4a15..6fa5746b7c4cc 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpConnectionScope.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpConnectionScope.cs @@ -46,7 +46,7 @@ internal class AmqpConnectionScope : IDisposable private const string PartitionProducerPathSuffixMask = "{0}/Partitions/{1}"; /// Indicates whether or not this instance has been disposed. - private volatile bool _disposed = false; + private volatile bool _disposed; /// /// The version of AMQP to use within the scope. diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpConsumer.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpConsumer.cs index 646af80c1c190..db4c02c78fc8c 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpConsumer.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpConsumer.cs @@ -33,7 +33,7 @@ internal class AmqpConsumer : TransportConsumer private static readonly IReadOnlyList EmptyEventSet = Array.Empty(); /// Indicates whether or not this instance has been closed. - private volatile bool _closed = false; + private volatile bool _closed; /// /// Indicates whether or not this consumer has been closed. diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpEventBatch.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpEventBatch.cs index bbc3b0d75f873..65294db7cda66 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpEventBatch.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpEventBatch.cs @@ -32,10 +32,10 @@ internal class AmqpEventBatch : TransportEventBatch private readonly long ReservedSize; /// A flag that indicates whether or not the instance has been disposed. - private volatile bool _disposed = false; + private volatile bool _disposed; /// The size of the batch, in bytes, as it will be sent via the AMQP transport. - private long _sizeBytes = 0; + private long _sizeBytes; /// /// The maximum size allowed for the batch, in bytes. This includes the events in the batch as diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpProducer.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpProducer.cs index 7977a183c13e1..058898aee8c96 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpProducer.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpProducer.cs @@ -28,10 +28,10 @@ namespace Azure.Messaging.EventHubs.Amqp internal class AmqpProducer : TransportProducer { /// Indicates whether or not this instance has been closed. - private volatile bool _closed = false; + private volatile bool _closed; /// The count of send operations performed by this instance; this is used to tag deliveries for the AMQP link. - private int _deliveryCount = 0; + private int _deliveryCount; /// /// Indicates whether or not this producer has been closed. diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Azure.Messaging.EventHubs.csproj b/sdk/eventhub/Azure.Messaging.EventHubs/src/Azure.Messaging.EventHubs.csproj index 34bee49629811..542ff2e242eef 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Azure.Messaging.EventHubs.csproj +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Azure.Messaging.EventHubs.csproj @@ -5,6 +5,10 @@ 5.2.0 Azure;Event Hubs;EventHubs;.NET;AMQP;IoT;$(PackageCommonTags) $(RequiredTargetFrameworks) + + + $(NoWarn);CA1816;CA2016 + diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Consumer/EventHubConsumerClient.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Consumer/EventHubConsumerClient.cs index 86bde84d9810c..fc86bc3d1146e 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Consumer/EventHubConsumerClient.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Consumer/EventHubConsumerClient.cs @@ -48,7 +48,7 @@ public class EventHubConsumerClient : IAsyncDisposable private readonly TimeSpan BackgroundPublishingWaitTime = TimeSpan.FromMilliseconds(250); /// Indicates whether or not this instance has been closed. - private volatile bool _closed = false; + private volatile bool _closed; /// /// The fully qualified Event Hubs namespace that the consumer is associated with. This is likely @@ -1060,7 +1060,7 @@ private Task StartBackgroundChannelPublishingAsync(TransportConsumer transportCo /// /// A bounded channel, configured for 1:many read/write usage. /// - private Channel CreateEventChannel(int capacity) => + private static Channel CreateEventChannel(int capacity) => Channel.CreateBounded(new BoundedChannelOptions(capacity) { FullMode = BoundedChannelFullMode.Wait, diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Consumer/ReadEventOptions.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Consumer/ReadEventOptions.cs index e12ad175f6035..daef96455a9f7 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Consumer/ReadEventOptions.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Consumer/ReadEventOptions.cs @@ -15,7 +15,7 @@ namespace Azure.Messaging.EventHubs.Consumer public class ReadEventOptions { /// The maximum amount of time to wait to for an event to be available before emitting an empty item; if null, empty items will not be emitted. - private TimeSpan? _maximumWaitTime = null; + private TimeSpan? _maximumWaitTime; /// The event catch count to use when reading events. private int _cacheEventCount = 100; @@ -24,7 +24,7 @@ public class ReadEventOptions private int _prefetchCount = 300; /// The prefetch size limit to use for the partition receiver. - private long? _prefetchSizeInBytes = default; + private long? _prefetchSizeInBytes; /// /// When populated, the owner level indicates that a reading is intended to be performed exclusively for events in the diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/EventHubConnectionOptions.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/EventHubConnectionOptions.cs index 6f0661ef604b3..d61e9faa1213c 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/EventHubConnectionOptions.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/EventHubConnectionOptions.cs @@ -31,7 +31,7 @@ public class EventHubConnectionOptions /// use, specifying a proxy is an invalid option. /// /// - public IWebProxy Proxy { get; set; } = null; + public IWebProxy Proxy { get; set; } /// /// Determines whether the specified is equal to this instance. diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/EventProcessorOptions.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/EventProcessorOptions.cs index 228434a7173c6..9f3f021b19a65 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/EventProcessorOptions.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/EventProcessorOptions.cs @@ -30,7 +30,7 @@ public class EventProcessorOptions private int _prefetchCount = 300; /// The prefetch size limit to use for the partition receiver. - private long? _prefetchSizeInBytes = default; + private long? _prefetchSizeInBytes; /// The desired amount of time to allow between load balancing verification attempts. private TimeSpan _loadBalancingUpdateInterval = TimeSpan.FromSeconds(10); diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/PartitionReceiver.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/PartitionReceiver.cs index 5ff839d7e5a8a..001f4e84b121d 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/PartitionReceiver.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/PartitionReceiver.cs @@ -39,7 +39,7 @@ namespace Azure.Messaging.EventHubs.Primitives public class PartitionReceiver : IAsyncDisposable { /// Indicates whether or not this instance has been closed. - private volatile bool _closed = false; + private volatile bool _closed; /// /// The fully qualified Event Hubs namespace that the client is associated with. This is likely diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/PartitionReceiverOptions.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/PartitionReceiverOptions.cs index 479136e29ea4d..c36d134bcdf7c 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/PartitionReceiverOptions.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Primitives/PartitionReceiverOptions.cs @@ -28,7 +28,7 @@ public class PartitionReceiverOptions private int _prefetchCount = 300; /// The prefetch size limit to use for the partition receiver. - private long? _prefetchSizeInBytes = default; + private long? _prefetchSizeInBytes; /// /// The options used for configuring the connection to the Event Hubs service. diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/CreateBatchOptions.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/CreateBatchOptions.cs index 703168c855bbf..c489a5eb53a50 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/CreateBatchOptions.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/CreateBatchOptions.cs @@ -14,7 +14,7 @@ namespace Azure.Messaging.EventHubs.Producer public class CreateBatchOptions : SendEventOptions { /// The requested maximum size to allow for the batch, in bytes. - private long? _maximumSizeInBytes = null; + private long? _maximumSizeInBytes; /// /// The maximum size to allow for a single batch of events, in bytes. diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/EventDataBatch.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/EventDataBatch.cs index 142b28fb4b718..f2b09cc39d1bb 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/EventDataBatch.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/EventDataBatch.cs @@ -27,7 +27,7 @@ public sealed class EventDataBatch : IDisposable private readonly object SyncGuard = new object(); /// A flag indicating that the batch is locked, such as when in use during a publish operation. - private bool _locked = false; + private bool _locked; /// /// The maximum size allowed for the batch, in bytes. This includes the events in the batch as diff --git a/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/EventHubProducerClient.cs b/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/EventHubProducerClient.cs index adf82fbe5d7ee..20f6357b34f21 100644 --- a/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/EventHubProducerClient.cs +++ b/sdk/eventhub/Azure.Messaging.EventHubs/src/Producer/EventHubProducerClient.cs @@ -61,7 +61,7 @@ public class EventHubProducerClient : IAsyncDisposable private static readonly TimeSpan PartitionProducerLifespan = TimeSpan.FromMinutes(5); /// Indicates whether or not this instance has been closed. - private volatile bool _closed = false; + private volatile bool _closed; /// /// The fully qualified Event Hubs namespace that the producer is associated with. This is likely diff --git a/sdk/eventhub/Microsoft.Azure.WebJobs.Extensions.EventHubs/src/Listeners/EventHubListener.cs b/sdk/eventhub/Microsoft.Azure.WebJobs.Extensions.EventHubs/src/Listeners/EventHubListener.cs index f32192bc0639f..06b485471cbd1 100644 --- a/sdk/eventhub/Microsoft.Azure.WebJobs.Extensions.EventHubs/src/Listeners/EventHubListener.cs +++ b/sdk/eventhub/Microsoft.Azure.WebJobs.Extensions.EventHubs/src/Listeners/EventHubListener.cs @@ -118,8 +118,8 @@ internal class EventProcessor : IEventProcessor, IDisposable, ICheckpointer private readonly CancellationTokenSource _cts = new CancellationTokenSource(); private readonly ICheckpointer _checkpointer; private readonly int _batchCheckpointFrequency; - private int _batchCounter = 0; - private bool _disposed = false; + private int _batchCounter; + private bool _disposed; public EventProcessor(EventHubOptions options, ITriggeredFunctionExecutor executor, ILogger logger, bool singleDispatch, ICheckpointer checkpointer = null) { @@ -275,7 +275,7 @@ async Task ICheckpointer.CheckpointAsync(ProcessorPartitionContext context) await context.CheckpointAsync().ConfigureAwait(false); } - private Dictionary GetLinksScope(EventData message) + private static Dictionary GetLinksScope(EventData message) { if (TryGetLinkedActivity(message, out var link)) { @@ -285,7 +285,7 @@ private Dictionary GetLinksScope(EventData message) return EmptyScope; } - private Dictionary GetLinksScope(EventData[] messages) + private static Dictionary GetLinksScope(EventData[] messages) { List links = null; @@ -325,7 +325,7 @@ private static bool TryGetLinkedActivity(EventData message, out Activity link) return false; } - private string GetOperationDetails(ProcessorPartitionContext context, string operation) + private static string GetOperationDetails(ProcessorPartitionContext context, string operation) { StringWriter sw = new StringWriter(); using (JsonTextWriter writer = new JsonTextWriter(sw) { Formatting = Formatting.None }) diff --git a/sdk/eventhub/Microsoft.Azure.WebJobs.Extensions.EventHubs/src/Processor/EventProcessorHost.cs b/sdk/eventhub/Microsoft.Azure.WebJobs.Extensions.EventHubs/src/Processor/EventProcessorHost.cs index 21a09057aa873..ef98095a1d858 100644 --- a/sdk/eventhub/Microsoft.Azure.WebJobs.Extensions.EventHubs/src/Processor/EventProcessorHost.cs +++ b/sdk/eventhub/Microsoft.Azure.WebJobs.Extensions.EventHubs/src/Processor/EventProcessorHost.cs @@ -271,7 +271,7 @@ internal virtual async Task CheckpointAsync(string partitionId, EventData checkp }; using MemoryStream legacyCheckpointStream = new MemoryStream(); - await JsonSerializer.SerializeAsync(legacyCheckpointStream, lease).ConfigureAwait(false); + await JsonSerializer.SerializeAsync(legacyCheckpointStream, lease, cancellationToken: cancellationToken).ConfigureAwait(false); string legacyCheckpointBlob = $"{LegacyCheckpointStorageBlobPrefix}{ConsumerGroup}/{partitionId}"; Dictionary legacyCheckpoitMetadata = new Dictionary() diff --git a/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/src/AzureKeyVaultConfigurationProvider.cs b/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/src/AzureKeyVaultConfigurationProvider.cs index 687c7b623f477..33f0eb13dd9c3 100644 --- a/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/src/AzureKeyVaultConfigurationProvider.cs +++ b/sdk/extensions/Azure.Extensions.AspNetCore.Configuration.Secrets/src/AzureKeyVaultConfigurationProvider.cs @@ -144,6 +144,7 @@ private void SetData(Dictionary loadedSecrets, bool fireTo public void Dispose() { _cancellationToken.Cancel(); + _cancellationToken.Dispose(); } private readonly struct LoadedSecret diff --git a/sdk/extensions/Azure.Extensions.AspNetCore.DataProtection.Blobs/src/AzureBlobXmlRepository.cs b/sdk/extensions/Azure.Extensions.AspNetCore.DataProtection.Blobs/src/AzureBlobXmlRepository.cs index 3f94b6fb9d470..6f464153ae4e0 100644 --- a/sdk/extensions/Azure.Extensions.AspNetCore.DataProtection.Blobs/src/AzureBlobXmlRepository.cs +++ b/sdk/extensions/Azure.Extensions.AspNetCore.DataProtection.Blobs/src/AzureBlobXmlRepository.cs @@ -71,7 +71,7 @@ public void StoreElement(XElement element, string friendlyName) Task.Run(() => StoreElementAsync(element)).GetAwaiter().GetResult(); } - private XDocument CreateDocumentFromBlob(byte[] blob) + private static XDocument CreateDocumentFromBlob(byte[] blob) { using (var memoryStream = new MemoryStream(blob)) { diff --git a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/ClientDiagnostics.cs b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/ClientDiagnostics.cs index 34e19e11a9db0..48681fc91ac2a 100644 --- a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/ClientDiagnostics.cs +++ b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/ClientDiagnostics.cs @@ -23,6 +23,7 @@ internal sealed partial class ClientDiagnostics /// The error message. /// The error code. /// Additional error details. +#pragma warning disable CA1822 // Member can be static partial void ExtractFailureContent( string? content, ref string? message, @@ -30,6 +31,7 @@ partial void ExtractFailureContent( #pragma warning disable CA1801 // Remove unused parameter ref IDictionary? additionalInfo) #pragma warning restore CA1801 // Remove unused parameter +#pragma warning restore CA1822 // Member can be static { if (!string.IsNullOrEmpty(content)) { diff --git a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/FormTrainingClient.cs b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/FormTrainingClient.cs index d5149a304926a..15773d9dac5a7 100644 --- a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/FormTrainingClient.cs +++ b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/FormTrainingClient.cs @@ -137,7 +137,7 @@ public virtual TrainingOperation StartTraining(Uri trainingFilesUri, bool useTra ModelName = modelName }; - ResponseWithHeaders response = ServiceClient.TrainCustomModelAsync(trainRequest); + ResponseWithHeaders response = ServiceClient.TrainCustomModelAsync(trainRequest, cancellationToken); return new TrainingOperation(response.Headers.Location, ServiceClient, Diagnostics); } catch (Exception e) @@ -179,7 +179,7 @@ public virtual async Task StartTrainingAsync(Uri trainingFile ModelName = modelName }; - ResponseWithHeaders response = await ServiceClient.TrainCustomModelAsyncAsync(trainRequest).ConfigureAwait(false); + ResponseWithHeaders response = await ServiceClient.TrainCustomModelAsyncAsync(trainRequest, cancellationToken).ConfigureAwait(false); return new TrainingOperation(response.Headers.Location, ServiceClient, Diagnostics); } catch (Exception e) @@ -220,7 +220,7 @@ public virtual TrainingOperation StartTraining(Uri trainingFilesUri, bool useTra UseLabelFile = useTrainingLabels }; - ResponseWithHeaders response = ServiceClient.TrainCustomModelAsync(trainRequest); + ResponseWithHeaders response = ServiceClient.TrainCustomModelAsync(trainRequest, cancellationToken); return new TrainingOperation(response.Headers.Location, ServiceClient, Diagnostics); } catch (Exception e) @@ -260,7 +260,7 @@ public virtual async Task StartTrainingAsync(Uri trainingFile UseLabelFile = useTrainingLabels }; - ResponseWithHeaders response = await ServiceClient.TrainCustomModelAsyncAsync(trainRequest).ConfigureAwait(false); + ResponseWithHeaders response = await ServiceClient.TrainCustomModelAsyncAsync(trainRequest, cancellationToken).ConfigureAwait(false); return new TrainingOperation(response.Headers.Location, ServiceClient, Diagnostics); } catch (Exception e) @@ -302,7 +302,7 @@ public virtual CreateComposedModelOperation StartCreateComposedModel(IEnumerable var composeRequest = new ComposeRequest(modelIdsGuid); composeRequest.ModelName = modelName; - ResponseWithHeaders response = ServiceClient.ComposeCustomModelsAsync(composeRequest); + ResponseWithHeaders response = ServiceClient.ComposeCustomModelsAsync(composeRequest, cancellationToken); return new CreateComposedModelOperation(response.Headers.Location, ServiceClient, Diagnostics); } catch (Exception e) @@ -340,7 +340,7 @@ public virtual async Task StartCreateComposedModel var composeRequest = new ComposeRequest(modelIdsGuid); composeRequest.ModelName = modelName; - ResponseWithHeaders response = await ServiceClient.ComposeCustomModelsAsyncAsync(composeRequest).ConfigureAwait(false); + ResponseWithHeaders response = await ServiceClient.ComposeCustomModelsAsyncAsync(composeRequest, cancellationToken).ConfigureAwait(false); return new CreateComposedModelOperation(response.Headers.Location, ServiceClient, Diagnostics); } catch (Exception e) diff --git a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeBusinessCardsOptions.cs b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeBusinessCardsOptions.cs index 0442f7cca54df..07b2bd2d4c158 100644 --- a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeBusinessCardsOptions.cs +++ b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeBusinessCardsOptions.cs @@ -19,13 +19,13 @@ public RecognizeBusinessCardsOptions() /// /// Whether or not to include form elements such as lines and words in addition to form fields. /// - public bool IncludeFieldElements { get; set; } = false; + public bool IncludeFieldElements { get; set; } /// /// When set, specifies the content type for uploaded streams and skips automatic /// content type detection. /// - public FormContentType? ContentType { get; set; } = null; + public FormContentType? ContentType { get; set; } /// /// Locale value. Supported locales include: en-AU, en-CA, en-GB, en-IN, en-US. diff --git a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeContentOptions.cs b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeContentOptions.cs index 2b44728da3869..d4ee72687d075 100644 --- a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeContentOptions.cs +++ b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeContentOptions.cs @@ -22,7 +22,7 @@ public RecognizeContentOptions() /// When set, specifies the content type for uploaded streams and skips automatic /// content type detection. /// - public FormContentType? ContentType { get; set; } = null; + public FormContentType? ContentType { get; set; } /// /// The BCP-47 language code of the text in the document. diff --git a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeCustomFormsOptions.cs b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeCustomFormsOptions.cs index 8fbd24a0595b7..14be8cce7be21 100644 --- a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeCustomFormsOptions.cs +++ b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeCustomFormsOptions.cs @@ -19,12 +19,12 @@ public RecognizeCustomFormsOptions() /// /// Whether or not to include form elements such as lines and words in addition to form fields. /// - public bool IncludeFieldElements { get; set; } = false; + public bool IncludeFieldElements { get; set; } /// /// When set, specifies the content type for uploaded streams and skips automatic /// content type detection. /// - public FormContentType? ContentType { get; set; } = null; + public FormContentType? ContentType { get; set; } } } diff --git a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeInvoicesOptions.cs b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeInvoicesOptions.cs index 5632bfb89bd80..2f3e610d14f5f 100644 --- a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeInvoicesOptions.cs +++ b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeInvoicesOptions.cs @@ -19,13 +19,13 @@ public RecognizeInvoicesOptions() /// /// Whether or not to include form elements such as lines and words in addition to form fields. /// - public bool IncludeFieldElements { get; set; } = false; + public bool IncludeFieldElements { get; set; } /// /// When set, specifies the content type for uploaded streams and skips automatic /// content type detection. /// - public FormContentType? ContentType { get; set; } = null; + public FormContentType? ContentType { get; set; } /// /// Locale value. Supported locales include: en-US. diff --git a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeReceiptsOptions.cs b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeReceiptsOptions.cs index e4655433357b8..3b455fc187686 100644 --- a/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeReceiptsOptions.cs +++ b/sdk/formrecognizer/Azure.AI.FormRecognizer/src/RecognizeReceiptsOptions.cs @@ -19,13 +19,13 @@ public RecognizeReceiptsOptions() /// /// Whether or not to include form elements such as lines and words in addition to form fields. /// - public bool IncludeFieldElements { get; set; } = false; + public bool IncludeFieldElements { get; set; } /// /// When set, specifies the content type for uploaded streams and skips automatic /// content type detection. /// - public FormContentType? ContentType { get; set; } = null; + public FormContentType? ContentType { get; set; } /// /// Locale value. Supported locales include: en-AU, en-CA, en-GB, en-IN, en-US. diff --git a/sdk/identity/Azure.Identity/src/AsyncLockWithValue.cs b/sdk/identity/Azure.Identity/src/AsyncLockWithValue.cs index 3704fc7005aa0..77b7d5d0a98df 100644 --- a/sdk/identity/Azure.Identity/src/AsyncLockWithValue.cs +++ b/sdk/identity/Azure.Identity/src/AsyncLockWithValue.cs @@ -76,7 +76,7 @@ public async ValueTask GetLockOrValueAsync(bool async, CancellationToken c { // Throw OperationCanceledException only if another thread hasn't set a value to this waiter // by calling either Reset or SetValue - if (valueTcs.TrySetCanceled()) + if (valueTcs.TrySetCanceled(cancellationToken)) { throw; } diff --git a/sdk/identity/Azure.Identity/src/DefaultAzureCredentialOptions.cs b/sdk/identity/Azure.Identity/src/DefaultAzureCredentialOptions.cs index 22d7937d7a84b..9007c10cae309 100644 --- a/sdk/identity/Azure.Identity/src/DefaultAzureCredentialOptions.cs +++ b/sdk/identity/Azure.Identity/src/DefaultAzureCredentialOptions.cs @@ -60,19 +60,19 @@ public class DefaultAzureCredentialOptions : TokenCredentialOptions /// Specifies whether the will be excluded from the authentication flow. Setting to true disables reading /// authentication details from the process' environment variables. /// - public bool ExcludeEnvironmentCredential { get; set; } = false; + public bool ExcludeEnvironmentCredential { get; set; } /// /// Specifies whether the will be excluded from the authentication flow. /// Setting to true disables authenticating with managed identity endpoints. /// - public bool ExcludeManagedIdentityCredential { get; set; } = false; + public bool ExcludeManagedIdentityCredential { get; set; } /// /// Specifies whether the will be excluded from the authentication flow. /// Setting to true disables single sign on authentication with development tools which write to the shared token cache. /// - public bool ExcludeSharedTokenCacheCredential { get; set; } = false; + public bool ExcludeSharedTokenCacheCredential { get; set; } /// /// Specifies whether the will be excluded from the authentication flow. @@ -83,17 +83,17 @@ public class DefaultAzureCredentialOptions : TokenCredentialOptions /// /// Specifies whether the will be excluded from the authentication flow. /// - public bool ExcludeAzureCliCredential { get; set; } = false; + public bool ExcludeAzureCliCredential { get; set; } /// /// Specifies whether the will be excluded from the authentication flow. /// - public bool ExcludeVisualStudioCredential { get; set; } = false; + public bool ExcludeVisualStudioCredential { get; set; } /// /// Specifies whether the will be excluded from the authentication flow. /// - public bool ExcludeVisualStudioCodeCredential { get; set; } = false; + public bool ExcludeVisualStudioCodeCredential { get; set; } } } diff --git a/sdk/identity/Azure.Identity/src/DeviceCodeCredentialOptions.cs b/sdk/identity/Azure.Identity/src/DeviceCodeCredentialOptions.cs index 79eede0e9e333..50602a5f99223 100644 --- a/sdk/identity/Azure.Identity/src/DeviceCodeCredentialOptions.cs +++ b/sdk/identity/Azure.Identity/src/DeviceCodeCredentialOptions.cs @@ -12,7 +12,7 @@ namespace Azure.Identity /// public class DeviceCodeCredentialOptions : TokenCredentialOptions, ITokenCacheOptions { - private string _tenantId = null; + private string _tenantId; /// /// Prevents the from automatically prompting the user. If automatic authentication is disabled a AuthenticationRequiredException will be thrown from and in the case that diff --git a/sdk/identity/Azure.Identity/src/InteractiveBrowserCredentialOptions.cs b/sdk/identity/Azure.Identity/src/InteractiveBrowserCredentialOptions.cs index 00de1da5ce2c6..abbb1832bb5a0 100644 --- a/sdk/identity/Azure.Identity/src/InteractiveBrowserCredentialOptions.cs +++ b/sdk/identity/Azure.Identity/src/InteractiveBrowserCredentialOptions.cs @@ -11,7 +11,7 @@ namespace Azure.Identity /// public class InteractiveBrowserCredentialOptions : TokenCredentialOptions, ITokenCacheOptions { - private string _tenantId = null; + private string _tenantId; /// /// Prevents the from automatically prompting the user. If automatic authentication is disabled a AuthenticationRequiredException will be thrown from and in the case that diff --git a/sdk/identity/Azure.Identity/src/SharedTokenCacheCredentialOptions.cs b/sdk/identity/Azure.Identity/src/SharedTokenCacheCredentialOptions.cs index 2042afbaa7aab..b1dbd77bf19ce 100644 --- a/sdk/identity/Azure.Identity/src/SharedTokenCacheCredentialOptions.cs +++ b/sdk/identity/Azure.Identity/src/SharedTokenCacheCredentialOptions.cs @@ -8,7 +8,7 @@ namespace Azure.Identity /// public class SharedTokenCacheCredentialOptions : TokenCredentialOptions, ITokenCacheOptions { - private string _tenantId = null; + private string _tenantId; /// /// The client id of the application registration used to authenticate users in the cache. diff --git a/sdk/identity/Azure.Identity/src/VisualStudioCodeCredentialOptions.cs b/sdk/identity/Azure.Identity/src/VisualStudioCodeCredentialOptions.cs index ad7a680ae71b0..863ac65b77577 100644 --- a/sdk/identity/Azure.Identity/src/VisualStudioCodeCredentialOptions.cs +++ b/sdk/identity/Azure.Identity/src/VisualStudioCodeCredentialOptions.cs @@ -12,7 +12,7 @@ namespace Azure.Identity /// public class VisualStudioCodeCredentialOptions : TokenCredentialOptions { - private string _tenantId = null; + private string _tenantId; /// /// The tenant ID the user will be authenticated to. If not specified the user will be authenticated to the tenant the user originally authenticated to via the Visual Studio Code Azure Account plugin. diff --git a/sdk/identity/Azure.Identity/src/VisualStudioCredentialOptions.cs b/sdk/identity/Azure.Identity/src/VisualStudioCredentialOptions.cs index e0d01a91e0966..1cd789bb3d332 100644 --- a/sdk/identity/Azure.Identity/src/VisualStudioCredentialOptions.cs +++ b/sdk/identity/Azure.Identity/src/VisualStudioCredentialOptions.cs @@ -8,7 +8,7 @@ namespace Azure.Identity /// public class VisualStudioCredentialOptions : TokenCredentialOptions { - private string _tenantId = null; + private string _tenantId; /// /// The tenant ID the user will be authenticated to. If not specified the user will be authenticated to their home tenant. diff --git a/sdk/identity/Azure.Identity/src/WindowsNativeMethods.cs b/sdk/identity/Azure.Identity/src/WindowsNativeMethods.cs index 8fd589d7fa138..129119e3547fe 100644 --- a/sdk/identity/Azure.Identity/src/WindowsNativeMethods.cs +++ b/sdk/identity/Azure.Identity/src/WindowsNativeMethods.cs @@ -10,12 +10,14 @@ namespace Azure.Identity { internal static class WindowsNativeMethods { + #pragma warning disable CA1712 // Do not prefix enum members public enum CRED_PERSIST : uint { CRED_PERSIST_SESSION = 1, CRED_PERSIST_LOCAL_MACHINE = 2, CRED_PERSIST_ENTERPRISE = 3 } +#pragma warning restore CA1712 // Do not prefix enum members public enum CRED_TYPE { diff --git a/sdk/identity/Azure.Identity/tests/CredentialTestHelpers.cs b/sdk/identity/Azure.Identity/tests/CredentialTestHelpers.cs index edfd126e58965..253318ac0e845 100644 --- a/sdk/identity/Azure.Identity/tests/CredentialTestHelpers.cs +++ b/sdk/identity/Azure.Identity/tests/CredentialTestHelpers.cs @@ -84,7 +84,7 @@ public static TestFileSystemService CreateFileSystemForVisualStudioCode(Identity if (testEnvironment.TestTenantId != default && cloudName != default) { - sb.Append(","); + sb.Append(','); } if (cloudName != default) @@ -92,7 +92,7 @@ public static TestFileSystemService CreateFileSystemForVisualStudioCode(Identity sb.AppendFormat("\"azure.cloud\": \"{0}\"", cloudName); } - sb.Append("}"); + sb.Append('}'); return new TestFileSystemService { diff --git a/sdk/iot/Azure.Iot.Hub.Service/src/JobsClient.cs b/sdk/iot/Azure.Iot.Hub.Service/src/JobsClient.cs index 9233278f5df38..ea5f5238d912c 100644 --- a/sdk/iot/Azure.Iot.Hub.Service/src/JobsClient.cs +++ b/sdk/iot/Azure.Iot.Hub.Service/src/JobsClient.cs @@ -203,7 +203,7 @@ public virtual Response CancelImportExportJob(string jobId, Cancellation { Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); - return _jobsRestClient.CancelImportExportJob(jobId); + return _jobsRestClient.CancelImportExportJob(jobId, cancellationToken); } /// @@ -216,7 +216,7 @@ public virtual Task> CancelImportExportJobAsync(string jobId, C { Argument.AssertNotNullOrEmpty(jobId, nameof(jobId)); - return _jobsRestClient.CancelImportExportJobAsync(jobId); + return _jobsRestClient.CancelImportExportJobAsync(jobId, cancellationToken); } } } diff --git a/sdk/iot/Azure.Iot.Hub.Service/src/StatisticsClient.cs b/sdk/iot/Azure.Iot.Hub.Service/src/StatisticsClient.cs index e582ac3d019d0..54de49966ec2d 100644 --- a/sdk/iot/Azure.Iot.Hub.Service/src/StatisticsClient.cs +++ b/sdk/iot/Azure.Iot.Hub.Service/src/StatisticsClient.cs @@ -13,7 +13,7 @@ namespace Azure.Iot.Hub.Service /// public class StatisticsClient { - private readonly StatisticsRestClient _statisticsRestClient = null; + private readonly StatisticsRestClient _statisticsRestClient; /// /// Initializes a new instance of StatisticsClient. diff --git a/sdk/keyvault/Azure.Security.KeyVault.Keys/src/Cryptography/SignatureAlgorithm.cs b/sdk/keyvault/Azure.Security.KeyVault.Keys/src/Cryptography/SignatureAlgorithm.cs index 9d5586ec5f66b..bfb3191c847c0 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Keys/src/Cryptography/SignatureAlgorithm.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Keys/src/Cryptography/SignatureAlgorithm.cs @@ -187,7 +187,7 @@ internal KeyCurveName GetEcKeyCurveName() return KeyCurveName.P521; default: - return KeyCurveName.s_default; + return default; } } diff --git a/sdk/keyvault/Azure.Security.KeyVault.Keys/src/KeyCurveName.cs b/sdk/keyvault/Azure.Security.KeyVault.Keys/src/KeyCurveName.cs index eba98ee42029a..adc2805fe2864 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Keys/src/KeyCurveName.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Keys/src/KeyCurveName.cs @@ -57,8 +57,6 @@ public KeyCurveName(string value) /// public static KeyCurveName P521 { get; } = new KeyCurveName(P521Value); - internal static readonly KeyCurveName s_default = default; - /// /// Determines if two values are the same. /// @@ -144,7 +142,7 @@ internal static KeyCurveName FromOid(Oid oid, int keySize = 0) } } - return s_default; + return default; } internal bool IsSupported diff --git a/sdk/keyvault/Azure.Security.KeyVault.Shared/src/ChallengeBasedAuthenticationPolicy.cs b/sdk/keyvault/Azure.Security.KeyVault.Shared/src/ChallengeBasedAuthenticationPolicy.cs index 3f1ea500131de..60cd4d67f90a4 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Shared/src/ChallengeBasedAuthenticationPolicy.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Shared/src/ChallengeBasedAuthenticationPolicy.cs @@ -16,7 +16,7 @@ internal class ChallengeBasedAuthenticationPolicy : HttpPipelinePolicy private readonly TokenCredential _credential; - private AuthenticationChallenge _challenge = null; + private AuthenticationChallenge _challenge; private string _headerValue; private DateTimeOffset _refreshOn; diff --git a/sdk/keyvault/Azure.Security.KeyVault.Shared/src/ClientDiagnostics.cs b/sdk/keyvault/Azure.Security.KeyVault.Shared/src/ClientDiagnostics.cs index 2b1907fa26258..2ab1a5d65efca 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Shared/src/ClientDiagnostics.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Shared/src/ClientDiagnostics.cs @@ -10,13 +10,15 @@ namespace Azure.Core.Pipeline { internal partial class ClientDiagnostics { +#pragma warning disable CA1822 // Member can be static partial void ExtractFailureContent( string? content, ref string? message, ref string? errorCode, -#pragma warning disable CA1801 // additionalInfo is not used at this time +#pragma warning disable CA1801 // Remove unused parameter ref IDictionary? additionalInfo) -#pragma warning restore CA1801 +#pragma warning restore CA1801 // Remove unused parameter +#pragma warning restore CA1822 // Member can be static { if (!string.IsNullOrEmpty(content)) { diff --git a/sdk/keyvault/Azure.Security.KeyVault.Shared/src/KeyVaultPipeline.cs b/sdk/keyvault/Azure.Security.KeyVault.Shared/src/KeyVaultPipeline.cs index 567d634a446df..0b6f6e0e6e065 100644 --- a/sdk/keyvault/Azure.Security.KeyVault.Shared/src/KeyVaultPipeline.cs +++ b/sdk/keyvault/Azure.Security.KeyVault.Shared/src/KeyVaultPipeline.cs @@ -91,12 +91,14 @@ public Request CreateRequest(RequestMethod method, params string[] path) return request; } +#pragma warning disable CA1822 // Member can be static public Response CreateResponse(Response response, T result) where T : IJsonDeserializable { result.Deserialize(response.ContentStream); return Response.FromValue(result, response); } +#pragma warning restore CA1822 // Member can be static public DiagnosticScope CreateScope(string name) { diff --git a/sdk/keyvault/samples/keyvaultproxy/src/KeyVaultProxy.cs b/sdk/keyvault/samples/keyvaultproxy/src/KeyVaultProxy.cs index ddb19ccead5e3..ff14a9524c7a7 100644 --- a/sdk/keyvault/samples/keyvaultproxy/src/KeyVaultProxy.cs +++ b/sdk/keyvault/samples/keyvaultproxy/src/KeyVaultProxy.cs @@ -45,7 +45,7 @@ public KeyVaultProxy(TimeSpan? ttl = null) /// public override void Process(HttpMessage message, ReadOnlyMemory pipeline) => #pragma warning disable AZC0102 // TaskExtensions.EnsureCompleted() is not in scope - ProcessAsync(false, message, pipeline).GetAwaiter().GetResult(); + ProcessAsync(false, message, pipeline).AsTask().GetAwaiter().GetResult(); #pragma warning restore AZC0102 /// diff --git a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetAnomaliesForDetectionConfigurationFilter.cs b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetAnomaliesForDetectionConfigurationFilter.cs index 22d89c12784cd..a3e113ba56cba 100644 --- a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetAnomaliesForDetectionConfigurationFilter.cs +++ b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetAnomaliesForDetectionConfigurationFilter.cs @@ -42,6 +42,7 @@ public GetAnomaliesForDetectionConfigurationFilter(AnomalySeverity minimumSeveri /// be returned. /// /// The value assigned to is null. +#pragma warning disable CA2227 // Collection properties should be readonly public IList SeriesGroupKeys { get => _seriesGroupKeys; @@ -51,6 +52,7 @@ public IList SeriesGroupKeys _seriesGroupKeys = value; } } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// The minimum severity level an anomaly must have to be returned. diff --git a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetIncidentsForDetectionConfigurationOptions.cs b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetIncidentsForDetectionConfigurationOptions.cs index c6a5085955da3..051035e4458c3 100644 --- a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetIncidentsForDetectionConfigurationOptions.cs +++ b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetIncidentsForDetectionConfigurationOptions.cs @@ -44,6 +44,7 @@ public GetIncidentsForDetectionConfigurationOptions(DateTimeOffset startTime, Da /// Filters the result by series. Only incidents detected in the time series groups specified will /// be returned. /// +#pragma warning disable CA2227 // Collection properties should be readonly public IList DimensionsToFilter { get => _dimensionsToFilter; @@ -53,6 +54,7 @@ public IList DimensionsToFilter _dimensionsToFilter = value; } } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// If set, skips the first set of items returned. This property specifies the amount of items to diff --git a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetMetricSeriesDefinitionsOptions.cs b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetMetricSeriesDefinitionsOptions.cs index 9560faf7451c1..26113b51bb9b9 100644 --- a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetMetricSeriesDefinitionsOptions.cs +++ b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/GetMetricSeriesDefinitionsOptions.cs @@ -34,6 +34,7 @@ public GetMetricSeriesDefinitionsOptions(DateTimeOffset activeSince) /// Filters the result, mapping a dimension's name to a list of possible values it can assume. Only time series /// with the specified dimension values will be returned. /// +#pragma warning disable CA2227 // Collection properties should be readonly public IDictionary> DimensionCombinationsToFilter { get => _dimensionCombinationsToFilter; @@ -43,6 +44,7 @@ public IDictionary> DimensionCombinationsToFilter _dimensionCombinationsToFilter = value; } } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// If set, skips the first set of items returned. This property specifies the amount of items to diff --git a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/AnomalyDetection/AnomalyDetectionConfiguration.cs b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/AnomalyDetection/AnomalyDetectionConfiguration.cs index 15bd170da3975..5d5a0909d88ce 100644 --- a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/AnomalyDetection/AnomalyDetectionConfiguration.cs +++ b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/AnomalyDetection/AnomalyDetectionConfiguration.cs @@ -89,6 +89,7 @@ private set /// /// is null. [CodeGenMember("DimensionGroupOverrideConfigurations")] +#pragma warning disable CA2227 // Collection properties should be readonly public IList SeriesGroupDetectionConditions { get => _seriesGroupDetectionConditions; @@ -98,6 +99,7 @@ public IList SeriesGroupDetectionConditions _seriesGroupDetectionConditions = value; } } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// The anomaly detection conditions to be applied to the time series associated with this configuration's @@ -106,6 +108,7 @@ public IList SeriesGroupDetectionConditions /// /// is null. [CodeGenMember("SeriesOverrideConfigurations")] +#pragma warning disable CA2227 // Collection properties should be readonly public IList SeriesDetectionConditions { get => _seriesDetectionConditions; @@ -115,6 +118,7 @@ public IList SeriesDetectionConditions _seriesDetectionConditions = value; } } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// A description about the . diff --git a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeed.cs b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeed.cs index f6041acc3d4f4..1057a77f4cd2a 100644 --- a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeed.cs +++ b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeed.cs @@ -167,6 +167,7 @@ internal DataFeed(DataFeedDetail dataFeedDetail) /// credentials used to authenticate to the data source. /// /// The value assigned to is null. +#pragma warning disable CA2227 // Collection properties should be readonly public IList Administrators { get => _administrators; @@ -176,12 +177,14 @@ public IList Administrators _administrators = value; } } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// The emails of this data feed's viewers. Viewers have read-only access to a data feed, and /// do not have access to the credentials used to authenticate to the data source. /// /// The value assigned to is null. +#pragma warning disable CA2227 // Collection properties should be readonly public IList Viewers { get => _viewers; @@ -191,6 +194,7 @@ public IList Viewers _viewers = value; } } +#pragma warning restore CA2227 // Collection properties should be readonly internal DataFeedDetail GetDataFeedDetail() { diff --git a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeedRollupSettings.cs b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeedRollupSettings.cs index a0cecfc017b20..cfd915279eb15 100644 --- a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeedRollupSettings.cs +++ b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeedRollupSettings.cs @@ -52,6 +52,7 @@ internal DataFeedRollupSettings(DataFeedDetail dataFeedDetail) /// Defines the column names to which these will apply. /// /// is null. +#pragma warning disable CA2227 // Collection properties should be readonly public IList AutoRollupGroupByColumnNames { get => _autoRollupGroupByColumnNames; @@ -61,5 +62,6 @@ public IList AutoRollupGroupByColumnNames _autoRollupGroupByColumnNames = value; } } +#pragma warning restore CA2227 // Collection properties should be readonly } } diff --git a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeedSchema.cs b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeedSchema.cs index 47559b44e5293..74f30eed71422 100644 --- a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeedSchema.cs +++ b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/DataFeed/DataFeedSchema.cs @@ -48,6 +48,7 @@ internal DataFeedSchema(DataFeedDetail dataFeedDetail) /// monitored in search of anomalies. /// /// is null. +#pragma warning disable CA2227 // Collection properties should be readonly public IList DimensionColumns { get => _dimensionColumns; @@ -57,6 +58,7 @@ public IList DimensionColumns _dimensionColumns = value; } } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// The name of the data source's column with date or string values to be used as timestamp. diff --git a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/NotificationHook/WebNotificationHook.cs b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/NotificationHook/WebNotificationHook.cs index 240a936264d51..0c7f72eebe3a4 100644 --- a/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/NotificationHook/WebNotificationHook.cs +++ b/sdk/metricsadvisor/Azure.AI.MetricsAdvisor/src/Models/NotificationHook/WebNotificationHook.cs @@ -68,6 +68,7 @@ internal WebNotificationHook(HookType hookType, string id, string name, string d /// Custom headers to send in the API call. /// /// The value assigned to is null. +#pragma warning disable CA2227 // Collection properties should be readonly public IDictionary Headers { get => HookParameter.Headers; @@ -77,6 +78,7 @@ public IDictionary Headers HookParameter.Headers = value; } } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Used by CodeGen during serialization. diff --git a/sdk/monitor/Microsoft.OpenTelemetry.Exporter.AzureMonitor/src/Microsoft.OpenTelemetry.Exporter.AzureMonitor.csproj b/sdk/monitor/Microsoft.OpenTelemetry.Exporter.AzureMonitor/src/Microsoft.OpenTelemetry.Exporter.AzureMonitor.csproj index 0cad2488491f1..46cbbe7bd3d91 100644 --- a/sdk/monitor/Microsoft.OpenTelemetry.Exporter.AzureMonitor/src/Microsoft.OpenTelemetry.Exporter.AzureMonitor.csproj +++ b/sdk/monitor/Microsoft.OpenTelemetry.Exporter.AzureMonitor/src/Microsoft.OpenTelemetry.Exporter.AzureMonitor.csproj @@ -29,22 +29,9 @@ - - - ;NU5105; - CA1716; - CA1308; - CA1819; - CA1710; - CA1028; - CA1032; - CA1063; - CA1066; - CA1815; - CA2007; - CA2231; - CA2225; - CA1714; ;AZC0001;CA1812;CS0108;CA1812;CS1591; + + $(NoWarn);AZC0001;CS0108;CS1591 diff --git a/sdk/monitor/Microsoft.OpenTelemetry.Exporter.AzureMonitor/src/TelemetryPartA.cs b/sdk/monitor/Microsoft.OpenTelemetry.Exporter.AzureMonitor/src/TelemetryPartA.cs index 25b5c60f786d4..89caa1f46c695 100644 --- a/sdk/monitor/Microsoft.OpenTelemetry.Exporter.AzureMonitor/src/TelemetryPartA.cs +++ b/sdk/monitor/Microsoft.OpenTelemetry.Exporter.AzureMonitor/src/TelemetryPartA.cs @@ -23,9 +23,9 @@ internal class TelemetryPartA [TelemetryType.Event] = "Event", }; - internal static string RoleName { get; set; } = null; + internal static string RoleName { get; set; } - internal static string RoleInstance { get; set; } = null; + internal static string RoleInstance { get; set; } internal static TelemetryItem GetTelemetryItem(Activity activity, string instrumentationKey) { diff --git a/sdk/search/Azure.Search.Documents/src/Batching/ChannelExtensions.cs b/sdk/search/Azure.Search.Documents/src/Batching/ChannelExtensions.cs index 4f27b3a464d49..1a998867552cb 100644 --- a/sdk/search/Azure.Search.Documents/src/Batching/ChannelExtensions.cs +++ b/sdk/search/Azure.Search.Documents/src/Batching/ChannelExtensions.cs @@ -40,7 +40,7 @@ internal static async Task WriteInternal( if (!writer.TryWrite(item)) { #pragma warning disable AZC0102 // Do not use GetAwaiter().GetResult(). - writer.WriteAsync(item).AsTask().GetAwaiter().GetResult(); + writer.WriteAsync(item, cancellationToken).AsTask().GetAwaiter().GetResult(); #pragma warning restore AZC0102 // Do not use GetAwaiter().GetResult(). } } diff --git a/sdk/search/Azure.Search.Documents/src/Batching/ManualRetryDelay.cs b/sdk/search/Azure.Search.Documents/src/Batching/ManualRetryDelay.cs index 922c23a25b37d..01c663bc537b2 100644 --- a/sdk/search/Azure.Search.Documents/src/Batching/ManualRetryDelay.cs +++ b/sdk/search/Azure.Search.Documents/src/Batching/ManualRetryDelay.cs @@ -32,7 +32,7 @@ internal class ManualRetryDelay /// /// The number of recent attempts that have been throttled. /// - private int _throttledAttempts = 0; + private int _throttledAttempts; /// /// When we should wait until before sending our next request. diff --git a/sdk/search/Azure.Search.Documents/src/Batching/Publisher{T}.cs b/sdk/search/Azure.Search.Documents/src/Batching/Publisher{T}.cs index ef7fd55cd1859..8f7e0fd794d2d 100644 --- a/sdk/search/Azure.Search.Documents/src/Batching/Publisher{T}.cs +++ b/sdk/search/Azure.Search.Documents/src/Batching/Publisher{T}.cs @@ -25,7 +25,7 @@ internal abstract partial class Publisher : IDisposable, IAsyncDisposable /// /// Flag indicating whether the publisher has been disposed. /// - private volatile int _disposed = 0; + private volatile int _disposed; /// /// Channel used to communicate between the sender and publisher. diff --git a/sdk/search/Azure.Search.Documents/src/Batching/SearchIndexingBufferedSenderOptions{T}.cs b/sdk/search/Azure.Search.Documents/src/Batching/SearchIndexingBufferedSenderOptions{T}.cs index 43495b98b94e1..fb6699d2d1074 100644 --- a/sdk/search/Azure.Search.Documents/src/Batching/SearchIndexingBufferedSenderOptions{T}.cs +++ b/sdk/search/Azure.Search.Documents/src/Batching/SearchIndexingBufferedSenderOptions{T}.cs @@ -45,7 +45,7 @@ public class SearchIndexingBufferedSenderOptions /// default value will be 512 if unset. The current service maximum is /// 32000. /// - public int? InitialBatchActionCount { get; set; } = null; + public int? InitialBatchActionCount { get; set; } internal const int DefaultInitialBatchActionCount = 512; /// diff --git a/sdk/search/Azure.Search.Documents/src/Batching/SearchIndexingBufferedSender{T}.cs b/sdk/search/Azure.Search.Documents/src/Batching/SearchIndexingBufferedSender{T}.cs index a0615f7e5fcd3..b14f95c2e881f 100644 --- a/sdk/search/Azure.Search.Documents/src/Batching/SearchIndexingBufferedSender{T}.cs +++ b/sdk/search/Azure.Search.Documents/src/Batching/SearchIndexingBufferedSender{T}.cs @@ -30,12 +30,14 @@ public class SearchIndexingBufferedSender : IDisposable, IAsyncDisposable /// /// Flag indicating whether the sender has been disposed. /// - private volatile int _disposed = 0; + private volatile int _disposed; /// /// The single publisher responsible for submitting requests. /// +#pragma warning disable CA2213 // Member should be disposed. Disposed in DisposeAsync private SearchIndexingPublisher _publisher; +#pragma warning restore CA2213 // Member should be disposed. Disposed in DisposeAsync /// /// Gets the used to send requests to the @@ -73,7 +75,7 @@ public class SearchIndexingBufferedSender : IDisposable, IAsyncDisposable /// Task used to minimize simultaneous requests for the key field /// accessor. /// - private Task _getKeyFieldAccessorTask = null; + private Task _getKeyFieldAccessorTask; /// /// Async event raised whenever an indexing action is added to the @@ -150,8 +152,10 @@ void IDisposable.Dispose() => /// /// A task that will complete when the object has finished disposing. /// +#pragma warning disable CA1816 // Dispose methods should call SuppressFinalize async ValueTask IAsyncDisposable.DisposeAsync() => await DisposeAsync(async: true).ConfigureAwait(false); +#pragma warning restore CA1816 // Dispose methods should call SuppressFinalize /// /// Dispose the sender and flush any remaining indexing actions that diff --git a/sdk/search/Azure.Search.Documents/src/Indexes/Models/IndexingParameters.cs b/sdk/search/Azure.Search.Documents/src/Indexes/Models/IndexingParameters.cs index 3697f1f23a8d9..33378cd077ab8 100644 --- a/sdk/search/Azure.Search.Documents/src/Indexes/Models/IndexingParameters.cs +++ b/sdk/search/Azure.Search.Documents/src/Indexes/Models/IndexingParameters.cs @@ -34,12 +34,14 @@ public IndexingParameters() /// Indexer-specific configuration properties. /// Each value must be of a primitive type. /// +#pragma warning disable CA2227 // Collection properties should be readonly [CodeGenMember("Configuration")] public IndexingParametersConfiguration IndexingParametersConfiguration { get => _indexingParametersConfiguration; set => _indexingParametersConfiguration = value; } +#pragma warning restore CA2227 // Collection properties should be readonly private class ConfigurationAdapter : IDictionary { diff --git a/sdk/search/Azure.Search.Documents/src/Indexes/Models/SearchIndex.cs b/sdk/search/Azure.Search.Documents/src/Indexes/Models/SearchIndex.cs index d398193cf455d..f2391184cc1fd 100644 --- a/sdk/search/Azure.Search.Documents/src/Indexes/Models/SearchIndex.cs +++ b/sdk/search/Azure.Search.Documents/src/Indexes/Models/SearchIndex.cs @@ -128,6 +128,7 @@ public SearchIndex(string name, IEnumerable fields) /// }; /// /// +#pragma warning disable CA2227 // Collection properties should be readonly public IList Fields { get => _fields; @@ -136,6 +137,7 @@ public IList Fields _fields = value ?? throw new ArgumentNullException(nameof(value), $"{nameof(Fields)} cannot be null. To clear values, call {nameof(Fields.Clear)}."); } } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Gets the scoring profiles for the index. diff --git a/sdk/search/Azure.Search.Documents/src/Options/IndexDocumentsOptions.cs b/sdk/search/Azure.Search.Documents/src/Options/IndexDocumentsOptions.cs index 0a7b17cb24734..ea59ba5947f13 100644 --- a/sdk/search/Azure.Search.Documents/src/Options/IndexDocumentsOptions.cs +++ b/sdk/search/Azure.Search.Documents/src/Options/IndexDocumentsOptions.cs @@ -16,6 +16,6 @@ public class IndexDocumentsOptions /// Set this to true if you're not inspecting the results of the Index /// Documents action. /// - public bool ThrowOnAnyError { get; set; } = false; + public bool ThrowOnAnyError { get; set; } } } diff --git a/sdk/search/Azure.Search.Documents/src/SearchClient.cs b/sdk/search/Azure.Search.Documents/src/SearchClient.cs index 853037ea2d456..bd146f066f566 100644 --- a/sdk/search/Azure.Search.Documents/src/SearchClient.cs +++ b/sdk/search/Azure.Search.Documents/src/SearchClient.cs @@ -35,7 +35,7 @@ public class SearchClient /// The name of the Search Service, lazily obtained from the /// . /// - private string _serviceName = null; + private string _serviceName; /// /// Gets the name of the Search Service. diff --git a/sdk/search/Azure.Search.Documents/src/SearchDocument/SearchDocument.Core.cs b/sdk/search/Azure.Search.Documents/src/SearchDocument/SearchDocument.Core.cs index 470db60df0343..23d0b40f7b7e5 100644 --- a/sdk/search/Azure.Search.Documents/src/SearchDocument/SearchDocument.Core.cs +++ b/sdk/search/Azure.Search.Documents/src/SearchDocument/SearchDocument.Core.cs @@ -21,7 +21,7 @@ public partial class SearchDocument /// /// The document properties. /// - private readonly IDictionary _values = null; + private readonly IDictionary _values; /// /// Set a document property. diff --git a/sdk/search/Azure.Search.Documents/src/SearchFilter.cs b/sdk/search/Azure.Search.Documents/src/SearchFilter.cs index add66b9cad88b..bdcddc70fbbc2 100644 --- a/sdk/search/Azure.Search.Documents/src/SearchFilter.cs +++ b/sdk/search/Azure.Search.Documents/src/SearchFilter.cs @@ -112,7 +112,7 @@ private static string Quote(string text) // Optimistically allocate an extra 5% for escapes StringBuilder builder = new StringBuilder(2 + (int)(text.Length * 1.05)); - builder.Append("'"); + builder.Append('\''); foreach (char ch in text) { builder.Append(ch); @@ -121,7 +121,7 @@ private static string Quote(string text) builder.Append(ch); } } - builder.Append("'"); + builder.Append('\''); return builder.ToString(); } diff --git a/sdk/search/Azure.Search.Documents/src/Spatial/SpatialFormatter.cs b/sdk/search/Azure.Search.Documents/src/Spatial/SpatialFormatter.cs index c45ccba4f7b71..6142434187b83 100644 --- a/sdk/search/Azure.Search.Documents/src/Spatial/SpatialFormatter.cs +++ b/sdk/search/Azure.Search.Documents/src/Spatial/SpatialFormatter.cs @@ -34,7 +34,7 @@ public static string EncodePoint(double longitude, double latitude) return new StringBuilder(maxLength) .Append("geography'POINT(") .Append(JsonSerialization.Double(longitude, CultureInfo.InvariantCulture)) - .Append(" ") + .Append(' ') .Append(JsonSerialization.Double(latitude, CultureInfo.InvariantCulture)) .Append(")'") .ToString(); @@ -77,7 +77,7 @@ public static string EncodePolygon(GeoLine line) { if (!first) { - odata.Append(","); + odata.Append(','); } else { @@ -85,7 +85,7 @@ public static string EncodePolygon(GeoLine line) } odata.Append(JsonSerialization.Double(position.Longitude, CultureInfo.InvariantCulture)) - .Append(" ") + .Append(' ') .Append(JsonSerialization.Double(position.Latitude, CultureInfo.InvariantCulture)); } @@ -149,7 +149,7 @@ public static string EncodePolygon(GeographyLineStringProxy line) { if (!first) { - odata.Append(","); + odata.Append(','); } else { @@ -157,7 +157,7 @@ public static string EncodePolygon(GeographyLineStringProxy line) } odata.Append(JsonSerialization.Double(point.Longitude, CultureInfo.InvariantCulture)) - .Append(" ") + .Append(' ') .Append(JsonSerialization.Double(point.Latitude, CultureInfo.InvariantCulture)); } diff --git a/sdk/search/Azure.Search.Documents/src/Utilities/ClientDiagnostics.ExtractFailureContent.cs b/sdk/search/Azure.Search.Documents/src/Utilities/ClientDiagnostics.ExtractFailureContent.cs index 478b01e37078b..59c2218a80c70 100644 --- a/sdk/search/Azure.Search.Documents/src/Utilities/ClientDiagnostics.ExtractFailureContent.cs +++ b/sdk/search/Azure.Search.Documents/src/Utilities/ClientDiagnostics.ExtractFailureContent.cs @@ -25,13 +25,15 @@ internal sealed partial class ClientDiagnostics : DiagnosticScopeFactory /// The error message. /// The error code. /// Additional error details. +#pragma warning disable CA1822 // Member can be static partial void ExtractFailureContent( string? content, ref string? message, ref string? errorCode, - #pragma warning disable CA1801 // We're not using it now - but see the TODO below +#pragma warning disable CA1801 // Remove unused parameter ref IDictionary? additionalInfo) - #pragma warning restore CA1801 +#pragma warning restore CA1801 // Remove unused parameter +#pragma warning restore CA1822 // Member can be static { if (!string.IsNullOrEmpty(content)) { diff --git a/sdk/search/Azure.Search.Documents/src/Utilities/SearchExtensions.cs b/sdk/search/Azure.Search.Documents/src/Utilities/SearchExtensions.cs index 961fca207df55..97696b6c4c2cd 100644 --- a/sdk/search/Azure.Search.Documents/src/Utilities/SearchExtensions.cs +++ b/sdk/search/Azure.Search.Documents/src/Utilities/SearchExtensions.cs @@ -62,7 +62,7 @@ public static string GetSearchServiceName(this Uri endpoint) /// The items to join. /// The items joined together by commas. public static string CommaJoin(this IEnumerable items) => - items != null && items.Count() > 0 ? string.Join(",", items) : null; + items != null && items.Any() ? string.Join(",", items) : null; /// /// Split a collection of strings by commas. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/ClientDiagnostics.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/ClientDiagnostics.cs index 659510b17e7a2..6301e0728744f 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/ClientDiagnostics.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/ClientDiagnostics.cs @@ -12,6 +12,7 @@ namespace Azure.Core.Pipeline { internal sealed partial class ClientDiagnostics { +#pragma warning disable CA1822 // Member can be static partial void ExtractFailureContent( string? content, ref string? message, @@ -19,6 +20,7 @@ partial void ExtractFailureContent( #pragma warning disable CA1801 // Remove unused parameter ref IDictionary? additionalInfo) #pragma warning restore CA1801 // Remove unused parameter +#pragma warning restore CA1822 // Member can be static { if (string.IsNullOrWhiteSpace(content)) { diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateQueueOptions.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateQueueOptions.cs index bf73809b14c2a..82024276dbb06 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateQueueOptions.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateQueueOptions.cs @@ -17,9 +17,9 @@ public class CreateQueueOptions : IEquatable private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan autoDeleteOnIdle = TimeSpan.MaxValue; private int _maxDeliveryCount = 10; - private string _forwardTo = null; - private string _forwardDeadLetteredMessagesTo = null; - private string _userMetadata = null; + private string _forwardTo; + private string _forwardDeadLetteredMessagesTo; + private string _userMetadata; /// /// Initializes a new instance of with the specified relative name. @@ -103,7 +103,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. @@ -112,7 +112,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 @@ -160,7 +160,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 subqueue. Default value is false. - public bool DeadLetteringOnMessageExpiration { get; set; } = false; + public bool DeadLetteringOnMessageExpiration { get; set; } /// /// The duration of duplicate detection history that is maintained by the service. @@ -277,7 +277,7 @@ public string ForwardDeadLetteredMessagesTo /// Indicates whether the queue is to be partitioned across multiple message brokers. /// /// Defaults to false. - public bool EnablePartitioning { get; set; } = false; + public bool EnablePartitioning { get; set; } /// /// Custom metadata that user can associate with the queue. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateSubscriptionOptions.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateSubscriptionOptions.cs index 325a8c7769546..f6da1978d5b16 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateSubscriptionOptions.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateSubscriptionOptions.cs @@ -17,9 +17,9 @@ public class CreateSubscriptionOptions : IEquatable private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; private int _maxDeliveryCount = 10; - private string _forwardTo = null; - private string _forwardDeadLetteredMessagesTo = null; - private string _userMetadata = null; + private string _forwardTo; + private string _forwardDeadLetteredMessagesTo; + private string _userMetadata; /// /// Initializes a new instance of SubscriptionDescription class with the specified name and topic name. @@ -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 @@ -130,7 +130,7 @@ public TimeSpan AutoDeleteOnIdle /// Indicates whether this subscription has dead letter support when a message expires. /// /// If true, the expired messages are moved to dead-letter subqueue. Default value is false. - public bool DeadLetteringOnMessageExpiration { get; set; } = false; + public bool DeadLetteringOnMessageExpiration { get; set; } /// /// indicates whether messages need to be forwarded to dead-letter sub queue when subscription rule evaluation fails. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateTopicOptions.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateTopicOptions.cs index 4cd8a0c229f9e..f5bd63f0e7857 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateTopicOptions.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/CreateTopicOptions.cs @@ -15,7 +15,7 @@ public class CreateTopicOptions : IEquatable private string _name; private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; - private string _userMetadata = null; + private string _userMetadata; /// /// Initializes a new instance of with the specified relative name. @@ -105,7 +105,7 @@ public TimeSpan AutoDeleteOnIdle /// will be discarded. /// /// Defaults to false. - public bool RequiresDuplicateDetection { get; set; } = false; + public bool RequiresDuplicateDetection { get; set; } /// /// The duration of duplicate detection history that is maintained by the service. @@ -158,14 +158,14 @@ public string Name /// Indicates whether the topic is to be partitioned across multiple message brokers. /// /// Defaults to false. - public bool EnablePartitioning { get; set; } = false; + public bool EnablePartitioning { get; set; } /// /// Defines whether ordering needs to be maintained. If true, messages sent to topic will be /// forwarded to the subscription in order. /// /// Defaults to false. - public bool SupportOrdering { get; set; } = false; + public bool SupportOrdering { get; set; } /// /// Indicates whether server-side batched operations are enabled. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/QueueProperties.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/QueueProperties.cs index 1e723a51f6937..67812d5f7947d 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/QueueProperties.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/QueueProperties.cs @@ -19,9 +19,9 @@ public class QueueProperties : IEquatable private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; private int _maxDeliveryCount = 10; - private string _forwardTo = null; - private string _forwardDeadLetteredMessagesTo = null; - private string _userMetadata = null; + private string _forwardTo; + private string _forwardDeadLetteredMessagesTo; + private string _userMetadata; /// /// Initializes a new instance of QueueProperties class with the specified relative name. @@ -151,7 +151,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 subqueue. Default value is false. - public bool DeadLetteringOnMessageExpiration { get; set; } = false; + public bool DeadLetteringOnMessageExpiration { get; set; } /// /// The duration of duplicate detection history that is maintained by the service. @@ -289,7 +289,7 @@ public string UserMetadata } } - internal bool IsAnonymousAccessible { get; set; } = false; + internal bool IsAnonymousAccessible { get; set; } internal bool SupportOrdering { @@ -303,9 +303,9 @@ internal bool SupportOrdering } } - internal bool? _internalSupportOrdering = null; + internal bool? _internalSupportOrdering; - internal bool EnableExpress { get; set; } = false; + internal bool EnableExpress { get; set; } /// /// List of properties that were retrieved using GetQueue but are not understood by this version of client is stored here. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/SubscriptionProperties.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/SubscriptionProperties.cs index 8709381e613ae..b50963f870abe 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/SubscriptionProperties.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/SubscriptionProperties.cs @@ -18,9 +18,9 @@ public class SubscriptionProperties : IEquatable private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; private int _maxDeliveryCount = 10; - private string _forwardTo = null; - private string _forwardDeadLetteredMessagesTo = null; - private string _userMetadata = null; + private string _forwardTo; + private string _forwardDeadLetteredMessagesTo; + private string _userMetadata; /// /// Initializes a new instance of SubscriptionDescription class with the specified name and topic name. @@ -76,7 +76,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 @@ -124,7 +124,7 @@ public TimeSpan AutoDeleteOnIdle /// Indicates whether this subscription has dead letter support when a message expires. /// /// If true, the expired messages are moved to dead-letter subqueue. Default value is false. - public bool DeadLetteringOnMessageExpiration { get; set; } = false; + public bool DeadLetteringOnMessageExpiration { get; set; } /// /// indicates whether messages need to be forwarded to dead-letter sub queue when subscription rule evaluation fails. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/TopicProperties.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/TopicProperties.cs index fd5bc4b8d1fbb..225c5e45edd2d 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/TopicProperties.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Administration/TopicProperties.cs @@ -17,7 +17,7 @@ public class TopicProperties : IEquatable private string _name; private TimeSpan _defaultMessageTimeToLive = TimeSpan.MaxValue; private TimeSpan _autoDeleteOnIdle = TimeSpan.MaxValue; - private string _userMetadata = null; + private string _userMetadata; /// /// Initializes a new instance of TopicDescription class with the specified relative name. @@ -105,7 +105,7 @@ public TimeSpan AutoDeleteOnIdle /// will be discarded. /// /// Defaults to false. - public bool RequiresDuplicateDetection { get; set; } = false; + public bool RequiresDuplicateDetection { get; set; } /// /// The duration of duplicate detection history that is maintained by the service. @@ -158,14 +158,14 @@ public string Name /// Indicates whether the topic is to be partitioned across multiple message brokers. /// /// Defaults to false. - public bool EnablePartitioning { get; set; } = false; + public bool EnablePartitioning { get; set; } /// /// Defines whether ordering needs to be maintained. If true, messages sent to topic will be /// forwarded to the subscription in order. /// /// Defaults to false. - public bool SupportOrdering { get; set; } = false; + public bool SupportOrdering { get; set; } /// /// Indicates whether server-side batched operations are enabled. @@ -192,15 +192,15 @@ public string UserMetadata } } - internal bool IsAnonymousAccessible { get; set; } = false; + internal bool IsAnonymousAccessible { get; set; } - internal bool FilteringMessagesBeforePublishing { get; set; } = false; + internal bool FilteringMessagesBeforePublishing { get; set; } - internal string ForwardTo { get; set; } = null; + internal string ForwardTo { get; set; } - internal bool EnableExpress { get; set; } = false; + internal bool EnableExpress { get; set; } - internal bool EnableSubscriptionPartitioning { get; set; } = false; + internal bool EnableSubscriptionPartitioning { get; set; } /// diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpClient.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpClient.cs index 92e99acb6d557..c4aafcaaa28c8 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpClient.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpClient.cs @@ -28,7 +28,7 @@ internal class AmqpClient : TransportClient private static TimeSpan CredentialRefreshBuffer { get; } = TimeSpan.FromMinutes(5); /// Indicates whether or not this instance has been closed. - private bool _closed = false; + private bool _closed; /// The currently active token to use for authorization with the Service Bus service. private AccessToken _accessToken; diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpMessageBatch.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpMessageBatch.cs index 068cc1bb17172..2eeb1c9eda968 100755 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpMessageBatch.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpMessageBatch.cs @@ -31,10 +31,10 @@ internal class AmqpMessageBatch : TransportMessageBatch private readonly long _reservedSize; /// A flag that indicates whether or not the instance has been disposed. - private bool _disposed = false; + private bool _disposed; /// The size of the batch, in bytes, as it will be sent via the AMQP transport. - private long _sizeBytes = 0; + private long _sizeBytes; /// /// The maximum size allowed for the batch, in bytes. This includes the messages in the batch as diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpReceiver.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpReceiver.cs index 6bff6b6e6e2e4..d2291adaece9a 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpReceiver.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpReceiver.cs @@ -31,7 +31,7 @@ internal class AmqpReceiver : TransportReceiver #pragma warning restore CA1001 // Types that own disposable fields should be disposable { /// Indicates whether or not this instance has been closed. - private bool _closed = false; + private bool _closed; /// /// Indicates whether or not this receiver has been closed. @@ -649,7 +649,7 @@ internal virtual Task DeadLetterInternalAsync( timeout); } - private Rejected GetRejectedOutcome( + private static Rejected GetRejectedOutcome( IDictionary propertiesToModify, string deadLetterReason, string deadLetterErrorDescription) diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpRuleManager.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpRuleManager.cs index bc9c92fdad9fa..ca9001fdcf62c 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpRuleManager.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpRuleManager.cs @@ -43,7 +43,7 @@ internal class AmqpRuleManager : TransportRuleManager /// /// Indicates whether or not this instance has been closed. /// - private bool _closed = false; + private bool _closed; /// /// Indicates whether or not this rule manager has been closed. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpSender.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpSender.cs index 1b55b38f80b0b..23428f0f30b70 100755 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpSender.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Amqp/AmqpSender.cs @@ -31,10 +31,10 @@ internal class AmqpSender : TransportSender #pragma warning restore CA1001 // Types that own disposable fields should be disposable { /// Indicates whether or not this instance has been closed. - private bool _closed = false; + private bool _closed; /// The count of send operations performed by this instance; this is used to tag deliveries for the AMQP link. - private int _deliveryCount = 0; + private int _deliveryCount; /// /// Indicates whether or not this sender has been closed. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Azure.Messaging.ServiceBus.csproj b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Azure.Messaging.ServiceBus.csproj index 8dc622b53febc..2bc2c44dda9e5 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Azure.Messaging.ServiceBus.csproj +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Azure.Messaging.ServiceBus.csproj @@ -4,6 +4,10 @@ 7.0.0-preview.10 Azure;Service Bus;ServiceBus;.NET;AMQP;$(PackageCommonTags) $(RequiredTargetFrameworks) + + + $(NoWarn);CA1816;CA2016;CA2213 + diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Client/ServiceBusClient.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Client/ServiceBusClient.cs index 80fa8540c6be7..1614bd571e942 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Client/ServiceBusClient.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Client/ServiceBusClient.cs @@ -38,7 +38,7 @@ public class ServiceBusClient : IAsyncDisposable /// /// true if the client is closed; otherwise, false. /// - public bool IsClosed { get; private set; } = false; + public bool IsClosed { get; private set; } /// /// The transport type used for this . diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Client/ServiceBusClientOptions.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Client/ServiceBusClientOptions.cs index 57987d188747f..59a643f7a176f 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Client/ServiceBusClientOptions.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Client/ServiceBusClientOptions.cs @@ -35,7 +35,7 @@ public class ServiceBusClientOptions /// use, specifying a proxy is an invalid option. /// /// - public IWebProxy WebProxy { get; set; } = null; + public IWebProxy WebProxy { get; set; } /// /// The set of options to use for determining whether a failed operation should be retried and, diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusProcessor.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusProcessor.cs index 9070f059f95f4..5c6fa73ffb510 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusProcessor.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusProcessor.cs @@ -31,7 +31,7 @@ public class ServiceBusProcessor : IAsyncDisposable private Func _processSessionMessageAsync; - private Func _processErrorAsync = default; + private Func _processErrorAsync; private Func _sessionInitializingAsync; @@ -154,7 +154,7 @@ public bool IsClosed } /// Indicates whether or not this instance has been closed. - private volatile bool _closed = false; + private volatile bool _closed; private readonly string[] _sessionIds; private readonly EntityScopeFactory _scopeFactory; diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusProcessorOptions.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusProcessorOptions.cs index 7d50a7c0cab42..93931990d2d29 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusProcessorOptions.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusProcessorOptions.cs @@ -31,7 +31,7 @@ public int PrefetchCount _prefetchCount = value; } } - private int _prefetchCount = 0; + private int _prefetchCount; /// /// Gets or sets the used to specify how messages diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusSessionProcessorOptions.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusSessionProcessorOptions.cs index d67b450cf599a..cf2a4fd93ff9d 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusSessionProcessorOptions.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/ServiceBusSessionProcessorOptions.cs @@ -27,7 +27,7 @@ public int PrefetchCount _prefetchCount = value; } } - private int _prefetchCount = 0; + private int _prefetchCount; /// public ServiceBusReceiveMode ReceiveMode { get; set; } = ServiceBusReceiveMode.PeekLock; diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/SessionReceiverManager.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/SessionReceiverManager.cs index e668fa994592b..7791572c24710 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/SessionReceiverManager.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Processor/SessionReceiverManager.cs @@ -24,7 +24,7 @@ namespace Azure.Messaging.ServiceBus internal class SessionReceiverManager : ReceiverManager #pragma warning restore CA1001 // Types that own disposable fields should be disposable { - private int _threadCount = 0; + private int _threadCount; private readonly Func _sessionInitHandler; private readonly Func _sessionCloseHandler; private readonly Func _messageHandler; diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusReceiver.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusReceiver.cs index 7296484ccffa6..d6af4557afd43 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusReceiver.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusReceiver.cs @@ -73,7 +73,7 @@ public bool IsClosed } /// Indicates whether or not this instance has been closed. - private volatile bool _closed = false; + private volatile bool _closed; /// /// The policy to use for determining retry behavior for when an operation fails. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusReceiverOptions.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusReceiverOptions.cs index e4a664a38081f..57e6152eab5af 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusReceiverOptions.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusReceiverOptions.cs @@ -29,7 +29,7 @@ public int PrefetchCount _prefetchCount = value; } } - private int _prefetchCount = 0; + private int _prefetchCount; /// /// Gets or sets the used to specify how messages are received. Defaults to PeekLock mode. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusSessionReceiverOptions.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusSessionReceiverOptions.cs index c7917e49f3194..8a5308796aa8a 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusSessionReceiverOptions.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusSessionReceiverOptions.cs @@ -29,7 +29,7 @@ public int PrefetchCount _prefetchCount = value; } } - private int _prefetchCount = 0; + private int _prefetchCount; /// /// Gets or sets the used to specify how messages are received. Defaults to PeekLock mode. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/RuleManager/ServiceBusRuleManager.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/RuleManager/ServiceBusRuleManager.cs index 1e4c354a2bc33..23f6de7126048 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/RuleManager/ServiceBusRuleManager.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/RuleManager/ServiceBusRuleManager.cs @@ -37,7 +37,7 @@ internal class ServiceBusRuleManager : IAsyncDisposable /// /// true if the rule manager is disposed; otherwise, false. /// - public bool IsDisposed { get; private set; } = false; + public bool IsDisposed { get; private set; } /// /// The active connection to the Azure Service Bus service, enabling client communications for metadata diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/CreateMessageBatchOptions.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/CreateMessageBatchOptions.cs index 41d1871e9fe7a..6b3298b5f3efd 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/CreateMessageBatchOptions.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/CreateMessageBatchOptions.cs @@ -15,7 +15,7 @@ namespace Azure.Messaging.ServiceBus public class CreateMessageBatchOptions { /// The requested maximum size to allow for the batch, in bytes. - private long? _maxSizeInBytes = null; + private long? _maxSizeInBytes; /// /// The maximum size to allow for a single batch of messages, in bytes. diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/ServiceBusMessageBatch.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/ServiceBusMessageBatch.cs index 44631ebc0869e..30d35f6578de3 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/ServiceBusMessageBatch.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/ServiceBusMessageBatch.cs @@ -22,7 +22,7 @@ public sealed class ServiceBusMessageBatch : IDisposable private readonly object _syncGuard = new object(); /// A flag indicating that the batch is locked, such as when in use during a send batch operation. - private bool _locked = false; + private bool _locked; /// /// The maximum size allowed for the batch, in bytes. This includes the messages in the batch as diff --git a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/ServiceBusSender.cs b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/ServiceBusSender.cs index 38cc179700477..1b74fb68b803f 100644 --- a/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/ServiceBusSender.cs +++ b/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/ServiceBusSender.cs @@ -56,7 +56,7 @@ public bool IsClosed } /// Indicates whether or not this instance has been closed. - private volatile bool _closed = false; + private volatile bool _closed; /// /// The instance of which can be mocked for testing. diff --git a/sdk/storage/Azure.Storage.Blobs.Batch/src/BlobBatch.cs b/sdk/storage/Azure.Storage.Blobs.Batch/src/BlobBatch.cs index 251ceb80083da..d7ef3eece13d3 100644 --- a/sdk/storage/Azure.Storage.Blobs.Batch/src/BlobBatch.cs +++ b/sdk/storage/Azure.Storage.Blobs.Batch/src/BlobBatch.cs @@ -33,7 +33,7 @@ public class BlobBatch : IDisposable /// Storage requires each batch request to contain the same type of /// operation. /// - private BlobBatchOperationType? _operationType = null; + private BlobBatchOperationType? _operationType; /// /// The list of messages that will be sent as part of this batch. @@ -43,7 +43,7 @@ public class BlobBatch : IDisposable /// /// A value indicating whether the batch has already been submitted. /// - internal bool Submitted { get; private set; } = false; + internal bool Submitted { get; private set; } /// /// Creates a new instance of the for mocking. diff --git a/sdk/storage/Azure.Storage.Blobs.Batch/src/DelayedResponse.cs b/sdk/storage/Azure.Storage.Blobs.Batch/src/DelayedResponse.cs index 0d395df954522..86110cf99568a 100644 --- a/sdk/storage/Azure.Storage.Blobs.Batch/src/DelayedResponse.cs +++ b/sdk/storage/Azure.Storage.Blobs.Batch/src/DelayedResponse.cs @@ -29,7 +29,7 @@ internal class DelayedResponse : Response /// BlobRestClient.Group.OperationName_CreateResponse methods which /// correctly throw when necessary. /// - private readonly Func _processResponse = null; + private readonly Func _processResponse; /// /// Gets the live Response or throws an InvalidOperationException if diff --git a/sdk/storage/Azure.Storage.Blobs.Batch/src/MemoryResponse.cs b/sdk/storage/Azure.Storage.Blobs.Batch/src/MemoryResponse.cs index ac084d4771617..154fcb488074d 100644 --- a/sdk/storage/Azure.Storage.Blobs.Batch/src/MemoryResponse.cs +++ b/sdk/storage/Azure.Storage.Blobs.Batch/src/MemoryResponse.cs @@ -24,7 +24,7 @@ internal class MemoryResponse : Response /// /// The Response . /// - private string _reasonPhrase = null; + private string _reasonPhrase; /// /// The . diff --git a/sdk/storage/Azure.Storage.Blobs.Batch/src/Multipart.cs b/sdk/storage/Azure.Storage.Blobs.Batch/src/Multipart.cs index cf1db025b2938..1e83c22a850cd 100644 --- a/sdk/storage/Azure.Storage.Blobs.Batch/src/Multipart.cs +++ b/sdk/storage/Azure.Storage.Blobs.Batch/src/Multipart.cs @@ -87,9 +87,9 @@ internal static class Multipart // Write the request URI content .Append(message.Request.Method.Method) - .Append(" ") + .Append(' ') .Append(message.Request.Uri.PathAndQuery) - .Append(" ") + .Append(' ') .Append(BatchConstants.HttpVersion) .Append(newline); diff --git a/sdk/storage/Azure.Storage.Blobs.Batch/src/RemoveVersionHeaderPolicy.cs b/sdk/storage/Azure.Storage.Blobs.Batch/src/RemoveVersionHeaderPolicy.cs index e4dc841edb7e3..4deed1e59dcec 100644 --- a/sdk/storage/Azure.Storage.Blobs.Batch/src/RemoveVersionHeaderPolicy.cs +++ b/sdk/storage/Azure.Storage.Blobs.Batch/src/RemoveVersionHeaderPolicy.cs @@ -22,7 +22,7 @@ internal class RemoveVersionHeaderPolicy : HttpPipelineSynchronousPolicy /// recordings which need repeatable x-ms-client-request-id values in /// the sub-operations. /// - internal bool RemoveClientRequestIdHeaders { get; set; } = false; + internal bool RemoveClientRequestIdHeaders { get; set; } /// public override void OnSendingRequest(HttpMessage message) diff --git a/sdk/storage/Azure.Storage.Blobs.Batch/src/Shared/BufferedReadStream.cs b/sdk/storage/Azure.Storage.Blobs.Batch/src/Shared/BufferedReadStream.cs index cb74d59bdb6bf..bfdb52571aa11 100644 --- a/sdk/storage/Azure.Storage.Blobs.Batch/src/Shared/BufferedReadStream.cs +++ b/sdk/storage/Azure.Storage.Blobs.Batch/src/Shared/BufferedReadStream.cs @@ -31,8 +31,8 @@ internal class BufferedReadStream : Stream private readonly Stream _inner; private readonly byte[] _buffer; private readonly ArrayPool _bytePool; - private int _bufferOffset = 0; - private int _bufferCount = 0; + private int _bufferOffset; + private int _bufferCount; private bool _disposed; /// @@ -172,6 +172,7 @@ public override void SetLength(long value) /// protected override void Dispose(bool disposing) { + base.Dispose(disposing); if (!_disposed) { _disposed = true; diff --git a/sdk/storage/Azure.Storage.Blobs.ChangeFeed/src/LazyLoadingBlobStream.cs b/sdk/storage/Azure.Storage.Blobs.ChangeFeed/src/LazyLoadingBlobStream.cs index ab1374ffde742..2d4a79a72cec4 100644 --- a/sdk/storage/Azure.Storage.Blobs.ChangeFeed/src/LazyLoadingBlobStream.cs +++ b/sdk/storage/Azure.Storage.Blobs.ChangeFeed/src/LazyLoadingBlobStream.cs @@ -138,7 +138,7 @@ private async Task ReadInternal( do { int copiedBytes = async - ? await _stream.ReadAsync(buffer, offset, count).ConfigureAwait(false) + ? await _stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false) : _stream.Read(buffer, offset, count); offset += copiedBytes; count -= copiedBytes; @@ -245,6 +245,10 @@ public override void Write(byte[] buffer, int offset, int count) throw new NotSupportedException(); } - protected override void Dispose(bool disposing) => _stream.Dispose(); + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + _stream.Dispose(); + } } } diff --git a/sdk/storage/Azure.Storage.Blobs/src/BlobQuickQueryStream.cs b/sdk/storage/Azure.Storage.Blobs/src/BlobQuickQueryStream.cs index 098bd7a1cc39d..1db1e249a81db 100644 --- a/sdk/storage/Azure.Storage.Blobs/src/BlobQuickQueryStream.cs +++ b/sdk/storage/Azure.Storage.Blobs/src/BlobQuickQueryStream.cs @@ -309,6 +309,8 @@ public override long Position /// protected override void Dispose(bool disposing) { + base.Dispose(true); + // Return the buffer to the pool if we're called from Dispose or a finalizer if (_buffer != null) { @@ -322,6 +324,8 @@ protected override void Dispose(bool disposing) ArrayPool.Shared.Return(_buffer, clearArray: true); _buffer = null; } + + _avroReader.Dispose(); } } } diff --git a/sdk/storage/Azure.Storage.Blobs/src/BlobUriBuilder.cs b/sdk/storage/Azure.Storage.Blobs/src/BlobUriBuilder.cs index 2fecae43b85c2..c1cca821e001e 100644 --- a/sdk/storage/Azure.Storage.Blobs/src/BlobUriBuilder.cs +++ b/sdk/storage/Azure.Storage.Blobs/src/BlobUriBuilder.cs @@ -299,14 +299,14 @@ private RequestUriBuilder BuildUri() // regular style Uri will already have account name in domain if (_isPathStyleUri && !string.IsNullOrWhiteSpace(AccountName)) { - path.Append("/").Append(AccountName); + path.Append('/').Append(AccountName); } if (!string.IsNullOrWhiteSpace(BlobContainerName)) { - path.Append("/").Append(BlobContainerName); + path.Append('/').Append(BlobContainerName); if (BlobName != null && BlobName.Length > 0) { - path.Append("/").Append(Uri.EscapeDataString(BlobName)); + path.Append('/').Append(Uri.EscapeDataString(BlobName)); } } @@ -315,20 +315,20 @@ private RequestUriBuilder BuildUri() if (!string.IsNullOrWhiteSpace(Snapshot)) { if (query.Length > 0) - { query.Append("&"); } - query.Append(Constants.SnapshotParameterName).Append("=").Append(Snapshot); + { query.Append('&'); } + query.Append(Constants.SnapshotParameterName).Append('=').Append(Snapshot); } if (!string.IsNullOrWhiteSpace(VersionId)) { if (query.Length > 0) - { query.Append("&"); } - query.Append(Constants.VersionIdParameterName).Append("=").Append(VersionId); + { query.Append('&'); } + query.Append(Constants.VersionIdParameterName).Append('=').Append(VersionId); } var sas = Sas?.ToString(); if (!string.IsNullOrWhiteSpace(sas)) { if (query.Length > 0) - { query.Append("&"); } + { query.Append('&'); } query.Append(sas); } diff --git a/sdk/storage/Azure.Storage.Blobs/src/Generated/BlobRestClient.cs b/sdk/storage/Azure.Storage.Blobs/src/Generated/BlobRestClient.cs index d0b5716f010b9..40c0a6926f528 100644 --- a/sdk/storage/Azure.Storage.Blobs/src/Generated/BlobRestClient.cs +++ b/sdk/storage/Azure.Storage.Blobs/src/Generated/BlobRestClient.cs @@ -19186,7 +19186,9 @@ public partial class BlobServiceProperties /// /// The set of CORS rules. /// +#pragma warning disable CA2227 // Collection properties should be readonly public System.Collections.Generic.IList Cors { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// The default version to use for requests to the Blob service if an incoming request's version is not specified. Possible values include version 2008-10-27 and all more recent versions diff --git a/sdk/storage/Azure.Storage.Blobs/src/Models/AppendBlobCreateOptions.cs b/sdk/storage/Azure.Storage.Blobs/src/Models/AppendBlobCreateOptions.cs index 95d26b703c74d..6574fe7df0ff3 100644 --- a/sdk/storage/Azure.Storage.Blobs/src/Models/AppendBlobCreateOptions.cs +++ b/sdk/storage/Azure.Storage.Blobs/src/Models/AppendBlobCreateOptions.cs @@ -20,12 +20,16 @@ public class AppendBlobCreateOptions /// /// Optional custom metadata to set for this append blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Metadata Metadata { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Options tags to set for this append blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Tags Tags { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Optional to add diff --git a/sdk/storage/Azure.Storage.Blobs/src/Models/BlobCopyFromUriOptions.cs b/sdk/storage/Azure.Storage.Blobs/src/Models/BlobCopyFromUriOptions.cs index 294ee3639f973..e960064acd0c1 100644 --- a/sdk/storage/Azure.Storage.Blobs/src/Models/BlobCopyFromUriOptions.cs +++ b/sdk/storage/Azure.Storage.Blobs/src/Models/BlobCopyFromUriOptions.cs @@ -14,12 +14,16 @@ public class BlobCopyFromUriOptions /// /// Optional custom metadata to set for this append blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Metadata Metadata { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Options tags to set for this append blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Tags Tags { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Optional diff --git a/sdk/storage/Azure.Storage.Blobs/src/Models/BlobUploadOptions.cs b/sdk/storage/Azure.Storage.Blobs/src/Models/BlobUploadOptions.cs index a7caddc32514d..52d7f4198d513 100644 --- a/sdk/storage/Azure.Storage.Blobs/src/Models/BlobUploadOptions.cs +++ b/sdk/storage/Azure.Storage.Blobs/src/Models/BlobUploadOptions.cs @@ -21,12 +21,16 @@ public class BlobUploadOptions /// /// Optional custom metadata to set for this append blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Metadata Metadata { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Options tags to set for this block blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Tags Tags { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Optional to add diff --git a/sdk/storage/Azure.Storage.Blobs/src/Models/BlockBlobOpenWriteOptions.cs b/sdk/storage/Azure.Storage.Blobs/src/Models/BlockBlobOpenWriteOptions.cs index 3f2d39c1bea57..a9c958a1f8e1e 100644 --- a/sdk/storage/Azure.Storage.Blobs/src/Models/BlockBlobOpenWriteOptions.cs +++ b/sdk/storage/Azure.Storage.Blobs/src/Models/BlockBlobOpenWriteOptions.cs @@ -38,11 +38,15 @@ public class BlockBlobOpenWriteOptions /// /// Optional custom metadata to set for this block blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Metadata Metadata { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Options tags to set for this block blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Tags Tags { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly } } diff --git a/sdk/storage/Azure.Storage.Blobs/src/Models/CommitBlockListOptions.cs b/sdk/storage/Azure.Storage.Blobs/src/Models/CommitBlockListOptions.cs index 124faede128de..d5803eac5d023 100644 --- a/sdk/storage/Azure.Storage.Blobs/src/Models/CommitBlockListOptions.cs +++ b/sdk/storage/Azure.Storage.Blobs/src/Models/CommitBlockListOptions.cs @@ -23,12 +23,16 @@ public class CommitBlockListOptions /// /// Optional custom metadata to set for this block blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Metadata Metadata { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Options tags to set for this block blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Tags Tags { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Optional to add diff --git a/sdk/storage/Azure.Storage.Blobs/src/Models/PageBlobCreateOptions.cs b/sdk/storage/Azure.Storage.Blobs/src/Models/PageBlobCreateOptions.cs index f007c4c6e45aa..ea3c97d8cab59 100644 --- a/sdk/storage/Azure.Storage.Blobs/src/Models/PageBlobCreateOptions.cs +++ b/sdk/storage/Azure.Storage.Blobs/src/Models/PageBlobCreateOptions.cs @@ -33,11 +33,15 @@ public class PageBlobCreateOptions /// /// Optional custom metadata to set for this page blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Metadata Metadata { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Options tags to set for this append blob. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Tags Tags { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly } } diff --git a/sdk/storage/Azure.Storage.Common/src/Shared/LazyLoadingReadOnlyStream.cs b/sdk/storage/Azure.Storage.Common/src/Shared/LazyLoadingReadOnlyStream.cs index 431c417c86c37..c61e00342ce0d 100644 --- a/sdk/storage/Azure.Storage.Common/src/Shared/LazyLoadingReadOnlyStream.cs +++ b/sdk/storage/Azure.Storage.Common/src/Shared/LazyLoadingReadOnlyStream.cs @@ -250,6 +250,7 @@ private static void ValidateReadParameters(byte[] buffer, int offset, int count) protected override void Dispose(bool disposing) { + base.Dispose(disposing); // Return the buffer to the pool if we're called from Dispose or a finalizer if (_buffer != null) { diff --git a/sdk/storage/Azure.Storage.Common/src/Shared/NonDisposingStream.cs b/sdk/storage/Azure.Storage.Common/src/Shared/NonDisposingStream.cs index 3115830fc0d3d..adfefc06fffde 100644 --- a/sdk/storage/Azure.Storage.Common/src/Shared/NonDisposingStream.cs +++ b/sdk/storage/Azure.Storage.Common/src/Shared/NonDisposingStream.cs @@ -42,8 +42,6 @@ internal class NonDisposingStream : Stream public override void Write(byte[] buffer, int offset, int count) => _innerStream.Write(buffer, offset, count); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => _innerStream.WriteAsync(buffer, offset, count, cancellationToken); - - protected override void Dispose(bool disposing) { /* swallow disposal */ } } internal static partial class StreamExtensions diff --git a/sdk/storage/Azure.Storage.Common/src/Shared/PooledMemoryStream.cs b/sdk/storage/Azure.Storage.Common/src/Shared/PooledMemoryStream.cs index 6854b21323c90..e1dae204f1d97 100644 --- a/sdk/storage/Azure.Storage.Common/src/Shared/PooledMemoryStream.cs +++ b/sdk/storage/Azure.Storage.Common/src/Shared/PooledMemoryStream.cs @@ -346,6 +346,7 @@ public override void Write(byte[] buffer, int offset, int count) protected override void Dispose(bool disposing) { + base.Dispose(disposing); Clear(); } diff --git a/sdk/storage/Azure.Storage.Common/src/Shared/ProgressIncrementingStream.cs b/sdk/storage/Azure.Storage.Common/src/Shared/ProgressIncrementingStream.cs index 8ae29b3752e40..89f1a249ab755 100644 --- a/sdk/storage/Azure.Storage.Common/src/Shared/ProgressIncrementingStream.cs +++ b/sdk/storage/Azure.Storage.Common/src/Shared/ProgressIncrementingStream.cs @@ -30,7 +30,11 @@ public ProgressIncrementingStream(Stream stream, AggregatingProgressIncrementer public override bool CanWrite => _innerStream.CanWrite; - protected override void Dispose(bool disposing) => _innerStream.Dispose(); + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + _innerStream.Dispose(); + } public override async Task FlushAsync(CancellationToken cancellationToken) { diff --git a/sdk/storage/Azure.Storage.Common/src/Shared/StorageMemoryPool.cs b/sdk/storage/Azure.Storage.Common/src/Shared/StorageMemoryPool.cs index bbc295744e15e..fbf46efca870b 100644 --- a/sdk/storage/Azure.Storage.Common/src/Shared/StorageMemoryPool.cs +++ b/sdk/storage/Azure.Storage.Common/src/Shared/StorageMemoryPool.cs @@ -47,7 +47,7 @@ public StorageMemoryOwner(StorageMemoryPool pool, int minimumLength) public Memory Memory { get; private set; } #region IDisposable Support - private bool _disposedValue = false; // To detect redundant calls + private bool _disposedValue; // To detect redundant calls public void Dispose() { diff --git a/sdk/storage/Azure.Storage.Common/src/Shared/StreamPartition.cs b/sdk/storage/Azure.Storage.Common/src/Shared/StreamPartition.cs index 649a413293c51..085adf52fef33 100644 --- a/sdk/storage/Azure.Storage.Common/src/Shared/StreamPartition.cs +++ b/sdk/storage/Azure.Storage.Common/src/Shared/StreamPartition.cs @@ -35,10 +35,10 @@ internal sealed class StreamPartition : Stream public Task DisposalTask { get; } -#pragma warning disable IDE0069 // Disposable fields should be disposed // disposed in DisposalTask +#pragma warning disable IDE0069, CA2213 // Disposable fields should be disposed // disposed in DisposalTask //ManualResetEventSlim disposalTaskCompletionSource; private SemaphoreSlim _disposalTaskCompletionSource; -#pragma warning restore IDE0069 // Disposable fields should be disposed +#pragma warning restore IDE0069, CA2213 // Disposable fields should be disposed public StreamPartition(ReadOnlyMemory buffer, long parentPosition, int count, Action disposeAction, CancellationToken ct) { @@ -86,7 +86,7 @@ protected override void Dispose(bool disposing) } } - private bool _disposedValue = false; // To detect redundant calls + private bool _disposedValue; // To detect redundant calls public override void Flush() { diff --git a/sdk/storage/Azure.Storage.Common/src/Shared/WindowStream.cs b/sdk/storage/Azure.Storage.Common/src/Shared/WindowStream.cs index 79e7611304720..7f75b8a569a96 100644 --- a/sdk/storage/Azure.Storage.Common/src/Shared/WindowStream.cs +++ b/sdk/storage/Azure.Storage.Common/src/Shared/WindowStream.cs @@ -116,7 +116,7 @@ private async Task ReadInternal(byte[] buffer, int offset, int count, bool /// private class UnseekableWindowStream : WindowStream { - private long _position = 0; + private long _position; private long MaxLength { get; } diff --git a/sdk/storage/Azure.Storage.Common/tests/CommonTestBase.cs b/sdk/storage/Azure.Storage.Common/tests/CommonTestBase.cs index 708f906e66f69..42d2b882f01b8 100644 --- a/sdk/storage/Azure.Storage.Common/tests/CommonTestBase.cs +++ b/sdk/storage/Azure.Storage.Common/tests/CommonTestBase.cs @@ -14,7 +14,7 @@ namespace Azure.Storage.Test /// /// Base class for Common tests /// - public class CommonTestBase : StorageTestBase + public abstract class CommonTestBase : StorageTestBase { public CommonTestBase(bool async, RecordedTestMode? mode = null) : base(async, mode /* RecordedTestMode.Record to re-record */) diff --git a/sdk/storage/Azure.Storage.Files.DataLake/src/DataLakePathClient.cs b/sdk/storage/Azure.Storage.Files.DataLake/src/DataLakePathClient.cs index 4b846cb8b8665..a066e29faa427 100644 --- a/sdk/storage/Azure.Storage.Files.DataLake/src/DataLakePathClient.cs +++ b/sdk/storage/Azure.Storage.Files.DataLake/src/DataLakePathClient.cs @@ -507,10 +507,10 @@ internal static string BuildMetadataString(Metadata metadata) foreach (KeyValuePair kv in metadata) { sb.Append(kv.Key); - sb.Append("="); + sb.Append('='); byte[] valueBytes = Encoding.UTF8.GetBytes(kv.Value); sb.Append(Convert.ToBase64String(valueBytes)); - sb.Append(","); + sb.Append(','); } sb.Remove(sb.Length - 1, 1); return sb.ToString(); @@ -3151,7 +3151,8 @@ public virtual Response SetMetadata( Response response = _blockBlobClient.SetMetadata( metadata, - conditions.ToBlobRequestConditions()); + conditions.ToBlobRequestConditions(), + cancellationToken); return Response.FromValue( response.Value.ToPathInfo(), @@ -3208,7 +3209,8 @@ public virtual async Task> SetMetadataAsync( Response response = await _blockBlobClient.SetMetadataAsync( metadata, - conditions.ToBlobRequestConditions()) + conditions.ToBlobRequestConditions(), + cancellationToken) .ConfigureAwait(false); return Response.FromValue( diff --git a/sdk/storage/Azure.Storage.Files.DataLake/src/DataLakeUriBuilder.cs b/sdk/storage/Azure.Storage.Files.DataLake/src/DataLakeUriBuilder.cs index 2651d27c914ce..3fee9f86cf213 100644 --- a/sdk/storage/Azure.Storage.Files.DataLake/src/DataLakeUriBuilder.cs +++ b/sdk/storage/Azure.Storage.Files.DataLake/src/DataLakeUriBuilder.cs @@ -354,11 +354,11 @@ private RequestUriBuilder BuildUri() // regular style Uri will already have account name in domain if (_isIPStyleUri && !string.IsNullOrWhiteSpace(AccountName)) { - path.Append("/").Append(AccountName); + path.Append('/').Append(AccountName); } if (!string.IsNullOrWhiteSpace(FileSystemName)) { - path.Append("/").Append(FileSystemName); + path.Append('/').Append(FileSystemName); if (!string.IsNullOrWhiteSpace(DirectoryOrFilePath)) { if (DirectoryOrFilePath == "/") @@ -368,7 +368,7 @@ private RequestUriBuilder BuildUri() else { // Encode path. - path.Append("/").Append(DirectoryOrFilePath.EscapePath()); + path.Append('/').Append(DirectoryOrFilePath.EscapePath()); } } } @@ -378,14 +378,14 @@ private RequestUriBuilder BuildUri() if (!string.IsNullOrWhiteSpace(Snapshot)) { if (query.Length > 0) - { query.Append("&"); } - query.Append(Constants.SnapshotParameterName).Append("=").Append(Snapshot); + { query.Append('&'); } + query.Append(Constants.SnapshotParameterName).Append('=').Append(Snapshot); } var sas = Sas?.ToString(); if (!string.IsNullOrWhiteSpace(sas)) { if (query.Length > 0) - { query.Append("&"); } + { query.Append('&'); } query.Append(sas); } diff --git a/sdk/storage/Azure.Storage.Files.DataLake/src/Models/DataLakeFileUploadOptions.cs b/sdk/storage/Azure.Storage.Files.DataLake/src/Models/DataLakeFileUploadOptions.cs index 0bc0f6806b5ec..64f234a14dfa2 100644 --- a/sdk/storage/Azure.Storage.Files.DataLake/src/Models/DataLakeFileUploadOptions.cs +++ b/sdk/storage/Azure.Storage.Files.DataLake/src/Models/DataLakeFileUploadOptions.cs @@ -19,7 +19,9 @@ public class DataLakeFileUploadOptions /// /// Optional custom metadata to set for this file. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Metadata Metadata { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Optional and only valid if Hierarchical Namespace is enabled for the account. Sets POSIX access diff --git a/sdk/storage/Azure.Storage.Files.DataLake/src/Models/PathAccessControlItem.cs b/sdk/storage/Azure.Storage.Files.DataLake/src/Models/PathAccessControlItem.cs index 697c00bd416cd..47cea1f6f0fc1 100644 --- a/sdk/storage/Azure.Storage.Files.DataLake/src/Models/PathAccessControlItem.cs +++ b/sdk/storage/Azure.Storage.Files.DataLake/src/Models/PathAccessControlItem.cs @@ -75,9 +75,9 @@ public override string ToString() stringBuilder.Append("default:"); } stringBuilder.Append(AccessControlType.ToString().ToLowerInvariant()); - stringBuilder.Append(":"); + stringBuilder.Append(':'); stringBuilder.Append(EntityId ?? ""); - stringBuilder.Append(":"); + stringBuilder.Append(':'); stringBuilder.Append(Permissions.ToSymbolicRolePermissions()); return stringBuilder.ToString(); diff --git a/sdk/storage/Azure.Storage.Files.DataLake/src/Models/PathPermissions.cs b/sdk/storage/Azure.Storage.Files.DataLake/src/Models/PathPermissions.cs index a7a5f2cac8632..d9ef021370349 100644 --- a/sdk/storage/Azure.Storage.Files.DataLake/src/Models/PathPermissions.cs +++ b/sdk/storage/Azure.Storage.Files.DataLake/src/Models/PathPermissions.cs @@ -199,12 +199,12 @@ public string ToSymbolicPermissions() if (StickyBit) { sb.Remove(8, 1); - sb.Append("t"); + sb.Append('t'); } if (ExtendedAcls) { - sb.Append("+"); + sb.Append('+'); } return sb.ToString(); diff --git a/sdk/storage/Azure.Storage.Files.DataLake/src/Models/RemovePathAccessControlItem.cs b/sdk/storage/Azure.Storage.Files.DataLake/src/Models/RemovePathAccessControlItem.cs index 3c1ae90d2c733..913fb150c7eec 100644 --- a/sdk/storage/Azure.Storage.Files.DataLake/src/Models/RemovePathAccessControlItem.cs +++ b/sdk/storage/Azure.Storage.Files.DataLake/src/Models/RemovePathAccessControlItem.cs @@ -65,7 +65,7 @@ public override string ToString() stringBuilder.Append(AccessControlType.ToString().ToLowerInvariant()); if (!string.IsNullOrWhiteSpace(EntityId)) { - stringBuilder.Append(":"); + stringBuilder.Append(':'); stringBuilder.Append(EntityId); } diff --git a/sdk/storage/Azure.Storage.Files.Shares/src/Generated/FileRestClient.cs b/sdk/storage/Azure.Storage.Files.Shares/src/Generated/FileRestClient.cs index e5583a7b5e1fc..e78386c9e1096 100644 --- a/sdk/storage/Azure.Storage.Files.Shares/src/Generated/FileRestClient.cs +++ b/sdk/storage/Azure.Storage.Files.Shares/src/Generated/FileRestClient.cs @@ -11683,7 +11683,9 @@ public partial class ShareServiceProperties /// /// The set of CORS rules. /// +#pragma warning disable CA2227 // Collection properties should be readonly public System.Collections.Generic.IList Cors { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Protocol settings diff --git a/sdk/storage/Azure.Storage.Files.Shares/src/Models/NtfsFileAttributes.cs b/sdk/storage/Azure.Storage.Files.Shares/src/Models/NtfsFileAttributes.cs index 129f64ab70aa4..f8e3973d273d1 100644 --- a/sdk/storage/Azure.Storage.Files.Shares/src/Models/NtfsFileAttributes.cs +++ b/sdk/storage/Azure.Storage.Files.Shares/src/Models/NtfsFileAttributes.cs @@ -143,7 +143,7 @@ public static string ToAttributesString(this NtfsFileAttributes attributes) private static void AppendAttribute(string attributeName, StringBuilder stringBuilder) { stringBuilder.Append(attributeName); - stringBuilder.Append("|"); + stringBuilder.Append('|'); } /// diff --git a/sdk/storage/Azure.Storage.Files.Shares/src/Models/ShareCreateOptions.cs b/sdk/storage/Azure.Storage.Files.Shares/src/Models/ShareCreateOptions.cs index e53414b5c1ed3..a34f0b18e5a07 100644 --- a/sdk/storage/Azure.Storage.Files.Shares/src/Models/ShareCreateOptions.cs +++ b/sdk/storage/Azure.Storage.Files.Shares/src/Models/ShareCreateOptions.cs @@ -16,7 +16,9 @@ public class ShareCreateOptions /// /// Optional custom metadata to set for this share. /// +#pragma warning disable CA2227 // Collection properties should be readonly public Metadata Metadata { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Optional. Maximum size of the share in gigabytes. If unspecified, use the service's default value. diff --git a/sdk/storage/Azure.Storage.Files.Shares/src/ShareClient.cs b/sdk/storage/Azure.Storage.Files.Shares/src/ShareClient.cs index f5a3e3e5b0906..18885f3e3daba 100644 --- a/sdk/storage/Azure.Storage.Files.Shares/src/ShareClient.cs +++ b/sdk/storage/Azure.Storage.Files.Shares/src/ShareClient.cs @@ -2970,7 +2970,7 @@ internal async Task> CreatePermissionInternal( writer.WriteEndObject(); if (async) { - await writer.FlushAsync().ConfigureAwait(false); + await writer.FlushAsync(cancellationToken).ConfigureAwait(false); } else { diff --git a/sdk/storage/Azure.Storage.Files.Shares/src/ShareUriBuilder.cs b/sdk/storage/Azure.Storage.Files.Shares/src/ShareUriBuilder.cs index d437530a990a5..38d0830aa5743 100644 --- a/sdk/storage/Azure.Storage.Files.Shares/src/ShareUriBuilder.cs +++ b/sdk/storage/Azure.Storage.Files.Shares/src/ShareUriBuilder.cs @@ -283,14 +283,14 @@ private RequestUriBuilder BuildUri() // regular style Uri will already have account name in domain if (_isPathStyleUri && !string.IsNullOrWhiteSpace(AccountName)) { - path.Append("/").Append(AccountName); + path.Append('/').Append(AccountName); } if (!string.IsNullOrWhiteSpace(ShareName)) { - path.Append("/").Append(ShareName); + path.Append('/').Append(ShareName); if (!string.IsNullOrWhiteSpace(_directoryOrFilePath)) { - path.Append("/").Append(_directoryOrFilePath.EscapePath()); + path.Append('/').Append(_directoryOrFilePath.EscapePath()); } } @@ -298,13 +298,13 @@ private RequestUriBuilder BuildUri() var query = new StringBuilder(Query); if (!string.IsNullOrWhiteSpace(Snapshot)) { - if (query.Length > 0) { query.Append("&"); } - query.Append(Constants.File.SnapshotParameterName).Append("=").Append(Snapshot); + if (query.Length > 0) { query.Append('&'); } + query.Append(Constants.File.SnapshotParameterName).Append('=').Append(Snapshot); } var sas = Sas?.ToString(); if (!string.IsNullOrWhiteSpace(sas)) { - if (query.Length > 0) { query.Append("&"); } + if (query.Length > 0) { query.Append('&'); } query.Append(sas); } diff --git a/sdk/storage/Azure.Storage.Internal.Avro/src/AvroReader.cs b/sdk/storage/Azure.Storage.Internal.Avro/src/AvroReader.cs index b83294913b02d..df4813fdaf5f8 100644 --- a/sdk/storage/Azure.Storage.Internal.Avro/src/AvroReader.cs +++ b/sdk/storage/Azure.Storage.Internal.Avro/src/AvroReader.cs @@ -63,7 +63,7 @@ internal class AvroReader : IDisposable /// /// To detect redundant calls /// - private bool _disposed = false; + private bool _disposed; /// /// Remembers where we started if partial data stream was provided. diff --git a/sdk/storage/Azure.Storage.Internal.Avro/src/StreamWithPosition.cs b/sdk/storage/Azure.Storage.Internal.Avro/src/StreamWithPosition.cs index 66a889e4d4b55..d854c52ec20c3 100644 --- a/sdk/storage/Azure.Storage.Internal.Avro/src/StreamWithPosition.cs +++ b/sdk/storage/Azure.Storage.Internal.Avro/src/StreamWithPosition.cs @@ -27,7 +27,7 @@ internal class StreamWithPosition : Stream /// /// To detect redundant calls. /// - private bool _disposed = false; + private bool _disposed; public StreamWithPosition( Stream stream, @@ -140,6 +140,8 @@ public override void Flush() /// protected override void Dispose(bool disposing) { + base.Dispose(disposing); + if (_disposed) { return; diff --git a/sdk/storage/Azure.Storage.Queues/src/Generated/QueueRestClient.cs b/sdk/storage/Azure.Storage.Queues/src/Generated/QueueRestClient.cs index f9bc77f8f0a6a..a5fec105ca746 100644 --- a/sdk/storage/Azure.Storage.Queues/src/Generated/QueueRestClient.cs +++ b/sdk/storage/Azure.Storage.Queues/src/Generated/QueueRestClient.cs @@ -3968,7 +3968,9 @@ public partial class QueueServiceProperties /// /// The set of CORS rules. /// +#pragma warning disable CA2227 // Collection properties should be readonly public System.Collections.Generic.IList Cors { get; set; } +#pragma warning restore CA2227 // Collection properties should be readonly /// /// Creates a new QueueServiceProperties instance diff --git a/sdk/storage/Azure.Storage.Queues/src/QueueUriBuilder.cs b/sdk/storage/Azure.Storage.Queues/src/QueueUriBuilder.cs index c2650e2d27b67..34c8c341e955a 100644 --- a/sdk/storage/Azure.Storage.Queues/src/QueueUriBuilder.cs +++ b/sdk/storage/Azure.Storage.Queues/src/QueueUriBuilder.cs @@ -261,18 +261,18 @@ private RequestUriBuilder BuildUri() // regular style Uri will already have account name in domain if (_isPathStyleUri && !string.IsNullOrWhiteSpace(AccountName)) { - path.Append("/").Append(AccountName); + path.Append('/').Append(AccountName); } if (!string.IsNullOrWhiteSpace(QueueName)) { - path.Append("/").Append(QueueName); + path.Append('/').Append(QueueName); if (Messages) { path.Append("/messages"); if (!string.IsNullOrWhiteSpace(MessageId)) { - path.Append("/").Append(MessageId); + path.Append('/').Append(MessageId); } } } @@ -282,7 +282,7 @@ private RequestUriBuilder BuildUri() var sas = Sas?.ToString(); if (!string.IsNullOrWhiteSpace(sas)) { - if (query.Length > 0) { query.Append("&"); } + if (query.Length > 0) { query.Append('&'); } query.Append(sas); } diff --git a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/BlobPathSource.cs b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/BlobPathSource.cs index 192e765ca7c86..a70e84799c099 100644 --- a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/BlobPathSource.cs +++ b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/BlobPathSource.cs @@ -41,7 +41,7 @@ public static IBlobPathSource Create(string pattern) BindingTemplateSource template = BindingTemplateSource.FromString(pattern); - if (template.ParameterNames.Count() > 0) + if (template.ParameterNames.Any()) { return new ParameterizedBlobPathSource(containerNamePattern, blobNamePattern, template); } diff --git a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/PollLogsStrategy.cs b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/PollLogsStrategy.cs index 37c48d60802ff..8fdb876d51eb4 100644 --- a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/PollLogsStrategy.cs +++ b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/PollLogsStrategy.cs @@ -136,7 +136,7 @@ public async Task ExecuteAsync(CancellationToken cancel } // Run subsequent iterations at 2 second intervals. - return new TaskSeriesCommandResult(wait: Task.Delay(TwoSeconds)); + return new TaskSeriesCommandResult(wait: Task.Delay(TwoSeconds, CancellationToken.None)); } public void Start() diff --git a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/ScanBlobScanLogHybridPollingStrategy.cs b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/ScanBlobScanLogHybridPollingStrategy.cs index fd2ee9d3de3be..b5aaf4d2bfb2e 100644 --- a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/ScanBlobScanLogHybridPollingStrategy.cs +++ b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/ScanBlobScanLogHybridPollingStrategy.cs @@ -131,7 +131,7 @@ public async Task ExecuteAsync(CancellationToken cancel await Task.WhenAll(pollingTasks).ConfigureAwait(false); // Run subsequent iterations at "_pollingInterval" second intervals. - return new TaskSeriesCommandResult(wait: Task.Delay(PollingInterval)); + return new TaskSeriesCommandResult(wait: Task.Delay(PollingInterval, CancellationToken.None)); } private async Task PollAndNotify(BlobContainerClient container, ContainerScanInfo containerScanInfo, diff --git a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/ScanContainersStrategy.cs b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/ScanContainersStrategy.cs index 206cdfd2ea616..975278470184c 100644 --- a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/ScanContainersStrategy.cs +++ b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/Listeners/ScanContainersStrategy.cs @@ -107,7 +107,7 @@ public async Task ExecuteAsync(CancellationToken cancel } // Run subsequent iterations at 2 second intervals. - return new TaskSeriesCommandResult(wait: Task.Delay(TwoSeconds)); + return new TaskSeriesCommandResult(wait: Task.Delay(TwoSeconds, CancellationToken.None)); } public void Cancel() diff --git a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/ParameterizedBlobPathSource.cs b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/ParameterizedBlobPathSource.cs index 83d0293b40a10..4ec28f0b47381 100644 --- a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/ParameterizedBlobPathSource.cs +++ b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Blobs/src/ParameterizedBlobPathSource.cs @@ -19,7 +19,7 @@ public ParameterizedBlobPathSource(string containerNamePattern, string blobNameP BindingTemplateSource template) { Debug.Assert(template != null, "template must not be null"); - Debug.Assert(template.ParameterNames.Count() > 0, "template must contain one or more parameters"); + Debug.Assert(template.ParameterNames.Any(), "template must contain one or more parameters"); _containerNamePattern = containerNamePattern; _blobNamePattern = blobNamePattern; diff --git a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Queues/QueueListener.cs b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Queues/QueueListener.cs index 86ac2f8f2250c..89b618dcbb204 100644 --- a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Queues/QueueListener.cs +++ b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Queues/QueueListener.cs @@ -194,7 +194,7 @@ public async Task ExecuteAsync(CancellationToken cancel // check anymore (steady state). // However the queue can always be deleted from underneath us, in which case // we need to recheck. That is handled below. - _queueExists = await _queue.ExistsAsync().ConfigureAwait(false); + _queueExists = await _queue.ExistsAsync(cancellationToken).ConfigureAwait(false); } if (_queueExists.Value) @@ -204,7 +204,7 @@ public async Task ExecuteAsync(CancellationToken cancel Response response = await _queue.ReceiveMessagesAsync(_queueProcessor.QueuesOptions.BatchSize, _visibilityTimeout, cancellationToken).ConfigureAwait(false); batch = response.Value; - int count = batch?.Count() ?? -1; + int count = batch?.Length ?? -1; Logger.GetMessages(_logger, _functionDescriptor.LogName, _queue.Name, response.GetRawResponse().ClientRequestId, count, sw.ElapsedMilliseconds); } } diff --git a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/StorageClientProvider.cs b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/StorageClientProvider.cs index e7d0907c771a2..0200dfa6b3530 100644 --- a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/StorageClientProvider.cs +++ b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/StorageClientProvider.cs @@ -96,7 +96,7 @@ private TClientOptions CreateClientOptions(IConfiguration configuration) return clientOptions; } - private HttpPipelineTransport CreateTransportForDynamicSku() + private static HttpPipelineTransport CreateTransportForDynamicSku() { return new HttpClientTransport(new HttpClient(new HttpClientHandler() { diff --git a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Timers/RecurrentTaskSeriesCommand.cs b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Timers/RecurrentTaskSeriesCommand.cs index d2ab5a6fde0ad..81ae70da5de36 100644 --- a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Timers/RecurrentTaskSeriesCommand.cs +++ b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Timers/RecurrentTaskSeriesCommand.cs @@ -20,7 +20,7 @@ public RecurrentTaskSeriesCommand(IRecurrentCommand innerCommand, IDelayStrategy public async Task ExecuteAsync(CancellationToken cancellationToken) { bool succeeded = await _innerCommand.TryExecuteAsync(cancellationToken).ConfigureAwait(false); - Task wait = Task.Delay(_delayStrategy.GetNextDelay(succeeded)); + Task wait = Task.Delay(_delayStrategy.GetNextDelay(succeeded), cancellationToken); return new TaskSeriesCommandResult(wait); } } diff --git a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Timers/TaskSeriesTimer.cs b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Timers/TaskSeriesTimer.cs index a6bc896b3e666..264f978f123f4 100644 --- a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Timers/TaskSeriesTimer.cs +++ b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/Timers/TaskSeriesTimer.cs @@ -79,7 +79,7 @@ public Task StopAsync(CancellationToken cancellationToken) private async Task StopAsyncCore(CancellationToken cancellationToken) { - await Task.Delay(0).ConfigureAwait(false); + await Task.Delay(0, cancellationToken).ConfigureAwait(false); TaskCompletionSource cancellationTaskSource = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using (cancellationToken.Register(() => cancellationTaskSource.SetCanceled())) diff --git a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/UpdateQueueMessageVisibilityCommand.cs b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/UpdateQueueMessageVisibilityCommand.cs index 41dfc2f37ea72..784d9fa654ac9 100644 --- a/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/UpdateQueueMessageVisibilityCommand.cs +++ b/sdk/storage/Microsoft.Azure.WebJobs.Extensions.Storage.Common/src/Shared/UpdateQueueMessageVisibilityCommand.cs @@ -84,7 +84,7 @@ public async Task ExecuteAsync(CancellationToken cancel } } - return new TaskSeriesCommandResult(wait: Task.Delay(delay)); + return new TaskSeriesCommandResult(wait: Task.Delay(delay, cancellationToken)); } } } diff --git a/sdk/tables/Azure.Data.Tables/src/Queryable/WebConvert.cs b/sdk/tables/Azure.Data.Tables/src/Queryable/WebConvert.cs index d6c2856e60c0d..2a3c04c44160a 100644 --- a/sdk/tables/Azure.Data.Tables/src/Queryable/WebConvert.cs +++ b/sdk/tables/Azure.Data.Tables/src/Queryable/WebConvert.cs @@ -16,14 +16,14 @@ internal static string ConvertByteArrayToKeyString(byte[] byteArray) { StringBuilder hexBuilder = new StringBuilder(3 + (byteArray.Length * 2)); hexBuilder.Append(XmlConstants.XmlBinaryPrefix); - hexBuilder.Append("'"); + hexBuilder.Append('\''); for (int i = 0; i < byteArray.Length; i++) { hexBuilder.Append(HexValues[byteArray[i] >> 4]); hexBuilder.Append(HexValues[byteArray[i] & 0x0F]); } - hexBuilder.Append("'"); + hexBuilder.Append('\''); return hexBuilder.ToString(); } diff --git a/sdk/tables/Azure.Data.Tables/src/Queryable/XmlConstants.cs b/sdk/tables/Azure.Data.Tables/src/Queryable/XmlConstants.cs index 05dc01f9d19c3..c213f6b2e869f 100644 --- a/sdk/tables/Azure.Data.Tables/src/Queryable/XmlConstants.cs +++ b/sdk/tables/Azure.Data.Tables/src/Queryable/XmlConstants.cs @@ -249,7 +249,7 @@ internal static class XmlConstants internal const string LiteralPrefixBinary = "binary"; internal const string LiteralPrefixDateTime = "datetime"; internal const string LiteralPrefixGuid = "guid"; - internal const string XmlBinaryPrefix = "X"; + internal const char XmlBinaryPrefix = 'X'; internal const string XmlDecimalLiteralSuffix = "M"; internal const string XmlInt64LiteralSuffix = "L"; internal const string XmlSingleLiteralSuffix = "f"; diff --git a/sdk/tables/Azure.Data.Tables/src/TableTransactionalBatch.cs b/sdk/tables/Azure.Data.Tables/src/TableTransactionalBatch.cs index 29f04b718f0e3..b733dfb010a9f 100644 --- a/sdk/tables/Azure.Data.Tables/src/TableTransactionalBatch.cs +++ b/sdk/tables/Azure.Data.Tables/src/TableTransactionalBatch.cs @@ -26,12 +26,12 @@ public partial class TableTransactionalBatch private readonly OdataMetadataFormat _format; private readonly ResponseFormat _returnNoContent = ResponseFormat.ReturnNoContent; internal MultipartContent _batch; - internal Guid _batchGuid = default; - internal Guid _changesetGuid = default; + internal Guid _batchGuid; + internal Guid _changesetGuid; internal ConcurrentDictionary _requestLookup = new ConcurrentDictionary(); internal ConcurrentQueue<(ITableEntity Entity, HttpMessage HttpMessage)> _requestMessages = new ConcurrentQueue<(ITableEntity Entity, HttpMessage HttpMessage)>(); private List<(ITableEntity entity, HttpMessage HttpMessage)> _submittedMessageList; - private bool _submitted = false; + private bool _submitted; /// /// Initializes a new instance of the class. diff --git a/sdk/textanalytics/Azure.AI.TextAnalytics/src/ClientDiagnostics.cs b/sdk/textanalytics/Azure.AI.TextAnalytics/src/ClientDiagnostics.cs index 31b4e991cfa22..e86d3bd96ef04 100644 --- a/sdk/textanalytics/Azure.AI.TextAnalytics/src/ClientDiagnostics.cs +++ b/sdk/textanalytics/Azure.AI.TextAnalytics/src/ClientDiagnostics.cs @@ -24,6 +24,7 @@ internal sealed partial class ClientDiagnostics /// The error message. /// The error code. /// Additional error details. +#pragma warning disable CA1822 // Member can be static partial void ExtractFailureContent( string? content, ref string? message, @@ -31,6 +32,7 @@ partial void ExtractFailureContent( #pragma warning disable CA1801 // Remove unused parameter ref IDictionary? additionalInfo) #pragma warning restore CA1801 // Remove unused parameter +#pragma warning restore CA1822 // Member can be static { if (!string.IsNullOrEmpty(content)) { diff --git a/sdk/textanalytics/Azure.AI.TextAnalytics/src/DocumentHealthcareResult.cs b/sdk/textanalytics/Azure.AI.TextAnalytics/src/DocumentHealthcareResult.cs index 57468d84f4b5c..3faa104d0970b 100644 --- a/sdk/textanalytics/Azure.AI.TextAnalytics/src/DocumentHealthcareResult.cs +++ b/sdk/textanalytics/Azure.AI.TextAnalytics/src/DocumentHealthcareResult.cs @@ -67,7 +67,7 @@ internal static IReadOnlyList ResolveHealthcareRelations(IEn public TextDocumentStatistics? Statistics { get; } /// TextAnalyticsError. - public TextAnalyticsError TextAnalyticsError { get; } = new TextAnalyticsError(); + public TextAnalyticsError TextAnalyticsError { get; } private static Regex _healthcareEntityRegex = new Regex(@"\#/results/documents\/(?\d*)\/entities\/(?\d*)$", RegexOptions.Compiled, TimeSpan.FromSeconds(2)); diff --git a/sdk/textanalytics/Azure.AI.TextAnalytics/src/TextAnalyticsClient.cs b/sdk/textanalytics/Azure.AI.TextAnalytics/src/TextAnalyticsClient.cs index 90fef9935d5de..c287b7907d3b9 100644 --- a/sdk/textanalytics/Azure.AI.TextAnalytics/src/TextAnalyticsClient.cs +++ b/sdk/textanalytics/Azure.AI.TextAnalytics/src/TextAnalyticsClient.cs @@ -2412,7 +2412,7 @@ async Task> FirstPageFunc(int? pageSizeHint) try { - Response response = await operation.WaitForCompletionAsync().ConfigureAwait(false); + Response response = await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false); RecognizeHealthcareEntitiesResultCollection result = operation.Value; return Page.FromValues(result.AsEnumerable(), operation.NextLink, response.GetRawResponse()); @@ -2444,7 +2444,7 @@ async Task> NextPageFunc(string nextLink, int? pa string[] jobIdParams = nextLinkSplit.Last().Split('?'); // jobIdParams = ['8002878d-2e43-4675-ad20-455fe004641b', '$skip=20&$top=0'] - if (jobIdParams.Count() != 2) + if (jobIdParams.Length != 2) { throw new InvalidOperationException($"Failed to parse element reference: {nextLink}"); } @@ -2476,7 +2476,7 @@ async Task> NextPageFunc(string nextLink, int? pa } } - Response jobState = await _serviceRestClient.HealthStatusAsync(new Guid(jobId), top, skip, showStats).ConfigureAwait(false); + Response jobState = await _serviceRestClient.HealthStatusAsync(new Guid(jobId), top, skip, showStats, cancellationToken).ConfigureAwait(false); RecognizeHealthcareEntitiesResultCollection result = Transforms.ConvertToRecognizeHealthcareEntitiesResultCollection(jobState.Value.Results, operation._idToIndexMap); return Page.FromValues(result.AsEnumerable(), jobState.Value.NextLink, jobState.GetRawResponse()); @@ -2765,7 +2765,7 @@ private LanguageBatchInput ConvertToLanguageInputs(IEnumerable documents private LanguageBatchInput ConvertToLanguageInputs(IEnumerable documents) => new LanguageBatchInput(documents.Select((document) => new LanguageInput(document.Id, document.Text) { CountryHint = document.CountryHint ?? _options.DefaultCountryHint }).ToList()); - private IDictionary CreateAdditionalInformation(TextAnalyticsError error) + private static IDictionary CreateAdditionalInformation(TextAnalyticsError error) { if (string.IsNullOrEmpty(error.Target)) return null;