Exemple #1
0
        public async Task SendMessagesAsync(CancellationToken token)
        {
            _bus = await Helper.StartBusControlFluent();

            _sender = await _bus.GetSendEndpoint(new Uri(Consts.Endpoint + _options.QueueName));

            Helper.WriteLine($"Started sending messages to queue \"{_options.QueueName}\".", ConsoleColor.Magenta);
            bool useMessage2 = false;

            while (!token.IsCancellationRequested)
            {
                ConsoleColor color;
                IMessageBase message;
                if (useMessage2)
                {
                    message = Helper.CreateMessage2();
                    await _sender.Send <IDemoMessage2>(message);

                    color = ConsoleColor.White;
                }
                else
                {
                    message = Helper.CreateMessage();
                    await _sender.Send <IDemoMessage>(message);

                    color = ConsoleColor.Yellow;
                }
                Helper.WriteLine($"Sent message {message.GetType().Name}: Id = {message.Id}", color);

                useMessage2 = !useMessage2;
                await Task.Delay(_options.ProcessTime);
            }
        }
        static void Main(string[] args)
        {
            var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host(new Uri("rabbitmq://localhost/"), hst =>
                {
                    hst.Username("guest");
                    hst.Password("guest");
                });
            });

            var           senUri = new Uri("rabbitmq://localhost/MailQue");
            ISendEndpoint send   = bus.GetSendEndpoint(senUri).Result;

            UserMail mail1 = new UserMail()
            {
                User = new User {
                    Mail = "*****@*****.**", Name = "feyyaz acet"
                }, Subject = "Sample MassTransit With RabbitMQ  ", Body = "RabbitMQ and MassTransit say Hello"
            };

            send.Send(mail1).Wait();

            UserMail mail2 = new UserMail()
            {
                User = new User {
                    Mail = "*****@*****.**", Name = "feyyaz acet"
                }, Subject = "Sample MassTransit With RabbitMQ  ", Body = "RabbitMQ and MassTransit say Hello"
            };

            send.Send(mail2).Wait();

            Console.ReadKey();
        }
Exemple #3
0
 public async Task Post([FromQuery] string type)
 {
     if (type == "1")
     {
         await _endPoint.Send <IRegisterCustomer>(new
         {
             Address         = "New Street",
             Id              = Guid.NewGuid(),
             Preferred       = true,
             RegisteredUtc   = DateTime.UtcNow,
             Name            = "Nice people LTD",
             Type            = 1,
             DefaultDiscount = 0
         });
     }
     else
     {
         await _endPoint.Send <IRegisterCustomer2>(new
         {
             Address         = "New Street",
             Id              = Guid.NewGuid(),
             Preferred       = true,
             RegisteredUtc   = DateTime.UtcNow,
             Name            = "Nice people LTD",
             Type            = 1,
             DefaultDiscount = 0
         });
     }
 }
Exemple #4
0
        public virtual Task Send <T>(T message, CancellationToken cancellationToken)
            where T : class
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            return(_endpoint.Send(message, GetPipeProxy <T>(), cancellationToken));
        }
        public Task Send <T>(T message, CancellationToken cancellationToken)
            where T : class
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var sendContextPipe = new ConsumeSendEndpointPipe <T>(_context, _requestId);

            return(ConsumeTask(_endpoint.Send(message, sendContextPipe, cancellationToken)));
        }
        public async Task Send(ISendEndpoint endpoint, TInput input, IPipe <SendContext> pipe, CancellationToken cancellationToken)
        {
            InitializeMessageContext <TMessage, TInput> messageContext = await InitializeMessage(input, cancellationToken).ConfigureAwait(false);

            if (_headerInitializers.Length > 0)
            {
                await endpoint.Send(messageContext.Message, new InitializerSendContextPipe(_headerInitializers, messageContext, pipe), cancellationToken)
                .ConfigureAwait(false);
            }
            else
            {
                await endpoint.Send(messageContext.Message, pipe, cancellationToken).ConfigureAwait(false);
            }
        }
Exemple #7
0
        private async Task LogAsync(string level, string message, string system)
        {
            var data = new Dictionary <string, string> {
                { "Level", level },
                { "System", system },
                { "Log", message }
            };

            try
            {
                var dto = new Dto(data.ToImmutableDictionary());
                if (_sendEndPoint != null)
                {
                    await DeCache();

                    await _sendEndPoint.Send(dto);
                }
                else
                {
                    var context = Context.CreateScope();
                    if (context != null)
                    {
                        using (IServiceScope serviceScope = context)
                        {
                            var busControl = serviceScope.ServiceProvider.GetService <IBusControl>();
                            _sendEndPoint = await busControl.GetSendEndpoint(new Uri(_queueUri));

                            if (_sendEndPoint != null)
                            {
                                await DeCache();

                                await _sendEndPoint.Send(dto);
                            }
                            else
                            {
                                _logCache.Add(data);
                            }
                        }
                    }
                    else
                    {
                        _logCache.Add(data);
                    }
                }
            }
            catch (Exception e) {
                _logCache.Add(data);
            }
        }
        public Task Send <T>(T message, CancellationToken cancellationToken)
            where T : class
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var sendContextPipe = new ConsumeSendContextPipe <T>(_context);

            var task = _endpoint.Send(message, sendContextPipe, cancellationToken);

            _context.ReceiveContext.AddPendingTask(task);
            return(task);
        }
Exemple #9
0
        async Task GenerateFault <T>(ConsumeContext <T> context, Exception exception)
            where T : class
        {
            Fault <T> fault = new FaultEvent <T>(context.Message, context.MessageId, HostMetadataCache.Host, exception);

            IPipe <SendContext <Fault <T> > > faultPipe = Pipe.Execute <SendContext <Fault <T> > >(x =>
            {
                x.SourceAddress = ReceiveContext.InputAddress;
                x.CorrelationId = CorrelationId;
                x.RequestId     = RequestId;

                foreach (var header in Headers.GetAll())
                {
                    x.Headers.Set(header.Key, header.Value);
                }
            });

            if (FaultAddress != null)
            {
                ISendEndpoint endpoint = await GetSendEndpoint(FaultAddress);

                await endpoint.Send(fault, faultPipe, CancellationToken);
            }
            else if (ResponseAddress != null)
            {
                ISendEndpoint endpoint = await GetSendEndpoint(ResponseAddress);

                await endpoint.Send(fault, faultPipe, CancellationToken);
            }
            else
            {
                await _publishEndpoint.Value.Publish(fault, faultPipe, CancellationToken);
            }
        }
Exemple #10
0
        public async Task Should_work_with_lifecycle_managed_bus()
        {
            var bus = _container.Resolve <IBusControl>();

            BusHandle busHandle = await bus.StartAsync();

            try
            {
                ISendEndpoint endpoint = await bus.GetSendEndpoint(new Uri("loopback://localhost/input_queue"));

                const string name = "Joe";

                await endpoint.Send(new SimpleMessageClass(name));

                SimpleConsumer lastConsumer = await SimpleConsumer.LastConsumer;
                lastConsumer.ShouldNotBe(null);

                SimpleMessageInterface last = await lastConsumer.Last;
                last.Name
                .ShouldBe(name);

                bool wasDisposed = await lastConsumer.Dependency.WasDisposed;
                wasDisposed
                .ShouldBe(true);     //Dependency was not disposed");

                lastConsumer.Dependency.SomethingDone
                .ShouldBe(true);     //Dependency was disposed before consumer executed");
            }
            finally
            {
                await busHandle.StopAsync();
            }
        }
Exemple #11
0
        public Task Act(TScenario scenario, CancellationToken cancellationToken)
        {
            ISendEndpoint endpoint = _endpointAccessor(scenario);

            return(endpoint.Send(_message, Pipe.New <SendContext <TMessage> >(x => x.UseExecute(context => _callback(scenario, context))),
                                 cancellationToken));
        }
Exemple #12
0
        /// <summary>
        /// Send a message
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="context"></param>
        /// <param name="destinationAddress"></param>
        /// <param name="values"></param>
        /// <param name="pipe"></param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static async Task Send <T>(this ConsumeContext context, Uri destinationAddress, object values, IPipe <SendContext> pipe)
            where T : class
        {
            ISendEndpoint endpoint = await context.GetSendEndpoint(destinationAddress).ConfigureAwait(false);

            await endpoint.Send <T>(values, pipe, context.CancellationToken).ConfigureAwait(false);
        }
Exemple #13
0
        //directly use send/publish without open/close the connection
        private static void RunMassTransitPublisherWithRabbit()
        {
            string rabbitMqAddress = "rabbitmq://dinosaur.rmq.cloudamqp.com/rsydflmj";
            string rabbitMqQueue   = "mycompany.domains.queues";
            Uri    rabbitMqRootUri = new Uri(rabbitMqAddress);
            //setup a RabbitMQ bus instance
            IBusControl rabbitBusControl = Bus.Factory.CreateUsingRabbitMq(rabbit =>
            {
                rabbit.Host(rabbitMqRootUri, settings =>
                {
                    settings.Password("RfVhrh7rBzjbRmgSOH12Y7HfvXCraAbB");
                    settings.Username("rsydflmj");
                });
            });

            Task <ISendEndpoint> sendEndpointTask = rabbitBusControl.GetSendEndpoint(new Uri(string.Concat(rabbitMqAddress, "/", rabbitMqQueue)));
            ISendEndpoint        sendEndpoint     = sendEndpointTask.Result;

            Task sendTask = sendEndpoint.Send <IRegisterCustomer>(new
            {
                Address         = "New Street",
                Id              = Guid.NewGuid(),
                Preferred       = true,
                RegisteredUtc   = DateTime.UtcNow,
                Name            = "Nice people LTD",
                Type            = 1,
                DefaultDiscount = 0
            });

            Console.ReadKey();
        }
        private async void btnSagaUpdateProducts_Click(object sender, EventArgs e)
        {
            try
            {
                _sagaSendPoint = await _azureBus.GetSendEndpointAsync(_sagaQueueName);

                // ReSharper disable once UseObjectOrCollectionInitializer
                var cmd = new SagaUpdateProductsBatchCommand();
                //cmd. = txtSagaCorrelate.Text.Trim();
                cmd.CorrelationId = _lastSagaCorrelationId;
                cmd.Products.Add(new ProductData());
                cmd.Products.Add(new ProductData());
                cmd.Products.Add(new ProductData());
                cmd.Products.Add(new ProductData());
                cmd.Products.Add(new ProductData());

                await _sagaSendPoint.Send(cmd);

                LogLine($"Message ({nameof(SagaUpdateProductsBatchCommand)}) sent OK \r\n");
            }
            catch (Exception ex)
            {
                LogError($"Exception);ption! \r\n ExType: {ex.GetType().Name}\r\n ExMessage: {ex.Message}\r\n");
            }
        }
Exemple #15
0
        /// <summary>
        /// Send a message
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="context"></param>
        /// <param name="endpointAddress"></param>
        /// <param name="values"></param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static async Task Send <T>(this ConsumeContext context, Uri endpointAddress, object values)
            where T : class
        {
            ISendEndpoint endpoint = await context.GetSendEndpoint(endpointAddress).ConfigureAwait(false);

            await endpoint.Send <T>(values, context.CancellationToken).ConfigureAwait(false);
        }
Exemple #16
0
        /// <summary>
        /// Send a message
        /// </summary>
        /// <typeparam name="T">The message type</typeparam>
        /// <param name="context"></param>
        /// <param name="endpointAddress"></param>
        /// <param name="message">The message</param>
        /// <param name="pipe"></param>
        /// <returns>The task which is completed once the Send is acknowledged by the broker</returns>
        public static async Task Send <T>(this ConsumeContext context, Uri endpointAddress, T message, IPipe <SendContext> pipe)
            where T : class
        {
            ISendEndpoint endpoint = await context.GetSendEndpoint(endpointAddress).ConfigureAwait(false);

            await endpoint.Send(message, pipe, context.CancellationToken).ConfigureAwait(false);
        }
Exemple #17
0
        public async Task Should_work_with_the_registry()
        {
            var bus = _container.GetInstance <IBusControl>();

            BusHandle busHandle = await bus.StartAsync();

            await busHandle.Ready;

            ISendEndpoint endpoint = await bus.GetSendEndpoint(new Uri("loopback://localhost/input_queue"));

            const string name = "Joe";

            await endpoint.Send(new SimpleMessageClass(name));

            var lastConsumer = await SimpleConsumer.LastConsumer;

            lastConsumer.ShouldNotBeNull();

            var last = await lastConsumer.Last;

            last.Name
            .ShouldBe(name);

            var wasDisposed = await lastConsumer.Dependency.WasDisposed;

            wasDisposed
            .ShouldBeTrue();     // Dependency was not disposed");

            lastConsumer.Dependency.SomethingDone
            .ShouldBeTrue();     // Dependency was disposed before consumer executed");
        }
        public async Task <IActionResult> CreateEvent([FromBody] EventData input)
        {
            var id  = Guid.NewGuid();
            var cmd = new CreateEvent()
            {
                Title       = input.Title,
                Description = input.Description,
                EventId     = id
            };

            await sendEndpoint.Send(cmd);

            return(Accepted(new EventCreateResponse {
                EventId = id
            }));
        }
 public async static Task Send(this ISendEndpoint endpoint, object message, RequestContext requestContext)
 {
     await endpoint.Send(message, context =>
     {
         context.SetHeaders(requestContext);
     });
 }
        Task ISendEndpointConverter.Send(ISendEndpoint endpoint, object message, IPipe <SendContext> pipe,
                                         CancellationToken cancellationToken)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException(nameof(endpoint));
            }
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }
            if (pipe == null)
            {
                throw new ArgumentNullException(nameof(pipe));
            }

            var msg = message as T;

            if (msg == null)
            {
                throw new ArgumentException("Unexpected message type: " + message.GetType().GetTypeName());
            }

            return(endpoint.Send(msg, pipe, cancellationToken));
        }
Exemple #21
0
        /// <summary>
        /// Sends registration message to the other application
        /// </summary>
        private static void SendMessage()
        {
            string address = "rabbitmq://localhost";
            string queue   = "uppgift4.domains.queueGrade";
            Uri    rootUri = new Uri(address);

            IBusControl busControl = Bus.Factory.CreateUsingRabbitMq(r =>
            {
                r.Host(rootUri, settings =>
                {
                    settings.Username("guest");
                    settings.Password("guest");
                });
            });

            Task <ISendEndpoint> sendEndpointTask = busControl.GetSendEndpoint(new Uri(string.Concat(address, "/", queue)));
            ISendEndpoint        sendEndpoint     = sendEndpointTask.Result;

            while (true)
            {
                var message = CreateMessage();

                Task sendTask = sendEndpoint.Send <IStudentRegistration>(new
                {
                    Ideal      = message[0],
                    CourseCode = message[1],
                    Term       = message[2],
                    ExamNumber = message[3],
                    Grade      = message[4]
                });
                WaitForMessage();
            }
        }
        private async void btnSagaStart_Click(object sender, EventArgs e)
        {
            _lastSagaCorrelationId = Guid.NewGuid();
            try
            {
                if (string.IsNullOrEmpty(txtSagaCorrelate.Text.Trim()))
                {
                    throw new ArgumentNullException($"{nameof(txtSagaCorrelate)}");
                }

                _sagaSendPoint = await _azureBus.GetSendEndpointAsync(_sagaQueueName);

                await _sagaSendPoint.Send(new SagaStartUpdatesCommand
                {
                    // We can either something pretty unique to correlate against. OrderId could be a candidate.
                    UniqueText = txtSagaCorrelate.Text.Trim(),
                    // OR! If the Saga-starting message is under your control, you can simplify things by generating your own CorrelationId.
                    CorrelationId = _lastSagaCorrelationId
                });

                LogLine($"Message ({nameof(SagaStartUpdatesCommand)}) sent OK \r\n");
            }
            catch (Exception ex)
            {
                LogError($"Exception! \r\n ExType: {ex.GetType().Name}\r\n ExMessage: {ex.Message}\r\n");
            }
        }
        protected async Task SendRequest(BehaviorContext <TInstance> context, ConsumeContext consumeContext, TRequest requestMessage)
        {
            var pipe = new SendRequestPipe(consumeContext.ReceiveContext.InputAddress);

            ISendEndpoint endpoint = await consumeContext.GetSendEndpoint(_request.Settings.ServiceAddress).ConfigureAwait(false);

            await endpoint.Send(requestMessage, pipe).ConfigureAwait(false);

            _request.SetRequestId(context.Instance, pipe.RequestId);

            if (_request.Settings.Timeout > TimeSpan.Zero)
            {
                DateTime now            = DateTime.UtcNow;
                DateTime expirationTime = now + _request.Settings.Timeout;

                RequestTimeoutExpired message = new TimeoutExpired(now, expirationTime, context.Instance.CorrelationId, pipe.RequestId);

                MessageSchedulerContext schedulerContext;
                if (_request.Settings.SchedulingServiceAddress != null)
                {
                    ISendEndpoint scheduleEndpoint = await consumeContext.GetSendEndpoint(_request.Settings.SchedulingServiceAddress).ConfigureAwait(false);

                    await scheduleEndpoint.ScheduleSend(consumeContext.ReceiveContext.InputAddress, expirationTime, message).ConfigureAwait(false);
                }
                else if (consumeContext.TryGetPayload(out schedulerContext))
                {
                    await schedulerContext.ScheduleSend(expirationTime, message).ConfigureAwait(false);
                }
                else
                {
                    throw new ConfigurationException("A request timeout was specified but no message scheduler was specified or available");
                }
            }
        }
Exemple #24
0
        private async Task SendEventAsync(Article article)
        {
            ISendEndpoint endPoint = await BusConfigurator.GetEndPointAsync(RabbitMqConstants.ArticleSagaQueue);

            foreach (IEvent @event in article.GetUncommittedEvents())
            {
                var obj = (ISagaArticleUpdatedEvent)@event;
                await endPoint.Send <ISagaArticleUpdatedEvent>(new
                {
                    obj.AggregateId,
                    obj.Abstract,
                    obj.Approved,
                    obj.Body,
                    obj.CategoryId,
                    obj.City,
                    obj.CommentsEnabled,
                    obj.Country,
                    obj.ExpireDate,
                    obj.Listed,
                    obj.OnlyForMembers,
                    obj.ReleaseDate,
                    obj.State,
                    obj.Title
                });
            }
        }
Exemple #25
0
        public async void Should_work_with_the_registry()
        {
            var bus = _container.GetInstance <IBusControl>();

            bus.Start();

            ISendEndpoint endpoint = await bus.GetSendEndpoint(new Uri("loopback://localhost/input_queue"));

            const string name = "Joe";

            await endpoint.Send(new SimpleMessageClass(name));

            SimpleConsumer lastConsumer = await SimpleConsumer.LastConsumer;

            lastConsumer.ShouldNotBe(null);

            SimpleMessageInterface last = await lastConsumer.Last;

            last.Name
            .ShouldBe(name);

            bool wasDisposed = await lastConsumer.Dependency.WasDisposed;

            wasDisposed
            .ShouldBe(true);     //Dependency was not disposed");

            lastConsumer.Dependency.SomethingDone
            .ShouldBe(true);     //Dependency was disposed before consumer executed");
        }
Exemple #26
0
        private static async Task SendOrders(ISendEndpoint endpointInstance)
        {
            Console.WriteLine("Press enter to send a message");
            Console.WriteLine("Press any key to exit");

            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();

                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }
                var id = Guid.NewGuid();

                await endpointInstance.Send <IPlaceOrderCommand>(new
                {
                    Product = "New shoes",
                    Id      = id
                });

                _processingCount++;
                await Console.Out.WriteLineAsync($"POST {nameof(IPlaceOrderCommand)} [{_processingCount}], {nameof(IPlaceOrderCommand.Id)}: {id:N}");
            }
        }
Exemple #27
0
        private static void RunMessageBus()
        {
            string rabbitMqAddress = "rabbitmq://localhost:5672/payment";
            string rabbitMqQueue   = "superdigital.payments.orderpayments";
            Uri    rabbitMqRootUri = new Uri(rabbitMqAddress);

            IBusControl rabbitBusControl = Bus.Factory.CreateUsingRabbitMq(rabbit =>
            {
                rabbit.Host(rabbitMqRootUri, settings =>
                {
                    settings.Password("guest");
                    settings.Username("guest");
                });
            });

            Task <ISendEndpoint> sendEndpointTask = rabbitBusControl.GetSendEndpoint(new Uri(string.Concat(rabbitMqAddress, "/", rabbitMqQueue)));
            ISendEndpoint        sendEndpoint     = sendEndpointTask.Result;


            for (int i = 0; i < 100; i++)
            {
                Task sendTask = sendEndpoint.Send <ICreatePayment>(new
                {
                    CreditAccount = 5587,
                    DebitAccount  = 6698,
                    Value         = i + 580,
                    PaymentType   = "Salary"
                });

                sendTask.Wait();
                Console.WriteLine("Mensagem {0} enviada", i);
            }
            Console.ReadKey();
        }
Exemple #28
0
        async Task GenerateFault <T>(T message, Exception exception)
            where T : class
        {
            Fault <T> fault = new FaultEvent <T>(message, HostMetadataCache.Host, exception);

            IPipe <SendContext <Fault <T> > > faultPipe = Pipe.New <SendContext <Fault <T> > >(x => x.UseExecute(v =>
            {
                v.SourceAddress = ReceiveContext.InputAddress;
                v.CorrelationId = CorrelationId;
                v.RequestId     = RequestId;

                foreach (var header in Headers.GetAll())
                {
                    v.Headers.Set(header.Key, header.Value);
                }
            }));

            if (ResponseAddress != null)
            {
                ISendEndpoint endpoint = await GetSendEndpoint(ResponseAddress).ConfigureAwait(false);

                await endpoint.Send(fault, faultPipe, CancellationToken).ConfigureAwait(false);
            }
            else
            {
                await _publishEndpoint.Publish(fault, faultPipe, CancellationToken).ConfigureAwait(false);
            }
        }
        public void SendCommand(string target, object message, Type messageType = null)
        {
            messageType = messageType ?? message.GetType();
            Uri           uri      = new Uri(Utils.CombineUrl(BusConfig.Current.Uri, target));
            ISendEndpoint endpoint = Control.GetSendEndpoint(uri).GetTaskResult();

            endpoint.Send(message, messageType);
        }
        public Task Send(Guid requestId, TRequest message, IPipe <SendContext <TRequest> > pipe, CancellationToken cancellationToken)
        {
            IPipe <SendContext <TRequest> > consumePipe = _consumeContext != null
                ? new ConsumeSendPipeAdapter <TRequest>(_consumeContext, pipe, requestId)
                : pipe;

            return(_endpoint.Send(message, consumePipe, cancellationToken));
        }
        async Task RunStripe(ISendEndpoint targetEndpoint, long messageCount)
        {
            await Task.Yield();

            for (long i = 0; i < messageCount; i++)
            {
                Guid messageId = NewId.NextGuid();
                Task task = targetEndpoint.Send(new LatencyTestMessage(messageId, _payload));

                await _capture.Sent(messageId, task);
            }
        }