예제 #1
0
        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);
        }
예제 #2
0
        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));
            }
        }
예제 #3
0
        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));
            }
        }
예제 #4
0
        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();
            }
        }
예제 #5
0
        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);
        }
예제 #6
0
        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);
        }
예제 #7
0
        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"));
        }
예제 #8
0
        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));
            }
        }
예제 #9
0
        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);
        }
예제 #10
0
        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);
        }
예제 #11
0
        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);
        }
예제 #12
0
        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);
            }
        }
예제 #14
0
        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);
        }
예제 #15
0
        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
            })));
        }
예제 #16
0
        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));
            }
        }
예제 #17
0
파일: Reg.cshtml.cs 프로젝트: yescent/emud
        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));
        }
예제 #19
0
        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;
            }
        }
예제 #20
0
        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);
        }
예제 #21
0
        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);
        }
예제 #22
0
 private bool IsValidOperation()
 {
     return(_notifications.HasNotifications());
 }
예제 #23
0
 protected virtual bool IsValid()
 {
     return(!_notifications.HasNotifications());
 }
 protected bool IsValidOperation()
 {
     return(!_notifications.HasNotifications());
 }
예제 #25
0
 public bool IsValidOperation()
 {
     return(!notifications.HasNotifications());
 }
예제 #26
0
        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);
            }
        }
예제 #27
0
 protected bool OperacaoValida()
 {
     return(!_notifications.HasNotifications());
 }
예제 #28
0
 protected bool IsValidOperation() => (!_notifications.HasNotifications());
예제 #29
0
 protected bool IsValid()
 {
     return(!_notification.HasNotifications());
 }
예제 #30
0
 protected bool HasNotifications()
 {
     return(_notifications.HasNotifications());
 }