Ejemplo n.º 1
0
        public async Task CreateSchedule(TimeSpan startTime, int[] daysOfWeek)
        {
            var schedule = Schedule.CreateSchedule(startTime, daysOfWeek);
            await _scheduleRespository.AddAsync(schedule).ConfigureAwait(false);

            await _domainEventDispatcher.DispatchAsync(schedule.Events.ToArray()).ConfigureAwait(false);
        }
Ejemplo n.º 2
0
        public override async Task <int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            int result = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

            // ignore events if no dispatcher provided
            if (_dispatcher == null)
            {
                return(result);
            }

            // dispatch events only if save was successful
            var entitiesWithEvents = ChangeTracker.Entries <AggregateRoot>()
                                     .Select(e => e.Entity)
                                     .Where(e => e.Events.Any())
                                     .ToArray();

            foreach (var entity in entitiesWithEvents)
            {
                var events = entity.Events.ToArray();
                entity.ClearEvents();
                foreach (var domainEvent in events)
                {
                    await _dispatcher.DispatchAsync(domainEvent).ConfigureAwait(false);
                }
            }

            return(result);
        }
Ejemplo n.º 3
0
        public async Task <Result <LoginUserFoundDTO> > Handle(LoginUserQuery request, CancellationToken cancellationToken)
        {
            var login    = Login.Create(request.Login);
            var password = Password.Create(request.Password, _passwordHasher);
            var result   = Result.Combine(login, password);

            if (result.Failure)
            {
                _logger.Error(result.Error);
                throw new GroceryException(result.Error);
            }
            var memberShip = new MemberShip(login.Value, password.Value);
            var user       = await _memberShipRepository.GetMemberShipByLoginPassword(memberShip.Login.LoginValue, memberShip.Password.PasswordValue);

            await _domainEventDispatcher.DispatchAsync(memberShip.DomainEvents.ToArray());

            if (user is null)
            {
                _logger.Error(nameof(Parameters.INVALID_USER), DateTime.Now);
                return(Result.Fail <LoginUserFoundDTO>(nameof(Parameters.INVALID_USER)));
            }
            var loggedUser = _mapper.Map <LoginUserFoundDTO>(user);

            loggedUser.JwtDTO = _jwtGenerator.Generate(user);
            _logger.Information($"User logged {loggedUser.MemberShipId} {DateTime.Now.ToStringDate()}");
            return(Result.Ok(loggedUser));
        }
Ejemplo n.º 4
0
        public async Task HandleAsync(CreateSubmission command)
        {
            var callForPapers = await _callForPapersRepository.GetAsync(command.ConferenceId);

            if (callForPapers is null)
            {
                throw new CallForPapersNotFoundException(command.ConferenceId);
            }

            if (!callForPapers.IsOpened)
            {
                throw new CallForPapersClosedException(command.ConferenceId);
            }

            var speakerIds = command.SpeakerIds.Select(id => new AggregateId(id));
            var speakers   = await _speakerRepository.BrowseAsync(speakerIds);

            if (speakers.Count() != command.SpeakerIds.Count())
            {
                throw new MissingSubmissionSpeakersException(command.Id);
            }

            var submission = Submission.Create(command.Id, command.ConferenceId, command.Title, command.Description,
                                               command.Level, command.Tags, speakers);

            await _submissionRepository.AddAsync(submission);

            await _dispatcher.DispatchAsync(submission.Events.ToArray());

            var integrationEvents = _eventMapper.MapAll(submission.Events);
            await _messageBroker.PublishAsync(integrationEvents.ToArray());
        }
Ejemplo n.º 5
0
        public async Task HandleAsync(RateStory command)
        {
            var story = await _storyRepository.GetAsync(command.StoryId);

            if (story is null)
            {
                throw new StoryNotFoundException(command.StoryId);
            }

            var user = await _userRepository.GetAsync(command.UserId);

            if (user is null)
            {
                throw new UserNotFoundException(command.UserId);
            }

            var rating = await _storyRatingService.RateAsync(story, user, command.Rate);

            await _storyRatingRepository.SetAsync(rating);

            var domainEvents = rating.Events.ToArray();
            await _domainEventDispatcher.DispatchAsync(domainEvents);

            var integrationEvents = _eventMapper.Map(domainEvents).ToArray();
            await _messageBroker.PublishAsync(integrationEvents);
        }
Ejemplo n.º 6
0
        public async Task HandleAsync(SendStory command)
        {
            var user = await _userRepository.GetAsync(command.UserId);

            if (user is null)
            {
                throw new UserNotFoundException(command.UserId);
            }

            if (!_storyAuthorPolicy.CanCreate(user))
            {
                throw new CannotCreateStoryException(user.Id);
            }

            var author     = Author.Create(user);
            var text       = _storyTextFactory.Create(command.Text);
            var now        = _clock.Current();
            var visibility = command.VisibleFrom.HasValue && command.VisibleTo.HasValue
                ? new Visibility(command.VisibleFrom.Value, command.VisibleTo.Value, command.Highlighted)
                : Visibility.Default(now);
            var storyId = command.StoryId <= 0 ? _idGenerator.Generate() : command.StoryId;
            var story   = Story.Create(storyId, author, command.Title, text, command.Tags, now, visibility);
            await _storyRepository.AddAsync(story);

            var domainEvents = story.Events.ToArray();
            await _domainEventDispatcher.DispatchAsync(domainEvents);

            var integrationEvents = _eventMapper.Map(domainEvents).ToArray();

            _storyRequestStorage.SetStoryId(command.Id, story.Id);
            await _messageBroker.PublishAsync(integrationEvents);
        }
        public void SaveEvents(Guid aggregateId, IEnumerable <Event> events, int expectedVersion)
        {
            // try to get event descriptors list for given aggregate id
            // otherwise -> create empty dictionary
            if (!FakeWriteDatabase.events.TryGetValue(aggregateId, out var eventDescriptors))
            {
                eventDescriptors = new List <EventDescriptor>();
                FakeWriteDatabase.events.TryAdd(aggregateId, eventDescriptors);
            }
            lock (eventDescriptors)
            {
                // check whether latest event version matches current aggregate version
                // otherwise -> throw exception
                if (expectedVersion != -1 && eventDescriptors[eventDescriptors.Count - 1].Version != expectedVersion)
                {
                    throw new ConcurrencyException();
                }
                var i = expectedVersion;

                // iterate through current aggregate events increasing version with each processed event
                foreach (var @event in events)
                {
                    i++;
                    @event.Version = i;

                    // push event to the event descriptors list for current aggregate
                    eventDescriptors.Add(new EventDescriptor(aggregateId, @event, i));

                    // publish current event to the bus for further processing by subscribers
                    _publisher.DispatchAsync(@event).Wait();
                }
            }
        }
Ejemplo n.º 8
0
    public async Task DispatchAsync(CancellationToken cancellationToken)
    {
        var domainEvents = _domainEventsAccessor.GetAllDomainEvents();

        foreach (var domainEvent in domainEvents)
        {
            await _domainEventDispatcher.DispatchAsync(domainEvent, cancellationToken);
        }
    }
Ejemplo n.º 9
0
        public async Task Handle_SubscribeMultipleEventHandlers_TriggerAllHandlers()
        {
            var employee = new Employee("Allen", "Yeager", "1");
            var @event   = new EntityCreatedEvent <Employee>(employee);
            await _dispatcher.DispatchAsync(@event);

            Assert.Equal(employee.FirstName, EmployeeCreatedEventHandler1.FirstName);
            Assert.Equal(employee.LastName, EmployeeCreatedEventHandler2.LastName);
        }
        private async Task PostCommitAsync(object entity, CancellationToken cancellationToken)
        {
            if (!(entity is Entity domainEntity))
            {
                return;
            }

            await eventDispatcher.DispatchAsync(domainEntity.DomainEvents, cancellationToken);

            domainEntity.ClearDomainEvents();
        }
Ejemplo n.º 11
0
        public async Task <Result> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
        {
            if ((request.MealsId?.Length == 0) || request.UserId == 0)
            {
                return(Result.Fail(nameof(Parameters.MISS_PARAMETERS)));
            }
            request.MealsId.ToList().ForEach(x =>
            {
                orders.Add(new Order(x, request.UserId));
            });
            await _repository.AddRange(orders);

            await _domainEventDispatcher.DispatchAsync(orders[0].DomainEvents.ToArray());

            return(Result.Ok());
        }
Ejemplo n.º 12
0
        public async Task <Result> Handle(CreateMealCommand request, CancellationToken cancellationToken)
        {
            var price = Price.Create(request.Price);
            var url   = ImageDish.Create(request.Url);

            if (price.Failure || url.Failure)
            {
                throw new GroceryException(price.Error, url.Error);
            }
            var meal = new Meal(request.MealName, price.Value, url.Value);
            await _repository.Add(meal);

            await _domainEventDispatcher.DispatchAsync(meal.DomainEvents.ToArray());

            return(Result.Ok(meal));
        }
Ejemplo n.º 13
0
        public async Task HandleAsync(RejectSubmission command)
        {
            var submission = await _repository.GetAsync(command.Id);

            if (submission is null)
            {
                throw new SubmissionNotFoundException(command.Id);
            }

            submission.Reject();

            await _repository.UpdateAsync(submission);

            await _dispatcher.DispatchAsync(submission.Events.ToArray());

            var integrationEvents = _eventMapper.MapAll(submission.Events);
            await _messageBroker.PublishAsync(integrationEvents.ToArray());
        }
Ejemplo n.º 14
0
        public async Task HandleAsync(ApproveSubmission command)
        {
            var submission = await _submissionRepository.GetAsync(command.Id);

            if (submission is null)
            {
                throw new SubmissionNotFoundException(command.Id);
            }

            submission.Approve();
            await _submissionRepository.UpdateAsync(submission);

            var events = _eventMapper.MapAll(submission.Events);
            await _messageBroker.PublishAsync(events.ToArray());



            await _domainEventDispatcher.DispatchAsync(submission.Events.ToArray());
        }
Ejemplo n.º 15
0
        public async Task HandleAsync(CreateSubmission command)
        {
            var speakersIds = command.SpeakersIds.Select(x => new AggregateId(x));
            var speakers    = await _speakerRepository.BrowserAsync(speakersIds);

            if (speakers.Count() != speakersIds.Count())
            {
                throw new InvalidSpeakerNumberException(command.Id);
            }

            var submission = Submission.Create(command.Id, command.ConferenceId, command.Title, command.Description,
                                               command.Level, command.Tags, speakers.ToList());

            await _submissionRepository.AddAsync(submission);

            var events = _eventMapper.MapAll(submission.Events);
            await _messageBroker.PublishAsync(events.ToArray());

            await _domainEventDispatcher.DispatchAsync(submission.Events.ToArray());
        }
Ejemplo n.º 16
0
        public async Task <Result> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            var password = Password.Create(request.Password, _passwordHasher);
            var email    = Email.Create(request.Email);
            var login    = Login.Create(request.Login);
            var result   = Result.Combine(email, password, login);

            if (result.Failure)
            {
                _logger.Error(result.Error);
                throw new GroceryException(result.Error);
            }
            if (await IsUserExists(login.Value, email.Value))
            {
                return(Result.Fail(nameof(Parameters.USER_EXISTS)));
            }
            MemberShip memberShip = new MemberShip(email.Value, login.Value, password.Value);
            await _memberShipRepository.Add(memberShip);

            await _domainEventDispatcher.DispatchAsync(memberShip.DomainEvents.ToArray());

            _logger.Information(nameof(EventMessage.CREATED_USER));
            return(Result.Ok(nameof(EventMessage.CREATED_USER)));
        }
 /// <inheritdoc />
 public async Task RaiseAsync <TEventMetaData>(IDomainEvent <TEventMetaData> @event)
     where TEventMetaData : EventMetaData
 {
     await _domainEventDispatcher.DispatchAsync(@event);
 }