public async Task <IActionResult> Put(Guid?id, [FromBody] ValueViewModel vm) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!id.HasValue || id == Guid.Empty || vm == null || vm.Version == null) { return(CreateInvalidRequestResult()); } var updateCommand = new UpdateValueCommand { Id = id.GetValueOrDefault(), Version = vm.Version.Value.GetValueOrDefault(), UpdateNameCmd = vm.Name != null ? new UpdateNameChildCmd(vm.Name.Value) : null, UpdateValueCmd = vm.Value != null ? new UpdateValueChildCmd(vm.Value.Value) : null, // NOTE: Let the user not modify the code directly, // TODO: We should provide an alternative way to modify the value code //UpdateCodeCmd = vm.Code != null ? new UpdateCodeChildCmd(vm.Code.Value) : null, }; var result = await _mediator.Send(updateCommand); if (result.Success) { var updatedVm = ToViewModel(result.Model); return(Ok(updatedVm)); } else { return(CreateBadRequestResult(result)); } }
public async Task <IActionResult> Post([FromBody] ValueViewModel request) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var createCommand = new CreateValueCommand { TenantId = request.TenantId?.Value, Name = request.Name.Value, Code = request.Code.Value, Value = request.Value.Value }; var result = await _mediator.Send(createCommand); if (result.Success) { var vm = ToViewModel(result.Model); return(Created($"~/api/values/{vm.Id}", vm)); } else { return(CreateBadRequestResult(result)); } }
public override void execute() { List <ValueViewModel> list = ApiRef.ApiValuesGet().ToList(); ImplUtil.PrintList(list); Console.WriteLine("Getting Value By Id (2)"); ValueViewModel model = ApiRef.ApiValuesByIdGet(2); Console.WriteLine("Id: " + model.Id + " Name: " + model.Name + " Value: " + model.Value); Console.WriteLine("Creating New Value"); ValueViewModel tmpModel = new ValueViewModel { Id = 6, Name = "Test", Value = 6 }; ApiRef.ApiValuesPost(tmpModel); list = ApiRef.ApiValuesGet().ToList(); ImplUtil.PrintList(list); Console.WriteLine("Updating Value (3)"); model.Name = "Ten"; model.Value = 10; ApiRef.ApiValuesByIdPut(2, model); list = ApiRef.ApiValuesGet().ToList(); ImplUtil.PrintList(list); Console.WriteLine("Deleting Value (4)"); ApiRef.ApiValuesByIdDelete(4); list = ApiRef.ApiValuesGet().ToList(); ImplUtil.PrintList(list); }
public IActionResult Post(int listId, [FromBody] ValueViewModel data) { return(Ok(new IdViewModel() { Id = _todoService.AddItem(listId, data.Value), })); }
public async Task <IActionResult> Put(string name, [FromBody] ValueViewModel value) { try { IReliableDictionary <string, string> dictionary = await this.stateManager.GetOrAddAsync <IReliableDictionary <string, string> >(ValuesDictionaryName); using (ITransaction tx = this.stateManager.CreateTransaction()) { await dictionary.AddAsync(tx, name, value.Value); await tx.CommitAsync(); } } catch (ArgumentException) { return(new ContentResult { StatusCode = 400, Content = $"A value with name {name} already exists." }); } catch (FabricNotPrimaryException) { return(new ContentResult { StatusCode = 503, Content = "The primary replica has moved. Please re-resolve the service." }); } catch (FabricException) { return(new ContentResult { StatusCode = 503, Content = "The service was unable to process the request. Please try again." }); } return(this.Ok()); }
public IActionResult Post([FromBody] ValueViewModel model) { ValueGenerator.Insert(model); CreatedAtRouteResult result = CreatedAtRoute("GetValue", new { controller = "Value", id = model.Id }, model); return(result); }
public IActionResult Post([FromBody] ValueViewModel data) { return(Ok(new IdViewModel() { Id = _todoService.AddList(data.Value), })); }
public ActionResult CreateValue(ValueSet set) { var model = new ValueViewModel { Set = set }; return(PartialView(model)); }
public async Task <ActionResult> GetApiValues() { ViewBag.Title = "Values"; var regularClient = OidcClient.GetClient(IdentityConstants.APIRegular); var secretClient = OidcClient.GetClient(IdentityConstants.APISecret); var publicValues = await regularClient.GetAsync("values/PublicValues") .ConfigureAwait(false); var managementValues = await regularClient.GetAsync("values/ManagementValues") .ConfigureAwait(false); var recruitmentValues = await regularClient.GetAsync("values/RecruitmentValues") .ConfigureAwait(false); var secretValues = await secretClient.GetAsync("values/SecretValues") .ConfigureAwait(false); var valuesAsString = await publicValues.Content.ReadAsStringAsync() .ConfigureAwait(false); var secretAsString = await secretValues.Content.ReadAsStringAsync() .ConfigureAwait(false); var managementAsString = await managementValues.Content.ReadAsStringAsync() .ConfigureAwait(false); var recruitmentAsString = await recruitmentValues.Content.ReadAsStringAsync() .ConfigureAwait(false); var publicValuesDeserialized = publicValues.IsSuccessStatusCode ? JsonConvert.DeserializeObject <List <string> >(valuesAsString) : null; var secretValuesDeserialized = secretValues.IsSuccessStatusCode ? JsonConvert.DeserializeObject <List <string> >(secretAsString) : null; var managementValuesDeserialized = managementValues.IsSuccessStatusCode ? JsonConvert.DeserializeObject <List <string> >(managementAsString) : null; var recruitmentValuesDeserialized = recruitmentValues.IsSuccessStatusCode ? JsonConvert.DeserializeObject <List <string> >(recruitmentAsString) : null; var vm = new ValueViewModel(publicValuesDeserialized, secretValuesDeserialized, managementValuesDeserialized, recruitmentValuesDeserialized, publicValues.IsSuccessStatusCode, secretValues.IsSuccessStatusCode, managementValues.IsSuccessStatusCode, recruitmentValues.IsSuccessStatusCode); return(View("Index", vm)); }
public IActionResult GetValues() { // call backend var response = _service.GetValueFromApi(); // create view model var model = new ValueViewModel(response); return(View(model)); }
public override void execute() { List <ValueViewModel> list = new List <ValueViewModel>(); Task.Run(() => { var response = ApiRef.ApiValuesGetAsync(); list = response.Result.ToList(); }).Wait(); ImplUtil.PrintList(list); Console.WriteLine("Getting Value By Id (2)"); ValueViewModel model = new ValueViewModel(); Task.Run(() => { var response = ApiRef.ApiValuesByIdGetAsync(2); model = response.Result; }).Wait(); Console.WriteLine("Id: " + model.Id + " Name: " + model.Name + " Value: " + model.Value); Console.WriteLine("Creating New Value"); ValueViewModel tmpModel = new ValueViewModel { Id = 6, Name = "Test", Value = 6 }; Task.Run(() => { var response = ApiRef.ApiValuesPostAsync(tmpModel); }).Wait(); list = ApiRef.ApiValuesGet().ToList(); ImplUtil.PrintList(list); Console.WriteLine("Updating Value (3)"); model.Name = "Ten"; model.Value = 10; Task.Run(() => { var response = ApiRef.ApiValuesByIdPutAsync(2, model); }).Wait(); list = ApiRef.ApiValuesGet().ToList(); ImplUtil.PrintList(list); Console.WriteLine("Deleting Value (4)"); Task.Run(() => { var response = ApiRef.ApiValuesByIdDeleteAsync(4); }).Wait(); list = ApiRef.ApiValuesGet().ToList(); ImplUtil.PrintList(list); }
public override object Copy(IDictionary <object, object>?shared) { var copy = new ValueViewModel(ServiceProvider) { Name = Name, Content = Content }; return(copy); }
public async Task <IHttpActionResult> Update(Guid id, ValueViewModel item) { if (!authorizationService.IsAuthorized(item.FormId, user.Email, AuthorizationService.AuthorizationType.IsUpdate, AuthorizationService.EndpointType.Data)) { return(Content(HttpStatusCode.Forbidden, "You are not authorized to perform this action.")); } var record = await repository.Update(id, item.ToEntity()); var model = record.ToViewModel(); return(Content(HttpStatusCode.OK, model)); }
public void AssignValue() { int value = 10; var vm = new ValueViewModel <int>(value); Assert.AreEqual(value, vm.Value); int newValue = 20; vm.Value = newValue; Assert.AreEqual(newValue, vm.Value); }
public ActionResult CreateValue([Bind(Include = "Id,Set,Option,Order")] ValueViewModel model) { if (ModelState.IsValid) { var values = Database.ValueSets.Where(v => v.Set == model.Set); model.Order = values.Any() ? values.Max(v => v.Order) + 1 : 1; Database.ValueSets.Add(model.MapToValue()); Database.SaveChanges(); } return(RedirectToAction("ValueSets", "Home")); }
public static bool Update(int id, ValueViewModel model) { int index = valuesList.IndexOf(valuesList.First(V => V.Id == id)); if (index >= 0) { valuesList[index].Name = model.Name; valuesList[index].Value = model.Value; return(true); } return(false); }
public async Task ShouldProperlyValidateModel() { var model = new ValueViewModel() { Id = 10, Capacity = -1 }; var content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, mediaType); HttpResponseMessage response = await _client.PostAsync(route, content); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); string responseText = await response.Content.ReadAsStringAsync(); Assert.Contains("Неверная модель данных в теле запроса.", responseText); Assert.Contains("bodyFields", responseText); }
public void HandleChangedValue() { int value = 10; int changedValue = 20; var vm = new ValueViewModel <int>(value); int numValueChanged = 0; vm.ValueChanged += (newValue) => { Assert.AreEqual(newValue, changedValue); ++numValueChanged; Assert.AreEqual(1, numValueChanged); }; vm.Value = changedValue; // ValueChanged should not be raised if value is unchanged. vm.Value = changedValue; }
public HttpResponseMessage Get(int id) { try { if (!values.ContainsKey(id)) { //Add extra message to distinguish from mere routing problems. return(Request.CreateResponse(HttpStatusCode.NotFound, "That id is not in the dictionary.")); } var value = ReadValue(id); //Cache stale or no IfModifiedSince date if (Request.Headers.IfModifiedSince == null || value.LastModified > Request.Headers.IfModifiedSince) { ValueViewModel result = (from KeyValuePair <int, DatedValue> s in values where s.Key == id select ViewModelFactory(s)).First(); HttpResponseMessage m = Request.CreateResponse(HttpStatusCode.OK, result); //DateTime d = DateTime.UtcNow; //string dateInRFormat = value.LastModified.ToUniversalTime().ToString("r"); // //m.Headers.ETag = new EntityTagHeaderValue(dateInRFormat); m.Headers.CacheControl = new CacheControlHeaderValue() { NoCache = false, Public = false, Private = true, MaxAge = new TimeSpan(24, 0, 0) }; return(m); } return(new HttpResponseMessage(HttpStatusCode.NotModified)); } catch (Exception ex) { Tracing.Err.TraceEvent(TraceEventType.Error, 0, ex.ToString()); throw; } }
public async Task <IHttpActionResult> Get(Guid id) { ValueViewModel model = null; try { var record = await repository.Get(id); if (!authorizationService.IsAuthorized(record.FormId, user.Email, AuthorizationService.AuthorizationType.IsRead, AuthorizationService.EndpointType.Data)) { return(Content(HttpStatusCode.Forbidden, "You are not authorized to perform this action.")); } model = record.ToViewModel(); return(Content(HttpStatusCode.OK, model)); } catch (Exception ex) { Console.WriteLine(ex); return(Content(HttpStatusCode.InternalServerError, ex)); } }
public async Task <IHttpActionResult> Create(ValueViewModel item) { ValueViewModel model = null; try { if (!authorizationService.IsAuthorized(item.FormId, user.Email, AuthorizationService.AuthorizationType.IsCreate, AuthorizationService.EndpointType.Data)) { return(Content(HttpStatusCode.Forbidden, "You are not authorized to perform this action.")); } item.UserId = User.Identity.GetUserId(); var record = await repository.Create(item.ToEntity()); model = record.ToViewModel(); return(Content(HttpStatusCode.OK, model)); } catch (Exception ex) { Console.WriteLine(ex); return(Content(HttpStatusCode.InternalServerError, ex)); } }
public async Task <ActionResult> Index() { ViewBag.Title = "Values"; var httpClient = ClientHttpClient.GetClient(); var publicValues = await httpClient.GetAsync("values/PublicValues").ConfigureAwait(false); var secretValues = await httpClient.GetAsync("values/SecretValues").ConfigureAwait(false); var managementValues = await httpClient.GetAsync("values/ManagementValues").ConfigureAwait(false); var valuesAsString = await publicValues.Content.ReadAsStringAsync().ConfigureAwait(false); var secretAsString = await secretValues.Content.ReadAsStringAsync().ConfigureAwait(false); var managementAsString = await managementValues.Content.ReadAsStringAsync().ConfigureAwait(false); var publicValuesDeserialized = publicValues.IsSuccessStatusCode ? JsonConvert.DeserializeObject <List <string> >(valuesAsString) : null; var secretValuesDeserialized = secretValues.IsSuccessStatusCode ? JsonConvert.DeserializeObject <List <string> >(secretAsString) : null; var managementValuesDeserialized = managementValues.IsSuccessStatusCode ? JsonConvert.DeserializeObject <List <string> >(managementAsString) : null; var vm = new ValueViewModel(publicValuesDeserialized, secretValuesDeserialized, managementValuesDeserialized); return(View(vm)); }
public IActionResult Put(int id, [FromBody] ValueViewModel model) { ValueGenerator.Update(id, model); return(new OkResult()); }
public IActionResult Put([Range(1, int.MaxValue)] int id, [FromBody] ValueViewModel value) { return(Ok(value)); }
public IActionResult Post([FromBody] ValueViewModel value) { return(Ok(value)); }
public IActionResult Post([FromBody] ValueViewModel request) { return(Ok(request)); }
public IActionResult Put(int listId, [FromBody] ValueViewModel data) { _todoService.ChangeListName(listId, data.Value); return(Ok()); }
/// <param name='model'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task <Microsoft.Rest.HttpOperationResponse <ValueViewModel> > ApiValuesTestPostWithHttpMessagesAsync(ValueViewModel model = default(ValueViewModel), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (model != null) { model.Validate(); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>(); tracingParameters.Add("model", model); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ApiValuesTestPost", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Values/Test").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (model != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(model, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse <ValueViewModel>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <ValueViewModel>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public virtual ActionResult Details(int questionnaireId) { var results = _resultsRepository.GetResultDetails(questionnaireId); var model = new ResultsListViewModel() { Title = _questionnairesRepository.GetById(questionnaireId).Name, Results = new List <ResultsViewModel>(), Legend = LegendViewModel.Details() }; var questionsIds = results.Select(x => x.QuestionId).Distinct(); foreach (var questionId in questionsIds) { var question = _questionsRepository.GetById(questionId); var questionResults = new ResultsViewModel() { Id = questionId, Text = $"{question.OrderNumber}. {question.Text}", Options = _answersRepository.GetDescriptions(questionId), DictionaryGroups = new List <DictionaryGroupViewModel>() }; var dictionaryGroupNames = results.Select(x => x.DictionaryTypeName).Distinct(); foreach (var dictionaryType in dictionaryGroupNames) { var dictionaryGroup = new DictionaryGroupViewModel() { GroupName = dictionaryType, DictionaryItems = new List <DictionaryItemViewModel>() }; var dictionaryItemsIds = results.Where(x => x.DictionaryTypeName == dictionaryType).Select(x => x.BaseDictionaryId).Distinct(); foreach (var itemId in dictionaryItemsIds) { var dictionaryItem = new DictionaryItemViewModel() { ItemName = _dictionariesRepository.GetById(itemId).Value, Badge = results.First(x => x.BaseDictionaryId == itemId).IntervieweeCount.ToString(), Values = new List <ValueViewModel>() }; var answersIdList = results.Where(x => x.QuestionId == questionId).Select(x => x.AnswerId).Distinct(); foreach (var answerId in answersIdList) { var resultItem = results .Where(x => x.QuestionId == questionId) .Where(x => x.BaseDictionaryId == itemId) .Where(x => x.AnswerId == answerId) .FirstOrDefault(); var value = new ValueViewModel() { Badge = resultItem.AnswersCount.ToString(), Count = resultItem.AnswersCount, TotalCount = resultItem.TotalAnswersCount }; value.SetValueByPercentage(); dictionaryItem.Values.Add(value); } dictionaryGroup.DictionaryItems.Add(dictionaryItem); } questionResults.DictionaryGroups.Add(dictionaryGroup); } model.Results.Add(questionResults); } return(View(MVC.Application.Results.Views.Results, model)); }
public static void Insert(ValueViewModel model) { model.Id = valuesList.Count + 1; valuesList.Add(model); }