public async Task SaveEvents_inserts_UniqueIndexedProperty_with_value_of_latest_indexed_event() { // Arrange var userId = Guid.NewGuid(); var created = new FakeUserCreated(); var usernameChanged = new FakeUsernameChanged(); var events = new DomainEvent[] { created, usernameChanged }; events.Raise(userId); var sut = new SqlEventStore( () => new FakeEventStoreDbContext(_dbContextOptions), new JsonMessageSerializer()); // Act await sut.SaveEvents <FakeUser>(events); // Assert using (var db = new FakeEventStoreDbContext(_dbContextOptions)) { UniqueIndexedProperty actual = await db .UniqueIndexedProperties .Where( p => p.AggregateId == userId && p.PropertyName == nameof(FakeUserCreated.Username)) .SingleOrDefaultAsync(); actual.PropertyValue.Should().Be(usernameChanged.Username); actual.Version.Should().Be(usernameChanged.Version); } }
public static void NotifyAll(IEnumerable <DomainNotification> notifications) { notifications.ToList().ForEach(validation => { DomainEvent.Raise <DomainNotification>(validation); }); }
public static User Create(string firstName, string lastName, Gender gender, string address, string email, string contactNo) { if (!RegexUtilities.IsValidContactNo(contactNo)) { throw new ArgumentException("Invalid contact number {0}", contactNo); } if (!RegexUtilities.IsValidEmail(email)) { throw new ArgumentException("Invalid email {0}", email); } var customer = new User { FirstName = firstName, LastName = lastName, Address = address, Email = email, ContactNo = contactNo, Gender = gender }; DomainEvent.Raise(new UserCreated { User = customer }); return(customer); }
/// <summary> /// If the visit does not have a Phq9, then it returns a newly created Phq9, /// else, it returns an existing one from the visit. /// </summary> /// <param name="visit">The visit.</param> /// <returns>A Phq9.</returns> public Phq9 CreatePhq9(Visit visit) { Check.IsNotNull(visit, "visit is required."); Phq9 phq9; var existingNidaDrugQuestionnaire = _phq9Repository.GetPhq9ByVisitKey(visit.Key); if (existingNidaDrugQuestionnaire != null) { phq9 = existingNidaDrugQuestionnaire; } else { var activityType = _lookupValueRepository.GetLookupByWellKnownName <ActivityType> (WellKnownNames.VisitModule.ActivityType.Phq9); phq9 = new Phq9(visit, activityType); _phq9Repository.MakePersistent(phq9); DomainEvent.Raise(new Phq9CreatedEvent { Phq9 = phq9 }); } return(phq9); }
public static Employee Create(string uniqueId, string firstName, string lastName, string middleName, Gender gender, DateTime dateOfBirth, string email, string contactNo) { if (!RegexUtilities.IsValidEmail(email)) { throw new ArgumentException("NewEmail is not valid.", nameof(email)); } if (!RegexUtilities.IsValidContactNo(contactNo)) { throw new ArgumentException("Contact number is not valid.", nameof(contactNo)); } var employee = new Employee { UniqueId = uniqueId, FirstName = firstName, LastName = lastName, MiddleName = middleName, Gender = gender, DateOfBirth = dateOfBirth, ContactNo = contactNo, Email = email }; DomainEvent.Raise(new EmployeeCreated { Employee = employee }); return(employee); }
public User Register(RegisterUserCommand command) { var user = new User(command.Name, command.Email, command.Password, command.Address, command.Complement, command.Number, command.District, command.City, command.Zip, command.State, command.Homephone, command.Cellphone, command.Photo, command.Facebook, command.Twitter, command.Instagram, command.YouTube ); user.Register(); _repository.Register(user); if (Commit()) { DomainEvent.Raise(new OnUserRegisteredEvent(user)); } //return user; return(user); }
/// <summary> /// If the visit does not have a Dast10, then it returns a newly created Dast10, /// else, it returns an existing one from the visit. /// </summary> /// <param name="visit">A visit.</param> /// <returns>A Dast10.</returns> public Dast10 CreateDast10(Visit visit) { Check.IsNotNull(visit, "visit is required."); Dast10 dast10; var existingNidaDrugQuestionnaire = _dast10Repository.GetDast10ByVisitKey(visit.Key); if (existingNidaDrugQuestionnaire != null) { dast10 = existingNidaDrugQuestionnaire; } else { var activityType = _lookupValueRepository.GetLookupByWellKnownName <ActivityType> (WellKnownNames.VisitModule.ActivityType.Dast10); dast10 = new Dast10(visit, activityType); _dast10Repository.MakePersistent(dast10); DomainEvent.Raise(new Dast10CreatedEvent { Dast10 = dast10 }); } return(dast10); }
public async Task SaveEvents_inserts_Aggregate_correctly_for_new_aggregate_id() { // Arrange var userId = Guid.NewGuid(); var created = new FakeUserCreated(); var events = new DomainEvent[] { created }; events.Raise(userId); var sut = new SqlEventStore( () => new FakeEventStoreDbContext(_dbContextOptions), new JsonMessageSerializer()); // Act await sut.SaveEvents <FakeUser>(events); // Assert using (var db = new FakeEventStoreDbContext(_dbContextOptions)) { Aggregate actual = await db .Aggregates .Where(a => a.AggregateId == userId) .SingleOrDefaultAsync(); actual.Should().NotBeNull(); actual.AggregateType.Should().Be(typeof(FakeUser).FullName); actual.Version.Should().Be(created.Version); } }
public Nutraceutical Register(RegisterNutraceuticalCommand command) { // Cria a instâcia do usuário var domain = new Nutraceutical(command.Name, command.Pharmacology, command.ActionMechanism, command.Indications, command.AgainstIndications, command.AdverseReactions, command.DrugInteractions, command.DescriptionDosages, command.RecomendedDosages, command.NutraceuticalReferences, command.NutraceuticalType, command.MinDosage, command.MaxDosage, command.Unity, command.MedicalOnly, command.CommonName); // Tenta ações e regras de negócio no domínio //domain.Register(); // Salva as alterações da tabela no contexto do banco de dados _repository.Save(domain); // Chama o commit if (Commit()) { // Dispara o evento de usuário registrado DomainEvent.Raise(new OnNutraceuticalRegisteredEvent(domain)); // Retorna o usuário return(domain); } // Se não comitou, retorna nulo return(null); }
public ICommandResult Handle(UserForgotPasswordCommand command) { var commandResult = new UserForgotPasswordCommandResult(); //Validações de coisas que não vão em repositório if (!(command.HasValidEmail())) { return(commandResult); } //Gera nova entidade //Trata fluxo demais regras var person = _personRepository.GetByEmail(command.Email); if (person != null) { string plainNewPassword = Guid.NewGuid().ToString().Substring(0, 7); string password = _passwordService.Encrypt(plainNewPassword); person.SetPassword(password); _personRepository.Update(person); if (Commit()) { DomainEvent.Raise(new UserForgotPasswordRequestedEvent(person, plainNewPassword)); commandResult.SerialKey = person.SerialKey; } } return(commandResult); }
public bool AtualizarSenhaAgenciaUsuario(SenhaViewModel model) { var status = false; var manager = _userManager; model.Code = _userManager.GeneratePasswordResetToken(model.UsuarioId); var user = manager.FindById(model.UsuarioId); var result = _userManager.ResetPassword(model.UsuarioId, model.Code.ToString(), model.Password); if (result.Succeeded) { status = true; var agenciausuario = ObterAgenciaUsuarioEditarPorId(Guid.Parse(user.Id)); DomainEvent.Raise(new AgenciaUsuarioEvent(Guid.Parse(usuario), nomeusuario, agenciausuario.UsuarioId.ToString(), agenciausuario.Nome, agenciausuario.CPF, agenciausuario.ClaimValue, "ALTERAR SENHA")); } else { var errosBr = new List <string>(); var notificationList = new List <DomainNotification>(); foreach (var erro in result.Errors) { string erroBr; if (erro.Contains("Senha incorreta.")) { erroBr = "Senha atual está incorreta."; notificationList.Add(new DomainNotification("IdentityValidation", erroBr)); errosBr.Add(erroBr); } if (erro.Contains("As senhas devem ter pelo menos um dígito ('0'-'9').")) { erroBr = "A senha precisa ter ao menos um dígito"; notificationList.Add(new DomainNotification("IdentityValidation", erroBr)); errosBr.Add(erroBr); } if (erro.Contains("As senhas devem ter pelo menos um caractere que não seja letra ou um caractere de dígito.")) { erroBr = "A senha precisa ter ao menos um caractere especial (@, #, etc...)"; notificationList.Add(new DomainNotification("IdentityValidation", erroBr)); errosBr.Add(erroBr); } if (erro.Contains("As senhas devem ter pelo menos um caractere em letra minúscula ('a'-'z').")) { erroBr = "A senha precisa ter ao menos uma letra em minúsculo"; notificationList.Add(new DomainNotification("IdentityValidation", erroBr)); errosBr.Add(erroBr); } if (erro.Contains("As senhas devem ter pelo menos um caractere em letra maiúscula ('A'-'Z').")) { erroBr = "A senha precisa ter ao menos uma letra em maiúsculo"; notificationList.Add(new DomainNotification("IdentityValidation", erroBr)); errosBr.Add(erroBr); } } notificationList.ForEach(DomainEvent.Raise); result = new IdentityResult(errosBr); } return(status); }
protected void RaiseEvent(TAggregateRootBaseEventClass theEvent) { theEvent.AggregateRootVersion = Version + 1; theEvent.UtcTimeStamp = TimeSource.UtcNow; if (Version == 0) { if (!theEvent.IsInstanceOf <IAggregateRootCreatedEvent>()) { throw new Exception($"The first raised event type {theEvent.GetType()} did not inherit {nameof(IAggregateRootCreatedEvent)}"); } theEvent.AggregateRootVersion = 1; } else { if (theEvent.AggregateRootId != Guid.Empty && theEvent.AggregateRootId != Id) { throw new ArgumentOutOfRangeException("Tried to raise event for AggregateRootId: {0} from AggregateRoot with Id: {1}." .FormatWith(theEvent.AggregateRootId, Id)); } if (_insertedVersionToAggregateVersionOffset != 0) { theEvent.InsertedVersion = theEvent.AggregateRootVersion + _insertedVersionToAggregateVersionOffset; theEvent.ManualVersion = theEvent.AggregateRootVersion; } theEvent.AggregateRootId = Id; } ApplyEvent(theEvent); AssertInvariantsAreMet(); _unCommittedEvents.Add(theEvent); _eventHandlersEventDispatcher.Dispatch(theEvent); DomainEvent.Raise(theEvent); }
/// <summary> /// If the visit does not have a NidaDrugQuestionnaire, then it returns a newly created NidaDrugQuestionnaire, /// else, it returns an existing one from the visit. /// </summary> /// <param name="visit">The visit.</param> /// <returns>A NidaDrugQuestionnaire.</returns> public NidaDrugQuestionnaire CreateNidaDrugQuestionnaire(Visit visit) { Check.IsNotNull(visit, "visit is required."); NidaDrugQuestionnaire nidaDrugQuestionnaire; var existingNidaDrugQuestionnaire = _nidaDrugQuestionnaireRepository.GetNidaDrugQuestionnaireInVisit(visit.Key); if (existingNidaDrugQuestionnaire != null) { nidaDrugQuestionnaire = existingNidaDrugQuestionnaire; } else { var activityType = _lookupValueRepository.GetLookupByWellKnownName <ActivityType> (WellKnownNames.VisitModule.ActivityType.NidaDrugQuestionnaire); nidaDrugQuestionnaire = new NidaDrugQuestionnaire(visit, activityType); _nidaDrugQuestionnaireRepository.MakePersistent(nidaDrugQuestionnaire); DomainEvent.Raise(new NidaDrugQuestionnaireCreatedEvent { NidaDrugQuestionnaire = nidaDrugQuestionnaire }); } return(nidaDrugQuestionnaire); }
public virtual void SubmitAssessment(string username = null) { IsSubmitted = true; CompletedTimestamp = DateTimeOffset.Now; DomainEvent.Raise(new AssessmentCompletedEvent { AssessmentKey = Key, Username = username }); }
public void EndSurvey() { EndTime = DateTime.Now; DomainEvent.Raise(new EndOfSurvey() { Survey = this }); }
public virtual void AddOrder(Order order) { DomainEvent.Raise(new UserAddedOrder { Order = order }); Orders.Add(order); }
public void NotificarException(DomainNotificationType notificationType, Exception exception) { DomainEvent.Raise(new DomainNotification(notificationType, exception.Message)); if (exception.InnerException != null) { DomainEvent.Raise(new DomainNotification(notificationType, exception.InnerException.Message)); } }
/// <summary> /// Reviews the visit. /// </summary> public virtual void ReviewVisit() { // Do something // Then raise a domain event DomainEvent.Raise(new VisitReviewedEvent { VisitKey = Visit.Key }); }
protected void NotificarErrosModelState() { var erros = ModelState.Values.SelectMany(x => x.Errors); foreach (var erro in erros) { DomainEvent.Raise(new DomainNotification(string.Empty, erro.ErrorMessage)); } }
public void NotificarDbException(DbException exception) { DomainEvent.Raise(new DomainNotification(DomainNotificationType.DatabaseError, exception.Message)); if (exception.InnerException != null) { DomainEvent.Raise(new DomainNotification(DomainNotificationType.DatabaseError, exception.InnerException.Message)); } }
/// <summary> /// Revises the gender. /// </summary> /// <param name="gender">The gender.</param> public virtual void ReviseGender(Gender gender) { Gender = gender; //TODO:Evaluate need for separate/more specific event DomainEvent.Raise(new PatientChangedEvent { Patient = this }); }
public void SendMessage(string text) { var nextId = Messages.Count == 0 ? 0 : Messages.Max(x => x.Id) + 1; Messages.Add(new Message(nextId, DateTime.Now.Date, text)); RemoveOldMessages(); DomainEvent.Raise(new SendMessageEvent(this, text)); }
public virtual double Checkout() { DomainEvent.Raise(new UserCheckout { Orders = Orders, GrandTotal = GrandTotal }); Orders = null; return(GrandTotal); }
/// <summary> /// Revises the name. /// </summary> /// <param name="name">The name.</param> public virtual void ReviseName(PersonName name) { Check.IsNotNull(name, "Name is required."); Name = name; //TODO:Evaluate need for separate/more specific event DomainEvent.Raise(new PatientChangedEvent { Patient = this }); }
public void AddCustomer(Customer customer) { DomainEvent.Raise(this, new EndOfSurveyEvent() { Customer = new Customer() { FullName = "Arman" } }); }
/// <summary> /// Revises the social history smoking. /// </summary> /// <param name="socialHistorySmoking">The social history smoking.</param> public virtual void ReviseSocialHistorySmoking(SocialHistorySmoking socialHistorySmoking) { Check.IsNotNull(socialHistorySmoking, "socialHistorySmoking is required."); _socialHistorySmoking = socialHistorySmoking; DomainEvent.Raise(new SocialHistorySmokingChangedEvent { SocialHistory = this }); }
public virtual void Confirm() { if (OrderStatus.Id != OrderStatus.PendingId) { throw new InvalidOperationException("Can only confirm when the order status is pending"); } OrderStatus = OrderStatus.Created; DomainEvent.Raise(new OrderConfirmed(this)); }
public void RaiseEventShouldCallAllRegisteredCallbacks() { bool called = false; Action <TestEvent> handler = x => called = true; DomainEvent.RegisterCallback(handler); DomainEvent.Raise(new TestEvent()); Assert.That(called, Is.EqualTo(true)); }
public async Task SaveEvents_saves_pending_events_correctly() { // Arrange var userId = Guid.NewGuid(); var created = new FakeUserCreated(); var usernameChanged = new FakeUsernameChanged(); var events = new DomainEvent[] { created, usernameChanged }; events.Raise(userId); var serializer = new JsonMessageSerializer(); var sut = new SqlEventStore( () => new FakeEventStoreDbContext(_dbContextOptions), serializer); string operationId = Guid.NewGuid().ToString(); var correlationId = Guid.NewGuid(); string contributor = Guid.NewGuid().ToString(); // Act await sut.SaveEvents <FakeUser>(events, operationId, correlationId, contributor); // Asseert using (var db = new FakeEventStoreDbContext(_dbContextOptions)) { var pendingEvents = db .PendingEvents .Where(e => e.AggregateId == userId) .OrderBy(e => e.Version) .ToList(); foreach (var t in pendingEvents.Zip(events, (pending, source) => new { Pending = pending, Source = source })) { var actual = new { t.Pending.Version, t.Pending.CorrelationId, t.Pending.Contributor, Message = serializer.Deserialize(t.Pending.EventJson), }; actual.ShouldBeEquivalentTo(new { t.Source.Version, OperationId = operationId, CorrelationId = correlationId, Contributor = contributor, Message = t.Source, }, opts => opts.RespectingRuntimeTypes()); } } }
public void Authenticate(string userName, string password) { var strongPassword = _encriptionService.GenereteEncryption(password); var user = _userRepository.FindUserByUserNameAndPassword(userName, strongPassword); if (user != null) { DomainEvent.Raise(new UserAuthenticated(user)); } }
public void TestEvent() { IEventHandlesRegistry eventHandlesRegistry = new UnityHandlesRegistry(container); eventHandlesRegistry.Register<DemoAddEvent, HandleDemoAdd>(); using (UnitOfWork unitwork = ServiceLocator.Current.GetInstance<UnitOfWork>()) { IRepository<Demo,Guid> demoRepository = ServiceLocator.Current.GetInstance<IRepository<Demo,Guid>>(); Demo demo = new Demo() { Name = "D" }; demoRepository.SaveOrUpdate(demo); DomainEvent<DemoAddEvent> demoAddEvent = new DomainEvent<DemoAddEvent>(eventHandlesRegistry); demoAddEvent.Raise(new DemoAddEvent(demo.Id)); unitwork.SaveChanges(); } }