示例#1
0
        public async Task ValidateAsyncMethodIncludeQueryError(HttpStatusCode statusCode, int resultStatusCode, System.Type resultType)
        {
            // preparation
            var cosmos    = new Mock <ICosmos>();
            var exception = new CosmosException("", statusCode, 0, "", 1.0);

            cosmos.Setup(_ => _.User.ReadItemAsync <UserModel>(It.IsAny <string>(),
                                                               It.IsAny <PartitionKey>(),
                                                               It.IsAny <ItemRequestOptions>(),
                                                               It.IsAny <CancellationToken>()))
            .ThrowsAsync(exception);
            var cryption = new Mock <ICryptionService>();

            cryption.Setup(_ => _.ValidateSecret(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(false);
            var logger   = new Mock <ILogger <ValidationUserService> >();
            var instance = new ValidationUserService(cosmos.Object, cryption.Object, logger.Object);
            var request  = new Mock <HttpRequest>();
            var outValue = new StringValues($"Bearer Value");

            request.Setup(_ => _.Headers.TryGetValue(It.IsAny <string>(), out outValue))
            .Returns(true);
            var user = new Mock <IUser>();

            user.Setup(_ => _.UserUuid)
            .Returns("XXXX");
            // action
            var actual = await instance.ValidateAsync(request.Object, user.Object);

            // assert
            Assert.AreEqual(false, actual.IsValid);
            Assert.IsNull(actual.User);
            Assert.IsInstanceOfType(actual.ErrorActionResult, resultType);
            Assert.AreEqual(resultStatusCode, ((StatusCodeResult)actual.ErrorActionResult).StatusCode);
        }
示例#2
0
        public override async ValueTask <bool> MoveNextAsync()
        {
            this.cancellationToken.ThrowIfCancellationRequested();

            try
            {
                if (!await this.inputStage.MoveNextAsync())
                {
                    this.Current = default;
                    return(false);
                }

                this.Current = this.inputStage.Current;
                return(true);
            }
            catch (OperationCanceledException) when(this.cancellationToken.IsCancellationRequested)
            {
                // Per cancellationToken.ThrowIfCancellationRequested(); line above, this function should still throw OperationCanceledException.
                throw;
            }
            catch (Exception ex)
            {
                CosmosException cosmosException = ExceptionToCosmosException.CreateFromException(ex);
                this.Current = TryCatch <QueryPage> .FromException(cosmosException);

                return(true);
            }
        }
        public async Task <(bool isSuccess, Exception error)> TryCheckpointAsync()
        {
            try
            {
                await this.checkpointer.CheckpointPartitionAsync(this.responseMessage.Headers.ContinuationToken);

                return(isSuccess : true, error : null);
            }
            catch (LeaseLostException leaseLostException)
            {
                // LeaseLost means another instance stole the lease due to load balancing, so the right status is 412
                CosmosException cosmosException = CosmosExceptionFactory.Create(
                    statusCode: HttpStatusCode.PreconditionFailed,
                    message: "Lease was lost due to load balancing and will be processed by another instance",
                    stackTrace: leaseLostException.StackTrace,
                    headers: new Headers(),
                    trace: NoOpTrace.Singleton,
                    error: null,
                    innerException: leaseLostException);
                return(isSuccess : false, error : cosmosException);
            }
            catch (Exception exception)
            {
                return(isSuccess : false, error : exception);
            }
        }
        private static bool TryCreateFromExceptionWithStackTrace(
            ExceptionWithStackTraceException exceptionWithStackTrace,
            ITrace trace,
            out CosmosException cosmosException)
        {
            // Use the original stack trace from the inner exception.
            if (exceptionWithStackTrace.InnerException is Microsoft.Azure.Documents.DocumentClientException ||
                exceptionWithStackTrace.InnerException is CosmosException)
            {
                return(ExceptionToCosmosException.TryCreateFromException(
                           exceptionWithStackTrace.InnerException,
                           trace,
                           out cosmosException));
            }

            if (!ExceptionToCosmosException.TryCreateFromException(
                    exceptionWithStackTrace.InnerException,
                    trace,
                    out cosmosException))
            {
                return(false);
            }

            cosmosException = CosmosExceptionFactory.Create(
                cosmosException.StatusCode,
                cosmosException.Message,
                exceptionWithStackTrace.StackTrace,
                headers: cosmosException.Headers,
                cosmosException.Trace,
                cosmosException.Error,
                cosmosException.InnerException);
            return(true);
        }
        private static async Task <int> CreateItemsAsync(Container container, CancellationToken cancellationToken, IReadOnlyCollection <PricePaidData> itemsToInsert)
        {
            int itemsCreated = 0;

            while (!cancellationToken.IsCancellationRequested)
            {
                List <Task> tasks = new List <Task>(ConcurrentDocuments);
                foreach (PricePaidData item in itemsToInsert)
                {
                    tasks.Add(
                        container.CreateItemAsync <PricePaidData>(item, new PartitionKey(item.pk))
                        .ContinueWith((Task <ItemResponse <PricePaidData> > task) =>
                    {
                        if (!task.IsCompletedSuccessfully)
                        {
                            AggregateException innerExceptions = task.Exception.Flatten();
                            CosmosException cosmosException    = innerExceptions.InnerExceptions.FirstOrDefault(innerEx => innerEx is CosmosException) as CosmosException;
                            Console.WriteLine($"Item {item.Transaction_unique_identifieroperty} failed with status code {cosmosException.StatusCode}");
                        }
                    }));
                }

                await Task.WhenAll(tasks);

                itemsCreated += tasks.Count(task => task.IsCompletedSuccessfully);
            }

            return(itemsCreated);
        }
示例#6
0
        public async Task RemoveSessionData_CustomPartitionKey()
        {
            const string sessionId  = "sessionId";
            const int    ttl        = 1400;
            const int    throughput = 2000;

            byte[] data = new byte[1] {
                1
            };
            const string partitionKeyAttribute = "notTheId";

            CosmosClientBuilder builder = new CosmosClientBuilder(ConfigurationManager.AppSettings["Endpoint"], ConfigurationManager.AppSettings["MasterKey"]);

            IOptions <CosmosCacheOptions> options = Options.Create(new CosmosCacheOptions()
            {
                ContainerName                  = "session",
                DatabaseName                   = CosmosCacheEmulatorTests.databaseName,
                ContainerThroughput            = throughput,
                CreateIfNotExists              = true,
                ClientBuilder                  = builder,
                ContainerPartitionKeyAttribute = partitionKeyAttribute,
            });

            CosmosCache cache = new CosmosCache(options);
            DistributedCacheEntryOptions cacheOptions = new DistributedCacheEntryOptions();

            cacheOptions.SlidingExpiration = TimeSpan.FromSeconds(ttl);
            await cache.SetAsync(sessionId, data, cacheOptions);

            await cache.RemoveAsync(sessionId);

            CosmosException exception = await Assert.ThrowsAsync <CosmosException>(() => this.testClient.GetContainer(CosmosCacheEmulatorTests.databaseName, "session").ReadItemAsync <dynamic>(sessionId, new PartitionKey(sessionId)));

            Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode);
        }
        public static QueryResponseCore CreateFromException(Exception exception)
        {
            QueryResponseCore queryResponseCore;

            if (exception is CosmosException cosmosException)
            {
                queryResponseCore = CreateFromCosmosException(cosmosException);
            }
            else if (exception is Microsoft.Azure.Documents.DocumentClientException documentClientException)
            {
                queryResponseCore = CreateFromDocumentClientException(documentClientException);
            }
            else if (exception is QueryException queryException)
            {
                CosmosException convertedException = queryException.Accept(QueryExceptionConverter.Singleton);
                queryResponseCore = CreateFromCosmosException(convertedException);
            }
            else if (exception is ExceptionWithStackTraceException exceptionWithStackTrace)
            {
                queryResponseCore = QueryResponseFactory.CreateFromExceptionWithStackTrace(exceptionWithStackTrace);
            }
            else
            {
                if (exception.InnerException != null)
                {
                    // retry with the inner exception
                    queryResponseCore = QueryResponseFactory.CreateFromException(exception.InnerException);
                }
                else
                {
                    CosmosException unkownCosmosException = CosmosExceptionFactory.CreateInternalServerErrorException(
                        subStatusCode: default,
示例#8
0
 private QueryResponseCore(
     IReadOnlyList <CosmosElement> result,
     bool isSuccess,
     HttpStatusCode statusCode,
     double requestCharge,
     string activityId,
     IReadOnlyCollection <QueryPageDiagnostics> diagnostics,
     long responseLengthBytes,
     string disallowContinuationTokenMessage,
     string continuationToken,
     CosmosException cosmosException,
     SubStatusCodes?subStatusCode)
 {
     this.IsSuccess           = isSuccess;
     this.CosmosElements      = result;
     this.StatusCode          = statusCode;
     this.ActivityId          = activityId;
     this.Diagnostics         = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics));
     this.ResponseLengthBytes = responseLengthBytes;
     this.RequestCharge       = requestCharge;
     this.DisallowContinuationTokenMessage = disallowContinuationTokenMessage;
     this.ContinuationToken = continuationToken;
     this.CosmosException   = cosmosException;
     this.SubStatusCode     = subStatusCode;
 }
示例#9
0
        private void TraceRequestCharge(CosmosException exception, string what)
        {
            var now = DateTime.UtcNow;

            Trace.TraceEvent(TraceEventType.Verbose, 0,
                             $"{now.ToString("o")} {what}. RU: {exception.RequestCharge}. HTTP: {exception.StatusCode}. Exp: {exception.Message}. Client Elapsed: {exception.Diagnostics.GetClientElapsedTime().TotalSeconds.ToString()}");
        }
示例#10
0
        public void VerifyNegativeCosmosQueryResponseStream()
        {
            string contianerRid  = "mockContainerRid";
            string errorMessage  = "TestErrorMessage";
            string activityId    = "TestActivityId";
            double requestCharge = 42.42;
            CosmosDiagnosticsContext diagnostics     = new CosmosDiagnosticsContextCore();
            CosmosException          cosmosException = CosmosExceptionFactory.CreateBadRequestException(errorMessage, diagnosticsContext: diagnostics);

            diagnostics.GetOverallScope().Dispose();
            QueryResponse queryResponse = QueryResponse.CreateFailure(
                statusCode: HttpStatusCode.NotFound,
                cosmosException: cosmosException,
                requestMessage: null,
                responseHeaders: new CosmosQueryResponseMessageHeaders(
                    null,
                    null,
                    ResourceType.Document,
                    contianerRid)
            {
                RequestCharge = requestCharge,
                ActivityId    = activityId
            },
                diagnostics: diagnostics);

            Assert.AreEqual(HttpStatusCode.NotFound, queryResponse.StatusCode);
            Assert.AreEqual(cosmosException.Message, queryResponse.ErrorMessage);
            Assert.AreEqual(requestCharge, queryResponse.Headers.RequestCharge);
            Assert.AreEqual(activityId, queryResponse.Headers.ActivityId);
            Assert.AreEqual(diagnostics, queryResponse.DiagnosticsContext);
            Assert.IsNull(queryResponse.Content);
        }
示例#11
0
        public async void Post_ClientWithEmptyScope_ReturnsStatusForbidden()
        {
            // Arrange
            string org        = "test";
            string appName    = "app20";
            string requestUri = $"{BasePath}/applications?appId={org}/{appName}";

            Application appInfo = CreateApplication(org, appName);

            CosmosException dex = CreateCosmosExceptionForTesting("Not found", HttpStatusCode.NotFound);

            Mock <IApplicationRepository> applicationRepository = new Mock <IApplicationRepository>();

            applicationRepository.Setup(s => s.FindOne(It.IsAny <string>(), It.IsAny <string>())).ThrowsAsync(dex);
            applicationRepository.Setup(s => s.Create(It.IsAny <Application>())).ReturnsAsync((Application app) => app);

            HttpClient client = GetTestClient(applicationRepository.Object);
            string     token  = PrincipalUtil.GetOrgToken("testorg", scope: string.Empty);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            // Act
            HttpResponseMessage response = await client.PostAsync(requestUri, JsonContent.Create(appInfo, new MediaTypeHeaderValue("application/json")));

            // Assert
            Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
            string content = response.Content.ReadAsStringAsync().Result;

            Assert.True(string.IsNullOrEmpty(content));
        }
示例#12
0
        internal static ResponseMessage AggregateExceptionConverter(AggregateException aggregateException, RequestMessage request)
        {
            AggregateException      innerExceptions    = aggregateException.Flatten();
            DocumentClientException docClientException = (DocumentClientException)innerExceptions.InnerExceptions.FirstOrDefault(innerEx => innerEx is DocumentClientException);

            if (docClientException != null)
            {
                return(docClientException.ToCosmosResponseMessage(request));
            }

            Exception       exception       = innerExceptions.InnerExceptions.FirstOrDefault(innerEx => innerEx is CosmosException);
            CosmosException cosmosException = exception as CosmosException;

            if (cosmosException != null)
            {
                return(new ResponseMessage(
                           headers: cosmosException.Headers,
                           requestMessage: request,
                           errorMessage: cosmosException.Message,
                           statusCode: cosmosException.StatusCode,
                           error: cosmosException.Error));
            }

            return(null);
        }
        public async Task InexistentPKRangeId()
        {
            ContainerInternal container = null;

            try
            {
                // Create a container large enough to have at least 2 partitions
                ContainerResponse containerResponse = await this.database.CreateContainerAsync(
                    id : Guid.NewGuid().ToString(),
                    partitionKeyPath : "/pk");

                container = (ContainerInlineCore)containerResponse;

                string    feedRangeSerialization = JsonConvert.SerializeObject(new { PKRangeId = "10" });
                FeedRange feedRange = FeedRange.FromJsonString(feedRangeSerialization);

                FeedIterator <ToDoActivity> feedIterator = container.GetItemQueryIterator <ToDoActivity>(
                    queryDefinition: new QueryDefinition("select * from T where STARTSWITH(T.id, \"BasicItem\")"),
                    feedRange: feedRange,
                    continuationToken: null);

                CosmosException exception = await Assert.ThrowsExceptionAsync <CosmosException>(() => feedIterator.ReadNextAsync());

                Assert.AreEqual(HttpStatusCode.Gone, exception.StatusCode);
                Assert.AreEqual((int)Documents.SubStatusCodes.PartitionKeyRangeGone, exception.SubStatusCode);
            }
            finally
            {
                await container?.DeleteContainerAsync();
            }
        }
        private static QueryResponseCore CreateFromExceptionWithStackTrace(ExceptionWithStackTraceException exceptionWithStackTrace)
        {
            // Use the original stack trace from the inner exception.
            if (exceptionWithStackTrace.InnerException is DocumentClientException ||
                exceptionWithStackTrace.InnerException is CosmosException)
            {
                return(QueryResponseFactory.CreateFromException(exceptionWithStackTrace.InnerException));
            }

            QueryResponseCore queryResponseCore = QueryResponseFactory.CreateFromException(exceptionWithStackTrace.InnerException);
            CosmosException   cosmosException   = queryResponseCore.CosmosException;

            queryResponseCore = QueryResponseCore.CreateFailure(
                statusCode: queryResponseCore.StatusCode,
                subStatusCodes: queryResponseCore.SubStatusCode,
                cosmosException: CosmosExceptionFactory.Create(
                    statusCode: cosmosException.StatusCode,
                    message: cosmosException.Message,
                    stackTrace: exceptionWithStackTrace.StackTrace,
                    headers: cosmosException.Headers,
                    trace: cosmosException.Trace,
                    error: cosmosException.Error,
                    innerException: cosmosException.InnerException),
                requestCharge: queryResponseCore.RequestCharge,
                activityId: queryResponseCore.ActivityId);

            return(queryResponseCore);
        }
示例#15
0
 private QueryResponseCore(
     IReadOnlyList <CosmosElement> result,
     bool isSuccess,
     HttpStatusCode statusCode,
     double requestCharge,
     string activityId,
     long responseLengthBytes,
     string disallowContinuationTokenMessage,
     string continuationToken,
     CosmosException cosmosException,
     SubStatusCodes?subStatusCode,
     CosmosQueryExecutionInfo cosmosQueryExecutionInfo = default)
 {
     this.IsSuccess           = isSuccess;
     this.CosmosElements      = result;
     this.StatusCode          = statusCode;
     this.ActivityId          = activityId;
     this.ResponseLengthBytes = responseLengthBytes;
     this.RequestCharge       = requestCharge;
     this.DisallowContinuationTokenMessage = disallowContinuationTokenMessage;
     this.ContinuationToken        = continuationToken;
     this.CosmosException          = cosmosException;
     this.SubStatusCode            = subStatusCode;
     this.CosmosQueryExecutionInfo = cosmosQueryExecutionInfo;
 }
        private static CosmosException CreateFromDocumentClientException(Microsoft.Azure.Documents.DocumentClientException documentClientException)
        {
            CosmosException cosmosException = CosmosExceptionFactory.Create(
                documentClientException,
                null);

            return(cosmosException);
        }
示例#17
0
 /// <summary>
 /// Determines if the error is due to a client customer-managed key error
 /// </summary>
 /// <param name="exception">The exception object</param>
 /// <returns>True iff the error is due to client CMK setting.</returns>
 public static bool IsCmkClientError(this CosmosException exception)
 {
     // NOTE: It has been confirmed that a SubStatusCode of value '3', although not listed in
     // https://docs.microsoft.com/en-us/rest/api/cosmos-db/http-status-codes-for-cosmosdb#substatus-codes-for-end-user-issues
     // as a possible CMK SubStatusCode by Cosmos DB, has been acknowledged as a possible value in some scenarios if the custtomer has disabled their key.
     return(exception.StatusCode == HttpStatusCode.Forbidden &&
            (Enum.IsDefined(typeof(KnownCosmosDbCmkSubStatusValueClientIssue), exception.SubStatusCode) || exception.SubStatusCode == 3));
 }
        public override async Task <ResponseMessage> SendAsync(
            RequestMessage request,
            CancellationToken cancellationToken)
        {
            try
            {
                ResponseMessage response = await this.ProcessMessageAsync(request, cancellationToken);

                Debug.Assert(System.Diagnostics.Trace.CorrelationManager.ActivityId != Guid.Empty, "Trace activity id is missing");

                return(response);
            }
            //catch DocumentClientException and exceptions that inherit it. Other exception types happen before a backend request
            catch (DocumentClientException ex)
            {
                Debug.Assert(System.Diagnostics.Trace.CorrelationManager.ActivityId != Guid.Empty, "Trace activity id is missing");
                return(ex.ToCosmosResponseMessage(request));
            }
            catch (CosmosException ce)
            {
                Debug.Assert(System.Diagnostics.Trace.CorrelationManager.ActivityId != Guid.Empty, "Trace activity id is missing");
                return(ce.ToCosmosResponseMessage(request));
            }
            catch (OperationCanceledException ex)
            {
                // Catch Operation Cancelled Exception and convert to Timeout 408 if the user did not cancel it.
                // Throw the exception if the user cancelled.
                if (cancellationToken.IsCancellationRequested)
                {
                    throw;
                }

                Debug.Assert(System.Diagnostics.Trace.CorrelationManager.ActivityId != Guid.Empty, "Trace activity id is missing");
                CosmosException cosmosException = CosmosExceptionFactory.CreateRequestTimeoutException(
                    message: ex.Data?["Message"].ToString(),
                    headers: new Headers()
                {
                    ActivityId = System.Diagnostics.Trace.CorrelationManager.ActivityId.ToString()
                },
                    innerException: ex,
                    trace: request.Trace);
                return(cosmosException.ToCosmosResponseMessage(request));
            }
            catch (AggregateException ex)
            {
                Debug.Assert(System.Diagnostics.Trace.CorrelationManager.ActivityId != Guid.Empty, "Trace activity id is missing");
                // TODO: because the SDK underneath this path uses ContinueWith or task.Result we need to catch AggregateExceptions here
                // in order to ensure that underlying DocumentClientExceptions get propagated up correctly. Once all ContinueWith and .Result
                // is removed this catch can be safely removed.
                ResponseMessage errorMessage = AggregateExceptionConverter(ex, request);
                if (errorMessage != null)
                {
                    return(errorMessage);
                }

                throw;
            }
        }
示例#19
0
        public void CosmosException()
        {
            CosmosException cosmosException = CosmosExceptionFactory.CreateBadRequestException(
                message: "asdf");
            QueryResponseCore queryResponse = QueryResponseFactory.CreateFromException(cosmosException);

            Assert.AreEqual(HttpStatusCode.BadRequest, queryResponse.StatusCode);
            Assert.IsNotNull(queryResponse.CosmosException);
        }
 /// <summary>
 ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
 ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
 ///     any release. You should only use it directly in your code with extreme caution and knowing that
 ///     doing so can result in application failures when updating to a new Entity Framework Core release.
 /// </summary>
 protected override bool ShouldRetryOn(Exception exception)
 {
     return(exception switch
     {
         CosmosException cosmosException => IsTransient(cosmosException.StatusCode),
         HttpException httpException => IsTransient(httpException.Response.StatusCode),
         WebException webException => IsTransient(((HttpWebResponse)webException.Response !).StatusCode),
         _ => false
     });
        public static AsyncPolicyWrap CreateExecutionPolicyWrapper()
        {
            // Following example causes the policy to return a bad request HttpResponseMessage with a probability of 5% if enabled
            var fault = new CosmosException("Simulated cosmos exception", HttpStatusCode.ServiceUnavailable, -1, "", 0);
            AsyncInjectOutcomePolicy injectOutcomePolicy = CreateChaosFaultPolicy <CosmosException>(fault);
            AsyncTimeoutPolicy       timeoutPolicy       = CreateTimeOutPolicy(5, TimeoutStrategy.Pessimistic);

            return(Policy.WrapAsync(timeoutPolicy, injectOutcomePolicy));
        }
 protected bool LogCosmosError(CosmosException e)
 {
     Logger.LogError(e,
                     "InternalDeleteItemAsync: CosmosException {ErrorCode} {StatusCode} {Message}",
                     e.StatusCode,
                     e.SubStatusCode,
                     e.Message);
     return(true);
 }
示例#23
0
    public async Task Startup_ContainerWithUniqueKeyPolicy_CreatesContainerCorrectly()
    {
        try
        {
            //Arrange
            await GetClient().UseClientAsync(PruneDatabases);

            ICosmosClientProvider             clientProvider          = _provider.GetRequiredService <ICosmosClientProvider>();
            IRepository <UniqueKeyPolicyItem> uniqueKeyItemRepository = _provider.GetRequiredService <IRepository <UniqueKeyPolicyItem> >();

            //Act
            Database database = await clientProvider.UseClientAsync(x => x.CreateDatabaseIfNotExistsAsync(BuildDatabaseName(UniquePolicyDb)));

            UniqueKeyPolicyItem bobInYorkshire  = new("bob", 22, "Yorkshire", "Red");
            UniqueKeyPolicyItem bobInDerbyshire = new("bob", 22, "Derbyshire", "Yellow");
            UniqueKeyPolicyItem cannotHaveAnotherBobInYorkshire      = new("bob", 22, "Derbyshire", "Green");
            UniqueKeyPolicyItem jeffFromYorkshireCannotLikeRedAsWell = new("jeff", 40, "Yorkshire", "Red");

            await uniqueKeyItemRepository.CreateAsync(bobInYorkshire);

            await uniqueKeyItemRepository.CreateAsync(bobInDerbyshire);

            //Assert
            ContainerProperties?properties = await GetContainerProperties(database, UniqueKeyPolicyContainerName);

            properties.Should().NotBeNull();
            properties !.UniqueKeyPolicy.UniqueKeys.Count.Should().Be(2);
            properties.UniqueKeyPolicy.UniqueKeys
            .Count(x =>
                   x.Paths.Contains("/firstName") &&
                   x.Paths.Contains("/age") &&
                   x.Paths.Count is 2)
            .Should()
            .Be(1);

            properties.UniqueKeyPolicy.UniqueKeys
            .Count(x =>
                   x.Paths.Contains("/favouriteColor") &&
                   x.Paths.Count is 1)
            .Should()
            .Be(1);

            CosmosException ex = await Assert.ThrowsAsync <CosmosException>(() =>
                                                                            uniqueKeyItemRepository.CreateAsync(cannotHaveAnotherBobInYorkshire).AsTask());

            ex.StatusCode.Should().Be(HttpStatusCode.Conflict);

            ex = await Assert.ThrowsAsync <CosmosException>(() =>
                                                            uniqueKeyItemRepository.CreateAsync(jeffFromYorkshireCannotLikeRedAsWell).AsTask());

            ex.StatusCode.Should().Be(HttpStatusCode.Conflict);
        }
        finally
        {
            await GetClient().UseClientAsync(PruneDatabases);
        }
    }
示例#24
0
        private void ValidateTransportException(CosmosException cosmosException)
        {
            string message = cosmosException.ToString();

            Assert.IsTrue(message.Contains("TransportException: A client transport error occurred: The connection failed"), "StoreResult Exception is missing");
            string diagnostics = cosmosException.Diagnostics.ToString();

            Assert.IsNotNull(diagnostics);
            Assert.IsTrue(diagnostics.Contains("TransportException: A client transport error occurred: The connection failed"));
        }
示例#25
0
        public async Task GetAsync_IdThatDoesNotExist_ThrowsCosmosException()
        {
            //Arrange
            //Act
            //Assert
            CosmosException ex = await Assert.ThrowsAsync <CosmosException>(() =>
                                                                            _personRepository.GetAsync(Guid.NewGuid().ToString()).AsTask());

            Assert.Equal(HttpStatusCode.NotFound, ex.StatusCode);
        }
示例#26
0
        public async Task GetAsync_IdAndPartitionKeyObjectNotFound_ThrowsCosmosException()
        {
            //Arrange
            //Act
            //Assert
            CosmosException ex = await Assert.ThrowsAsync <CosmosException>(() =>
                                                                            _dogRepository.GetAsync(Guid.NewGuid().ToString(), new PartitionKey("cocker-spaniel")).AsTask());

            Assert.Equal(HttpStatusCode.NotFound, ex.StatusCode);
        }
        private void ValidateTransportException(CosmosException cosmosException)
        {
            Assert.AreEqual(HttpStatusCode.ServiceUnavailable, cosmosException.StatusCode);
            string message = cosmosException.ToString();

            Assert.IsTrue(message.Contains("TransportException: A client transport error occurred: The connection failed"), "StoreResult Exception is missing");
            string diagnostics = cosmosException.Diagnostics.ToString();

            Assert.IsNotNull(diagnostics);
            Assert.IsTrue(diagnostics.Contains("TransportException: A client transport error occurred: The connection failed"));
        }
        private static QueryResponseCore CreateFromCosmosException(CosmosException cosmosException)
        {
            QueryResponseCore queryResponseCore = QueryResponseCore.CreateFailure(
                statusCode: cosmosException.StatusCode,
                subStatusCodes: (Microsoft.Azure.Documents.SubStatusCodes)cosmosException.SubStatusCode,
                cosmosException: cosmosException,
                requestCharge: 0,
                activityId: cosmosException.ActivityId);

            return(queryResponseCore);
        }
示例#29
0
        public async Task NotExistentLeaseContainer()
        {
            Container           notFoundContainer = this.cosmosClient.GetContainer(this.database.Id, "NonExistent");
            ChangeFeedProcessor processor         = this.Container
                                                    .GetChangeFeedProcessorBuilder("test", (IReadOnlyCollection <TestClass> docs, CancellationToken token) => Task.CompletedTask)
                                                    .WithInstanceName("random")
                                                    .WithLeaseContainer(notFoundContainer).Build();

            CosmosException exception = await Assert.ThrowsExceptionAsync <CosmosException>(() => processor.StartAsync());

            Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
        }
#pragma warning restore EF1001 // Internal EF Core API usage.

        private Exception ThrowUpdateException(CosmosException exception, IUpdateEntry entry)
        {
            var documentSource = GetDocumentSource(entry.EntityType);
            var id             = documentSource.GetId(entry.SharedIdentityEntry ?? entry);

            throw exception.StatusCode switch
                  {
                      HttpStatusCode.PreconditionFailed => new DbUpdateConcurrencyException(CosmosStrings.UpdateConflict(id), exception, new[] { entry }),
                      HttpStatusCode.Conflict => new DbUpdateException(CosmosStrings.UpdateConflict(id), exception, new[] { entry }),
                      _ => Rethrow(exception),
                  };
        }