public async Task <List <SupportActivityDetail> > GetRegistrationFormSupportActivities(RegistrationFormVariant registrationFormVariant, CancellationToken cancellationToken) { GetRegistrationFormSupportActivitiesRequest request = new GetRegistrationFormSupportActivitiesRequest() { RegistrationFormVariantRequest = new RegistrationFormVariantRequest() { RegistrationFormVariant = registrationFormVariant } }; string path = $"api/GetRegistrationFormSupportActivities"; var jsonContent = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"); using (HttpResponseMessage response = await _httpClientWrapper.PostAsync(HttpClientConfigName.GroupService, path, jsonContent, cancellationToken).ConfigureAwait(false)) { string jsonResponse = await response.Content.ReadAsStringAsync(); var emailSentResponse = JsonConvert.DeserializeObject <ResponseWrapper <GetRegistrationFormSupportActivitiesResponse, CommunicationServiceErrorCode> >(jsonResponse); if (emailSentResponse.HasContent && emailSentResponse.IsSuccessful) { return(emailSentResponse.Content.SupportActivityDetails); } else { throw new Exception($"Unable to retrieve support activities for registration form"); } } }
public async Task <List <User> > PostUsersForListOfUserID(List <int> UserIDs) { List <User> result = new List <User>(); string path = $"/api/PostUsersForListOfUserID"; string absolutePath = $"{path}"; PostUsersForListOfUserIDRequest postUsersForListOfUserIDRequest = new PostUsersForListOfUserIDRequest() { ListUserID = new ListUserID() { UserIDs = UserIDs } }; string json = JsonConvert.SerializeObject(postUsersForListOfUserIDRequest, Formatting.Indented); var httpContent = new StringContent(json); using (HttpResponseMessage response = await _httpClientWrapper.PostAsync(HttpClientConfigName.UserService, path, httpContent, CancellationToken.None).ConfigureAwait(false)) { string jsonResponse = await response.Content.ReadAsStringAsync(); var postUsersForListOfUserIDResponse = JsonConvert.DeserializeObject <ResponseWrapper <PostUsersForListOfUserIDResponse, UserServiceErrorCode> >(jsonResponse); if (postUsersForListOfUserIDResponse.HasContent && postUsersForListOfUserIDResponse.IsSuccessful) { return(postUsersForListOfUserIDResponse.Content.Users); } else { throw new System.Exception(postUsersForListOfUserIDResponse.Errors.ToString()); } } }
/// <summary> /// Create payment and send request to "bank" of card details with amount /// </summary> /// <param name="payment"></param> /// <returns></returns> public async Task <bool> CreatePaymentAsync(PaymentDto payment) { Log.Information($"Connecting with bank to process payment"); using (var req = _httpClient.PostAsync(_bankUri, new StringContent(JsonConvert.SerializeObject(new UserModel()).ToString(), Encoding.UTF8, "application/json"))) { var bankResponse = await req; switch (bankResponse.StatusCode) { case HttpStatusCode.OK: Log.Information("Payment has been successfully made"); var result = await bankResponse.Content.ReadAsStringAsync(); payment.Uid = result; payment.State = PaymentState.Completed; // Insert payment into database var res = _db.Insert(payment) > 0; if (!res) { Log.Error("Unknown error occured when inserting payment into DB"); return(false); } break; default: _ = bankResponse.Headers.TryGetValues("TraceIdentifier", out var tridVal) ? tridVal : null; Log.Error($"Unknown error code with status code: {bankResponse.StatusCode} and TraceIdentifier: {tridVal}"); return(false); } } return(true); }
public async Task <NotificationStatusEntity> SendNotification(NotificationEntity entity) { // Get user access tokens var subscriptionEntity = _repository.GetSubscription(entity.Username).ToSubscriptionEntity(); // Send notification var headers = new Dictionary <string, string>(); var content = JsonConvert.SerializeObject(new { body = entity.NoteText, title = entity.NoteTitle, type = "note" }); var stringContent = new StringContent(content, Encoding.UTF8, "application/json"); stringContent.Headers.Add("Access-Token", subscriptionEntity.AccessToken); var response = await _httpClient.PostAsync(_pushUrl, null, stringContent); if (!response.IsSuccessStatusCode) { return(new NotificationStatusEntity { IsSent = false, StatusText = "Unable to send notification" }); } subscriptionEntity.TotalNotificationsPushed++; // Update subscription _repository.Update(subscriptionEntity.ToSubscriptionDataModel()); return(new NotificationStatusEntity { IsSent = true, StatusText = "Success" }); }
public async System.Threading.Tasks.Task <IEnumerable <int> > GenerateRandomNumbersAsync(Settings settings) { var requestBuilder = new GenerateIntegersRequestBuilder(); GenerateIntegersRequest request = requestBuilder .AddJsonRpc("2.0") .AddMethod("generateIntegers") .AddApiKey(_apiKey) .AddNumberOfIntegers(settings.NumberOfIntegers) .AddMinimalValue(settings.MinimalIntValue) .AddMaximumValue(settings.MaximumIntValue) .AddReplacement(true) .AddBase(10) .AddId(1) .Build(); string json = JsonConvert.SerializeObject(request); var httpContent = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage httpResponse = await _httpClient.PostAsync(_apiUrl, httpContent); string responseString = await httpResponse.Content.ReadAsStringAsync(); GenerateIntegersResponse response = JsonConvert.DeserializeObject <GenerateIntegersResponse>(responseString); return(response.result.random.data); }
public async Task SaveToDoItemAsync(ToDoItem item, bool isNewItem = false) { try { string jsonItem = JsonConvert.SerializeObject(item); StringContent content = new StringContent(jsonItem, Encoding.UTF8, JsonMediaType); string requestUri = string.Format(Constants.ToDoApiUri, string.Empty); HttpResponseMessage response = null; if (isNewItem) { response = await _client.PostAsync(requestUri, content); } else { response = await _client.PutAsync(requestUri, content); } if (response.IsSuccessStatusCode) { Debug.WriteLine("TodoItem successfully saved."); } } catch (Exception ex) { Debug.WriteLine($"Error occurred calling ToDoApi: {ex.Message}"); } }
private void Post(Job job) { _log.Debug($"[JobId={job.JobId}] [MessageText=Sending HTTP POST request to {job.CallbackUrl}.]"); var content = new StringContent(job.Payload, Encoding.UTF8, job.ContentType); var request = _client.PostAsync(job.CallbackUrl, content).Result; request.EnsureSuccessStatusCode(); }
/// <summary> /// Sends a POST request. /// </summary> /// <typeparam name="TResult">Assumed type of response.</typeparam> /// <param name="url">Request URL.</param> /// <param name="jsonData">Request JSON body.</param> /// <returns>Response object.</returns> private async Task <TResult> PostAsync <TResult>(string url, string jsonData) where TResult : class, new() { using var content = new StringContent(jsonData, Encoding.UTF8, "application/json"); using var response = await _httpClient.PostAsync(url, content).ConfigureAwait(false); return(await ProcessResponseAsync <TResult>(response).ConfigureAwait(false)); }
public TResponse PostJson <TRequest, TResponse>(TRequest request, string path) { var stringContent = new StringContent( JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"); var uri = BuildHttpClientUri( GatewayHost, $"{GatewayApiPath}/{path}", GatewayPort); var response = Send <TResponse>(async() => await _client .PostAsync(uri, stringContent) .ConfigureAwait(false)); return(response); }
public async Task <bool> RequestCommunication(RequestCommunicationRequest request, CancellationToken cancellationToken) { string path = $"api/RequestCommunication"; var jsonContent = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"); using (HttpResponseMessage response = await _httpClientWrapper.PostAsync(HttpClientConfigName.CommunicationService, path, jsonContent, cancellationToken).ConfigureAwait(false)) { string jsonResponse = await response.Content.ReadAsStringAsync(); var requestCommunicationResponse = JsonConvert.DeserializeObject <ResponseWrapper <RequestCommunicationResponse, CommunicationServiceErrorCode> >(jsonResponse); if (requestCommunicationResponse.HasContent && requestCommunicationResponse.IsSuccessful) { return(requestCommunicationResponse.Content.Success); } return(false); } }
public async Task <GetPostcodeCoordinatesResponse> GetPostcodeCoordinates(GetPostcodeCoordinatesRequest getPostcodeCoordinatesRequest) { string json = JsonConvert.SerializeObject(getPostcodeCoordinatesRequest); StringContent data = new StringContent(json, Encoding.UTF8, "application/json"); using (HttpResponseMessage response = await _httpClientWrapper.PostAsync(HttpClientConfigName.AddressService, "/api/GetPostcodeCoordinates", data, CancellationToken.None)) { string jsonResponse = await response.Content.ReadAsStringAsync(); var sendEmailResponse = JsonConvert.DeserializeObject <ResponseWrapper <GetPostcodeCoordinatesResponse, AddressServiceErrorCode> >(jsonResponse); if (sendEmailResponse.HasContent && sendEmailResponse.IsSuccessful) { return(sendEmailResponse.Content); } } return(null); }
public async Task <GetLocationsResponse> GetLocations(GetLocationsRequest request) { string path = $"/api/GetLocations"; string absolutePath = $"{path}"; var jsonContent = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"); using (HttpResponseMessage response = await _httpClientWrapper.PostAsync(HttpClientConfigName.AddressService, absolutePath, jsonContent, CancellationToken.None).ConfigureAwait(false)) { string jsonResponse = await response.Content.ReadAsStringAsync(); var getJobsResponse = JsonConvert.DeserializeObject <ResponseWrapper <GetLocationsResponse, AddressServiceErrorCode> >(jsonResponse); if (getJobsResponse.HasContent && getJobsResponse.IsSuccessful) { return(getJobsResponse.Content); } return(null); } }
public async Task <Order> PostOrder(Order order) { var content = new StringContent(JsonConvert.SerializeObject(order), Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync($"https://localhost:44395/api/orders", content); var result = await response.Content.ReadAsStringAsync(); return(order); }
public async Task SaveSelectedSectorsAsync_CallsApi() { // arrange SaveSelectedSectorsDto dto = SaveSelectedSectorsDtoBuilder.Build(); string endpoint = "endPoint"; configuration[EndPoints.Api.SaveSelectedSectors].Returns(endpoint); // act await sectorService.SaveSelectedSectorsAsync(dto); // assert await httpClient.PostAsync <SaveSelectedSectorsDto>(endpoint, dto); }
public async Task <ActionResult <SubjectLectureModel> > PostLecture(Guid id, SubjectLectureModel subjectLectureModel) { subjectLectureModel.SubjectId = id; var subjectLectureModelJson = JsonConvert.SerializeObject(subjectLectureModel); var response = await _httpClientWrapper.PostAsync($"http://localhost:1000/api/v1/Lectures", new StringContent(subjectLectureModelJson, Encoding.UTF8, "application/json")); if (response.IsSuccessStatusCode) { var jsonString = await response?.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject <SubjectLectureModel>(jsonString); return(result); } return(BadRequest("Error occurred during execution")); }
public async Task <TResult> PostAsync <TResult, TBody>(string apiUrl, TBody body) where TResult : class where TBody : class { EnsureRequiredArgumentsAndAction(apiUrl, body); var dataAsString = JsonSerializer.Serialize(body); var content = new StringContent(dataAsString, Encoding.UTF8, "application/json"); var httpResponse = await _httpClientWrapper.PostAsync(GetCompleteApiUrl(apiUrl, '?'), content); var stream = await ReadAndReturnResponseStream(httpResponse); return(await JsonSerializer.DeserializeAsync <TResult>(stream)); }
public async Task <Instructions> GetGroupSupportActivityInstructions(int groupId, SupportActivities supportActivity) { GetGroupSupportActivityInstructionsRequest request = new GetGroupSupportActivityInstructionsRequest() { GroupId = groupId, SupportActivityType = new SupportActivityType() { SupportActivity = supportActivity } }; string json = JsonConvert.SerializeObject(request); StringContent data = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await _httpClientWrapper.PostAsync(HttpClientConfigName.GroupService, "/api/GetGroupSupportActivityInstructions", data, CancellationToken.None); string str = await response.Content.ReadAsStringAsync(); var deserializedResponse = JsonConvert.DeserializeObject <ResponseWrapper <GetGroupSupportActivityInstructionsResponse, GroupServiceErrorCode> >(str); if (deserializedResponse.HasContent && deserializedResponse.IsSuccessful) { return(deserializedResponse.Content.Instructions); } throw new Exception("Bad response from GetGroupSupportActivityInstructions"); }
public async Task CreateImposterAsync(Imposter imposter, CancellationToken cancellationToken = default) { var json = JsonConvert.SerializeObject(imposter); using ( var response = await _httpClient.PostAsync( ImpostersResource, new StringContent(json), cancellationToken ).ConfigureAwait(false)) { await HandleResponse(response, HttpStatusCode.Created, $"Failed to create the imposter with port {imposter.Port} and protocol {imposter.Protocol}.").ConfigureAwait(false); await HandleDynamicPort(response, imposter).ConfigureAwait(false); } }
public async Task <string> GetTranslation( string textToTranslate, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(textToTranslate)) { throw new ArgumentNullException("Value cannot be null or whitespace.", nameof(textToTranslate)); } var payload = CreatePostPayload(textToTranslate); var response = await _httpClientWrapper.PostAsync(Api, payload, cancellationToken).ConfigureAwait(false); var translationResponse = await ReadTranslationResponse(response).ConfigureAwait(false); return(translationResponse?.Contents is null ? default : ParseDuplicatedWhitespaces(translationResponse)); }
/// <summary> /// Extracts data from a transcription. /// </summary> /// <param name="transcript">The transcript to extract data from.</param> /// <param name="log">Trace logging instance.</param> /// <returns>A Task returning the data extracted from the transcription.</returns> public async Task<TranscriptionData> ExtractAsync(string transcript, ILogger log) { try { Uri requestUri = new Uri($"{_config.NlpEndpoint}&subscription-key={_config.NlpSubscriptionKey.Value}"); byte[] buffer = Encoding.UTF8.GetBytes($"\"{transcript}\""); ByteArrayContent content = new ByteArrayContent(buffer); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = await _httpClient.PostAsync(requestUri.AbsoluteUri, content, log); if (response.StatusCode != HttpStatusCode.OK) { // TODO: Throw a better exception throw new Exception("Request failed!"); } string responseContent = await response.Content.ReadAsStringAsync(); LuisResponse luisResponse = JsonConvert.DeserializeObject<LuisResponse>(responseContent); TranscriptionData data = new TranscriptionData(); data.EvaluatedTranscription = transcript; if (luisResponse.TopScoringIntent != null) { data.Intent = luisResponse.TopScoringIntent.Intent; data.IntentConfidence = luisResponse.TopScoringIntent.Score; } data.Dates = ExtractDateTimes(luisResponse, log); data.Location = ExtractLocation(luisResponse, log); data.Person = ExtractPerson(luisResponse, log); data.AdditionalData = EnumerateAdditionalEntities(luisResponse, log); return data; } catch (HttpRequestException ex) { throw new DataExtractorException("Exception encountered extracting data! See inner exception for details.", ex); } }
public async Task <ProviderResponseWrapper> ReallocatedRemovedOrderStock(List <string> reallocatedStockList) { try { HttpClient client = new HttpClient(); string requestURI = "http://localhost:52772/api/Stock/UpdateStockAddAllocation"; for (int x = 0; x < reallocatedStockList.Count; x++) { // How to get rid of this? var content = new StringContent(""); HttpResponseMessage response = await _httpClient.PostAsync($"{requestURI}/?body={reallocatedStockList[x]}", content); } return(prwBuilderHelper.PRWBuilder("Order Successfully Removed", HTTPResponseCodes.HTTP_OK_RESPONSE)); } catch (Exception ex) { return(prwBuilderHelper.PRWBuilder(ex.ToString(), HTTPResponseCodes.HTTP_SERVER_FAILURE_RESPONSE)); } }
/// <summary> /// Calls the dynamic service and returns the result. /// </summary> /// <param name="serviceInfo">Information about the service to call</param> /// <param name="cacheRegion">The cache region to look for values for post parameters under in</param> /// <param name="cancellationToken">Cancellation token to cancel the request</param> /// <param name="additionalParameters">Additional post parameters to include in the request body</param> /// <returns>A service response representing the result of the call to the dynamic service</returns> protected override async Task <ServiceResponse> CallServiceInternal(CalledServiceInfo serviceInfo, string cacheRegion, CancellationToken cancellationToken, IEnumerable <KeyValuePair <string, string> > additionalParameters) { var serviceResponse = new ServiceResponse { ServiceId = serviceInfo.Id }; try { AsyncPolicyWrap <ServiceResponse> breaker = GetCircuitBreakerPolicy(serviceInfo); return(await breaker.ExecuteAsync(async (cancelToken) => { IEnumerable <KeyValuePair <string, string> > postParameters = GetPostParameters(serviceInfo, cacheRegion, additionalParameters); HttpClientResponse response = await _httpClientWrapper.PostAsync(serviceInfo.Endpoint, postParameters, cancelToken); if (response.HttpStatusCode.IsOkStatus()) { serviceResponse.Value = response.Response; serviceResponse.Status = ServiceResponseStatus.Success; serviceResponse.TokenResponses = _tokenService.ParseTokens(cacheRegion, response.Response, serviceInfo.Tokens).ToArray(); } else { serviceResponse.Status = ServiceResponseStatus.Error; } return serviceResponse; }, cancellationToken : cancellationToken)); } catch (Exception) { serviceResponse.Status = ServiceResponseStatus.Error; return(serviceResponse); } }
public async Task <GetPostcodeCoordinatesResponse> GetPostcodeCoordinatesAsync(GetPostcodeCoordinatesRequest getPostcodeCoordinatesRequest, CancellationToken cancellationToken) { string path = $"api/GetPostcodeCoordinates"; var streamContent = HttpContentUtils.SerialiseToJsonAndCompress(getPostcodeCoordinatesRequest); ResponseWrapper <GetPostcodeCoordinatesResponse, AddressServiceErrorCode> getPostcodeCoordinatesResponseWithWrapper; using (HttpResponseMessage response = await _httpClientWrapper.PostAsync(HttpClientConfigName.AddressService, path, streamContent, cancellationToken).ConfigureAwait(false)) { response.EnsureSuccessStatusCode(); Stream stream = await response.Content.ReadAsStreamAsync(); getPostcodeCoordinatesResponseWithWrapper = await Utf8Json.JsonSerializer.DeserializeAsync <ResponseWrapper <GetPostcodeCoordinatesResponse, AddressServiceErrorCode> >(stream, StandardResolver.AllowPrivate); } if (!getPostcodeCoordinatesResponseWithWrapper.IsSuccessful) { throw new Exception($"Calling Address Service GetPostcodeCoordinatesAsync endpoint unsuccessful: {getPostcodeCoordinatesResponseWithWrapper.Errors.FirstOrDefault()?.ErrorMessage}"); } return(getPostcodeCoordinatesResponseWithWrapper.Content); }
private HttpResponseMessage ExecutePost(string resource, string json) => _httpClient.PostAsync(resource, new StringContent(json)).Result;
public async Task <decimal> GetLowestTrolleyTotal(TrolleyTotalRequest trolleyRequest) { return(await _httpClientWrapper.PostAsync <decimal, TrolleyTotalRequest>(trolleyRequest, _connectionSettings.BaseUrl, $"/api/resource/trolleyCalculator?token={_connectionSettings.Token}")); }
/// <summary> /// This method performs the call to the cached service if no value is available in the cache. /// </summary> /// <param name="serviceInfo">Information about the service to call</param> /// <param name="cacheRegion">The cache region to look for an existing response and to look for values for post parameters under in</param> /// <param name="cancellationToken">Cancellation token to cancel the request</param> /// <param name="additionalParameters">Additional post parameters to include in the request body</param> /// <returns>A service response representing the result of the call to the cached service</returns> protected override async Task <ServiceResponse> CallServiceInternal(CalledServiceInfo serviceInfo, string cacheRegion, CancellationToken cancellationToken, IEnumerable <KeyValuePair <string, string> > additionalParameters) { SemaphoreSlim semaphore = _semaphores.GetOrAdd($"{cacheRegion}-{serviceInfo.CacheKey}", _ => new SemaphoreSlim(1, 1)); try { await semaphore.WaitAsync(cancellationToken); if (cancellationToken.IsCancellationRequested) { return(new ServiceResponse { ServiceId = serviceInfo.Id, Status = ServiceResponseStatus.Timeout }); } CacheEntry <string> cacheResult = Cache.Get <string>(cacheRegion, serviceInfo.CacheKey); if (cacheResult != null) { Log.Debug("Read value for service {ServiceName} from cache. Entry has value: {HasValue}", serviceInfo.Name, cacheResult.Value != null); ServiceResponse serviceResponse = new ServiceResponse { ServiceId = serviceInfo.Id, Status = ServiceResponseStatus.Success, Value = cacheResult.Value }; if (string.IsNullOrEmpty(serviceResponse.Value)) { return(serviceResponse); } serviceResponse.TokenResponses = _tokenService.ParseTokens(cacheRegion, cacheResult.Value, serviceInfo.Tokens); foreach (TokenResponse token in serviceResponse.TokenResponses) { Cache.Set(cacheRegion, token.CacheKey, token.Value); } return(serviceResponse); } AsyncPolicyWrap <ServiceResponse> breaker = GetCircuitBreakerPolicy(serviceInfo); return(await breaker.ExecuteAsync(async (cancelToken) => { IEnumerable <KeyValuePair <string, string> > postParameters = GetPostParameters(serviceInfo, cacheRegion, additionalParameters); HttpClientResponse response = await _httpClientWrapper.PostAsync(serviceInfo.Endpoint, postParameters, cancelToken); var serviceResponse = new ServiceResponse { ServiceId = serviceInfo.Id }; if (response.HttpStatusCode.IsOkStatus()) { serviceResponse.Value = response.Response; serviceResponse.Status = ServiceResponseStatus.Success; serviceResponse.TokenResponses = _tokenService.ParseTokens(cacheRegion, response.Response, serviceInfo.Tokens); foreach (TokenResponse token in serviceResponse.TokenResponses) { Cache.Set(cacheRegion, token.CacheKey, token.Value); } Cache.Set(cacheRegion, serviceInfo.CacheKey, response.Response); } else { Cache.Set <string>(cacheRegion, serviceInfo.CacheKey, null); serviceResponse.Status = ServiceResponseStatus.Error; } return serviceResponse; }, cancellationToken : cancellationToken)); } catch (TaskCanceledException) { return(new ServiceResponse { ServiceId = serviceInfo.Id, Status = ServiceResponseStatus.Timeout }); } finally { if (semaphore.CurrentCount == 0) { semaphore.Release(); } } }
public async Task SaveSelectedSectorsAsync(SaveSelectedSectorsDto selectedSectorDto) { string saveSelectedSectorsUrl = configuration[EndPoints.Api.SaveSelectedSectors]; await httpClient.PostAsync <SaveSelectedSectorsDto>(saveSelectedSectorsUrl, selectedSectorDto); }
public async Task <RuleApiModel> CreateAsync(RuleApiModel rule) { return(await httpClient.PostAsync <RuleApiModel>(uri, rule, "monitoring rules")); }
private Task <HttpResponseMessage> ExecutePostAsync(string resource, string json) => _httpClient.PostAsync(resource, new StringContent(json));