Example #1
0
 public async Task HandleAsync(MakeOrder message, ISagaContext context)
 {
     _logger.LogInformation($"Started a saga for order: {message.OrderId}, customer: {message.CustomerId}," +
                            $"parcels: {message.ParcelId}");
     Data.ParcelIds.Add(message.ParcelId);
     Data.OrderId    = message.OrderId;
     Data.CustomerId = message.CustomerId;
     await _publisher.SendAsync(new CreateOrder(Data.OrderId, message.CustomerId), _accessor.CorrelationContext);
 }
Example #2
0
        public async Task HandleAsync(TeamsCreated @event, ICorrelationContext context)
        {
            int[] playerIds = @event.Teams.SelectMany(inner => inner).ToArray();

            var query = new PlayersQuery
            {
                LeagueId  = new [] { @event.LeagueId },
                PlayerId  = playerIds,
                QueryType = PlayersQueryType.Actual,
                Page      = 1,
                Size      = playerIds.Length
            };

            List <PlayerWithRateDto> playersInfo = (await _playersService.GetAsync(query)).ToList();

            int teamNumber = 1;

            foreach (var team in @event.Teams)
            {
                var body = CreateTeamAndRateBody(team, playersInfo, teamNumber);

                InboxNotification notification = InboxNotificationBuilder
                                                 .Create()
                                                 .WithReceiver(team)
                                                 .WithSender("Notification service")
                                                 .WithTopic($"Teams for tour: {@event.TourId} in league: {@event.LeagueId} are formed!")
                                                 .WithBody($"{body}")
                                                 .Build();

                await _busPublisher.SendAsync(notification, context);

                teamNumber++;
            }

            int[] registeredPlayers =
                (await _toursService.GetAsync(new RegisteredOnTourPlayers {
                TourId = @event.TourId
            }))
                .Select(dto => dto.InternalId)
                .ToArray();
            int[] unhappyPlayers = registeredPlayers.Except(playerIds).ToArray();

            if (unhappyPlayers.Length != 0)
            {
                InboxNotification notification = InboxNotificationBuilder
                                                 .Create()
                                                 .WithReceiver(unhappyPlayers)
                                                 .WithSender("Notification service")
                                                 .WithTopic($"Teams for tour: {@event.TourId} in league: {@event.LeagueId} are formed!")
                                                 .WithBody("Sorry you are out of the game. Try next time!")
                                                 .Build();

                await _busPublisher.SendAsync(notification, context);
            }
        }
        public async Task <IActionResult> Post(CreateCustomerCommand command)
        {
            var context = GetContext();
            await _busPublisher.SendAsync(command, context);

            return(Accepted());
        }
Example #4
0
        public async Task HandleAsync(SynchronizationAcceptedEvent @event, ISagaContext sagaContext)
        {
            logger.LogInformation($"{nameof(@event)} ({sagaContext.CorrelationId}) {this.GetType()}");

            await busPublisher.SendAsync(
                new MergeSynchronizationDataCommand(),
                CorrelationContext.Create(sagaContext.CorrelationId));
        }
        protected async Task <IActionResult> SendAsync <T>(T command,
                                                           Guid?resourceId = null, string resource = "") where T : IRequest
        {
            var context = GetContext <T>(resourceId, resource);
            await _busPublisher.SendAsync(command, context);

            return(Accepted(context));
        }
        /// <summary>
        /// Method to publish a command to the bus. Some subscriber will handle the command.
        /// </summary>
        /// <typeparam name="T">Type of the command</typeparam>
        /// <param name="command">Command to be sent to the bus</param>
        /// <param name="resourceId"></param>
        /// <param name="resource"></param>
        /// <returns>Http Accepted</returns>
        protected async Task <IActionResult> PublishAsync <T>(T command,
                                                              Guid?resourceId = null, string resource = "") where T : ICommand
        {
            ICorrelationContext context = CorrelationContext.Empty; //GetContext<T>(resourceId, resource); TODO: Implement GetContext
            await _busPublisher.SendAsync(command, context);

            return(Accepted(context));
        }
        public async Task <IActionResult> Post([FromBody] CreateReservation command)
        {
            var context = new CorrelationContext(Guid.NewGuid(), command.UserId, "reservations",
                                                 _tracer.ActiveSpan.Context.ToString());
            await _busPublisher.SendAsync(command, context);

            return(Accepted($"reservations/{context.Id}"));
        }
Example #8
0
        public async Task <IActionResult> CreateItem(CreateOrderCommand command)
        {
            await _dispatcher.SendAsync(command);

            await _busPublisher.SendAsync(command, CorrelationContext.Empty);

            return(Accepted());
        }
Example #9
0
        public async Task <ActionResult> CreatePersonReportsByLocation(CreatePersonReportsByLocationCommand command)
        {
            var context = CorrelationContext.Create(Guid.NewGuid(), command.PersonId);

            await BusPublisher.SendAsync(command, context);

            return(Accepted(context));
        }
Example #10
0
        public async Task <IActionResult> CreateAddress([FromBody] CreateAddress command)
        {
            try
            {
                await _busPublisher.SendAsync(command.BindId(x => x.Id), CorrelationContext.Empty);
            }
            catch (Exception ex) { }

            return(Accepted());
        }
Example #11
0
        public async Task <bool> Handle(ReserveBookCommand request, CancellationToken cancellationToken)
        {
            var reservation = await _db.Reservations
                              .Include(x => x.Loans)
                              .Include(x => x.Member)
                              .FirstOrDefaultAsync(x => x.Number == request.Number, cancellationToken);

            if (reservation == null)
            {
                reservation = new Reservation
                {
                    RequestDate = _dateTimeService.Now(),
                    Status      = StatusReservation.Opened,
                    Number      = request.Number,
                    Member      = await _db.Members.FirstOrDefaultAsync(x => x.DocumentId == request.MemberId, cancellationToken)
                };

                if (reservation.Member == null)
                {
                    reservation.Member = new Member
                    {
                        DocumentId = request.MemberId,
                        Name       = request.MemberName
                    };
                }

                await _db.AddAsync(reservation, cancellationToken);
            }

            reservation.Loans = new List <Loan>();

            foreach (var item in request.Items)
            {
                var loan = new Loan
                {
                    Copy    = await _db.Copies.FirstOrDefaultAsync(x => x.Number == item.Number, cancellationToken),
                    DueDate = reservation.RequestDate.AddDays(7)
                };

                reservation.Loans.Add(loan);
            }

            await _db.SaveChangesAsync(cancellationToken);

            var message = new PublishReservationEventCommand
            {
                ReservationId = reservation.Id
            };

            await _bus.SendAsync(ContextNames.Queue.Library, message);

            return(true);
        }
Example #12
0
 public async Task HandleAsync(TourRegistrationClosed message, ISagaContext context)
 {
     await _busPublisher.SendAsync(
         new GenerateTeams(
             message.TourId,
             message.LeagueId,
             message.PlayersInTeam,
             message.TeamsInTour,
             message.Pid,
             message.GenerateTeamsStrategy),
         CorrelationContext.Empty);
 }
Example #13
0
        public async Task CompensateAsync(OrderCreated message, ISagaContext context)
        {
            var diff = DateTime.UtcNow.Subtract(Data.CustomerCreatedAt);

            if (diff.TotalHours <= CreationHoursLimit)
            {
                await _busPublisher.SendAsync(new CreateOrderDiscount(
                                                  message.Id, message.CustomerId, 10), CorrelationContext.Empty);

                Complete();
            }
            else
            {
                Reject();
            }
        }
        public async Task HandleAsync(TourRegistrationOpened @event, ICorrelationContext context)
        {
            IEnumerable <PlayerInternalIdDto> playersDto =
                await _leaguesService.GetLeagueJoinedPlayersAsync(new LeagueJoinedPlayersQuery(@event.LeagueId));

            int[] playerIds = playersDto.Select(p => p.InternalId).ToArray();

            InboxNotification notification = InboxNotificationBuilder
                                             .Create()
                                             .WithReceiver(playerIds)
                                             .WithSender("Notification service")
                                             .WithTopic("Tour registration opened!")
                                             .WithBody($"Tour number: {@event.TourId}. Tour date: {@event.Date}")
                                             .Build();

            await _busPublisher.SendAsync(notification, context);
        }
Example #15
0
        public async Task <bool> Handle(ExpireReservationCommand request, CancellationToken cancellationToken)
        {
            var reservation = await _db.Reservations.FirstOrDefaultAsync(x => x.Id == request.ReservationId, cancellationToken);

            reservation.Status = StatusReservation.Expired;

            await _db.SaveChangesAsync(cancellationToken);

            var message = new PublishReservationEventCommand
            {
                ReservationId = reservation.Id
            };

            await _bus.SendAsync(ContextNames.Queue.Library, message);

            return(true);
        }
        public async Task HandleAsync(ChangePasswordCommand command, ICorrelationContext context)
        {
            var user = await _userRepository.GetAsync(command.UserId);

            if (user == null)
            {
                throw new DomainException(Codes.UserNotFound, string.Format(MessagesCode.UserNotFound, command.UserId));
            }

            if (!user.ValidatePassword(command.PasswordHash, _passwordHasher))
            {
                throw new DomainException(Codes.InvalidCurrentPassword, MessagesCode.InvalidCurrentPassword);
            }

            user.SetPassword(command.PasswordHash, _passwordHasher);

            await _busPublisher.SendAsync(new ChangePasswordCommand(user.Id, user.PasswordHash), CorrelationContext.Empty);
        }
        public async Task HandleAsync(SignUpCommand command, ICorrelationContext context)
        {
            var user = await _userRepository.GetAsync(command.Email);

            if (user != null)
            {
                throw new DomainException(Codes.EmailInUse, string.Format(MessagesCode.EmailInUse, command.Email));
            }

            if (string.IsNullOrWhiteSpace(command.Password))
            {
                throw new DomainException(Codes.InvalidPassword, MessagesCode.InvalidPassword);
            }

            user = new User(command.Email);

            user.SetPassword(command.Password, _passwordHasher);

            await _busPublisher.SendAsync(new SignedUpCommand(user.Email, user.PasswordHash), CorrelationContext.Empty);
        }
Example #18
0
        public async Task <bool> Handle(CheckDueCommand request, CancellationToken cancellationToken)
        {
            var date = _dateTimeService.Now().Date.AddDays(1).AddSeconds(-1);

            var expiredList = await _db.Reservations
                              .Where(x => x.Loans.Any(l => l.DueDate.Date <= date))
                              .ToListAsync(cancellationToken);

            foreach (var item in expiredList)
            {
                var message = new ExpireReservationCommand
                {
                    ReservationId = item.Id
                };

                await _bus.SendAsync(ContextNames.Queue.Library, message);
            }

            return(true);
        }
Example #19
0
        public async Task <IActionResult> Post(GreetUser command)
        {
            await _busPublisher.SendAsync(command, GetContext());

            return(Accepted());
        }
Example #20
0
 public Task HandleAsync(DiscountCreated message, ISagaContext context)
 {
     return(_busPublisher.SendAsync(new SendEmailNotification("*****@*****.**",
                                                              "Discount", $"New discount: {message.Code}"),
                                    CorrelationContext.Empty));
 }
Example #21
0
 public Task CompensateAsync(DiscountCreated message, ISagaContext context)
 {
     return _busPublisher.SendAsync(new SendEmailNotification("*****@*****.**", "Discount", $"New Discount:{message.Code}"),
         CorrelationContext.Empty);
 }
Example #22
0
        public async Task <IActionResult> Add([FromBody] AddPaymentMethod command)
        {
            await _busPublisher.SendAsync <AddPaymentMethod>(command.BindId(x => x.Id), null);

            return(Accepted());
        }
Example #23
0
        public async Task <IActionResult> GetOrderSummary(RemoveItemFromOrder command)
        {
            await _busPublisher.SendAsync <RemoveItemFromOrder>(command, null);

            return(Accepted());
        }
Example #24
0
        public async Task <IActionResult> Post(CreateArticle command)
        {
            await _busPublisher.SendAsync(command);

            return(Accepted());
        }
Example #25
0
 public static async Task SendAsync <TMessage>(this IBusPublisher publisher, string queueName, TMessage message)
     where TMessage : class, IBusMessage
 {
     await publisher.SendAsync(queueName, new[] { message });
 }
        public async Task <IActionResult> AddAddress(AddPendingRegistration command)
        {
            await _busPublisher.SendAsync(command.Bind(x => x.Id, Guid.NewGuid()), null);

            return(Accepted());
        }
Example #27
0
        public async Task <IActionResult> CreateBasket([FromBody] CreateBasket command)
        {
            await _busPublisher.SendAsync(command.Bind(x => x.BasketId, Guid.NewGuid()), null);

            return(Accepted());
        }
 public Task SendAsync <T>(T command) where T : class, ICommand
 {
     return(_busPublisher.SendAsync(command, _accessor.CorrelationContext));
 }
Example #29
0
 public async Task HandleAsync(OrderCanceled message, ISagaContext context)
 {
     await _busPublisher.SendAsync(new ReleaseProducts(message.Id, message.Products),
                                   CorrelationContext.FromId(context.SagaId /* CorrelationId*/));
 }
Example #30
0
        public async Task <IActionResult> ScheduleSynchronization(ScheduleSynchronizationCommand command)
        {
            await busPublisher.SendAsync(command, CorrelationContext.Create());

            return(Accepted());
        }