Example #1
0
        /// <inheritdoc />
        /// <summary>
        /// Uninitializes the Chroma SDK by sending a DELETE request to <c>/</c>.
        /// </summary>
        /// <returns>A <see cref="Task" /> representing the asynchronous operation.</returns>
        /// <exception cref="RestException">Thrown if there is an error calling the REST API.</exception>
        /// <exception cref="ApiException">Thrown if the SDK responds with an error code.</exception>
        public async Task UninitializeAsync()
        {
            var response = await _client.DeleteAsync <SdkResponse>("/").ConfigureAwait(false);

            if (!response.IsSuccessful)
            {
                Log.Error("Chroma SDK uninitialization failed");
                throw new RestException(
                          "Failed to uninitialize Chroma REST API",
                          response.Data?.Result ?? Result.RzFailed,
                          new Uri(_client.BaseAddress, "/"),
                          response.Status,
                          response.Data?.ToString());
            }

            var data = response.Data;

            if (data == null)
            {
                throw new ApiException("Uninitialize API returned NULL response");
            }

            if (!data.Result)
            {
                throw new ApiException("Exception when calling uninitialize API", data.Result);
            }

            Log.Debug("Stopping heartbeat timer");
            _heartbeatTimer.Change(Timeout.Infinite, Timeout.Infinite);
        }
        public async Task Should_Throw_Should_Throw_ArgumentException_If_Path_Is_Null_Or_Empty()
        {
            IRestClient _restClient = CreateRestClient();

            await Assert.ThrowsAsync <ArgumentNullException>(() => _restClient.DeleteAsync <DeleteUserResponse>(null)).ConfigureAwait(false);

            await Assert.ThrowsAsync <ArgumentException>(() => _restClient.DeleteAsync <DeleteUserResponse>(string.Empty)).ConfigureAwait(false);
        }
Example #3
0
        // AJAX: /ShoppingCart/RemoveFromCart/5
        public async Task <IActionResult> RemoveFromCart(int id, CancellationToken requestAborted)
        {
            // Remove from cart
            await _IRestClient.DeleteAsync($"{baseUrl}/Basket/{_cookieLogic.GetBasketId()}/item/{id}");

            TempData[ToastrMessage.Success] = "Successfully Removed Song";

            return(RedirectToAction("Index"));
        }
        /// <summary>
        /// Execute request
        /// </summary>
        /// <param name="values">List of parameters for request (content)</param>
        /// <returns>RestResponse</returns>
        public async Task <RestResponse <T> > Execute(IEnumerable <KeyValuePair <string, string> > values)
        {
            HttpContent content = null;

            if (values != null)
            {
                if (values is Dictionary <string, string> )
                {
                    content = new StringContent(JsonConvert.SerializeObject(values), Encoding.UTF8, "application/json");
                }
                else
                {
                    content = new FormUrlEncodedContent(values);
                }
            }

            HttpResponseMessage message = null;

            switch (_method)
            {
            case Method.GET:
                message = await _client.GetAsync(_path);

                break;

            case Method.POST:
                message = await _client.PostAsync(_path, content);

                break;

            case Method.PUT:
                message = await _client.PutAsync(_path, content);

                break;

            case Method.DELETE:
                if (content == null)
                {
                    message = await _client.DeleteAsync(_path);
                }
                else
                {
                    message = await _client.DeleteAsync(_path, content);
                }
                break;
            }

            RestResponse <T> response = new RestResponse <T>(message);

            return(response);
        }
        public async Task DeleteAsync_ExecutesRetryPolicyAsExpected()
        {
            // Expect the parameters to be passed to the method of the inner rest client.
            // We'll throw an exception from within the callback method to trigger retries.
            this.mockRestClient
            .Setup(c => c.DeleteAsync(
                       It.Is <EndpointName>(e => e.Equals(this.endpointName)),
                       It.Is <IEnumerable <int> >(j => j.Equals(this.deleteIds)),
                       It.Is <LogContext>(l => l.Equals(this.logContext)),
                       It.IsAny <CancellationToken>()))
            .Callback((EndpointName en, IEnumerable <int> di, LogContext lc, CancellationToken ct)
                      => throw new ServiceUnavailableException("Something went wrong."));

            try
            {
                IRestClient restClient = GetRestClientWithRetries();
                await restClient.DeleteAsync(this.endpointName, this.deleteIds, this.logContext, default);

                Assert.Fail("Expected exception to be thrown.");
            }
            catch (ServiceUnavailableException)
            {
            }

            // Verify our inner rest client was called 4 times (original invocation + retries)
            this.mockRestClient.Verify(m => m.DeleteAsync(this.endpointName, this.deleteIds, this.logContext, default),
                                       Times.Exactly(RetryCount + 1));
        }
        public async Task DeleteAsync_FailsOnFirstTryWhenExceptionIsNotHandledByPolicy()
        {
            // Expect the parameters to be passed to the method of the inner rest client.
            // We'll throw an exception from within the callback method to trigger retries.
            this.mockRestClient
            .Setup(c => c.DeleteAsync(
                       It.Is <EndpointName>(e => e.Equals(this.endpointName)),
                       It.Is <IEnumerable <int> >(j => j.Equals(this.deleteIds)),
                       It.Is <LogContext>(l => l.Equals(this.logContext)),
                       It.IsAny <CancellationToken>()))
            .Callback((EndpointName en, IEnumerable <int> di, LogContext lc, CancellationToken ct)
                      => throw new BadRequestException("Bad request."));

            try
            {
                IRestClient restClient = GetRestClientWithRetries();
                await restClient.DeleteAsync(this.endpointName, this.deleteIds, this.logContext, default);

                Assert.Fail("Expected exception to be thrown.");
            }
            catch (BadRequestException)
            {
            }

            // Verify our inner rest client was called exactly once.
            this.mockRestClient.Verify(m => m.DeleteAsync(this.endpointName, this.deleteIds, this.logContext, default),
                                       Times.Once);
        }
        public async Task Should_Return_DeleteUserResponse()
        {
            const string path    = "/api/users/[email protected]";
            const string content = "{\"msg\": \"test message\",\"code\": \"Success\"}";

            IRestClient _restClient = CreateRestClient(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(content)
            });

            ApiResponse <DeleteUserResponse> apiResponse = await _restClient.DeleteAsync <DeleteUserResponse>(path).ConfigureAwait(false);

            Assert.NotNull(apiResponse);
            Assert.Equal(HttpStatusCode.OK, apiResponse.HttpStatusCode);
            Assert.Equal(path, apiResponse.UrlPath);
            Assert.NotNull(apiResponse.Headers);
            Assert.Equal(1, apiResponse.Headers.Count);
            Assert.NotNull(apiResponse.Model);
            Assert.IsType <DeleteUserResponse>(apiResponse.Model);
            Assert.Equal("test message", apiResponse.Model.Msg);
            Assert.Equal("Success", apiResponse.Model.Code);

            VerifyRestClient(Times.Once(), HttpMethod.Delete, path);
        }
        public async Task Should_Throw_ArgumentException_If_Request_Is_Null_Or_Empty()
        {
            const string path        = "/api/users/delete";
            IRestClient  _restClient = CreateRestClient();

            await Assert.ThrowsAsync <ArgumentNullException>(() => _restClient.DeleteAsync <DeleteUserResponse>(path, null)).ConfigureAwait(false);
        }
Example #9
0
        public Task CancelComputationAsync(ApiSession apiSession, string computationId, CancellationToken cancellationToken)
        {
            if (apiSession == null)
            {
                throw new ArgumentNullException(nameof(apiSession));
            }
            if (computationId == null)
            {
                throw new ArgumentNullException(nameof(computationId));
            }

            var spaceName = apiSession.SpaceName;
            var url       = UrlHelper.JoinUrl("space", spaceName, "computations", computationId);

            return(apiClient.DeleteAsync <NoContentRequest>(url, null, apiSession.ToHeadersCollection(), cancellationToken));
        }
Example #10
0
 public static Task <T> DeleteAsync <T>(
     this IRestClient client,
     string requestUri,
     CancellationToken cancellationToken = default)
 {
     return(client.DeleteAsync <T>(new Uri(requestUri), cancellationToken));
 }
Example #11
0
        private async Task ExecuteDeleteCommand()
        {
            if (!await _dialog.DisplayAlertAsync($"Delete {AlterEgo}", "Are you sure?", "Cancel", "OK"))
            {
                return;
            }

            IsBusy = true;

            try
            {
                var status = await _client.DeleteAsync($"superheroes/{Id}");

                if (status != HttpStatusCode.NoContent)
                {
                    await _dialog.DisplayAlertAsync("Error", $"Error from api: {status}", "OK");
                }
                else
                {
                    _messaging.Send(this, DeleteSuperhero, Id);

                    await _navigation.BackAsync();
                }
            }
            catch (Exception e)
            {
                await _dialog.DisplayAlertAsync(e);
            }

            IsBusy = false;
        }
Example #12
0
        public async Task <IResult> DeleteCustomer(Guid customerId)
        {
            if (customerId == null || customerId == Guid.Empty)
            {
                throw new UnableToUpdateCustomerDetailsException(
                          $"Unable To Updated customer details for customer. No details provided.");
            }
            try
            {
                using (var request = CreateRequestMessage())
                {
                    request.Headers.Remove("version");
                    request.Headers.Add("version", _dssSettings.Value.DigitalIdentitiesPatchByCustomerIdApiVersion);

                    _logger.LogInformation($"call to {_dssSettings.Value.DigitalIdentitiesPatchByCustomerIdApiUrl.Replace(CustomerIdTag, customerId.ToString())} made");
                    _logger.LogInformation($" Request contains the following headers{string.Join(",", request.Headers)}");

                    await _restClient.DeleteAsync(
                        apiPath : $"{_dssSettings.Value.DigitalIdentitiesPatchByCustomerIdApiUrl.Replace(CustomerIdTag, customerId.ToString())}", request);
                }

                if (!_restClient.LastResponse.IsSuccess)
                {
                    throw new UnableToUpdateCustomerDetailsException(
                              $"Unable To Updated customer details for customer {customerId}, Response {_restClient.LastResponse.Content}");
                }

                return(Result.Ok());
            }
            catch (Exception e)
            {
                throw new UnableToUpdateCustomerDetailsException(
                          $"Unable To Updated customer details for customer {customerId}, Response {_restClient.LastResponse.Content}");
            }
        }
        public async Task <IActionResult> RemoveCart()
        {
            var basketId = Request.Query["id"];

            await _IRestClient.DeleteAsync($"{baseUrl}/Basket/{basketId}");

            TempData[ToastrMessage.Success] = "Successfully Removed Shopping Cart";

            return(RedirectToAction("Index"));
        }
Example #14
0
        public async Task <Todo> DeleteAsync(Todo todo)
        {
            RestRequest restRequest = new RestRequest("/" + todo.Id);

            restRequest.AddHeader("Content-Type", "application/json");

            var response = await restClient.DeleteAsync <Todo>(restRequest);

            return(response);
        }
Example #15
0
        public async Task <IActionResult> DeleteLineItem(string basketId, int productId)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var correlationToken = CorrelationTokenManager.GenerateToken();

            // Note: Sending querystring parameters in the post.
            var success = await client.DeleteAsync(ServiceEnum.Basket,
                                                   $"api/basket/{basketId}/lineitem/{productId}?correlationToken={correlationToken}");

            if (success)
            {
                return(NoContent());
            }

            return(NotFound());
        }
Example #16
0
            public async Task <Unit> Handle(Request request, CancellationToken cancellationToken)
            {
                if (request == null)
                {
                    throw new ArgumentNullException(nameof(request));
                }
                var restRequest = new RestRequest(new Uri(string.Format(DeleteUserUrlFormat, request.Id), UriKind.Relative));
                var response    = await restClient.DeleteAsync <ApiResult <User> >(restRequest, cancellationToken).ConfigureAwait(false);

                response.GetResult(HttpStatusCode.NoContent);
                return(Unit.Value);
            }
        private IObservable <Unit> ObserveDelete()
        {
            return(DeleteCommand.ActivateGestures()
                   .SelectMany(x => _restClient.DeleteAsync(Url).ToObservable(), (x, y) => y)
                   .Take(1)
                   .AsUnit()
                   .Catch <Unit, Exception>(x =>
            {
                _schedulerService.Dispatcher.Schedule(() => _messageService.Post(Constants.UI.ExceptionTitle, _exceptionFactory(x)));

                return ObserveDelete();
            }));
        }
        public async Task <IActionResult> DeleteLineItem(string basketId, int productId)
        {
            var correlationToken = CorrelationTokenManager.GenerateToken();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Note: Sending querystring parameters in the post.
            var success = await _restClient.DeleteAsync(ServiceEnum.Basket,
                                                        $"api/basket/{basketId}/lineitem/{productId}", correlationToken);

            if (!success)
            {
                _logger.LogError(LoggingEvents.Checkout, $"Could not delete line item {productId} for Basket {basketId} for Request {correlationToken}");
                return(BadRequest($"Could not delete line item {productId} for Basket {basketId} for Request {correlationToken}"));
            }

            _logger.LogInformation(LoggingEvents.DeleteLineItem, $"Basket: Line item deleted for correlationToken: {correlationToken}");

            return(NoContent());
        }
        private async Task ExecuteDeleteCommand()
        {
            // TODO: Implement confirm dialog

            IsBusy = true;

            await _client.DeleteAsync($"superheroes/{Id}");

            _messaging.Send(this, DeleteSuperhero, Id);

            await _navigation.BackAsync();

            IsBusy = false;
        }
Example #20
0
    public async void CrudAsync_NewUser_Success()
    {
        // Create.
        User            original = DataFactory.RandomUser;
        Response <User> created  = await _client.PostAsync <User, User>(content : original);

        Assert.Equal(HttpStatusCode.Created, created.StatusCode);
        Assert.NotNull(created.Data);
        Assert.NotNull(created.Data.Id);
        Assert.Equal(original.Email, created.Data.Email);
        Assert.Equal(original.FirstName, created.Data.FirstName);
        Assert.Equal(original.LastName, created.Data.LastName);
        _output.WriteLine($"Created new user:\n{created.Data.ToJson()}");

        // Retrieve single.
        Response <User> retrieved = await _client.GetAsync <User>(created.Data.Id);

        Assert.Equal(HttpStatusCode.OK, retrieved.StatusCode);
        Assert.NotNull(retrieved.Data);
        Assert.Equal(created.Data.Id, retrieved.Data.Id);
        _output.WriteLine($"Retrieved newly created user:\n{retrieved.ToJson()}");

        // Update.
        const string newMiddleName = "Perry";
        User         retrievedUser = retrieved.Data;

        retrievedUser.MiddleNames = newMiddleName;
        Response updatedResponse = await _client.PutAsync(retrievedUser.Id, retrievedUser);

        Assert.Equal(HttpStatusCode.OK, updatedResponse.StatusCode);

        Response <User> updated = await _client.GetAsync <User>(retrievedUser.Id);

        Assert.Equal(HttpStatusCode.OK, updated.StatusCode);
        Assert.NotNull(updated.Data);
        Assert.Equal(retrievedUser.Id, updated.Data.Id);
        Assert.Equal(newMiddleName, updated.Data.MiddleNames);
        _output.WriteLine($"Updated the MiddleNames property of the newly created user:\n{updated.ToJson()}");

        // Delete.
        Response deleteResponse = await _client.DeleteAsync(created.Data.Id);

        Assert.Equal(HttpStatusCode.OK, deleteResponse.StatusCode);

        Response headResponse = await _client.HeadAsync(created.Data.Id);

        Assert.Equal(HttpStatusCode.NotFound, headResponse.StatusCode);
        _output.WriteLine($"Successfully deleted user {created.Data.Id}.");
    }
Example #21
0
        /// <summary>
        /// Remove previously uploaded payload
        /// </summary>
        /// <returns>True if successfully removed from server</returns>
        public async Task <bool> RemovePayloadAsync()
        {
            if (payloadID.HasValue)
            {
                var request  = new RestRequest($"payload/{payloadID.Value}");
                var response = await client.DeleteAsync <bool>(request);

                if (response)
                {
                    payloadID = null;
                }
                return(response);
            }
            return(true);
        }
        public void should_delete_xml_object()
        {
            // ARRANGE
            var url = new Uri(_baseUrl + "/api/employees/1");

            // ACT
            var task = _xmlRestClient.DeleteAsync(url);

            task.Wait();

            var response = task.Result;

            // ASSIGN
            Assert.That(response, Is.Not.Null);
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
        }
        public async Task<BaseResponse<bool>> HandleAsync(DeleteAccountCommand command, CancellationToken cancellationToken)
        {
            var endpoint = $"{command.Id}";
            var baseResponse = new BaseResponse<bool>()
            {
                StatusCode = HttpStatusCode.OK,
                Errors = string.Empty,
                IsSuccess = true,
                Result = true
            };

            var response = await _restClient.DeleteAsync(endpoint);

            if (response != HttpStatusCode.NoContent)
            {
                _logger.LogError($"DeleteCommandHandler/DeleteAsync returned {response}");
            }

            return baseResponse;
        }
        public async Task DeleteAsync_SucceedsOnFirstTryWhenNoExceptionIsThrown()
        {
            // Expect the parameters to be passed to the method of the inner rest client.
            // We'll throw an exception from within the callback method to trigger retries.
            this.mockRestClient
            .Setup(c => c.DeleteAsync(
                       It.Is <EndpointName>(e => e.Equals(this.endpointName)),
                       It.Is <IEnumerable <int> >(j => j.Equals(this.deleteIds)),
                       It.Is <LogContext>(l => l.Equals(this.logContext)),
                       It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult("Done."));

            IRestClient restClient = GetRestClientWithRetries();

            string result = await restClient.DeleteAsync(this.endpointName, this.deleteIds, this.logContext, default);

            Assert.AreEqual(SuccessResult, result, $"Expected result: '{SuccessResult}'.");

            // Verify our inner rest client was called only once.
            this.mockRestClient.Verify(m => m.DeleteAsync(this.endpointName, this.deleteIds, this.logContext, default),
                                       Times.Once);
        }
Example #25
0
 public async Task <RestResponse> Delete(Guid id)
 {
     return(await _restClient.DeleteAsync($"posts/{id}"));
 }
Example #26
0
 public async Task DeleteAsync()
 {
     await _restClient.DeleteAsync("api/test/1");
 }
Example #27
0
        public async Task <ApiResponse <DeleteUserResponse> > DeleteByEmailAsync(string email)
        {
            Ensure.ArgumentNotNullOrEmptyString(email, nameof(email));

            return(await _client.DeleteAsync <DeleteUserResponse>($"/api/users/{email}").ConfigureAwait(false));
        }
Example #28
0
 public async Task DeleteAsync(string url)
 {
     var requestUri = Client.BuildUri(url);
     await Client.DeleteAsync <object>(requestUri, null, resource : ResourceName).ConfigureAwait(false);
 }
        public Task Delete(int Id)
        {
            var urlstring = url + "/" + 0 + "/" + Id;

            return(_restClient.DeleteAsync <Offer>(urlstring));
        }
Example #30
0
        public async Task <bool> RemoveItem(int productId)
        {
            var response = await _restClient.DeleteAsync($"{baseUrl}/Basket/{GetBasketId()}/item/{productId}");

            return(response.Data);
        }