public bool Commit() { if (_notifications.HasNotifications()) { return(false); } var commitResponse = _uow.Commit(); //report messages from the commit, Include Info and warnings in the event of success Bus.RaiseOnResponse(commitResponse, "Commit"); if (commitResponse.Success) { return(true); } Bus.RaiseEvent(new DomainNotification(EventType.Error, "Commit", "We had a problem during saving your data.")); return(false); }
public ActionResult Create(OrderViewModel OrderViewModel) { try { //_cache.Remove("ErrorData"); //ViewBag.ErrorData = null; // 视图模型验证 if (!ModelState.IsValid) { return(View(OrderViewModel)); } // 这里为了测试,手动赋值items OrderViewModel.Items = new List <OrderItemViewModel>() { new OrderItemViewModel() { Name = "详情" + DateTime.Now } }; // 执行添加方法 _OrderAppService.Register(OrderViewModel); //var errorData = _cache.Get("ErrorData"); //if (errorData == null) // 是否存在消息通知 if (!_notifications.HasNotifications()) { ViewBag.Sucesso = "Order Registered!"; } return(View(OrderViewModel)); } catch (Exception e) { return(View(e.Message)); } }
public IActionResult Create(StudentViewModel studentViewModel) { try { ViewBag.ErrorData = null; if (!ModelState.IsValid) { return(View(studentViewModel)); } #region 除 -- 使用命令验证,采用构造函数方法实例 // //RegisterStudentCommand registerStudentCommand = new RegisterStudentCommand(studentViewModel.Name, studentViewModel.Email, studentViewModel.BirthDate); //// 如果命令无效,证明有错误 //if (!registerStudentCommand.IsValid()) //{ // List<string> errorInfo = new List<string>(); // //获取到错误,请思考这个Result从哪里来的 // foreach (var error in registerStudentCommand.ValidationResult.Errors) // { // errorInfo.Add(error.ErrorMessage); // } // //对错误进行记录,还需要抛给前台 // ViewBag.ErrorData = errorInfo; // return View(studentViewModel); //} #endregion studentAppService.Register(studentViewModel); if (!notifications.HasNotifications()) { ViewBag.Success = "Student Registered!"; } return(View(studentViewModel)); } catch (Exception e) { return(View(e.Message)); } }
public async Task AddFotoAsync(Guid clienteId, Guid Id, string Descricao, Stream stream) { await _imageStorage.UploadAsync(Id, stream); if (!_notifications.HasNotifications()) { var foto = new Foto() { Id = Id, ClienteId = clienteId, Descricao = Descricao, Ordem = 0, StatusAnalise = EnumStatusAnalise.NaoVerificado }; _clienteRepository.Add(foto); await _clienteRepository.SaveChangesAsync(); } }
protected async Task <bool> Commit() { if (_notifications.HasNotifications()) { await _mediatorHandler.RaiseDomainNotificationAsync(new DomainNotification("Commit", CoreUserMessages.ErroPersistenciaDados.Message)); return(false); } if (await _uow.CommitAsync()) { return(true); } await _mediatorHandler.RaiseDomainNotificationAsync(new DomainNotification("Commit", CoreUserMessages.ErroPersistenciaDados.Message)); return(false); }
public void AuthenticateApplicationService_Authenticate_invalid_password() { var user = new UserBuilder().WithEmail("*****@*****.**").WithPassword("qwe123").Builder(); _userRepository.Add(user); _unitOfWork.Commit(); var model = new AuthenticateModel { Email = user.Email, Password = "******" }; var result = _authenticateApplicationService.Authenticate(model); result.Token.Should().BeNullOrEmpty(); result.User.Should().BeNull(); DomainNotificationHandler.HasNotifications().Should().BeTrue(); DomainNotificationHandler.GetNotifications.First().Value.Should().Be(DomainError.InvalidPassoword); }
public async Task <IActionResult> Novo([FromBody] UsuarioModel usuario) { try { _logger.LogInformation($"Incluindo novo usuario."); _ = await _mediatr.Send(new AdicionarUsuarioCommand(usuario.Nome, usuario.Email, usuario.Senha)); if (_notifications.HasNotifications()) { return(BadRequest(_notifications.Notifications.Select(s => s.Value))); } } catch (Exception except) { return(StatusCode(500, except.Message)); } return(Ok("Novo usuário criado com sucesso")); }
public async Task <IActionResult> Create(StudentViewModel studentViewModel) { try { _cache.Remove("ErrorData"); ViewBag.ErrorData = null; // 视图模型验证 if (!ModelState.IsValid) { return(View(studentViewModel)); } #region 除命令验证 //添加命令验证,采用构造函数方法实例 //RegisterStudentCommand registerStudentCommand = new RegisterStudentCommand(studentViewModel.Name, studentViewModel.Email, studentViewModel.BirthDate, studentViewModel.Phone); //如果命令无效,证明有错误 //if (!registerStudentCommand.IsValid()) //{ // List<string> errorInfo = new List<string>(); //获取到错误,请思考这个Result从哪里来的 // foreach (var error in registerStudentCommand.ValidationResult.Errors) // { // errorInfo.Add(error.ErrorMessage); // } //对错误进行记录,还需要抛给前台 // ViewBag.ErrorData = errorInfo; return View(studentViewModel); //} #endregion // 执行添加方法 await _studentAppService.AddAsync(studentViewModel); if (!_notifications.HasNotifications()) { ViewBag.Sucesso = "Student Registered!"; } return(View(studentViewModel)); } catch (Exception e) { return(View(e.Message)); } }
public void UserApplicationService_Disable_not_found() { var currentUser = new UserBuilder().WithProfile(ProfileType.Administrator).Builder(); _userRepository.Add(currentUser); _unitOfWork.Commit(); _requestScope.SetUserId(currentUser.Id); var user = new UserBuilder().WithProfile(ProfileType.Standard).WithActive(true).Builder(); _userRepository.Add(user); _unitOfWork.Commit(); _userApplicationService.Disable(Guid.NewGuid()); var result = _userRepository.GetById(user.Id); result.Active.Should().BeTrue(); DomainNotificationHandler.HasNotifications().Should().BeTrue(); DomainNotificationHandler.GetNotifications.First().Value.Should().Be(DomainError.UserNotFound); }
public void UserApplicationService_Disable_without_permission() { var currentUser = new UserBuilder().WithProfile(ProfileType.Standard).Builder(); _userRepository.Add(currentUser); _unitOfWork.Commit(); _requestScope.SetUserId(currentUser.Id); var user = new UserBuilder().WithProfile(ProfileType.Standard).WithActive(true).Builder(); _userRepository.Add(user); _unitOfWork.Commit(); _userApplicationService.Disable(user.Id); var result = _userRepository.GetById(user.Id); result.Active.Should().BeTrue(); DomainNotificationHandler.HasNotifications().Should().BeTrue(); DomainNotificationHandler.GetNotifications.First().Value.Should().Be(DomainError.StandardProfileUserDoesNotHavePermission); }
public void UserApplicationService_Delete_without_permission() { var currentUser = new UserBuilder().WithProfile(ProfileType.Standard).Builder(); _userRepository.Add(currentUser); _unitOfWork.Commit(); _requestScope.SetUserId(currentUser.Id); var user = new UserBuilder().WithProfile(ProfileType.Standard).Builder(); _userRepository.Add(user); _unitOfWork.Commit(); var result = _userRepository.Get(new Filter()); _userApplicationService.Delete(user.Id); result.totalItems.Should().Be(2); result.entities.Should().HaveCount(2); DomainNotificationHandler.HasNotifications().Should().BeTrue(); DomainNotificationHandler.GetNotifications.First().Value.Should().Be(DomainError.StandardProfileUserDoesNotHavePermission); }
public async Task <IActionResult> OnPostAsync([FromBody] PlayerCreateDto dto) { var userId = _accountContext.UserId; var command = new CreateCommand(dto.Name, dto.Gender, userId, dto.Str, dto.Con, dto.Dex, dto.Int); await _bus.SendCommand(command); if (_notifications.HasNotifications()) { var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content)); return(await Task.FromResult(new JsonResult(new { status = false, errorMessage }))); } return(await Task.FromResult(new JsonResult(new { status = true }))); }
public bool Commit() { if (_notifications.HasNotifications()) { return(false); } try { if (_uow.Commit()) { return(true); } Bus.RaiseEvent(new DomainNotification("Commit", "Não foi possível salvar os dados")); return(false); } catch (System.Exception ex) { Bus.RaiseEvent(new DomainNotification("Commit", $"Não foi possível salvar os dados MESSAGE:{ex.Message}")); return(false); } }
public Task Handle(DeleteUserEvent @event) { _logger.LogInformation("Handling 'DeleteUserEvent' event", @event.Id, AppDomain.CurrentDomain.FriendlyName, @event); TimeSpan timeSpan = TimeSpan.FromMinutes(_cacheKeyManager.CacheTime); _locker.PerformActionWithLock(_cacheKeyManager.BuilerRedisEventLockKey(@event), timeSpan, async() => { var command = new DeleteUserCommand(@event.OtherId); _bus.SendCommand(command).Wait(); if (_notifications.HasNotifications()) { var(errorCode, errorMessage) = _notifications.GetNotificationMessage(); _logger.LogError( $"Handling 'DeleteUserEvent' event Error Code:{errorCode},Message:{errorMessage}", @event); } }); return(Task.CompletedTask); }
public async Task <IActionResult> OnPostAsync() { var userId = _accountContext.UserId; var command = new LogoutCommand(userId); await _bus.SendCommand(command); if (_notifications.HasNotifications()) { var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content)); return(await Task.FromResult(new JsonResult(new { status = false, errorMessage }))); } return(await Task.FromResult(new JsonResult(new { status = true }))); }
protected IActionResult CreateResponse(HttpStatusCode code, object result) { switch (code) { case HttpStatusCode.OK: if (_notifications.HasNotifications()) { return(Ok(new { success = false, data = _notifications.GetNotifications() })); } if (result == null) { return(Ok(new { success = false, data = "Nenhum resultado gerado no request." })); } return(Ok(new { success = true, data = result })); case HttpStatusCode.BadRequest: return(BadRequest(result)); default: return(BadRequest(result)); } }
public async Task <IActionResult> OnPostAsync([FromBody] UserRegDto dto) { var userId = _accountContext.UserId; var command = new RegCommand(dto.Email, dto.Password, dto.Code); await _bus.SendCommand(command); if (_notifications.HasNotifications()) { var errorMessage = string.Join(";", _notifications.GetNotifications().Select(x => x.Content)); return(await Task.FromResult(new JsonResult(new { status = false, errorMessage }))); } return(await Task.FromResult(new JsonResult(new { status = true }))); }
public async Task <IActionResult> Register(RegisterInputModel model) { if (ModelState.IsValid) { // todo : register user var user = new RegisterUserViewModel { Email = model.Email, Password = model.Password, ConfirmPassword = model.ConfirmPassword }; await _users.RegisterAsync(user); if (!_notifications.HasNotifications()) { return(RedirectToAction(nameof(Login), new { returnUrl = model.ReturnUrl })); } } var vm = await BuildRegisterViewModelAsync(model); return(View(vm)); }
public bool Commit() { if (_notifications.HasNotifications()) { return(false); } try { var commandResult = _uow.Commit(); if (!commandResult.Success) { _bus.RaiseEvent(DomainNotification.Factory.Create("Commit", "Ocorreu um erro ao salvar os dados no banco.")); } return(commandResult.Success); } catch (Exception ex) { throw ex; } }
public static TResponse checkHasNotification(DomainNotificationHandler _notifications, TResponse response) { if (_notifications.HasNotifications()) { if (_notifications.GetNotifications().Any(x => x.ResultCode == NotificationCode.Error)) { foreach (var item in _notifications.GetNotifications()) { response.Message += item.request + "; "; } } _notifications.Dispose(); response.Success = false; response.Status = (int)StatusCode.Error; } else { response.Status = (int)StatusCode.Success; response.Message = StatusCode.Success.ToString(); response.Success = true; } return(response); }
public async Task <bool> CommitAsync() { if (!_notificationHandler.HasNotifications()) { foreach (var entry in ChangeTracker.Entries().Where(entry => entry.Entity.GetType().GetProperty("DataCriacao") != null)) { if (entry.State == EntityState.Added) { entry.Property("DataCriacao").CurrentValue = DateTime.Now; } if (entry.State == EntityState.Modified) { entry.Property("DataCriacao").IsModified = false; } } var sucesso = await base.SaveChangesAsync() > 0; //if (sucesso) await _mediatorHandler.PublicarEventos(this); return(sucesso); } return(false); }
private bool IsValidOperation() { return(_notifications.HasNotifications()); }
protected virtual bool IsValid() { return(!_notifications.HasNotifications()); }
protected bool IsValidOperation() { return(!_notifications.HasNotifications()); }
public bool IsValidOperation() { return(!notifications.HasNotifications()); }
public async Task <UserEditViewModel> CreateAsync([FromForm] UserEditViewModel model) { var currentUser = EngineContext.Current.GetCurrentUser(); if (currentUser == null) { throw new GirvsException(StatusCodes.Status401Unauthorized, "未登录"); } //如果超级管理员创建的用户,则是特殊用户,如果是租户管理创建的用户,则是普通用户 var targetUserType = currentUser.UserType == UserType.AdminUser ? UserType.SpecialUser : UserType.GeneralUser; var command = new CreateUserCommand( model.UserAccount, model.UserPassword.ToMd5(), model.UserName, model.ContactNumber, model.State, targetUserType, null ); await _bus.SendCommand(command); if (_notifications.HasNotifications()) { var errorMessage = _notifications.GetNotificationMessage(); throw new GirvsException(StatusCodes.Status400BadRequest, errorMessage); } else { model.Id = command.Id; return(model); } }
protected bool OperacaoValida() { return(!_notifications.HasNotifications()); }
protected bool IsValidOperation() => (!_notifications.HasNotifications());
protected bool IsValid() { return(!_notification.HasNotifications()); }
protected bool HasNotifications() { return(_notifications.HasNotifications()); }