Esempio n. 1
0
        public async Task <IActionResult> Update(Guid id, SubmitUpdateReservationCommand command)
        {
            if (id != command.Id)
            {
                return(BadRequest());
            }

            var validator = new SubmitUpdateReservationCommandValidator();
            var result    = await validator.ValidateAsync(command);

            if (!result.IsValid)
            {
                return(BadRequest(result.Errors));
            }

            var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("exchange:submit-update-reservation"));

            await endpoint.Send <SubmitUpdateReservation>(new
            {
                command.Id,
                command.From,
                command.To
            });

            return(NoContent());
        }
        public async Task <IActionResult> Update(Guid id, SubmitUpdateUserCommand command)
        {
            if (id != command.Id)
            {
                return(BadRequest());
            }

            var validator = new SubmitUpdateUserCommandValidator();
            var result    = await validator.ValidateAsync(command);

            if (!result.IsValid)
            {
                return(BadRequest(result.Errors));
            }

            var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("exchange:submit-update-user"));

            await endpoint.Send <SubmitUpdateUser>(new
            {
                command.Id,
                command.Username,
                command.Email,
                command.Password,
                command.FirstName,
                command.LastName,
                command.Address,
                command.City,
                command.Country,
                command.ZipCode,
            });

            return(NoContent());
        }
Esempio n. 3
0
        public async Task <IActionResult> Update(Guid id, SubmitUpdateResourceCommand command)
        {
            if (id != command.Id)
            {
                return(BadRequest());
            }

            var validator = new SubmitUpdateResourceCommandValidator();
            var result    = await validator.ValidateAsync(command);

            if (!result.IsValid)
            {
                return(BadRequest(result.Errors));
            }

            foreach (var dayAndTime in command.Available.Where(dayAndTime => dayAndTime.Id == Guid.Empty))
            {
                dayAndTime.Id = Guid.NewGuid();
            }

            var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("exchange:submit-update-resource"));

            await endpoint.Send <SubmitUpdateResource>(new
            {
                command.Id,
                command.Name,
                command.Description,
                command.Available
            });

            return(NoContent());
        }
Esempio n. 4
0
        /// <summary>
        /// Index视图
        /// </summary>
        /// <returns>Index视图</returns>
        public IActionResult Index()
        {
            var endpoint = send.GetSendEndpoint(new Uri($"rabbitmq://localhost/{typeof(MyMessageIntegrationEvent).Name}")).Result;

            endpoint.Send(new MyMessageIntegrationEvent("dxq", DateTime.Now));
            return(View());
        }
        public async Task CancelScheduledSend(Uri destinationAddress, Guid tokenId)
        {
            var command = new CancelScheduledMessageCommand(tokenId);

            var endpoint = await _sendEndpointProvider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);

            await endpoint.Send <CancelScheduledMessage>(command).ConfigureAwait(false);
        }
Esempio n. 6
0
        public async Task <ActionResult> NewProposal([FromBody] string proposalId)
        {
            var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri(RabbitMqConnectionInformation.ProposalSagaEndpoint));

            await endpoint.Send <INewProposalRequested>(new NewProposalRequested(proposalId));

            return(Ok());
        }
Esempio n. 7
0
        private async Task PublishFailed(SearchRequestEvent baseEvent, string message)
        {
            var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri($"rabbitmq://{this._rabbitMqConfiguration.Host}:{this._rabbitMqConfiguration.Port}/{nameof(SearchRequestFailed)}_queue"));

            _logger.LogInformation($"SearchRequestFailed has been published to {endpoint.ToString()}");
            await endpoint.Send <SearchRequestFailed>(new SearchRequestFailedEvent(baseEvent)
            {
                Cause = message
            });
        }
        public async Task <IActionResult> AddRate([FromBody] RatingViewModel vm)
        {
            var orderItem = _context.OrderItems.Include(o => o.Order).Where(o => o.OrderItemId == vm.OrderItemId).SingleOrDefault();



            if (orderItem == null)
            {
                return(NotFound(new { success = false, message = "Not Found" }));
            }
            else
            {
                if (orderItem.Order.Status != 3)
                {
                    return(BadRequest(new { success = false, message = "You cant not rate this item when order is not done" }));
                }
                if (orderItem.isRate == true)
                {
                    return(BadRequest(new { success = false, message = "This item has rated" }));
                }
                else
                {
                    var endPoint = await _sendEndpointProvider.
                                   GetSendEndpoint(new Uri("queue:" + BusConstant.CommentQueue));

                    await endPoint.Send <CommentMessage>(new
                    {
                        CommentId   = vm.CommentId,
                        BuyerId     = vm.BuyerId,
                        FullName    = vm.FullName,
                        UserId      = vm.UserId,
                        BookId      = vm.BookId,
                        Rating      = vm.Rating,
                        Content     = vm.Content,
                        CreatedDate = DateTime.UtcNow
                    });

                    var endPoint1 = await _sendEndpointProvider.
                                    GetSendEndpoint(new Uri("queue:" + BusConstant.RateQueue));

                    await endPoint1.Send <RatingMessage>(new {
                        BookId = vm.BookId,
                        Rating = vm.Rating
                    });

                    orderItem.isRate = true;

                    await _context.SaveChangesAsync();

                    return(Ok(new { success = true, message = "Rating success" }));
                }
            }
        }
Esempio n. 9
0
        public async Task <ScheduledMessage <T> > ScheduleSend <T>(Uri destinationAddress, DateTime scheduledTime, Task <T> message, IPipe <SendContext <T> > pipe,
                                                                   CancellationToken cancellationToken)
            where T : class
        {
            var payload = await message.ConfigureAwait(false);

            var scheduleMessagePipe = new ScheduleSendPipe <T>(pipe, scheduledTime);

            var endpoint = await _sendEndpointProvider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);

            await endpoint.Send(payload, scheduleMessagePipe, cancellationToken).ConfigureAwait(false);

            return(new ScheduledMessageHandle <T>(scheduleMessagePipe.ScheduledMessageId ?? NewId.NextGuid(), scheduledTime, destinationAddress, payload));
        }
Esempio n. 10
0
        public async Task <IActionResult> Create([FromBody] InputModel input)
        {
            var newCorrelationId = Guid.NewGuid();

            var sendEndpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("queue:create-work-item"));

            await sendEndpoint.Send <CreateWorkItemEvent>(new
            {
                CorrelationId = newCorrelationId,
                input.BizIdentifier,
                input.ScheduledDate
            });

            return(Accepted(new { correlationId = newCorrelationId }));
        }
Esempio n. 11
0
        public async Task <IEnumerable <WeatherForecast> > Get()
        {
            var rng = new Random();
            IEnumerable <WeatherForecast> data = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date         = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary      = Summaries[rng.Next(Summaries.Length)]
            })
                                                 .ToArray();

            var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("queue:test-queue"));

            var message = new WeatherForecastUpdatedList(data.Select(x => _mapper.Map <WeatherForecastUpdated>(x)).ToList());

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken       cancellationToken       = cancellationTokenSource.Token;

            cancellationTokenSource.CancelAfter(30000);
            cancellationToken.ThrowIfCancellationRequested();

            await endpoint.Send <WeatherForecastUpdatedList>(message, cancellationToken);

            return(data);
        }
        public async Task <Unit> Handle(CreateBookingRequestCommand request, CancellationToken cancellationToken)
        {
            var customerId = new CustomerId(request.CustomerId);
            var facilityId = new FacilityId(request.FacilityId);
            var offerIds   = request.BookedRecords.Select(r => new OfferId(r.OfferId));
            var offers     = await offerRepository.GetByIdsAsync(offerIds);

            var bookedRecords = MappBookedRecords(request, offers);

            var booking = Booking.CreateRequested(
                customerId,
                facilityId,
                bookedRecords
                );

            await bookingRepository.AddAsync(booking);

            await unitOfWork.CommitAsync();

            var sendEndpoint = await sendEndpointProvider.GetSendEndpoint(new Uri($"exchange:{request.EventBusExchanges[EventBusExchange.BookingRequests]}"));

            await sendEndpoint.Send(new BookingRequested(
                                        facilityId,
                                        booking.Id)
                                    );

            return(Unit.Value);
        }
        public async Task Send <T>(T message) where T : class
        {
            var sendEndpoint = await _sendEndpointProvider.GetSendEndpoint(typeof(T).GetUriForMessage());

            Console.WriteLine($"{typeof(T).GetUriForMessage()} send: {JsonConvert.SerializeObject(message)}");
            await sendEndpoint.Send(message);
        }
Esempio n. 14
0
        public async Task <IActionResult> ReceivePayment(PaymentDto paymentDto)
        {
            // paymentDto ile ödeme işlemi

            var sendEndpoint = await _sendEndpointProvider.GetSendEndpoint(new System.Uri("queue:create-order-service"));

            var createOrderMessageCommand = new CreateOrderMessageCommand();

            createOrderMessageCommand.BuyerId  = paymentDto.Order.BuyerId;
            createOrderMessageCommand.Province = paymentDto.Order.Address.Province;
            createOrderMessageCommand.District = paymentDto.Order.Address.District;
            createOrderMessageCommand.Street   = paymentDto.Order.Address.Street;
            createOrderMessageCommand.Line     = paymentDto.Order.Address.Line;
            createOrderMessageCommand.ZipCode  = paymentDto.Order.Address.ZipCode;

            paymentDto.Order.OrderItems.ForEach(x =>
            {
                createOrderMessageCommand.OrderItems.Add(new OrderItem
                {
                    PictureUrl  = x.PictureUrl,
                    Price       = x.Price,
                    ProductId   = x.ProductId,
                    ProductName = x.ProductName
                });
            });

            await sendEndpoint.Send <CreateOrderMessageCommand>(createOrderMessageCommand);

            return(CreateActionResultInstance(Shared.Dtos.Response <NoContent> .Success(200)));
        }
Esempio n. 15
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ISendEndpointProvider endpointProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHealthChecks("/health", new HealthCheckOptions {
                Predicate = check => check.Tags.Contains("ready")
            });

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                async Task RequestDelegate(HttpContext context)
                {
                    int value = 0;
                    int count = 0;

                    do
                    {
                        value += 1;
                        await context.Response.WriteAsync($"Message: {value} \n");
                        count += 1;

                        var endpoint = await endpointProvider.GetSendEndpoint(new Uri("rabbitmq://localhost/test-work-queue"));

                        await endpoint.Send <INotification>(new { ThreadId = value, Name = $"Message: {value}", CreatedAt = DateTime.UtcNow });
                    } while (count <= 100);
                }

                endpoints.MapGet("/", RequestDelegate);
            });
        }
        public async Task Submit(SubmitOrder order)
        {
            //_publishEndpoint.Publish<ISubmitOrder>(order);
            var sendEndpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("queue:order-saga"));

            await sendEndpoint.Send <ISubmitOrder>(order);
        }
Esempio n. 17
0
        public async Task SendResponseAsync(ICalculation calculation)
        {
            Logger.Instance.Info($"Sending Response Id:{calculation.Id}, Current:{calculation.Current}.");
            var endpoint = await _endpointProvider.GetSendEndpoint(EndpointUri);

            await endpoint.Send(calculation);
        }
        public async Task SendMessage <T>(T message, string targetEndPoint)
        {
            var endpoint      = $"rabbitmq://{_rabbitConfig.Host}:{_rabbitConfig.Port}/{targetEndPoint}?durable={_rabbitConfig.DurableQueue}";
            var finalEndpoint = await _sendEndpoint.GetSendEndpoint(new Uri(endpoint));

            await finalEndpoint.Send(message);
        }
        async Task PublishSubscriptionEvent <T>(RoutingSlipEvents eventFlag, Func <RoutingSlipEventContents, T> messageFactory, Subscription subscription)
            where T : class
        {
            if ((subscription.Events & RoutingSlipEvents.EventMask) == RoutingSlipEvents.All || subscription.Events.HasFlag(eventFlag))
            {
                if (string.IsNullOrWhiteSpace(_activityName) || string.IsNullOrWhiteSpace(subscription.ActivityName) ||
                    _activityName.Equals(subscription.ActivityName, StringComparison.OrdinalIgnoreCase))
                {
                    var endpoint = await _sendEndpointProvider.GetSendEndpoint(subscription.Address).ConfigureAwait(false);

                    var message = messageFactory(subscription.Include);

                    if (subscription.Message != null)
                    {
                        var adapter = new MessageEnvelopeContextAdapter(null, subscription.Message, JsonMessageSerializer.ContentTypeHeaderValue, message);

                        await endpoint.Send(message, adapter).ConfigureAwait(false);
                    }
                    else
                    {
                        await endpoint.Send(message).ConfigureAwait(false);
                    }
                }
            }
        }
Esempio n. 20
0
        public async Task <ActionResult <GuildResponseDto> > CreateGuild(
            [FromBody] CreateGuildRequestDto createGuildRequestDto
            )
        {
            Debug.Assert(HttpContext.Items["StrifeUserId"] != null, "HttpContext.Items['UserId'] != null");
            var userId = (Guid)HttpContext.Items["StrifeUserId"];

            try
            {
                var guild = _mapper.Map <Guild>(createGuildRequestDto);
                guild.Id = Guid.NewGuid();

                var createGuildEndpoint =
                    await _sendEndpointProvider.GetSendEndpoint(GuildAddresses.CreateGuildConsumer);

                await createGuildEndpoint.Send <ICreateGuild>(new
                {
                    GuildId = guild.Id,
                    guild.Name,
                    InitiatedBy = userId,
                });

                return(Ok(_mapper.Map <GuildResponseDto>(guild)));
            }
            catch (Exception exception)
            {
                Log.Fatal(exception, "Fatal exception while creating Guild");
                return(Problem());
            }
        }
Esempio n. 21
0
        public async Task<IActionResult> UpdateSubmitCustomer([FromBody] CustomerRequest customerRequest)
        {
            var endpoint = await _sendEndpointProvider.GetSendEndpoint(new System.Uri("exchange:submit-customer"));

            await endpoint.Send<SubmitCustomer>(customerRequest);
            return Ok();
        }
Esempio n. 22
0
        public async Task <IActionResult> CreateBookingUsingStateMachineInDb([FromBody] BookingModel bookingModel)
        {
            bookingModel.BookingId = Guid.NewGuid();
            var endpoint = await _sendEndpointProvider.GetSendEndpoint(new Uri("queue:" + BusConstants.StartBookingTranastionQueue));

            //var clientconfig = new ClientConfig();

            //clientconfig.GetGroupConfig().SetName("prod");
            //clientconfig.GetNetworkConfig().AddAddress("localhost:44398");

            //var client = HazelcastClient.NewHazelcastClient(clientconfig);

            //var map = client.GetMap<string, BookingModel>("my-distributed-map");

            //map.Put("BookingDetails", bookingModel);

            _bookingDataAccess.SaveBooking(bookingModel);

            await endpoint.Send <IStartBooking>(new
            {
                BookingId     = bookingModel.BookingId,
                CardDetails   = bookingModel.CardDetails,
                FlightDetails = bookingModel.FlightDetails
            });

            return(Ok("Success"));
        }
Esempio n. 23
0
        public async Task <TRequest> Send(Guid requestId, object values, IPipe <SendContext <TRequest> > pipe, CancellationToken cancellationToken)
        {
            var endpoint = await _provider.GetSendEndpoint(_destinationAddress).ConfigureAwait(false);

            var initializer = MessageInitializerCache <TRequest> .GetInitializer(values.GetType());

            if (_consumeContext != null)
            {
                var initializeContext = initializer.Create(_consumeContext);

                return(await initializer.Send(endpoint, initializeContext, values, new ConsumeSendEndpointPipe <TRequest>(_consumeContext, pipe, requestId))
                       .ConfigureAwait(false));
            }

            return(await initializer.Send(endpoint, values, pipe, cancellationToken).ConfigureAwait(false));
        }
Esempio n. 24
0
        /// <summary>
        /// Send a message
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="provider"></param>
        /// <param name="values"></param>
        /// <param name="pipe"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static async Task Send <T>(this ISendEndpointProvider provider, object values, IPipe <SendContext> pipe,
                                          CancellationToken cancellationToken = default)
            where T : class
        {
            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            if (!EndpointConvention.TryGetDestinationAddress <T>(out var destinationAddress))
            {
                throw new ArgumentException($"A convention for the message type {TypeMetadataCache<T>.ShortName} was not found");
            }

            var endpoint = await provider.GetSendEndpoint(destinationAddress).ConfigureAwait(false);

            var initializer = MessageInitializerCache <T> .GetInitializer(values.GetType());

            if (provider is ConsumeContext context)
            {
                await initializer.Send(endpoint, initializer.Create(context), values, pipe).ConfigureAwait(false);
            }
            else
            {
                await initializer.Send(endpoint, values, pipe, cancellationToken).ConfigureAwait(false);
            }
        }
        public async Task Send <T>(T message, IPipe <SendContext <T> > pipe, CancellationToken cancellationToken)
            where T : class
        {
            var sendEndpoint = await _context.GetSendEndpoint(_destinationAddress).ConfigureAwait(false);

            await sendEndpoint.Send(message, pipe, cancellationToken).ConfigureAwait(false);
        }
Esempio n. 26
0
        public async Task Send <T>(T message, CancellationToken cancellationToken = default(CancellationToken)) where T : class, ICommand
        {
            var destinationQ = _routeRegistry.For <T>();
            var sendEndpoint = await _sendEndpointProvider.GetSendEndpoint(destinationQ);

            await sendEndpoint.Send(message, cancellationToken);
        }
Esempio n. 27
0
        public async Task Send <TCommand>(string queueName, TCommand command)
            where TCommand : IQueueMessageBase
        {
            var endPoint = await _sendEndpointProvider.GetSendEndpoint(_queueUriBuilder.Create(queueName));

            await endPoint.Send(command);
        }
        public async Task Consume(ConsumeContext <InventoryCheckRequestMessage> context)
        {
            Console.WriteLine($"Inventory Check Request Received: OrderId: {context.Message.OrderId}");

            var product = _repo.GetById(context.Message.ProductId);

            var response = new InventoryCheckResponseMessage
            {
                ProductId = context.Message.ProductId,
                OrderId   = context.Message.OrderId,
                Succeeded = false                       // default to fail
            };
            var sendEP = await _sendEPProvider.GetSendEndpoint(
                new Uri($"sb://{Constants.SB_HOST}/{Constants.SB_QUEUE_IC_RES}"));

            if (product != null && product.Quantity >= context.Message.Quantity)
            {
                product.Quantity -= context.Message.Quantity;
                _repo.Update(product);
                await _repo.SaveChangesAsync();

                response.Succeeded = true;
                await sendEP.Send <InventoryCheckResponseMessage>(response);
            }
            else
            {
                await sendEP.Send <InventoryCheckResponseMessage>(response);
            }
        }
        public async Task ExecuteAsync(ISendEndpointProvider endpointProvider, ProducerOptions options, CancellationToken stoppingToken)
        {
            var endpoint = await endpointProvider.GetSendEndpoint(new Uri(@"queue:record-timestamp"));

            while (!stoppingToken.IsCancellationRequested && _executionCount < options.MaxSendCount)
            {
                Task[] tasks = new Task[options.MaxSendConcurrency];

                for (int i = 0; i < tasks.Length; i++)
                {
                    _logger.LogInformation("Sending message {Index}/{Total}, total = {ExecutionCount} ...", i, options.MaxSendConcurrency, _executionCount);

                    tasks[i] = endpoint.Send <RecordTimestamp>(new
                    {
                        TaskId     = i,
                        ThreadId   = Thread.CurrentThread.ManagedThreadId,
                        ProducerId = Id,
                        SentTime   = DateTime.UtcNow
                    });

                    _executionCount++;
                }

                Task.WaitAll(tasks);

                if (options.Interval > 0)
                {
                    await Task.Delay(options.Interval, stoppingToken);
                }
            }
        }
Esempio n. 30
0
        async Task IBusManager.SendMessage <T>(T message, string queueaName)
        {
            var endpoint = await _sendEndpointProvider.GetSendEndpoint(
                new Uri(_config.GetSection("RabbitMq:Endpoint").Value + "/" + queueaName));

            await endpoint.Send(message, x => { x.Durable = true; });
        }