Beispiel #1
0
        public async void DeleteUser(Guid userId)
        {
            var uriString = _apiConfig.IdentityApiUrl + "/api/users/" + userId;
            var response  = await _apiClient.DeleteAsync(uriString);

            response.EnsureSuccessStatusCode();
        }
Beispiel #2
0
 public virtual async Task <RestClientResponse <TResult> > DeleteAsync <TResult>(string route, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var response = HttpClient.DeleteAsync(route, cancellationToken))
     {
         return(await GetRestClientResponseAsync <TResult>(response).ConfigureAwait(false));
     }
 }
Beispiel #3
0
        public async Task <bool> DeleteFridge(int householdId, int fridgeId)
        {
            var response = await httpClient.DeleteAsync($"api/household/{householdId}/fridge/{fridgeId}");

            await localStorageHouseholdService.RemoveFridge(householdId, fridgeId);

            return(response.IsSuccessStatusCode);
        }
Beispiel #4
0
        public async Task DeleteMenuType(int typeId)
        {
            var deleteTypeUri = ApiPaths.Menu.DeleteMenuType(baseUrl, typeId);

            var accessToken = httpContext.HttpContext.User.Claims.Where(x => x.Type == "AcessToken")
                              .Select(x => x.Value).FirstOrDefault();

            await httpClient.DeleteAsync(deleteTypeUri, accessToken);
        }
Beispiel #5
0
        /// <inheritdoc/>
        public async Task DeleteChannelAsync(
            ulong channelId)
        {
            var response = await httpClient.DeleteAsync(
                DiscordApiRoutes.Channel(channelId))
                           .ConfigureAwait(false);

            HandleErrors(response, options);
        }
Beispiel #6
0
        public async Task <ReturnObj> Delete(Guid id)
        {
            var token = await GetUserTokenAsync();

            var response = await _apiClient.DeleteAsync(API.Auth.Delete(_remoteServiceBaseUrl, id), token);

            response.EnsureSuccessStatusCode();
            var result = await response.Content.ReadAsStringAsync();

            return(JsonConvert.DeserializeObject <ReturnObj>(result));
        }
Beispiel #7
0
        public async Task RemoveFromPolicyTests_Pet()
        {
            var addPetToPolicyResult = await _httpClient.PostAsync <Pet, Pet>
                                           (new Uri(_petsBaseUrl),
                                           new Pet
            {
                Name       = "ForDeleteFromIntegration",
                BreedName  = "Maltipoo",
                PetOwnerId = 3
            });

            var addedPet = addPetToPolicyResult.Content;

            addPetToPolicyResult.StatusCode.Should().Be(HttpStatusCode.Created);
            addedPet.Name.Should().Be("ForDeleteFromIntegration");
            addedPet.BreedName.Should().Be("Maltipoo");
            addedPet.PetOwnerId.Should().Be(3);
            addedPet.Archived.Should().Be(false);

            var removePetFromPolicyResult = await _httpClient.DeleteAsync <Pet>
                                                (new Uri(_petsBaseUrl + "/" + addedPet.Id));

            removePetFromPolicyResult.StatusCode.Should().Be(200);
            removePetFromPolicyResult.Content.Should().Be(null);
        }
        public async void DeletePost(Guid postId)
        {
            var uriString = _apiConfig.PostsApiUrl + "/api/posts/" + postId;
            var response  = await _apiClient.DeleteAsync(uriString);

            response.EnsureSuccessStatusCode();
        }
Beispiel #9
0
        public async Task HttpDeleteServices(string url, string token = null)
        {
            GetOriginFromUri(url);
            string errorMsg = string.Empty;

            try
            {
                var response = await _httpClient.DeleteAsync(url, token);

                //if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(responseContent) /* && JsonHelper.IsJson(responseContent)*/)
                    {
                        var result = JsonHelper.ToObject <AjaxResponse>(responseContent);
                        if (result.Success)
                        {
                            return;
                        }
                        errorMsg = result.Error.Message;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"HttpDeleteServices{url}调用其他服务接口错误:{ ex.Message }");
                _logger.Error($"HttpDeleteServices{url}调用其他服务接口错误:{ ex.StackTrace }");
                throw new UserFriendlyException($"HttpDeleteServices{url}调用其他服务接口错误:{ ex.Message }");
            }

            _logger.Error($"HttpDeleteServices{url}调用其他服务接口错误:" + errorMsg);
            throw new UserFriendlyException(errorMsg);
        }
Beispiel #10
0
        public async Task <Response <T> > DeleteRequest <T>(string relativeUri, bool?isNative = null) where T : new()
        {
            isNative = isNative ?? !IsCommercial;
            Uri         uri        = BuildUri(relativeUri, (bool)isNative);
            IHttpClient httpClient = authenticationHelper.IsAuthIntended() ? await GetAuthClient() : await GetClient();

            Response <T> response = new Response <T>();

            try
            {
                string res = await httpClient.DeleteAsync(uri);

                JObject o = JObject.Parse(res);
                if ((bool)o["success"])
                {
                    response.Content = o["data"].ToObject <T>();
                }
                else
                {
                    response.IsError = true;
                    response.Message = o["data"]["error"].ToString();
                }
            }
            catch (Exception ex)
            {
                response.IsError = true;
                response.Error   = ex;
            }
            return(response);
        }
Beispiel #11
0
        public async Task <HttpResponseMessage> SendAsync(HttpRequest request, object content = null)
        {
            var url         = request.GetUrl(_urlBuiler, _baseUrl);
            var jsonContent = content != null?GetJSONStringContent(content) : null;

            if (AuthorizationType == AuthorizationType.BearerToken && !await AddBearerTokenAsync())
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            if (Equals(request.Method.Method, HttpMethod.Get.Method))
            {
                return(await _httpClient.GetAsync(url));
            }

            if (Equals(request.Method.Method, HttpMethod.Post.Method))
            {
                return(await _httpClient.PostAsync(url, jsonContent));
            }

            if (Equals(request.Method.Method, HttpMethod.Put.Method))
            {
                return(await _httpClient.PutAsync(url, jsonContent));
            }

            if (Equals(request.Method.Method, HttpMethod.Delete.Method))
            {
                return(await _httpClient.DeleteAsync(url));
            }

            throw new NotSupportedException("The http method is not supported: " + request.Method.Method);
        }
Beispiel #12
0
        public async Task DeleteAsync(int id)
        {
            var uri      = $"{_remoteServiceBaseUrl}/{id}";
            var response = await _httpClient.DeleteAsync(uri);

            response.EnsureSuccessStatusCode();
        }
Beispiel #13
0
        /// <summary>
        /// Deletes a solutoion.
        /// </summary>
        /// <param name="solutionUniqueName">The unique name of the solution.</param>
        /// <returns>Information regarding the deleted solution.</returns>
        public async Task <DynamicsCrmSolution> DeleteSolutionAsync(string solutionUniqueName)
        {
            DynamicsCrmSolution solution = await GetSolutionAsync(solutionUniqueName);

            if (solution == null)
            {
                return(null);
            }

            LogInformation("Acquiring access token...");
            IHttpClient httpClient = TokenProvider.GetHttpClient(_audience);

            LogInformation($"Deleting solution from Dynamics CRM instance with id '{solution.SolutionId}'...");
            HttpResponseMessage response = await httpClient.DeleteAsync(
                $"{_baseAddress}solutions({solution.SolutionId})");

            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                return(solution);
            }
            else
            {
                LogError($"ERROR: ({response.StatusCode}) {response.ReasonPhrase}");
                throw new RequestException(response);
            }
        }
Beispiel #14
0
        public async Task ClearCart(ApplicationUser user)
        {
            var token = await GetUserTokenAsync();

            var cleanBasketUri = ApiPaths.Basket.CleanBasket(_remoteServiceBaseUrl, user.Email);
            var response       = await _apiClient.DeleteAsync(cleanBasketUri);
        }
Beispiel #15
0
        public async void DeleteImage(Guid imageId)
        {
            var uriString = _apiConfig.ImagesApiUrl + "/api/images/" + imageId;
            var response  = await _apiClient.DeleteAsync(uriString);

            response.EnsureSuccessStatusCode();
        }
Beispiel #16
0
        /// <summary>
        /// Submits the http delete request to the specified uri.
        /// </summary>
        /// <param name="client">The HTTP client to use.</param>
        /// <param name="uri">The uri to which the delete request will be issued.</param>
        /// <returns>Task tracking HTTP completion</returns>
        public static async Task <Stream> DeleteAsync(
            IHttpClient client,
            Uri uri)
        {
            MemoryStream dataStream = null;

            using (HttpResponseMessage response = await client.DeleteAsync(uri).ConfigureAwait(false))
            {
                if (!response.IsSuccessStatusCode)
                {
                    throw await DevicePortalException.CreateAsync(response);
                }

                if (response.Content != null)
                {
                    using (HttpContent content = response.Content)
                    {
                        dataStream = new MemoryStream();

                        await content.CopyToAsync(dataStream).ConfigureAwait(false);

                        // Ensure we return with the stream pointed at the origin.
                        dataStream.Position = 0;
                    }
                }
            }

            return(dataStream);
        }
        public async Task <HttpResponse> DeleteAsync(string requestURI, Dictionary <string, string> headers)
        {
            _logger.LogInformation("Deleting: " + requestURI);

            try
            {
                HttpResponse response = await _inner.DeleteAsync(requestURI, headers);

                _logger.LogDebug("Response: " + response);
                return(await Task.FromResult(response));
            }
            catch (AggregateException ae)
            {
                ae.Handle(ex => {
                    bool handle = ex is HttpRequestException;
                    if (handle)
                    {
                        _logger.LogError(0, ex, "Failed to post the requested resource: ");
                    }
                    return(handle);
                });
            }

            return(await Task.FromResult(new HttpResponse((int)HttpStatusCode.OK, null, string.Empty)));
        }
        public async Task ClearCartForUser(string userID)
        {
            var token = await GetUserTokenAsync();

            string basketURI = ApiPaths.Basket.CleanBasket(remoteServiceBaseUrl, userID);
            await apiClient.DeleteAsync(basketURI, token);
        }
        public async Task DeletePetOwnerTests()
        {
            var enrollResult = await _httpClient.PostAsync <PetOwner, PetOwner>
                                   (new Uri(_baseUrl),
                                   new PetOwner
            {
                Name           = "ForDeleteFromIntegration",
                CountryIsoCode = "ETH",
                Email          = "*****@*****.**"
            });

            var enrollPolicy = enrollResult.Content;

            enrollPolicy.Name.Should().Be("ForDeleteFromIntegration");
            enrollPolicy.CountryIsoCode.Should().Be("ETH");
            enrollPolicy.Email.Should().Be("*****@*****.**");
            enrollPolicy.Archived.Should().Be(false);

            var cancelResult = await _httpClient.DeleteAsync <PetOwner>
                                   (new Uri(_baseUrl + "/" + enrollPolicy.Id));

            var cancelPolicy = cancelResult.Content;

            cancelPolicy.Name.Should().Be("ForDeleteFromIntegration");
            cancelPolicy.CountryIsoCode.Should().Be("ETH");
            cancelPolicy.Email.Should().Be("*****@*****.**");
            cancelPolicy.Archived.Should().Be(true);
        }
Beispiel #20
0
        public async Task DeleteAsync(Guid taskId)
        {
            await AuthoriseAsync(_client, _authenticationService);

            var response = await _client.DeleteAsync(TaskUrls.DeleteTaskUrl(taskId));

            await _proxyHelper.ProcessResponseAsync(response, this);
        }
Beispiel #21
0
        public void Delete(RestRequest request)
        {
            request.VisitClient(client);

            using (var response = client.DeleteAsync(request.Url).Result)
            {
                VerifyResponse(response);
            }
        }
        public async Task CleanBasket(ApplicationUser user)
        {
            var token = await GetUserTokenAsync();

            var cleanBasketUri = API.Basket.CleanBasket(_remoteServiceBaseUrl, user.Id);

            var response = await _apiClient.DeleteAsync(cleanBasketUri, token);

            //CCE: response status code...
        }
Beispiel #23
0
        public async Task <bool> Delete(int id)
        {
            var url = API.Game.DeleteGame(_enderecoRemoto, id);

            var authorizationToken = await GetUserTokenAsync();

            var response = await _apiClient.DeleteAsync(url, authorizationToken);

            return(response.IsSuccessStatusCode);
        }
Beispiel #24
0
        public async Task <bool> DeleteAsync(int id)
        {
            var response = await client.DeleteAsync(delete + id);

            if (response.IsSuccessAndNotNull())
            {
                return(await ReadWithFormatter <bool>(response));
            }
            return(false);
        }
Beispiel #25
0
        /// <summary>
        /// Sends an HTTP request to the server and handles the response.
        /// </summary>
        /// <param name="verb">The HTTP verb to use for the request.</param>
        /// <param name="urlParameter">Any URL parameters to send.</param>
        /// <param name="bodyParameter">Any body parameters to send.</param>
        /// <returns>The HTTP Response information.</returns>
        /// <exception cref="System.NotImplementedException">Thrown when the HTTP verb given has not been
        /// implemented yet.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when the request was already sent by
        /// the client instance or the URI is invalid.</exception>
        public async Task <HttpResponse> Send(HttpVerb verb, IHttpRequestParameter urlParameter = null, IHttpRequestParameter bodyParameter = null)
        {
            string              fullRequestUrl  = $"{_requestUrl}{ConstructParameterString(urlParameter)}";
            HttpContent         content         = new StringContent(ConstructParameterString(bodyParameter));
            HttpResponseMessage responseMessage = null;

            try
            {
                switch (verb)
                {
                case HttpVerb.DELETE:
                    responseMessage = await _httpClient.DeleteAsync(fullRequestUrl);

                    break;

                case HttpVerb.GET:
                    responseMessage = await _httpClient.GetAsync(fullRequestUrl);

                    break;

                case HttpVerb.POST:
                    responseMessage = await _httpClient.PostAsync(fullRequestUrl, content);

                    break;

                case HttpVerb.PUT:
                    responseMessage = await _httpClient.PutAsync(fullRequestUrl, content);

                    break;

                default:
                    throw new NotImplementedException($"HTTP Verb not implemented: {verb.ToString()}");
                }
            }
            catch (HttpRequestException ex)
            {
                string error = ExceptionUtilities.GetAllExceptionMessages(ex);
                return(new HttpResponse(
                           fullRequestUrl,
                           System.Net.HttpStatusCode.InternalServerError,
                           error,
                           verb
                           ));
            }

            string responseBody = await responseMessage.Content.ReadAsStringAsync();

            return(new HttpResponse(
                       fullRequestUrl,
                       responseMessage.StatusCode,
                       responseBody,
                       verb
                       ));
        }
Beispiel #26
0
        public async Task ClearCart(ApplicationUser user)
        {
            var token = await GetUserTokenAsync();

            var cleanBasketUri = ApiPaths.Basket.CleanBasket(_remoteServiceBaseUrl, user.Id);

            _logger.LogDebug("Clean Basket uri : " + cleanBasketUri);
            var response = await _apiClient.DeleteAsync(cleanBasketUri);

            _logger.LogDebug("Basket cleaned");
        }
Beispiel #27
0
        public async Task CleanBasket(ApplicationUser user)
        {
            var context = _httpContextAccesor.HttpContext;
            var token   = await context.Authentication.GetTokenAsync("access_token");

            _apiClient.Inst.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            var basketUrl = $"{_remoteServiceBaseUrl}/{user.Id}";
            var response  = await _apiClient.DeleteAsync(basketUrl);

            //CCE: response status code...
        }
        public static async Task <T> DeleteAsJsonAsync <T>(this IHttpClient httpClient, string uri)
        {
            T result;

            using (HttpResponseMessage responce = await httpClient.DeleteAsync(uri))
            {
                using (HttpContent content = responce.Content)
                {
                    result = await ReadAsJsonAsync <T>(responce.Content);
                }
            }
            return(result);
        }
        /// <summary>
        /// Internal callback helper
        /// </summary>
        /// <param name="client"></param>
        /// <param name="payload"></param>
        /// <param name="query"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        internal static Task CallAsync(IHttpClient client, JToken payload,
                                       string query, CallbackModel model)
        {
            var builder = new UriBuilder(model.Uri);

            if (!string.IsNullOrEmpty(query))
            {
                if (string.IsNullOrEmpty(builder.Query))
                {
                    builder.Query = "?";
                }
                else
                {
                    builder.Query += "&";
                }
                builder.Query += query;
            }
            var request = client.NewRequest(builder.Uri);

            if (!string.IsNullOrWhiteSpace(model.AuthenticationHeader))
            {
                request.AddHeader("Authentication", model.AuthenticationHeader);
            }
            switch (model.Method)
            {
            case CallbackMethodType.Put:
                if (payload != null)
                {
                    request.SetContent(payload);
                }
                return(client.PutAsync(request));

            case CallbackMethodType.Delete:
                return(client.DeleteAsync(request));

            case CallbackMethodType.Get:
                return(client.GetAsync(request));

            case CallbackMethodType.Post:
                if (payload != null)
                {
                    request.SetContent(payload);
                }
                return(client.PostAsync(request));

            default:
                return(Task.FromException(new ArgumentException("bad method value",
                                                                nameof(model.Method))));
            }
        }
Beispiel #30
0
        public void Signal(Node input)
        {
            if (input.Children.Count() > 1 || input.Children.Any((x) => x.Name != "token"))
            {
                throw new ApplicationException("[http.delete.json] can only handle one [token] child node");
            }

            var url   = input.GetEx <string>(_signaler);
            var token = input.Children.FirstOrDefault((x) => x.Name == "token")?.GetEx <string>(_signaler);

            // Notice, to sanity check the result we still want to roundtrip through a JToken result.
            input.Value = _httpClient.DeleteAsync <string>(url, token).Result;
            input.Clear();
        }