public async Task <IActionResult> CreateOrder([FromBody] SaveOrderResource orderResource) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // check whether current user sent a request var currentUser = await userRepository.GetCurrentUser(); if (currentUser.Id != orderResource.IdentityId) { return(NotFound()); } var order = await repository.GetAsync(orderResource.IdentityId, (int)orderResource.VehicleId); if (order != null) { return(BadRequest(ModelState.AddError("invalid_request", "Order is already done"))); } order = mapper.Map <Order>(orderResource); await repository.AddAsync(order); await uow.CommitAsync(); order = await repository.GetAsync(orderResource.IdentityId, (int)orderResource.VehicleId); var result = mapper.Map <PlainOrderResource>(order); return(Ok(result)); }
public IHttpActionResult Post(FestivalCreateViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Festival item = Mapper.Map <FestivalCreateViewModel, Festival>(model); if (!_festivalService.IsValid(item)) { ModelState.AddError(_festivalService.Errors); return(BadRequest(ModelState)); } try { _festivalService.Add(item); _db.SaveChanges(); } catch (Exception ex) { string innerMessage = ex.GetInnerException(); ModelState.AddModelError("Error", innerMessage); return(BadRequest(ModelState)); } return(Ok()); }
protected override async Task <List <string> > SaveExecuteAsync(List <CurrencyForSave> entities, bool returnIds) { foreach (var(entity, index) in entities.Indexed()) { // Ensure that Id is supplied if (string.IsNullOrEmpty(entity.Id)) { string path = $"[{index}].{nameof(entity.Id)}"; string msg = _localizer[ErrorMessages.Error_Field0IsRequired, _localizer["Code"]]; ModelState.AddError(path, msg); } else if (entity.Id.Length > 3) { string path = $"[{index}].{nameof(entity.Id)}"; string msg = _localizer[ErrorMessages.Error_Field0LengthMaximumOf1, _localizer["Code"], 3]; ModelState.AddError(path, msg); } } // Save OperationOutput result = await _behavior.Repository.Currencies__Save( entities : entities, validateOnly : ModelState.IsError, top : ModelState.RemainingErrors, userId : UserId); AddErrorsAndThrowIfInvalid(result.Errors); // Return return(entities.Select(e => e.Id).ToList()); }
protected void AddErrors(IEnumerable <KeyValuePair <string, string> > errors) { foreach (var error in errors) { ModelState.AddError(error); } }
protected override async Task DeleteExecuteAsync(List <int> ids) { var defs = await _behavior.Definitions(); int jvDefinitionId = defs.ManualJournalVouchersDefinitionId; foreach (var(id, index) in ids.Indexed()) { if (id == jvDefinitionId) { string path = $"[{index}]"; string msg = _localizer["Error_CannotModifySystemItem"]; ModelState.AddError(path, msg); } } DeleteOutput result = await _behavior.Repository.DocumentDefinitions__Delete( ids : ids, validateOnly : ModelState.IsError, top : ModelState.RemainingErrors, userId : UserId); AddErrorsAndThrowIfInvalid(result.Errors); }
public JsonResult Delete([DataSourceRequest] DataSourceRequest request, DisplacementsDay model) { _displacementsDaysBL.Delete(model.Id); ModelState.AddError(_validationService); return(Json(ModelState.ToDataSourceResult())); }
public async Task <ActionResult> Delete([DataSourceRequest] DataSourceRequest request, DayExtensions model) { _dayExtensionsBL.Delete(model.Id); ModelState.AddError(_validationService); return(Json(ModelState.ToDataSourceResult())); }
#pragma warning disable CS1998 // El método asincrónico carece de operadores "await" y se ejecutará de forma sincrónica. Puede usar el operador 'await' para esperar llamadas API que no sean de bloqueo o 'await Task.Run(...)' para hacer tareas enlazadas a la CPU en un subproceso en segundo plano. public async Task <ActionResult> Delete([DataSourceRequest] DataSourceRequest request, DayExtensions model) #pragma warning restore CS1998 // El método asincrónico carece de operadores "await" y se ejecutará de forma sincrónica. Puede usar el operador 'await' para esperar llamadas API que no sean de bloqueo o 'await Task.Run(...)' para hacer tareas enlazadas a la CPU en un subproceso en segundo plano. { _dayExtensionsBL.Delete(model.Id); ModelState.AddError(_validationService); return(Json(ModelState.ToDataSourceResult())); }
async Task <IActionResult> CannotCommentAsync(int issueId) { if (!await Db.CanCommentAsync(GetUserId(), issueId)) { return(BadRequest(ModelState.AddError("", CannotCommentIssue))); } return(null); }
public async Task <ActionResult> Delete([DataSourceRequest] DataSourceRequest request, Vacations model) { if (model != null) { _vacationsBL.Delete(model.Id); } ModelState.AddError(_validationService); return(Json(ModelState.ToDataSourceResult())); }
public JsonResult Add([DataSourceRequest] DataSourceRequest request, List <int> personsIds, DisplacementsDay model) { ModelState.Remove("PersonsId"); if (ModelState.IsValid) { _displacementsDaysBL.Add(personsIds, model); ModelState.AddError(_validationService); } return(Json(ModelState.ToDataSourceResult())); }
protected override void OnSavingRow() { ModelState.Required(Customers.CompanyName); ModelState.Exists(Customers.CustomerID, new Northwind.Models.Customers().CustomerID); if (Customers.CustomerID.WasChanged) { if (Customers.Contains(Customers.CustomerID.IsEqualTo(Customers.CustomerID.Value))) { ModelState.AddError(Customers.CustomerID, "Customer ID already in use"); } } }
protected override void OnSavingRow() { if (Activity == Activities.Insert) { Orders.OrderID.Value = Orders.Max(Orders.OrderID) + 1; } ModelState.Required(Orders.CustomerID); if (Orders.OrderDate.Year < 1990) { ModelState.AddError(Orders.OrderDate, "Invalid Date"); } ModelState.Exists(Orders.CustomerID, new Northwind.Models.Customers().CustomerID); ModelState.Exists(Orders.ShipVia, new Northwind.Models.Shippers().ShipperID); }
public JsonResult Add([DataSourceRequest] DataSourceRequest request, List <int> personsIds, List <DateTime> vacationDates, Vacations model) { ModelState.Remove("PersonsId"); ModelState.Remove("Date"); if (model != null && ModelState.IsValid) { var state = _vacationsBL.Add(personsIds, vacationDates, model); ModelState.AddError(_validationService); } return(Json(new[] { model }.ToDataSourceResult(request, ModelState))); }
protected override async Task <List <int> > SaveExecuteAsync(List <DocumentDefinitionForSave> entities, bool returnIds) { #region Validate foreach (var(docDef, docDefIndex) in entities.Indexed()) { if (docDef.LineDefinitions == null || docDef.LineDefinitions.Count == 0) { string path = $"[{docDefIndex}].{nameof(DocumentDefinition.LineDefinitions)}"; string msg = _localizer["Error_OneLineDefinitionIsRquired"]; ModelState.AddError(path, msg); } else { // Line Definitions that are duplicated within the same document var duplicateIndices = docDef.LineDefinitions .Select((entity, index) => (entity.LineDefinitionId, index)) .GroupBy(pair => pair.LineDefinitionId) .Where(g => g.Count() > 1) .SelectMany(g => g) .Select((_, index) => index); foreach (var index in duplicateIndices) { string path = $"[{docDefIndex}].{nameof(DocumentDefinition.LineDefinitions)}[{index}].{nameof(DocumentDefinitionLineDefinition.LineDefinitionId)}"; string msg = _localizer["Error_DuplicateLineDefinition"]; ModelState.AddError(path, msg); } } } #endregion #region Save SaveOutput result = await _behavior.Repository.DocumentDefinitions__Save( entities : entities, returnIds : returnIds, validateOnly : ModelState.IsError, top : ModelState.RemainingErrors, userId : UserId); AddErrorsAndThrowIfInvalid(result.Errors); return(result.Ids); #endregion }
public virtual ServiceResult Delete(TEntity entity) { var result = ServiceResult.Run(() => { Repository.Delete(entity); Repository.Save(); }); if (result.Exception != null) { ModelState.AddError("Exception", result.Exception.ToString()); } return(result); }
public IHttpActionResult ConfirmerPost(UserInDeptRoleConfirmViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!_userInDeptRolesService.UpdateConfirmer(model.UserId, model.IsConfirm)) { ModelState.AddError(_userInDeptRolesService.Errors); return(BadRequest(ModelState)); } return(Ok()); }
public JsonResult Edit([DataSourceRequest] DataSourceRequest request, int personsId, Vacations model) { if (model != null) { model.PersonsId = personsId; if (ModelState.IsValid) { _vacationsBL.Update(model); } } ModelState.AddError(_validationService); return(Json(ModelState.ToDataSourceResult())); }
private EntityServiceResult <TEntity> RunWithValidation(TEntity entity, Func <TEntity> func) { var result = new EntityServiceResult <TEntity>(); result.Success = false; if (Validate(entity)) { result = EntityServiceResult <TEntity> .Run(func); if (result.Exception != null) { ModelState.AddError("Exception", result.Exception.ToString()); } } return(result); }
public async Task <IActionResult> DeleteOrder(int id) { var currentUser = await userRepository.GetCurrentUser(); var order = await repository.GetAsync(currentUser.Id, id); if (order == null) { return(BadRequest(ModelState.AddError("invalid_request", "Order is already deleted"))); } repository.Remove(order); await uow.CommitAsync(); return(Ok(mapper.Map <SaveOrderResource>(order))); }
public ActionResult SignUp(SignUpModel model) { if (!ModelState.IsValid) { return(View("SignUp", model)); } var signUpResult = signUpManager.SignUp(model); if (!signUpResult.Succedeed) { ModelState.AddError(signUpResult.Content.Errors.ToList()); return(View("SignUp", model)); } return(RedirectToAction("SignIn", "Account")); }
public async Task <ActionResult> SignIn(SignInModel model) { if (ModelState.IsValid) { var operationResult = await signInManager.SignInAsync(model); if (!operationResult.Succedeed) { ModelState.AddError(operationResult.Message); } else { return(RedirectToAction("Index", "Home")); } } return(View("SignIn", model)); }
public async Task InvokeAsync(HttpContext context, ITopicsRepository topicsRepository, IMapper mapper, DefaultEventGridEventHandler eventHandler, IOptions <AwesomeEventGridOptions> options) { try { ModelState.Reset(); using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8)) { var topicToCreate = JsonConvert.DeserializeObject <TopicModel>(await reader.ReadToEndAsync(), options.Value.SerializerSettings); if (topicToCreate == null) { ModelState.AddError("", "Request body is required"); } Validate(topicToCreate); if (!ModelState.IsValid) { await BadRequest(context); return; } if (topicsRepository.FindByName(topicToCreate.Name) != null) { ModelState.AddError("name", "Topic does already exists"); await BadRequest(context); return; } var topic = mapper.Map <Topic>(topicToCreate); topic = topicsRepository.Add(topic); var topicModel = mapper.Map <TopicModel>(topic); //todo fix url: await CreatedAt(context, "http://foo", topicModel); } } catch (JsonException ex) { ModelState.AddError("", ex.Message); await BadRequest(context); } }
public async Task InvokeAsync(HttpContext context, ITopicsRepository topicsRepository, IMapper mapper) { ModelState.Reset(); var name = (string)context.GetRouteData().Values["name"]; var topic = topicsRepository.FindByName(name); if (topic == null) { ModelState.AddError("name", "Topic with this name not found"); await NotFound(context); } else { var model = mapper.Map <TopicModel>(topic); await Ok(context, model); } }
private async Task <EntitiesResult <Currency> > SetIsActive(List <string> ids, ActionArguments args, bool isActive) { await Initialize(); // Check user permissions var action = "IsActive"; var actionFilter = await UserPermissionsFilter(action, cancellation : default); ids = await CheckActionPermissionsBefore(actionFilter, ids); var settings = await _behavior.Settings(); foreach (var(id, index) in ids.Indexed()) { if (ids.Any(id => id != null && id == settings.FunctionalCurrencyId)) { string path = $"[{index}]"; string msg = _localizer["Error_CannotDeactivateTheFunctionalCurrency"]; ModelState.AddError(path, msg); } } // Execute and return using var trx = TransactionFactory.ReadCommitted(); OperationOutput output = await _behavior.Repository.Currencies__Activate( ids : ids, isActive : isActive, validateOnly : ModelState.IsError, top : ModelState.RemainingErrors, userId : UserId); AddErrorsAndThrowIfInvalid(output.Errors); var result = (args.ReturnEntities ?? false) ? await GetByIds(ids, args, action, cancellation : default) : EntitiesResult <Currency> .Empty(); // Check user permissions again await CheckActionPermissionsAfter(actionFilter, ids, result.Data); trx.Complete(); return(result); }
public virtual async Task <IActionResult> PasswordRecovery(PasswordRecoveryModel model) { //Get IUploder instance from service IUploader uploader = await authService.GetUserByMailAsync(model.Email); if (uploader != null) { //If user with specified email address exist, send password recovery email string token = await authService.CreatePasswordRecoveryTokenAsync(uploader); string url = urlService.CreateUrl(this, uploader.UserId, token, Name, nameof(ConfirmPassword)); await mailService.SendPasswordRecoveryAsync(uploader.UserMail, url, token); return(RedirectToAction(nameof(Login))); } ModelState.AddError("User", "User doesnt exist"); return(View()); }
private void UpdateColumnsBasedIn(DataItem item) { foreach (var c in _columns) { c.UpdateDataBasedOnItem(item, _denyUpdateColumns, _onlyAllowUpdateOf, ModelState, _bp.From, _ignoreUpdateOf, IgnoreUpdateOfNonUpdatableColumns); } try { if (ModelState.IsValid) { OnSavingRow(); } } catch (FlowAbortException ex) { ModelState.AddError(ex); throw; } }
protected override async Task SaveExecute(FinancialSettingsForSave settingsForSave, SelectExpandArguments args) { // Make sure the archive date is not in the future if (settingsForSave.ArchiveDate != null && settingsForSave.ArchiveDate.Value > DateTime.Today.AddDays(1)) { ModelState.AddError(nameof(settingsForSave.ArchiveDate), _localizer["Error_DateCannotBeInTheFuture"]); } // Persist var result = await Repository.FinancialSettings__Save( settingsForSave : settingsForSave, validateOnly : ModelState.IsError, top : ModelState.RemainingErrors, userId : UserId); AddLocalizedErrors(result.Errors, _localizer); ModelState.ThrowIfInvalid(); }
protected override async Task <List <int> > SaveExecuteAsync(List <MessageTemplateForSave> entities, bool returnIds) { #region Validation var definitionedCollections = new string[] { nameof(Document), nameof(Resource), nameof(Agent), nameof(Lookup) }; foreach (var(entity, index) in entities.Indexed()) { if (entity.Cardinality == Cardinalities.Multiple) { // ListExpression if (string.IsNullOrWhiteSpace(entity.ListExpression)) { var path = $"[{index}].{nameof(entity.ListExpression)}"; var msg = _localizer[ErrorMessages.Error_Field0IsRequired, _localizer["NotificationTemplate_ListExpression"]]; ModelState.AddError(path, msg); } else { try { TemplexBase.Parse(entity.ListExpression); } catch { var path = $"[{index}].{nameof(entity.ListExpression)}"; var msg = _localizer["Error_InvalidTemplateExpression0", entity.ListExpression]; ModelState.AddError(path, msg); } } } if (entity.Trigger == Triggers.Automatic) { // Automatic notifications can only be created by a Read-All user. var permissions = await FactBehavior.UserPermissions(view : "all", action : "Read", cancellation : default);
public IHttpActionResult Post(PeriodCreateViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Period item = Mapper.Map <PeriodCreateViewModel, Period>(model); if (!_periodService.IsValid(item)) { ModelState.AddError(_periodService.Errors); return(BadRequest(ModelState)); } _periodService.Add(item); _db.SaveChanges(); return(Ok()); }