protected void NotifyValidationErrors(Command message) { foreach (var error in message.ValidationResult.Errors) { _bus.RaiseEvent(new DomainNotification("", error.ErrorMessage)); } }
public async Task EnviarEmailAsync(string email, string assunto, string conteudo) { try { using (var mensagemDeEmail = new MailMessage()) { using (var smtpClient = new SmtpClient(_host, _porta)) { mensagemDeEmail.From = new MailAddress(_emailFrom, _nomeExibicao); mensagemDeEmail.To.Add(email); mensagemDeEmail.Subject = assunto; mensagemDeEmail.Body = conteudo; mensagemDeEmail.IsBodyHtml = true; smtpClient.Credentials = new NetworkCredential(_usuario, _senha); smtpClient.EnableSsl = _ssl; smtpClient.Send(mensagemDeEmail); } } } catch (Exception exception) { _logger.LogError(1, exception.ToString()); await _mediator.RaiseEvent(new DomainNotification("EmailSender", exception.Message)); } }
// RegisterUsersCommand命令的处理程序 // 整个命令处理程序的核心都在这里 // 不仅包括命令验证的收集,持久化,还有领域事件和通知的添加 public async Task <Unit> Handle(CreateMenusCommand request, CancellationToken cancellationToken) { if (!request.IsValid()) { NotifyValidationErrors(request); return(await Task.FromResult(new Unit())); } #region var menu = new Menus(); menu.Name = request.Name; //user.IsSuperMan = request.IsSuperMan; #endregion #region 检查 // 判断名称是否存在 // 这些业务逻辑,当然要在领域层中(领域命令处理程序中)进行处理 var existingUsers = _MenusRepository.GetByName(menu.Name); if (existingUsers != null && existingUsers.Id != menu.Id) { //引发错误事件 await Bus.RaiseEvent(new DomainNotification("", "该名称已经被使用!")); return(await Task.FromResult(new Unit())); } #endregion await _MenusRepository.AddAsync(menu); var result = await CommitAsync(); return(await Task.FromResult(new Unit())); }
public async Task <ActionResult <RegisterUserViewModel> > Register([FromBody] RegisterUserViewModel model) { if (!ModelState.IsValid) { NotifyModelStateErrors(); return(ModelStateErrorResponseError()); } if (await _reCaptchaService.IsCaptchaEnabled()) { var captchaSucces = await _reCaptchaService.IsCaptchaPassed(); if (!captchaSucces) { await _mediator.RaiseEvent(new DomainNotification("Recatcha", "ReCaptcha failed")); return(BadRequest(new ValidationProblemDetails(_notifications.GetNotificationsByKey()))); } } if (model.ContainsFederationGateway()) { await _userAppService.RegisterWithProvider(model); } else { await _userAppService.Register(model); } model.ClearSensitiveData(); return(ResponsePost("UserData", "Account", null, model)); }
public Task <object> Handle(CreateDriverCommand command, CancellationToken cancellationToken) { Driver driver = new Driver( id: null, name: new Model.ValueObject.Name(command.Name), code: new Model.ValueObject.Code(command.Code), phoneNumber: new Model.ValueObject.PhoneNumber(command.PhoneNumber), status: new Model.ValueObject.Status(command.Status), address: new Model.ValueObject.Address( city: command.City, country: command.Country, district: command.District, street: command.Street, streetNumber: command.StreetNumber ), dateOfBirth: new Model.ValueObject.Day(Convert.ToDateTime(command.DoB)), cardNumber: new Model.ValueObject.CardNumber(command.IDCardNumber), note: new Model.ValueObject.Note(command.Note), sex: new Model.ValueObject.Sex(command.Sex), startDate: new Model.ValueObject.Day(Convert.ToDateTime(command.StartDate)), userID: new Model.ValueObject.Identity(command.UserID), vehicleTypeID: new Model.ValueObject.VehicleTypeID(String.Join(',', command.VehicleTypeIDs)) ); var driverModel = _driverRepository.Add(driver); _bus.RaiseEvent(new DomainNotification("", "Create successfully!!", TypeNotification.Success)); return(Task.FromResult(driverModel as object)); }
public Task <bool> Handle(RegisterNewOccupationCommand request, CancellationToken cancellationToken) { if (!request.IsValid()) { NotifyValidationErrors(request); return(Task.FromResult(false)); } var model = new Occupation() { PeopleId = request.PeopleId, //People = request.People, BestWorkTimes = request.BestWorkTimes, WorkAvailabilities = request.WorkAvailabilities }; //TODO Validar se não existe! occupationRepository.Add(model); if (Commit()) { bus.RaiseEvent(new OccupationRegisteredEvent(model.Id, model.PeopleId, model.People, model.WorkAvailabilities, model.BestWorkTimes, model.EntityState, model.DateCreated)); } return(Task.FromResult(true)); }
public async Task <BaseResult> Handle(CreateUserCommand request, CancellationToken cancellationToken) { var result = new BaseResult(); //命令验证 if (!request.IsValid()) { result.Message = request.ValidationResult.Errors.FirstOrDefault()?.ErrorMessage; return(result); } //业务校验 var userModel = _mapper.Map <Models.User>(request); if (await _userRepository.AnyAsync(s => s.Email == userModel.Email)) { result.Message = "该邮箱已经被使用"; return(result); } //数据持久化 var userEntity = await _userRepository.AddReturnEntityAsync(userModel); //领域事件 if (result.IsSuccess = await _uow.CommitAsync()) { await _bus.RaiseEvent(new UserCreatedEvent(userEntity.Id, userEntity.Name, userEntity.Email)); } return(result); }
public async Task <bool> Handle(UpdateGameCommand request, CancellationToken cancellationToken) { if (!request.IsValid()) { NotifyValidationErrors(request); return(false); } else if (!_gameRepository.IsExistGame(request.Id)) { await _Bus.RaiseEvent(new DomainNotification(request.MessageType, "Could not update game. The informed Id game does not exist")); return(false); } else { var game = await _gameRepository.GetById(request.Id); _Mapper.Map <UpdateGameCommand, Game>(request, game); _gameRepository.Update(game); return(Commit()); } }
//public async Task Handle(CreateNewProductCommand message) //{ // var product = Product.ProductFactory.CreateNewProduct(message.Id, // message.Description, message.InternalCode,message.BarCode, // message.CostPrice,message.SalePrice, message.CategoryId, message.ProductTypeId); // if (!IsValid(product)) return; // // TODO: // // validate business rules! // await _productRepository.Add(product); // if (await Commit()) // { // await _mediator.RaiseEvent(new ProductCreatedEvent(product.Id,product.Description, product.InternalCode, // product.BarCode, product.CostPrice, product.SalePrice, product.CategoryId, product.ProductTypeId)); // } //} public async Task <Unit> Handle(CreateNewProductCommand message, CancellationToken cancellationToken) { var product = Product.ProductFactory.CreateNewProduct(message.Id, message.Description, message.InternalCode, message.BarCode, message.CostPrice, message.SalePrice, message.CategoryId, message.ProductTypeId); if (!IsValid(product)) { return(await Task <Unit> .Factory.StartNew(() => new Unit())); } // TODO: // // validate business rules! await _productRepository.Add(product); if (await Commit()) { await _mediator.RaiseEvent(new ProductCreatedEvent(product.Id, product.Description, product.InternalCode, product.BarCode, product.CostPrice, product.SalePrice, product.CategoryId, product.ProductTypeId)); } return(await Task <Unit> .Factory.StartNew(() => new Unit() )); }
protected void NotifyValidationErrors(DomainCommand message) { foreach (var error in message.ValidationResult.Errors) { _mediatorHandler.RaiseEvent(new DomainNotification(message.MessageType, error.ErrorMessage)); } }
public string WithdrawFromBalanceById(Guid id) { try { var employee = GetById(id); if (employee == null) _mediator.RaiseEvent(new DomainNotification("0", "Funcionário não reconhecido.")); if (employee.BirthDate.Day != DateTime.Now.Day || employee.BirthDate.Month != DateTime.Now.Month) _mediator.RaiseEvent(new DomainNotification("0", "Impossível sacar, dia atual não corresponde ao aniversário.")); var balance = employee.Balance; var value = 0.00; if (balance < 500) value = 0 + balance * 0.5; if (balance > 500 && balance < 1000) value = 50 + balance * 0.4; if (balance > 1000.01 && balance < 5000) value = 150 + balance * 0.3; if (balance > 5000.01 && balance < 10000) value = 650 + balance * 0.2; if (balance > 10000.01 && balance < 15000) value = 1150 + balance * 0.15; if (balance > 15000.01 && balance < 20000) value = 1900 + balance * 0.1; if (balance > 20000.01) value = 2900 + balance * 0.05; employee.Balance = balance - value; Update(employee); return $"Saque realizado, valor: {value}"; } catch (Exception) { return ""; } }
public async Task <IActionResult> Edit(int id) { var room = await _roomDomainService.Get(id); await _bus.RaiseEvent(new EntityUpdatedEvent <RoomEntity>(room)).ConfigureAwait(false); return(Ok()); }
public Order CalcDiscount(string code, Order order) { var cupon = _repostory.GetCupon(code); if (cupon == null) { _bus.RaiseEvent(new DomainNotification(this.MessageType, $"Cupom {code} não foi encontrado")); return(order); } if (cupon.Expired) { _bus.RaiseEvent(new DomainNotification(this.MessageType, $"Cupom {cupon.Cod} está expirado")); } return(order.ApplyDiscount(cupon)); }
public Task <Unit> Handle(RegisterAnnotationCommand request, CancellationToken cancellationToken) { var annotation = new Annotation(request.Title, request.Description); if (!AnnotationValid(annotation.AnnotationHistory.FirstOrDefault())) { return(Unit.Task); } _annotationRepository.Add(annotation); if (Commit()) { _mediator.RaiseEvent(new AnnotationRegistredEvent(annotation.Id)); } return(Unit.Task); }
//将领域命令中的验证错误信息收集 //目前用的是缓存方法(以后通过领域通知替换) protected void NotifyValidationErrors(Command message) { foreach (var error in message.ValidationResult.Errors) { //将错误信息提交到事件总线,派发出去 _Bus.RaiseEvent(new DomainNotification("", error.ErrorMessage), ""); } }
/// <summary> /// 收集命令验证中的错误信息。 /// </summary> /// <param name="command">命令。</param> protected void NotifyValidationErrors(Command command) { foreach (var error in command.ValidationResult.Errors) { //将错误信息提交到事件总线,派发出去 _bus.RaiseEvent(new Notification("", error.ErrorMessage)); } }
public Task <bool> Handle(RegistrarNovoTipoAppCommand message, CancellationToken cancellationToken) { #region Basic Validation if (!message.IsValid()) { NotifyValidationErrors(message); return(Task.FromResult(false)); } #endregion if (Commit()) { _bus.RaiseEvent(new RegistrarNovoPerfilEvent()); } return(Task.FromResult(true)); }
public async Task <IActionResult> Edit(int id) { var npc = await _npcDomainService.Get(id); await _bus.RaiseEvent(new EntityUpdatedEvent <NpcEntity>(npc)).ConfigureAwait(false); return(Ok()); }
public Task <bool> Handle(RegisterNewCustomerCommand message, CancellationToken cancellationToken) { if (!message.IsValid()) { NotifyValidationErrors(message); return(Task.FromResult(false)); } var customer = new Customer(message.Id, message.Name, message.Email, message.BirthDate); if (_customerRepository.GetByEmail(message.Email) != null) { Bus.RaiseEvent(new DomainNotification(message.MessageType, "The customer e-mail has already been taken.")); return(Task.FromResult(false)); } if (_customerRepository.GetById(message.Id) != null) { Bus.RaiseEvent(new DomainNotification(message.MessageType, "The customer id has already been taken.")); return(Task.FromResult(false)); } _customerRepository.Add(customer); if (Commit()) { Bus.RaiseEvent(new CustomerRegisteredEvent(customer.Id, customer.Name, customer.Email, customer.BirthDate)); } return(Task.FromResult(true)); }
public Task Handle(RegisterNewPalestraCommand message, CancellationToken cancellationToken) { if (!message.IsValid()) { NotifyValidationErrors(message); return(Task.CompletedTask); } var palestra = new Palestra(Guid.NewGuid(), message.Titulo, message.Descricao, message.Data, message.PalestranteId); var existingPalestra = _palestraRepository.GetByTitulo(palestra.Titulo); if (existingPalestra != null && existingPalestra.Id != palestra.Id && existingPalestra.Data == palestra.Data) { Bus.RaiseEvent(new DomainNotification(message.MessageType, "Palestra já cadastrada!")); return(Task.CompletedTask); } var existingConflictPalestras = _palestraRepository.GetConflitctPalestranteDate(message.Data, message.PalestranteId); if (existingConflictPalestras != null) { Bus.RaiseEvent(new DomainNotification(message.MessageType, "Palestrante já possui palestra para essa data!")); return(Task.CompletedTask); } _palestraRepository.Add(palestra); if (Commit()) { Bus.RaiseEvent(new PalestraRegisteredEvent(palestra.Id, palestra.Titulo, palestra.Descricao, palestra.Data, palestra.PalestranteId)); } return(Task.CompletedTask); }
public Task <bool> Handle(RegisterNewCardTypeCommand message, CancellationToken cancellationToken) { if (!message.IsValid()) { NotifyValidationErrors(message); return(Task.FromResult(false)); } var transactionType = new CardType(message.Id, message.Name); if (_cardTypeRepository.GetByName(message.Name) != null) { Bus.RaiseEvent(new DomainNotification(message.MessageType, "The card type name has already been taken.")); return(Task.FromResult(false)); } if (_cardTypeRepository.GetById(message.Id) != null) { Bus.RaiseEvent(new DomainNotification(message.MessageType, "The card type id has already been taken.")); return(Task.FromResult(false)); } _cardTypeRepository.Add(transactionType); if (Commit()) { Bus.RaiseEvent(new CardTypeRegisteredEvent(transactionType.Id, transactionType.Name)); } return(Task.FromResult(true)); }
public Task <bool> Handle(RegisterNewCardCommand message, CancellationToken cancellationToken) { if (!message.IsValid()) { NotifyValidationErrors(message); return(Task.FromResult(false)); } var card = new Card(message.Id, message.IdCustomer, message.IdBrand, message.IdCardType, message.CardNumber, message.ExpirationDate, message.HasPassword, message.Password, message.Limit, message.LimitAvailable, message.Attempts, message.Blocked); if (_cardRepository.GetByCardNumber(message.CardNumber) != null) { Bus.RaiseEvent(new DomainNotification(message.MessageType, "The card number has already been taken.")); return(Task.FromResult(false)); } if (_cardRepository.GetById(message.Id) != null) { Bus.RaiseEvent(new DomainNotification(message.MessageType, "The card id has already been taken.")); return(Task.FromResult(false)); } _cardRepository.Add(card); if (Commit()) { Bus.RaiseEvent(new CardRegisteredEvent(card.Id, message.IdCustomer, message.IdBrand, message.IdCardType, message.CardNumber, message.ExpirationDate, message.HasPassword, StringCipher.Encrypt(message.Password, "StefanSilva@#@Stone##2019"), message.Limit, message.LimitAvailable, message.Attempts, message.Blocked)); } return(Task.FromResult(true)); }
public Task <bool> Handle(RegisterNewCardBrandCommand message, CancellationToken cancellationToken) { if (!message.IsValid()) { NotifyValidationErrors(message); return(Task.FromResult(false)); } //var cardBrand = new CardBrand(Guid.NewGuid(), message.Name); var cardBrand = new CardBrand(message.Id, message.Name); if (_cardBrandRepository.GetByName(message.Name) != null) { Bus.RaiseEvent(new DomainNotification(message.MessageType, "The card brand name has already been taken.")); return(Task.FromResult(false)); } if (_cardBrandRepository.GetById(message.Id) != null) { Bus.RaiseEvent(new DomainNotification(message.MessageType, "The card brand id has already been taken.")); return(Task.FromResult(false)); } _cardBrandRepository.Add(cardBrand); if (Commit()) { Bus.RaiseEvent(new CardBrandRegisteredEvent(cardBrand.Id, cardBrand.Name)); } return(Task.FromResult(true)); }
protected void NotifyValidationErrors(BaseCommand message) { List <string> errorInfo = new List <string>(); foreach (var error in message.ValidationResult.Errors) { _bus.RaiseEvent(new DomainNotification("", error.ErrorMessage, TypeNotification.Fail)); } }
public void QuandoForSolicitadoOCadastro() { bus.RaiseEvent(Arg.Any <ClienteCadastradoEvent>()); repository.InserirCliente(Arg.Any <Application.Models.Cliente>()); var handler = new ClienteCommandHandler(bus, repository); retorno = handler.Handle(command, CancellationToken.None).Result; }
public void Handle(RegisterNewCustomerCommand message) { if (!message.IsValid()) { NotifyValidationErrors(message); return; } var customer = new Customer(Guid.NewGuid(), message.Name, message.Email, message.BirthDate); Bus.RaiseEvent(new DomainNotification(message.MessageType, "The customer e-mail has already been taken.")); return; //Bus.RaiseEvent(new CustomerRegisteredEvent(customer.Id, customer.Name, customer.Email, customer.BirthDate)); }
public Task <bool> Handle(AddNewOrganizationCommand request, CancellationToken cancellationToken) { if (!request.IsValid()) { NotifyValidationErrors(request); return(Task.FromResult(false)); } var Organization = new Organization(request.Id, request.Name, request.EmployeesCount); _organizationRepository.Add(Organization); if (Commit()) { _bus.RaiseEvent(new OrganizationAddedEvent(request.Id, request.Name, request.EmployeesCount)); } return(Task.FromResult(true)); }
// RegisterStudentCommand命令的处理程序 // 整个命令处理程序的核心都在这里 // 不仅包括命令验证的收集,持久化,还有领域事件和通知的添加 public Task <Unit> Handle(RegisterStudentCommand message, CancellationToken cancellationToken) { // 命令验证 if (!message.IsValid()) { // 错误信息收集 NotifyValidationErrors(message); // 返回,结束当前线程 return(Task.FromResult(new Unit())); } // 实例化领域模型,这里才真正的用到了领域模型 // 注意这里是通过构造函数方法实现 var address = new Address(message.Province, message.City, message.County, message.Street); var student = new Student(Guid.NewGuid(), message.Name, message.Email, message.Phone, message.BirthDate, address); // 判断邮箱是否存在 // 这些业务逻辑,当然要在领域层中(领域命令处理程序中)进行处理 if (_studentRepository.GetByEmail(student.Email) != null) { ////这里对错误信息进行发布,目前采用缓存形式 //List<string> errorInfo = new List<string>() { "该邮箱已经被使用!" }; //Cache.Set("ErrorData", errorInfo); //引发错误事件 Bus.RaiseEvent(new DomainNotification("", "该邮箱已经被使用!")); return(Task.FromResult(new Unit())); } // 持久化 _studentRepository.Add(student); // 统一提交 if (Commit()) { // 提交成功后,这里需要发布领域事件 // 比如欢迎用户注册邮件呀,短信呀等 Bus.RaiseEvent(new StudentRegisteredEvent(student.Id, student.Name, student.Email, student.BirthDate, student.Phone)); } return(Task.FromResult(new Unit())); }
public async Task <Unit> Handle(ShowFriendCommand command, CancellationToken cancellationToken) { var playerId = command.PlayerId; var player = await _playerDomainService.Get(playerId); if (player == null) { await _bus.RaiseEvent(new DomainNotification($"角色不存在!")); return(Unit.Value); } var playerRelationQuery = await _playerRelationDomainService.GetAll(); //我加了别人的 var requestIds = playerRelationQuery.Where(x => x.PlayerId == playerId && x.Type == PlayerRelationTypeEnum.好友).Select(x => x.RelationId).ToList(); //别人加了我的 var friendToMeIds = playerRelationQuery.Where(x => x.RelationId == playerId && x.Type == PlayerRelationTypeEnum.好友).Select(x => x.PlayerId).ToList(); //互相加了的 var friendIds = requestIds.Intersect(friendToMeIds).ToList(); requestIds = requestIds.Except(friendIds).ToList(); friendToMeIds = friendToMeIds.Except(friendIds).ToList(); var playerQuery = await _playerDomainService.GetAll(); var players = playerQuery.Where(x => friendIds.Contains(x.Id)).ToList(); var requests = playerQuery.Where(x => requestIds.Contains(x.Id)).ToList(); var friendToMes = playerQuery.Where(x => friendToMeIds.Contains(x.Id)).ToList(); await _mudProvider.ShowFriend(playerId, new MyFriendModel { Friends = _mapper.Map <List <PlayerBaseInfo> >(players), Requests = _mapper.Map <List <PlayerBaseInfo> >(requests), FriendMes = _mapper.Map <List <PlayerBaseInfo> >(friendToMes) }); return(Unit.Value); }
public Task <bool> Handle(AddNewPersonCommand message, CancellationToken cancellationToken) { if (!message.IsValid()) { NotifyValidationErrors(message); return(Task.FromResult(false)); } var person = new Person(Guid.NewGuid(), message.Name); _postRepository.Add(person); if (Commit()) { _bus.RaiseEvent(new PersonAddedEvent(person.Id, person.Name)); } return(Task.FromResult(true)); }