protected static async Task <T> PutRequestToApi <T>(string requestUri, T model) { var json = JsonConvert.SerializeObject(model); var response = await HttpRequestFactory.Put(requestUri, model); return(response.ContentAsType <T>()); }
public async Task <IActionResult> Edit([Bind] ScheduledNotificationViewModel scheduledNotificationViewModel) { ScheduledNotificationDTO scheduledNotification = scheduledNotificationViewModel.ScheduledNotification; string url = $"{NotificationsApiUrl}ScheduledNotifications/Update"; var accessToken = await HttpContext.GetTokenAsync("access_token"); var response = await HttpRequestFactory.Put(accessToken, url, scheduledNotification); if (response.StatusCode == HttpStatusCode.OK) { AppContextHelper.SetToastMessage("Scheduled notification has been successfully updated", MessageType.Success, 1, Response); return(RedirectToAction(nameof(Index))); } else { AppContextHelper.SetToastMessage("Failed to update scheduled notification", MessageType.Danger, 1, Response); ModelState.AddModelError("", HttpResponseHandler.Process(response)); } scheduledNotificationViewModel.EscalationRules = await GetEscalationRules(); scheduledNotificationViewModel.NotificationTemplates = await GetNotificationTemplates(); scheduledNotificationViewModel.NotificationChannels = await GetNotificationChannels(); return(View(scheduledNotificationViewModel)); }
public async Task <IActionResult> Edit([Bind] TeamMappingResponse teamMappingResponse) { ResponseTeamMappingDTO responseTeamMember = new ResponseTeamMappingDTO { CreatedBy = teamMappingResponse.CreatedBy, DistrictCode = teamMappingResponse.DistrictCode, MappingId = teamMappingResponse.MappingId, TeamMemberId = teamMappingResponse.TeamMemberId }; string url = $"{CoreApiUrl}ResponseTeamMappings/Update"; var accessToken = await HttpContext.GetTokenAsync("access_token"); var response = await HttpRequestFactory.Put(accessToken, url, responseTeamMember); if (response.StatusCode == HttpStatusCode.OK) { AppContextHelper.SetToastMessage("Response team member mapping has been successfully updated", MessageType.Success, 1, Response); return(RedirectToAction(nameof(Index), new { teamMemberId = _teamMemberId, teamMemberName = _teamMemberName })); } else { AppContextHelper.SetToastMessage("Failed to update response team member mapping", MessageType.Danger, 1, Response); ModelState.AddModelError("", HttpResponseHandler.Process(response)); ViewBag.TeamMemberName = _teamMemberName; } return(View(teamMappingResponse)); }
public async Task <IActionResult> Update(CategoryBookingStatusViewModel model, string saveCommand = null) { if (!ModelState.IsValid) { return(View("CategoryBookingStatusForm", model)); } var entity = new CategoryBookingStatus(); _mapper.Map(model, entity); var response = await HttpRequestFactory.Put(Constants.BaseApiUrl + "CategoryBookingStatus/" + model.Id, entity); var outmodel = response.ContentAsType <SingleModelResponse <CategoryBookingStatus> >(); if (outmodel.DidError || !response.IsSuccessStatusCode) { ViewBag.ErrorMsg = outmodel.ErrorMessage ?? response.ReasonPhrase; return(View("CategoryBookingStatusForm", model)); } AlertShow(); if (saveCommand != Constants.SaveContinute) { return(RedirectToAction("Index")); } model = _mapper.Map(outmodel.Model, model); return(RedirectToAction("Edit", new { id = model.Id })); }
public async Task <IActionResult> Edit([Bind] PatientResponseViewModel patientResponseViewModel) { PatientDTO patient = patientResponseViewModel.PatientResponse; string url = $"{PatientsApiUrl}Update"; var accessToken = await HttpContext.GetTokenAsync("access_token"); var response = await HttpRequestFactory.Put(accessToken, url, patient); if (response.StatusCode == HttpStatusCode.OK) { AppContextHelper.SetToastMessage("Patient has been successfully updated", MessageType.Success, 1, Response); return(RedirectToAction(nameof(Index))); } else { AppContextHelper.SetToastMessage("Failed to update patient", MessageType.Danger, 1, Response); ModelState.AddModelError("", HttpResponseHandler.Process(response)); } patientResponseViewModel.PatientStatuses = await GetPatientStatuses(); patientResponseViewModel.IdentificationTypes = await GetIdentificationTypes(); patientResponseViewModel.TransmissionClassifications = await GetClassifications(); return(View(patientResponseViewModel)); }
public async Task <IActionResult> Edit([Bind] DataCenterResponseViewModel dataCenterResponseViewModel) { DataCenterDTO dataCenter = dataCenterResponseViewModel.DataCenterResponse; string url = $"{CoreApiUrl}DataCenters/Update"; var accessToken = await HttpContext.GetTokenAsync("access_token"); var response = await HttpRequestFactory.Put(accessToken, url, dataCenter); if (response.StatusCode == HttpStatusCode.OK) { AppContextHelper.SetToastMessage("Identification type has been successfully updated", MessageType.Success, 1, Response); return(RedirectToAction(nameof(Index))); } else { AppContextHelper.SetToastMessage("Failed to update identification type", MessageType.Danger, 1, Response); ModelState.AddModelError("", HttpResponseHandler.Process(response)); } dataCenterResponseViewModel.Districts = await GetDistricts(); dataCenterResponseViewModel.FacilityTypes = await GetFacilityTypes(); return(View(dataCenter)); }
/// <summary> /// Deletes the asynchronous. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requestUri">The request URI.</param> /// <param name="value">The value.</param> /// <returns></returns> public async Task <T> PutAsync <T>(string requestUri, object value) { T result = default(T); try { HttpResponseMessage response = await HttpRequestFactory.Put(requestUri, value, this.auth_token, this.dbName); if (response.IsSuccessStatusCode) { return(await response.Content.ReadAsAsync <T>()); } else { var error = response.Content.ReadAsStringAsync().Result; ViewBag.Message = error; TempData["Message"] = error; Utilities.LogAppInformation(this.logger, error); return(result); } } catch (Exception ex) { ModelState.AddModelError("CommonController", ex.Message); ViewBag.Message = ex.Message; TempData["Message"] = ex.Message; Utilities.LogAppError(this.logger, ex); return(result); } }
public ActionResult UpdateUniverso(UniversoUpdateDto dto) { string token = Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.GetTokenAsync(HttpContext, "access_token").Result; var response = HttpRequestFactory.Put(_configuration["Endpoints:Universos"], dto, token).Result; _logger.LogInformation(string.Format("UpdateUniverso: StatusCode:{0} , RequestMessage:{1} ", response.StatusCode, response.RequestMessage)); return(convertMessage(response, response.ContentAsType <UniversoUpdateDto>())); }
public ActionResult RefreshToken(PayloadPost dto) { string token = Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.GetTokenAsync(HttpContext, "access_token").Result; var response = HttpRequestFactory.Put(_configuration["Endpoints:Usuarios"], dto, token).Result; _logger.LogInformation(string.Format("RefreshToken: StatusCode:{0} , RequestMessage:{1} ", response.StatusCode, response.RequestMessage)); return(convertMessage(response, response.ContentAsJson())); }
public async Task WhenISendAnUpdateCategoryRequest() { updateCategoryRequest = new CategoryRequestBuilder() .WithName("Updated Category Name") .WithDescription("Updated Category Description") .Build(); String path = $"{MenuSteps.menuPath}{menuSteps.existingMenuId}{categoryPath}{existingCategoryId}"; lastResponse = await HttpRequestFactory.Put(baseUrl, path, updateCategoryRequest); }
public async Task <T> Update(T model) { var response = await HttpRequestFactory.Put(URI, model); if ((int)response.StatusCode == 200) { return(response.ContentAsType <T>()); } return(null); }
public async Task <bool> UpdaeEventDetails(string token, EventViewModelPost _input) { bool result; var requestUri = $"{HostedUri}"; var response = await HttpRequestFactory.Put(requestUri, _input, token); Console.WriteLine($"Status: {response.StatusCode}"); result = response.ContentAsType <bool>(); return(await Task.Run(() => result)); }
public async Task <bool> UpdateVendorsInvitationStatus(string token, VendorInvitation _input) { bool result; var requestUri = $"{HostedUri}" + "/UpdateVendorsInvitationStatus/"; var response = await HttpRequestFactory.Put(requestUri, _input, token); Console.WriteLine($"Status: {response.StatusCode}"); result = response.ContentAsType <bool>(); return(await Task.Run(() => result)); }
public async Task WhenISendAnUpdateMenuRequest() { updateMenuRequest = new MenuRequestBuilder() .WithName("Updated Menu Name") .WithDescription("Updated Description") .SetEnabled(true) .Build(); lastResponse = await HttpRequestFactory.Put(baseUrl, $"{menuPath}{existingMenuId}", updateMenuRequest); }
private async Task <String> CreateAKSAsync(string servername, string token) { var subscriptionID = "b9049f27-f15e-41ae-8853-8bc37dce9630"; var resourceGroup = "desafio2"; var requestUri = String.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.ContainerService/managedClusters/{2}?api-version=2018-03-31", subscriptionID, resourceGroup, servername); var response = await HttpRequestFactory.Put(requestUri, token); return(response.StatusCode.ToString()); }
public async Task WhenISendAnUpdateItemRequest() { updateItemRequest = new MenuItemBuilder() .WithName("Updated item name") .WithDescription("Updated item description") .WithPrice(4.5) .WithAvailablity(true) .Build(); String path = $"{MenuSteps.menuPath}{existingMenuId}{categoryPath}{existingCategoryId}{itemPath}{existingItemId}"; lastResponse = await HttpRequestFactory.Put(baseUrl, path, updateItemRequest); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } var baseUri = Startup.Configuration["API_URL"]; var requestUri = $"{baseUri}/{this.Movie.Id}"; var response = await HttpRequestFactory.Put(requestUri, this.Movie); return(RedirectToPage("./Index")); }
private static async Task Put() { var model = new MovieInputModel { Id = 4, Title = "again", ReleaseYear = 1990, Summary = "well" }; var requestUrl = $"{baseUrl}"; var response = await HttpRequestFactory.Put(requestUrl, model); }
private static async Task Put() { var model = new MovieModel { Id = 4, Title = "Thunderball-Put", ReleaseYear = 1965, Summary = "James Bond heads to The Bahamas to recover two nuclear warheads stolen by SPECTRE agent Emilio Largo in an international extortion scheme." }; var requestUri = $"{baseUri}/4"; var response = await HttpRequestFactory.Put(requestUri, model); Console.WriteLine($"Status: {response.StatusCode}"); }
public async Task <IActionResult> Create([FromBody] PartnerContactViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } model.UpdateByUser = await GetUserId(User.Identity.Name); model.UpdateDate = DateTime.Now; if (model.Id == 0) { var response = await HttpRequestFactory.Post(Constants.BaseApiUrl + "PartnerContact", model); if (!response.IsSuccessStatusCode) { return(BadRequest(response.StatusCode)); } var outPutModel = response.ContentAsType <SingleModelResponse <PartnerContact> >(); return(Json(new { title = "Thêm thành công!", message = "Dữ liệu đã được lưu.", data = outPutModel.Model })); } else { var response = await HttpRequestFactory.Put(Constants.BaseApiUrl + "PartnerContact/" + model.Id, model); if (!response.IsSuccessStatusCode) { return(BadRequest(response.StatusCode)); } var outPutModel = response.ContentAsType <SingleModelResponse <PartnerContact> >(); return(Json(new { title = "Cập nhật thành công!", message = "Dữ liệu đã được lưu.", data = outPutModel.Model })); } }
public async Task <ResponseMessage> ResponseMessageFromPutUrl(string requestUri, object data) { try { var response = await HttpRequestFactory.Put(requestUri, data, this._httpContextAccessor.HttpContext.Session.GetString(SessionTypes.TOKEN), this._roleCodeController); response.EnsureSuccessStatusCode(); return(JsonConvert.DeserializeObject <ResponseMessage>(await response.Content.ReadAsStringAsync())); } catch (Exception e) { this._errorHandler.WriteToFile(e); } return(new ResponseMessage("-1", this._requestFailMessage)); }
public async Task <IActionResult> Edit([Bind] ResourceDTO resource) { string url = $"{ResourcesApiUrl}Update"; var accessToken = await HttpContext.GetTokenAsync("access_token"); var response = await HttpRequestFactory.Put(accessToken, url, resource); if (response.StatusCode == HttpStatusCode.OK) { AppContextHelper.SetToastMessage("Resource has been successfully updated", MessageType.Success, 1, Response); return(RedirectToAction(nameof(Index))); } else { AppContextHelper.SetToastMessage("Failed to update resource", MessageType.Danger, 1, Response); ModelState.AddModelError("", HttpResponseHandler.Process(response)); } return(View(resource)); }
public async Task <IActionResult> VerifyConfirmPatient(long patientId) { string url = $"{PatientsApiUrl}ConfirmPatient?patientId={patientId}"; var patient = new PatientResponse(); var accessToken = await HttpContext.GetTokenAsync("access_token"); var response = await HttpRequestFactory.Put(accessToken, url, patientId); if (response.StatusCode == HttpStatusCode.OK) { AppContextHelper.SetToastMessage("Patient has been successfully confirmed", MessageType.Success, 1, Response); return(RedirectToAction(nameof(Index))); } else { AppContextHelper.SetToastMessage("Failed to confirm patient", MessageType.Danger, 1, Response); ModelState.AddModelError("", HttpResponseHandler.Process(response)); } return(RedirectToAction(nameof(ConfirmPatient), new { patientId })); }
public async Task <ActionResult> Update(TenantViewModel model) { try { if (ModelState.IsValid) { var requestUri = $"{WebApiBaseUrl}{TenantUpdateEndPoint}"; HttpResponseMessage httpResponseMessage = await HttpRequestFactory.Put(requestUri, model); var response = httpResponseMessage.ContentAsType <ApiResponse>(); if (response.StatusCode == HttpStatusCode.OK) { return(RedirectToAction("Index", "Tenant")); } } return(View(model)); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> Edit([Bind] HealthCareWorkerResponseViewModel healthCareWorkerViewModel) { HealthCareWorkerDTO healthCareWorker = healthCareWorkerViewModel.HealthCareWorkerResponse; string url = $"{CoreApiUrl}HealthCareWorkers/Update"; var accessToken = await HttpContext.GetTokenAsync("access_token"); var response = await HttpRequestFactory.Put(accessToken, url, healthCareWorker); if (response.StatusCode == HttpStatusCode.OK) { AppContextHelper.SetToastMessage("Health care worker has been successfully updated", MessageType.Success, 1, Response); return(RedirectToAction(nameof(Index))); } else { AppContextHelper.SetToastMessage("Failed to update health care worker", MessageType.Danger, 1, Response); ModelState.AddModelError("", HttpResponseHandler.Process(response)); } healthCareWorkerViewModel.IdentificationTypes = await GetIdentificationTypes(); return(View(healthCareWorkerViewModel)); }
public async Task <SessionResponse> ActivateSession(SessionViewModel sessionVM) { var baseUri = PegaUriBaseSession() + "api/session/ActivateSession"; var requestUri = $"{baseUri}"; var httpResponse = await HttpRequestFactory.Put(requestUri, sessionVM); if (!httpResponse.IsSuccessStatusCode) { throw new Exception("Erro ao atualizar sessão."); } var response = httpResponse.Content.ReadAsStringAsync() .Result .Replace("\\", "").Trim(new char[1] { '"' }); // Por algum motivo, o metodo ReadAsStringAsync() está serializando com \\ e "" extras. var session = JsonConvert.DeserializeObject <SessionResponse>(response); return(session); }
public async Task <IActionResult> Update(PartnerViewModel model, string saveCommand = null) { await PreparePartnerGroupList(model); var outputModel = await GetSingle(model.Id); model.PartnerContacts = outputModel.Model.PartnerContacts.ToList(); if (!ModelState.IsValid) { return(View("PartnerForm", model)); } var entity = new PartnerResource(); _mapper.Map(model, entity); entity.UpdateByUser = await GetUserId(User.Identity.Name); entity.UpdateDate = DateTime.Now; var response = await HttpRequestFactory.Put(Constants.BaseApiUrl + "Partner/" + model.Id, entity); var outmodel = response.ContentAsType <SingleModelResponse <PartnerResource> >(); if (outmodel.DidError || !response.IsSuccessStatusCode) { ViewBag.ErrorMsg = outmodel.ErrorMessage ?? response.ReasonPhrase; return(View("PartnerForm", model)); } AlertShow(); if (saveCommand != Constants.SaveContinute) { return(RedirectToAction("Index")); } model = _mapper.Map(outmodel.Model, model); return(RedirectToAction("Edit", new { id = model.Id })); }
public async Task <TResponse> Execute <TResponse>(ApiRequestBase <TResponse> request) where TResponse : ApiResponseBase { if (request.HttpMethod == HttpMethod.Post) { return(await HttpRequestFactory.Post(request.Url, request.GetPostContent(), request.Header, true).ContentToType <TResponse>()); } if (request.HttpMethod == HttpMethod.Put) { return(await HttpRequestFactory.Put(request.Url, request.GetPostContent(), request.Header).ContentToType <TResponse>()); } if (request.HttpMethod == HttpMethod.Get) { return(await HttpRequestFactory.Get(request.Url, request.Header, true).ContentToType <TResponse>()); } if (request.HttpMethod == HttpMethod.Delete) { return(await HttpRequestFactory.Delete(request.Url, request.Header).ContentToType <TResponse>()); } throw new NotSupportedException("不支持的方法"); }
protected static async Task <T> PutRequestToApi <T>(string requestUri, T model) { var response = await HttpRequestFactory.Put(requestUri, model); return(response.ContentAsType <T>()); }
public async Task PutWorks() { var data = new MockData(); await HttpRequestFactory.Put("https://jsonplaceholder.typicode.com/posts/1", data); }