/// <summary>
        /// Determines whether the exception is due to a 400 Bad Request error with the error code PopReceiptMismatch.
        /// </summary>
        /// <param name="exception">The storage exception.</param>
        /// <returns>
        /// <see langword="true"/> if the exception is due to a 400 Bad Request error with the error code
        /// PopReceiptMismatch; otherwise <see langword="false"/>.
        /// </returns>
        public static bool IsBadRequestPopReceiptMismatch(this RequestFailedException exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            if (exception.Status != 400)
            {
                return(false);
            }

            return(exception.ErrorCode == "PopReceiptMismatch");
        }
        /// <summary>
        /// Determines whether the exception is due to a 409 Conflict error with the error code QueueBeingDeleted or
        /// QueueDisabled.
        /// </summary>
        /// <param name="exception">The storage exception.</param>
        /// <returns>
        /// <see langword="true"/> if the exception is due to a 409 Conflict error with the error code QueueBeingDeleted
        /// or QueueDisabled; otherwise <see langword="false"/>.
        /// </returns>
        public static bool IsConflictQueueBeingDeletedOrDisabled(this RequestFailedException exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            if (exception.Status != 409)
            {
                return(false);
            }

            return(exception.ErrorCode == "QueueBeingDeleted");
        }
        public async Task StartTrainingFailsWithInvalidPrefix()
        {
            var client           = CreateFormTrainingClient();
            var trainingFilesUri = new Uri(TestEnvironment.BlobContainerSasUrl);

            var filter = new TrainingFileFilter {
                IncludeSubFolders = true, Prefix = "invalidPrefix"
            };
            TrainingOperation operation = await client.StartTrainingAsync(trainingFilesUri, useTrainingLabels : false, filter);

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() => await operation.WaitForCompletionAsync(PollingInterval));

            Assert.AreEqual("2014", ex.ErrorCode);
        }
        public void UpdateCheckpointForMissingCheckpointThrowsAndLogsCheckpointUpdateError()
        {
            var checkpoint = new Checkpoint(FullyQualifiedNamespace, EventHubName, ConsumerGroup, PartitionId, 0L, 0L);
            var ex         = new RequestFailedException(404, BlobErrorCode.ContainerNotFound.ToString(), BlobErrorCode.ContainerNotFound.ToString(), null);
            var target     = new BlobsCheckpointStore(new MockBlobContainerClient(blobClientUploadBlobException: ex),
                                                      new BasicRetryPolicy(new EventHubsRetryOptions()));
            var mockLog = new Mock <BlobEventStoreEventSource>();

            target.Logger = mockLog.Object;

            Assert.ThrowsAsync <RequestFailedException>(async() => await target.UpdateCheckpointAsync(checkpoint, new CancellationToken()));

            mockLog.Verify(m => m.CheckpointUpdateError(PartitionId, It.Is <string>(s => s.Contains(BlobErrorCode.ContainerNotFound.ToString()))));
        }
        public async Task ShouldNotRequireGetPermissionForKey()
        {
            // Test for https://github.com/Azure/azure-sdk-for-net/issues/11574
            MockTransport transport = new(request => new MockResponse((int)HttpStatusCode.Forbidden, nameof(HttpStatusCode.Forbidden)));

            KeyResolver resolver = GetResolver(transport);

            // This would otherwise throw if "keys/get" permission was denied and #11574 was not resolved.
            CryptographyClient client = await resolver.ResolveAsync(new Uri("https://mock.vault.azure.net/keys/mock-key"));

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() => await client.UnwrapKeyAsync(KeyWrapAlgorithm.A256KW, new byte[] { 0, 1, 2, 3 }));

            Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.Status);
        }
Пример #6
0
        public void StartRecognizeIdentityDocumentsThrowsForDamagedFile()
        {
            var client = CreateFormRecognizerClient();

            // First 4 bytes are PDF signature, but fill the rest of the "file" with garbage.

            var damagedFile = new byte[] { 0x25, 0x50, 0x44, 0x46, 0x55, 0x55, 0x55 };

            using var stream = new MemoryStream(damagedFile);

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() => await client.StartRecognizeIdentityDocumentsAsync(stream));

            Assert.AreEqual("BadArgument", ex.ErrorCode);
        }
        public void ListOwnershipLogsErrorOnException()
        {
            var ex = new RequestFailedException(0, "foo", BlobErrorCode.ContainerNotFound.ToString(), null);

            var target = new BlobsCheckpointStore(new MockBlobContainerClient(getBlobsAsyncException: ex),
                                                  new BasicRetryPolicy(new EventHubsRetryOptions()));
            var mockLog = new Mock <BlobEventStoreEventSource>();

            target.Logger = mockLog.Object;

            Assert.ThrowsAsync <RequestFailedException>(async() => await target.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup, new CancellationToken()));

            mockLog.Verify(m => m.ListOwnershipAsyncError(FullyQualifiedNamespace, EventHubName, ConsumerGroup, It.Is <string>(e => e.Contains("RequestFailedException"))));
        }
        /// <summary>
        /// Determines whether the exception is due to a 412 Precondition Failed error with the error code LeaseLost.
        /// </summary>
        /// <param name="exception">The storage exception.</param>
        /// <returns>
        /// <see langword="true"/> if the exception is due to a 412 Precondition Failed error with the error code
        /// LeaseLost; otherwise <see langword="false"/>.
        /// </returns>
        public static bool IsPreconditionFailedLeaseLost(this RequestFailedException exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            if (exception.Status != 412)
            {
                return(false);
            }

            return(exception.ErrorCode == "LeaseLost");
        }
Пример #9
0
        public async Task ThrowsWhenRequestIsMalformed()
        {
            await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this);

            SearchIndexClient client         = resources.GetQueryClient();
            SearchOptions     invalidOptions = new SearchOptions {
                Filter = "This is not a valid filter."
            };
            RequestFailedException ex = await CatchAsync <RequestFailedException>(
                async() => await client.SearchAsync("*", invalidOptions));

            Assert.AreEqual(400, ex.Status);
            StringAssert.StartsWith("Invalid expression: Syntax error at position 7 in 'This is not a valid filter.'", ex.Message);
        }
Пример #10
0
        public async Task GetGenericsBadApiVersion()
        {
            var              rgName  = Recording.GenerateAssetName("testrg");
            var              rgOp    = await(await Client.GetDefaultSubscriptionAsync().ConfigureAwait(false)).GetResourceGroups().Construct(Location.WestUS2).CreateOrUpdateAsync(rgName);
            ResourceGroup    rg      = rgOp.Value;
            ArmClientOptions options = new ArmClientOptions();

            options.ApiVersions.SetApiVersion(rg.Id.ResourceType, "1500-10-10");
            var client = GetArmClient(options);
            var genericResourceOperations    = client.GetGenericResource(rg.Id);
            RequestFailedException exception = Assert.ThrowsAsync <RequestFailedException>(async() => await genericResourceOperations.GetAsync());

            Assert.IsTrue(exception.Message.Contains("InvalidApiVersionParameter"));
        }
        /// <summary>
        /// Determines whether the exception is due to a 409 Conflict error with the error code LeaseAlreadyPresent.
        /// </summary>
        /// <param name="exception">The storage exception.</param>
        /// <returns>
        /// <see langword="true"/> if the exception is due to a 409 Conflict error with the error code
        /// LeaseAlreadyPresent; otherwise <see langword="false"/>.
        /// </returns>
        public static bool IsConflictLeaseAlreadyPresent(this RequestFailedException exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            if (exception.Status != 409)
            {
                return(false);
            }

            return(exception.ErrorCode == "LeaseAlreadyPresent");
        }
Пример #12
0
        /// <summary>
        /// Calls the server to get updated status of the long-running operation.
        /// </summary>
        /// <param name="async">When <c>true</c>, the method will be executed asynchronously; otherwise, it will execute synchronously.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param>
        /// <returns>The HTTP response received from the server.</returns>
        private async ValueTask <Response> UpdateStatusAsync(bool async, CancellationToken cancellationToken)
        {
            if (!_hasCompleted)
            {
                using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(DocumentTranslationOperation)}.{nameof(UpdateStatus)}");
                scope.Start();

                try
                {
                    var update = async
                        ? await _serviceClient.GetTranslationStatusAsync(new Guid(Id), cancellationToken).ConfigureAwait(false)
                        : _serviceClient.GetTranslationStatus(new Guid(Id), cancellationToken);

                    _response = update.GetRawResponse();
                    _retryAfterHeaderValue = update.Headers.RetryAfter;

                    _createdOn           = update.Value.CreatedOn;
                    _lastModified        = update.Value.LastModified;
                    _status              = update.Value.Status;
                    _documentsTotal      = update.Value.DocumentsTotal;
                    _documentsFailed     = update.Value.DocumentsFailed;
                    _documentsInProgress = update.Value.DocumentsInProgress;
                    _documentsSucceeded  = update.Value.DocumentsSucceeded;
                    _documentsNotStarted = update.Value.DocumentsNotStarted;
                    _documentsCanceled   = update.Value.DocumentsCanceled;

                    if (update.Value.Status == DocumentTranslationStatus.Succeeded ||
                        update.Value.Status == DocumentTranslationStatus.Canceled ||
                        update.Value.Status == DocumentTranslationStatus.Failed)
                    {
                        _hasCompleted = true;
                        _hasValue     = true;
                    }
                    else if (update.Value.Status == DocumentTranslationStatus.ValidationFailed)
                    {
                        DocumentTranslationError error = (DocumentTranslationError)update.Value.Error;
                        _requestFailedException = _diagnostics.CreateRequestFailedException(_response, error.Message, error.ErrorCode.ToString(), CreateAdditionalInformation(error));
                        _hasCompleted           = true;
                        throw _requestFailedException;
                    }
                }
                catch (Exception e)
                {
                    scope.Failed(e);
                    throw;
                }
            }

            return(GetRawResponse());
        }
        public void CopyModelError()
        {
            var sourceClient = CreateFormTrainingClient();
            var targetClient = CreateFormTrainingClient();
            var resourceId   = TestEnvironment.TargetResourceId;
            var region       = TestEnvironment.TargetResourceRegion;

            CopyAuthorization targetAuth = CopyAuthorization.FromJson("{\"modelId\":\"328c3b7d - a563 - 4ba2 - 8c2f - 2f26d664486a\",\"accessToken\":\"5b5685e4 - 2f24 - 4423 - ab18 - 000000000000\",\"expirationDateTimeTicks\":1591932653,\"resourceId\":\"resourceId\",\"resourceRegion\":\"westcentralus\"}");

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() => await sourceClient.StartCopyModelAsync("00000000-0000-0000-0000-000000000000", targetAuth));

            Assert.AreEqual(400, ex.Status);
            Assert.AreEqual("1002", ex.ErrorCode);
        }
        /// <summary>
        /// Determines whether the exception is due to a 404 Not Found error with the error code ContainerNotFound.
        /// </summary>
        /// <param name="exception">The storage exception.</param>
        /// <returns>
        /// <see langword="true"/> if the exception is due to a 404 Not Found error with the error code
        /// ContainerNotFound; otherwise <see langword="false"/>.
        /// </returns>
        public static bool IsNotFoundContainerNotFound(this RequestFailedException exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            if (exception.Status != 404)
            {
                return(false);
            }

            return(exception.ErrorCode == "ContainerNotFound");
        }
        public async Task Get()
        {
            SubscriptionResource subscription = await Client.GetDefaultSubscriptionAsync().ConfigureAwait(false);

            string subscriptionId       = subscription.Id.SubscriptionId;
            SubscriptionResource result = await Client.GetSubscriptions().GetAsync(subscriptionId).ConfigureAwait(false);

            Assert.AreEqual(subscriptionId, result.Id.SubscriptionId);

            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await Client.GetSubscriptions().GetAsync(null).ConfigureAwait(false));
            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() => _ = await Client.GetSubscriptions().GetAsync(new Guid().ToString()).ConfigureAwait(false));

            Assert.AreEqual(404, ex.Status);
        }
        /// <summary>
        /// Determines whether the exception is due to a 409 Conflict error with the error code
        /// LeaseIdMismatchWithLeaseOperation.
        /// </summary>
        /// <param name="exception">The storage exception.</param>
        /// <returns>
        /// <see langword="true"/> if the exception is due to a 409 Conflict error with the error code
        /// LeaseIdMismatchWithLeaseOperation; otherwise <see langword="false"/>.
        /// </returns>
        public static bool IsConflictLeaseIdMismatchWithLeaseOperation(this RequestFailedException exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            if (exception.Status != 409)
            {
                return(false);
            }

            return(exception.ErrorCode == "LeaseIdMismatchWithLeaseOperation");
        }
Пример #17
0
        public async Task ThrowsWhenNoSuggesterName()
        {
            await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this);

            RequestFailedException ex = await CatchAsync <RequestFailedException>(
                async() => await resources.GetQueryClient().AutocompleteAsync(
                    "very po",
                    suggesterName: string.Empty));

            Assert.AreEqual(400, ex.Status);
            StringAssert.StartsWith(
                "Cannot find fields enabled for suggestions. Please provide a value for 'suggesterName' in the query.",
                ex.Message);
        }
Пример #18
0
        public void SetReadOnlySetting()
        {
            var response = new MockResponse(409);

            var mockTransport           = new MockTransport(response);
            ConfigurationClient service = CreateTestService(mockTransport);

            RequestFailedException exception = Assert.ThrowsAsync <RequestFailedException>(async() =>
            {
                ConfigurationSetting setting = await service.SetConfigurationSettingAsync(s_testSetting);
            });

            Assert.AreEqual(409, exception.Status);
        }
        public void AnalyzeOperationWithGenericError()
        {
            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(@"
                {
                    ""displayName"": ""AnalyzeOperationBatchWithErrorTest"",
                    ""jobId"": ""75d521bc-c2aa-4d8a-aabe-713e72d53a2d"",
                    ""lastUpdateDateTime"": ""2021-03-03T22:39:37Z"",
                    ""createdDateTime"": ""2021-03-03T22:39:36Z"",
                    ""expirationDateTime"": ""2021-03-04T22:39:36Z"",
                    ""status"": ""failed"",
                    ""errors"": [
                      {
                        ""code"": ""InternalServerError"",
                        ""message"": ""Some error""
                      }
                    ],
                    ""tasks"": {
                      ""details"": {
                        ""name"": ""AnalyzeOperationBatchWithErrorTest"",
                        ""lastUpdateDateTime"": ""2021-03-03T22:39:37Z""
                      },
                      ""completed"": 0,
                      ""failed"": 1,
                      ""inProgress"": 0,
                      ""total"": 1,
                      ""entityRecognitionTasks"": [
                        {
                          ""lastUpdateDateTime"": ""2021-03-03T22:39:37.1716697Z"",
                          ""taskName"": ""something"",
                          ""state"": ""failed""
                        }
                      ]
                    }
                }"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = stream;

            var mockTransport = new MockTransport(new[] { mockResponse });
            var client        = CreateTestClient(mockTransport);

            var operation = CreateOperation(client);

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() => await operation.UpdateStatusAsync());

            Assert.AreEqual("InternalServerError", ex.ErrorCode);
            Assert.IsTrue(ex.Message.Contains("Some error"));
        }
Пример #20
0
        public async Task StartCreateComposedModelFailsWithInvalidId()
        {
            var client           = CreateFormTrainingClient();
            var trainingFilesUri = new Uri(TestEnvironment.BlobContainerSasUrl);

            await using var trainedModelA = await CreateDisposableTrainedModelAsync(useTrainingLabels : true);

            var modelIds = new List <string> {
                trainedModelA.ModelId, "00000000-0000-0000-0000-000000000000"
            };

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() => await client.StartCreateComposedModelAsync(modelIds, "My composed model"));

            Assert.AreEqual("1001", ex.ErrorCode);
        }
Пример #21
0
        public void GetGenericOperationsWithListOfInvalidResource()
        {
            var ids = new List <string>()
            {
                $"/subscriptions/{TestEnvironment.SubscriptionId}/resourceGroups/non-existent"
            };

            var genericResourceOperationsList = Client.GetGenericResourceOperations(ids);

            foreach (GenericResourceOperations operations in genericResourceOperationsList)
            {
                RequestFailedException exception = Assert.ThrowsAsync <RequestFailedException>(async() => await operations.GetAsync());
                Assert.AreEqual(404, exception.Status);
            }
        }
Пример #22
0
 private bool _handleWebException(BlobClient blob, RequestFailedException err)
 {
     if (err.Status == 404)
     {
         _azureDirectory.CreateContainer();
         using (var stream = new MemoryStream())
             using (var writer = new StreamWriter(stream))
             {
                 writer.Write(_lockFile);
                 blob.Upload(stream);
             }
         return(true);
     }
     return(false);
 }
Пример #23
0
        public void RequestFailedExceptionIsSerializeable()
        {
            var dataContractSerializer = new DataContractSerializer(typeof(RequestFailedException));
            var exception = new RequestFailedException(201, "Message", "Error", null);
            RequestFailedException deserialized;

            using var memoryStream = new MemoryStream();
            dataContractSerializer.WriteObject(memoryStream, exception);
            memoryStream.Position = 0;
            deserialized          = (RequestFailedException)dataContractSerializer.ReadObject(memoryStream);

            Assert.AreEqual(exception.Message, deserialized.Message);
            Assert.AreEqual(exception.Status, deserialized.Status);
            Assert.AreEqual(exception.ErrorCode, deserialized.ErrorCode);
        }
Пример #24
0
        public async Task StartRecognizeCustomFormsFromUriThrowsForNonExistingContent(bool useTrainingLabels)
        {
            var client     = CreateFormRecognizerClient();
            var invalidUri = new Uri("https://idont.ex.ist");

            await using var trainedModel = await CreateDisposableTrainedModelAsync(useTrainingLabels);

            var operation = await client.StartRecognizeCustomFormsFromUriAsync(trainedModel.ModelId, invalidUri);

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() => await operation.WaitForCompletionAsync());

            Assert.AreEqual("2003", ex.ErrorCode);
            Assert.True(operation.HasCompleted);
            Assert.False(operation.HasValue);
        }
Пример #25
0
        public void AnalyzeConversationsInvalidArgument()
        {
            AnalyzeConversationOptions options = new AnalyzeConversationOptions(
                TestEnvironment.ProjectName,
                TestEnvironment.DeploymentName,
                "");

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() =>
            {
                await Client.AnalyzeConversationAsync(options);
            });

            Assert.That(ex.Status, Is.EqualTo(400));
            Assert.That(ex.ErrorCode, Is.EqualTo("InvalidArgument"));
        }
Пример #26
0
        public async Task RegexSpecialCharsUnescapedThrows()
        {
            await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this);

            SearchIndexClient      client = resources.GetQueryClient();
            RequestFailedException ex     = await CatchAsync <RequestFailedException>(
                async() => await client.SearchAsync(
                    @"/.*/.*/",
                    new SearchOptions {
                QueryType = SearchQueryType.Full
            }));

            Assert.AreEqual(400, ex.Status);
            StringAssert.StartsWith("Failed to parse query string at line 1, column 8.", ex.Message);
        }
        public async Task StartTrainingError()
        {
            var client = CreateFormTrainingClient();

            var containerUrl = new Uri("https://someUrl");

            TrainingOperation operation = await client.StartTrainingAsync(containerUrl, useTrainingLabels : false);

            RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>(async() => await operation.WaitForCompletionAsync(PollingInterval));

            Assert.AreEqual("2001", ex.ErrorCode);

            Assert.False(operation.HasValue);
            Assert.Throws <RequestFailedException>(() => operation.Value.GetType());
        }
Пример #28
0
        public static bool IsConflictLeaseIdMismatchWithLeaseOperation(Exception ex)
        {
            RequestFailedException exception = ex as RequestFailedException;

            if (exception == null)
            {
                return(false);
            }
            if (exception.Status != 409)
            {
                return(false);
            }

            return(exception.ErrorCode == "LeaseIdMismatchWithLeaseOperation");
        }
Пример #29
0
        public async Task ThrowsWhenGivenBadSuggesterName()
        {
            await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this);

            string invalidName        = "Invalid suggester";
            RequestFailedException ex = await CatchAsync <RequestFailedException>(
                async() => await resources.GetQueryClient().SuggestAsync(
                    "hotel",
                    invalidName));

            Assert.AreEqual(400, ex.Status);
            StringAssert.StartsWith(
                $"The specified suggester name '{invalidName}' does not exist in this index definition.",
                ex.Message);
        }
        public async Task False_Is_Returned_If_Error_Is_ParentNotFound()
        {
            var ex = new RequestFailedException(
                500,
                "Error",
                ShareErrorCode.ParentNotFound.ToString(),
                null);

            _directory.Setup(s => s.ExistsAsync(It.IsAny <CancellationToken>()))
            .ThrowsAsync(ex);

            var exists = await ClassInTest.ExistsAsync("some-path", CancellationToken.None);

            Assert.That(exists, Is.False);
        }