Example #1
0
        public void TestParseOk()
        {
            string             uriLike = "fanout://name/key";
            PublicationAddress addr    = PublicationAddress.Parse(uriLike);

            Assert.AreEqual(ExchangeType.Fanout, addr.ExchangeType);
            Assert.AreEqual("name", addr.ExchangeName);
            Assert.AreEqual("key", addr.RoutingKey);
            Assert.AreEqual(uriLike, addr.ToString());
        }
Example #2
0
        public void TestEmptyRoutingKey()
        {
            string             uriLike = "direct://exch/";
            PublicationAddress addr    = PublicationAddress.Parse(uriLike);

            Assert.AreEqual(ExchangeType.Direct, addr.ExchangeType);
            Assert.AreEqual("exch", addr.ExchangeName);
            Assert.AreEqual("", addr.RoutingKey);
            Assert.AreEqual(uriLike, addr.ToString());
        }
Example #3
0
        private static void SendDurableMessageToDurableQueue(IModel model)
        {
            IBasicProperties basicProperties = model.CreateBasicProperties();

            basicProperties.SetPersistent(true);
            byte[]             payload = Encoding.UTF8.GetBytes("This is a persistent message from Visual Studio");
            PublicationAddress address = new PublicationAddress(ExchangeType.Topic, "DurableExchange", "durable");

            model.BasicPublish(address, basicProperties, payload);
        }
Example #4
0
 public void Reply <TReplyMessage>(TReplyMessage responseMessage)
 {
     if (_basicProperties.ReplyTo != null)
     {
         PublicationAddress publicationAddress = PublicationAddress.Parse(_basicProperties.ReplyTo);
         var replyProperties = new BasicProperties();
         replyProperties.CorrelationId = _basicProperties.CorrelationId;
         _messagePublisher.PublishReply <TMessage, TReplyMessage>(publicationAddress, responseMessage, replyProperties);
     }
 }
        /// <summary>
        /// Publishes Message to RabbitMQ
        /// </summary>
        /// <param name="message">
        /// JSON/Plain-Text Message. HAS TO BE PREFORMATTED for Json Serialization
        /// </param>
        /// <param name="index">
        /// Index for Dynamic Server Allocation
        /// </param>
        /// <param name="uidGuid">
        /// </param>
        /// <returns>
        /// Message success state
        /// </returns>
        private static bool?PublishMessage(string message, int index, Guid uidGuid)
        {
            try
            {
                var properties = FactoryChannel[index].CreateBasicProperties();
                if (SerialCommunications[index].MessageType == "JSON")
                {
                    try
                    {
                        //CalculateNpChart(index);
                        JsonConvert.DeserializeObject <Messages[]>(message);
                        properties.ContentType = "jsonObject";
                    }
                    catch (JsonException ex)
                    {
                        /*if (OutOfControl(index))
                         * {
                         *  var sf = StackTracing.GetFrame(0);
                         *  LogError(ex, LogLevel.Critical, sf);
                         *  CloseSerialPortUnexpectedly(index, UiDispatcher);
                         *  return true;
                         * }*/
                    }
                }
                else
                {
                    properties.ContentType = "plain-text";
                }

                properties.Persistent = true;

                var address = new PublicationAddress(ExchangeType.Direct,
                                                     ServerInformation[index].ExchangeName, "");
                FactoryChannel[index].BasicPublish(address, properties, Encoding.UTF8.GetBytes(message));
                FactoryChannel[index].BasicAcks += (sender, args) => { RemoveProtectedData(uidGuid); };
                return(true);
            }
            catch (AlreadyClosedException ex)
            {
                var indexOf    = ex.Message.IndexOf("\"", StringComparison.Ordinal);
                var indexOff   = ex.Message.IndexOf("\"", indexOf + 1, StringComparison.Ordinal);
                var errmessage = ex.Message.Substring(indexOf + 1, indexOff - indexOf - 1);
                MessageBox.Show(errmessage, @"Connection Already Closed", MessageBoxButtons.OK,
                                MessageBoxIcon.Asterisk);

                return(null);
            }
            catch (Exception ex)
            {
                //Log Message
                var sf = StackTracing.GetFrame(0);
                LogError(ex, LogLevel.Critical, sf);
                return(null);
            }
        }
Example #6
0
        public RabbitMqSender(ITransportLogger logger, RabbitMqAgent agent,
                              CancellationToken cancellation)
        {
            _mapper       = agent.EnvelopeMapping;
            _logger       = logger;
            _agent        = agent;
            _cancellation = cancellation;
            Destination   = agent.Uri;

            _address = agent.PublicationAddress();
        }
Example #7
0
        public RabbitMqSender(ITransportLogger logger, RabbitMqEndpoint endpoint,
                              CancellationToken cancellation)
        {
            _protocol     = endpoint.Protocol;
            _logger       = logger;
            _endpoint     = endpoint;
            _cancellation = cancellation;
            Destination   = endpoint.TransportUri.ToUri();

            _address = new PublicationAddress(endpoint.ExchangeType.ToString(), endpoint.ExchangeName ?? "", endpoint.TransportUri.QueueName);
        }
Example #8
0
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="queName"></param>
        /// <param name="msg"></param>
        public void SendMsg <T>(T msg) where T : class
        {
            var basicProperties = channel.CreateBasicProperties();

            //1:非持久化 2:可持久化
            basicProperties.DeliveryMode = 2;
            var payload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(msg));
            var address = new PublicationAddress(RabbitMQClientFactory.rabbitmq.RoutType, RabbitMQClientFactory.rabbitmq.ExchangeName, RabbitMQClientFactory.rabbitmq.RoutKey);

            channel.BasicPublish(address, basicProperties, payload);
        }
Example #9
0
        protected virtual void DeclareSystemExchange(IModel channel, PublicationAddress address)
        {
            if (this.DispatchOnly || address == null)
            {
                return;
            }

            channel.ExchangeDeclare(address.ExchangeName, address.ExchangeType, true, false, null);
            channel.QueueDeclare(address.ExchangeName, true, false, false, null);
            channel.QueueBind(address.ExchangeName, address.ExchangeName, address.RoutingKey, null);
        }
Example #10
0
        public void SendMsg <T>(string queName, string exchangName, string routType, T msg) where T : class
        {
            var basicProperties = channel.CreateBasicProperties();

            //1:非持久化 2:可持久化
            basicProperties.DeliveryMode = 2;
            var payload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(msg));
            var address = new PublicationAddress(routType, exchangName, queName);

            channel.BasicPublish(address, basicProperties, payload);
        }
Example #11
0
        public string PutMessage()
        {
            #region Variables
            string ContentType  = "text/plain";
            string ExchangeName = "Exchange";
            string RoutingKey   = "RoutingKey";
            string messageIn    = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            #endregion

            try
            {
                // Create a ConnectionFactory and set the Uri to the CloudAMQP url
                ConnectionFactory factory = new ConnectionFactory();
                factory.ContinuationTimeout = new TimeSpan(10, 0, 0, 0);
                factory.Uri = new Uri("amqps://*****:*****@test.rmq.cloudamqp.com:5671/dev");

                // Create a connection and open a channel, dispose them when done
                using (IConnection connection = factory.CreateConnection())
                {
                    Console.WriteLine(string.Concat("Connection open: ", connection.IsOpen));
                    using (var channel = connection.CreateModel())
                    {
                        Console.WriteLine(string.Concat("channel open: ", channel.IsOpen));
                        try
                        {
                            // The message we want to put on the queue
                            string message = messageIn;
                            // the data put on the queue must be a byte array
                            var body = Encoding.UTF8.GetBytes(message);

                            // Begin. Sent message
                            IBasicProperties properties = channel.CreateBasicProperties();
                            properties.Persistent  = true;
                            properties.ContentType = ContentType;
                            PublicationAddress address = new PublicationAddress(exchangeType: ExchangeType.Topic, exchangeName: ExchangeName, routingKey: RoutingKey);
                            Console.WriteLine("Inicia el envio del mensaje");
                            channel.BasicPublish(addr: address, basicProperties: properties, body: body);
                            Console.WriteLine("Termina el envio del mensaje");
                            // End. Sent message
                        }
                        catch (Exception EX)
                        {
                            Console.WriteLine(EX.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(string.Empty);
        }
        public void TestTryParseFail()
        {
            PublicationAddress.TryParse(null, out PublicationAddress result);
            Assert.IsNull(result);

            PublicationAddress.TryParse("not a valid URI", out result);
            Assert.IsNull(result);

            PublicationAddress.TryParse("}}}}}}}}", out result);
            Assert.IsNull(result);
        }
        /// <summary>
        /// Выполняет отправку сообщений в RabbitMQ
        /// </summary>
        /// <param name="message">Отправляемое сообщение</param>
        public void SendMessageToQueue(string message)
        {
            var model = PrepareModel();
            IBasicProperties basicProperties = model.CreateBasicProperties();

            basicProperties.Persistent = true;
            byte[]             payload = Encoding.UTF8.GetBytes(message);
            PublicationAddress address = new PublicationAddress(ExchangeType.Topic, ExchangeName, RoutingKey);

            model.BasicPublish(address, basicProperties, payload);
        }
Example #14
0
 /// <summary>
 /// 发送多条消息
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="exchangeName"></param>
 /// <param name="queName"></param>
 /// <param name="msgs"></param>
 /// <param name="delay"></param>
 /// <param name="expires"></param>
 /// <param name="ttl"></param>
 /// <returns></returns>
 public bool SendMessages <T>(string exchangeName, string queName, List <T> msgs, bool delay = false, int expires = 0, int ttl = 0) where T : class
 {
     if (msgs == null && !msgs.Any())
     {
         return(false);
     }
     try
     {
         if (connection == null || !connection.IsOpen)
         {
             CreateConn(queName);
         }
         using (var channel = connection.CreateModel())
         {
             if (!string.IsNullOrEmpty(exchangeName))
             {
                 Dictionary <string, object> dic = new Dictionary <string, object>
                 {
                     { "x-expires", expires * 1000 },
                     { "x-message-ttl", ttl * 1000 },                 //队列上消息过期时间,应小于队列过期时间
                     { "x-dead-letter-exchange", "exchange-direct" }, //过期消息转向路由
                     { "x-dead-letter-routing-key", "routing-delay" }//过期消息转向路由相匹配routingkey
                 };
                 //声明交换机
                 channel.ExchangeDeclare(exchangeName, ExchangeType.Direct, true);
                 //声明一个队列
                 channel.QueueDeclare(queName, true, false, false, arguments: delay ? dic : null);
                 //绑定队列,交换机,路由键
                 channel.QueueBind(queName, exchangeName, queName);
             }
             else
             {
                 //声明一个队列
                 channel.QueueDeclare(queName, true, false, false, null);
             }
             var basicProperties = channel.CreateBasicProperties();
             //1:非持久化 2:可持久化
             basicProperties.DeliveryMode = 2;
             var address = new PublicationAddress(ExchangeType.Direct, exchangeName, queName);
             msgs.ForEach((msg) =>
             {
                 var payload = Encoding.UTF8.GetBytes(msg.ToJson());
                 channel.BasicPublish(address, basicProperties, payload);
             });
         }
         return(true);
     }
     catch (Exception ex)
     {
         var gewa = ex;
         return(false);
     }
 }
        public void AddCustomerDataToQueue(CustomerModel custModel)
        {
            IBasicProperties properties = _channel.CreateBasicProperties();

            properties.Persistent  = true;
            properties.ContentType = "text/plain";

            PublicationAddress address = new PublicationAddress(ExchangeType.Direct, "TestSolutionsMessageExchange", "CustomerCreation");

            _channel.BasicPublish(address, properties, custModel.Serialize());
            _channel.Close();
        }
Example #16
0
        public void AddOrderToQueue(OrderModel order)
        {
            IBasicProperties properties = _channel.CreateBasicProperties();

            properties.Persistent  = true;
            properties.ContentType = "text/plain";

            PublicationAddress address = new PublicationAddress(ExchangeType.Direct, _exchange, _routingKey);

            _channel.BasicPublish(address, properties, order.Serialize());
            _channel.Close();
        }
Example #17
0
        public bool VerifyDestination(Destination destination, EndpointUsage usage, bool configureIfRequired, out string error)
        {
            try
            {
                var publish = PublicationAddress.Parse(destination.Publish) ?? new PublicationAddress("topic", destination.Publish, "");;
                using (IConnection connection = m_Factory.CreateConnection())
                {
                    using (IModel channel = connection.CreateModel())
                    {
                        if ((usage & EndpointUsage.Publish) == EndpointUsage.Publish)
                        {
                            if (configureIfRequired)
                            {
                                channel.ExchangeDeclare(publish.ExchangeName, publish.ExchangeType, true);
                            }
                            else
                            {
                                channel.ExchangeDeclarePassive(publish.ExchangeName);
                            }
                        }

                        if ((usage & EndpointUsage.Subscribe) == EndpointUsage.Subscribe)
                        {
                            if (configureIfRequired)
                            {
                                channel.QueueDeclare(destination.Subscribe, true, false, false, null);
                            }
                            else
                            {
                                channel.QueueDeclarePassive(destination.Subscribe);
                            }

                            if (configureIfRequired)
                            {
                                channel.QueueBind(destination.Subscribe, publish.ExchangeName, publish.RoutingKey == "" ? "#" : publish.RoutingKey);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (!e.GetType().Namespace.StartsWith("RabbitMQ") || e.GetType().Assembly != typeof(OperationInterruptedException).Assembly)
                {
                    throw;
                }
                error = e.Message;
                return(false);
            }
            error = null;
            return(true);
        }
Example #18
0
 public bool SendMessages <T>(string exchangeName, string queueName, IList <T> msgs)
 {
     if (msgs == null && !msgs.Any())
     {
         return(false);
     }
     try
     {
         if (_connection == null || !_connection.IsOpen)
         {
             CreateConn(queueName);
         }
         using (var channel = _connection.CreateModel())
         {
             if (!string.IsNullOrEmpty(exchangeName))
             {
                 //声明交换机
                 channel.ExchangeDeclare(exchangeName, ExchangeType.Direct, true);
                 //声明一个队列
                 channel.QueueDeclare(queueName, true, false, false);
                 //绑定队列,交换机,路由键
                 channel.QueueBind(queueName, exchangeName, queueName);
             }
             else
             {
                 //声明一个队列
                 channel.QueueDeclare(queueName, true, false, false, null);
             }
             var basicProperties = channel.CreateBasicProperties();
             //1:非持久化 2:可持久化
             basicProperties.DeliveryMode = 2;
             var address = new PublicationAddress(ExchangeType.Direct, exchangeName, queueName);
             var headers = new Dictionary <string, string>
             {
                 { Core.Amqp.Messages.Headers.Type, typeof(T).FullName },
                 { Core.Amqp.Messages.Headers.SentTime, DateTimeOffset.Now.ToString() }
             };
             foreach (var msg in msgs)
             {
                 var message = new Message(headers, msg);
                 var payload = Encoding.UTF8.GetBytes(message.ToJson());
                 channel.BasicPublish(address, basicProperties, payload);
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         _logger.LogError($"RabbitMQ Error: {ex.Message}");
         return(false);
     }
 }
Example #19
0
        static void Main(string[] args)
        {
            // Exchange / Queue Declaration & Binding
            channel.ExchangeDeclare("company.exchange.topic", ExchangeType.Topic, true, false, null);
            channel.QueueDeclare("company.queue.topic", true, false, false, null);

            // A queue can be dedicated to one or more routing keys.
            channel.QueueBind("company.queue.topic", "company.exchange.topic", "*.world");
            channel.QueueBind("company.queue.topic", "company.exchange.topic", "world.#");

            // Basic message properties
            IBasicProperties properties = channel.CreateBasicProperties();

            properties.Persistent  = true; // Keep even after server restart
            properties.ContentType = "text/plain";

            // Publish messages (THESE MATCH THE ABOVE PATTERNS)
            PublicationAddress address = new PublicationAddress(ExchangeType.Topic, "company.exchange.topic", "beautiful.world");

            channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("The world is beautiful"));

            address = new PublicationAddress(ExchangeType.Topic, "company.exchange.topic", "world.news.and.more");
            channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("It's Friday night"));

            // Publish messages (THESE DO NOT MATCH THE ABOVE PATTERNS !!!)
            address = new PublicationAddress(ExchangeType.Topic, "company.exchange.topic", "news of the world");
            channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("This is some random news from the world"));

            address = new PublicationAddress(ExchangeType.Topic, "company.exchange.topic", "news.of.the.world");
            channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("trololo"));

            address = new PublicationAddress(ExchangeType.Topic, "company.exchange.topic", "the world is crumbling");
            channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("whatever"));

            address = new PublicationAddress(ExchangeType.Topic, "company.exchange.topic", "the.world.is.crumbling");
            channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("Hello"));


            address = new PublicationAddress(ExchangeType.Topic, "company.exchange.topic", "world news and more");
            channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("No more tears"));


            Console.WriteLine("Messages sent");

            // Close Connection & Channel
            channel.Close();
            connection.Close();

            // Finish
            Console.WriteLine(string.Concat("Channel is closed: ", channel.IsClosed));
            Console.ReadKey();
        }
        /// <summary>
        /// Constructor for RabbitMqClient
        /// </summary>
        /// <param name="configuration">mandatory</param>
        public RabbitMQClient(RabbitMQConfiguration configuration, bool autoCreateExchange)
        {
            // load configuration
            _config             = configuration;
            _publicationAddress = new PublicationAddress(_config.ExchangeType, _config.Exchange, _config.RouteKey);

            // initialize
            InitializeEndpoint();
            if (autoCreateExchange)
            {
                _model.ExchangeDeclare(_config.Exchange, _config.ExchangeType, _config.DeliveryMode == RabbitMQDeliveryMode.Durable);
            }
        }
        public void ShouldSerializeWithExchange()
        {
            //Arrange
            var addr = new PublicationAddress("exchange-type", "exchange-name", "routing-key");

            //Act
            var str = addr.ToString();

            _output.WriteLine(str);

            //Assert
            Assert.Equal("exchange-type://exchange-name/routing-key", str);
        }
Example #22
0
        /// <summary>
        /// Creates an instance of <c>TacitusLogger.Destinations.RabbitMq.PublicationAddressProviders.DirectPublicationAddressProvider</c>
        /// using the exchange name, type and the routing key.
        /// </summary>
        /// <param name="exchangeName">RabbitMQ exchange name.</param>
        /// <param name="exchangeType">RabbitMQ exchange type.</param>
        /// <param name="routingKey">Routing key.</param>
        public DirectPublicationAddressProvider(string exchangeName, string exchangeType, string routingKey = "")
        {
            if (exchangeName == null)
            {
                throw new ArgumentNullException("exchangeName");
            }
            if (exchangeType == null)
            {
                throw new ArgumentNullException("exchangeType");
            }

            _publicationAddress = new PublicationAddress(exchangeType, exchangeName, routingKey);
        }
        public void ShouldSerializeWithoutExchange()
        {
            //Arrange
            var addr = new PublicationAddress(null, null, "routing-key");

            //Act
            var str = addr.ToString();

            _output.WriteLine(str);

            //Assert
            Assert.Equal(":///routing-key", str);
        }
        public void GetPublicationAddress_When_Called_Returns_Address_Using_Factory_Method()
        {
            //Arrange
            PublicationAddress publicationAddress = new PublicationAddress("fanout", "name", "rkey");
            LogModelFunc <PublicationAddress>       factoryMethod = d => publicationAddress;
            FactoryMethodPublicationAddressProvider factoryMethodPublicationAddressProvider = new FactoryMethodPublicationAddressProvider(factoryMethod);

            //Act
            var publicationAddressReturned = factoryMethodPublicationAddressProvider.GetPublicationAddress(new LogModel());

            //Assert
            Assert.AreEqual(publicationAddress, publicationAddressReturned);
        }
Example #25
0
        /// <summary>
        /// Broadcast Transaction
        /// </summary>
        /// <param name="messageQueueAppConfig"></param>
        public ResponseModel <MessageQueue> BroadcastTransaction(MessageQueueAppConfig messageQueueAppConfig)
        {
            ResponseModel <MessageQueue> response = new ResponseModel <MessageQueue>();

            response.Entity = new MessageQueue();

            IModel channel = null;

            try
            {
                channel = _connection.CreateModel();

                string exchangeName = messageQueueAppConfig.TriggerExchangeName;
                string queueName    = messageQueueAppConfig.TriggerQueueName;
                string routingKey   = messageQueueAppConfig.RoutingKey;

                channel.ExchangeDeclare(exchangeName, "fanout", true, false);
                channel.QueueDeclare(queueName, true, false, false);
                channel.QueueBind(queueName, exchangeName, routingKey);

                MessageQueue messageQueue = new MessageQueue();
                messageQueue.TransactionCode = TransactionQueueTypes.TriggerImmediately;

                string output = JsonConvert.SerializeObject(messageQueue);

                byte[] payload = Encoding.UTF8.GetBytes(output);

                PublicationAddress address = new PublicationAddress(ExchangeType.Fanout, exchangeName, routingKey);

                channel.BasicPublish(address, _basicProperties, payload);

                response.Entity.Payload = output;

                response.ReturnStatus = true;
            }
            catch (Exception ex)
            {
                response.ReturnStatus = false;
                response.ReturnMessage.Add(ex.Message);
            }
            finally
            {
                if (channel != null)
                {
                    channel.Close();
                    channel.Dispose();
                }
            }

            return(response);
        }
Example #26
0
        public Task <Message <U> > SendCommand <T, U>(string commandQueueName, Message <T> command) where U : new()
        {
            var n = PublicationAddress.Parse(commandQueueName);

            lock (_channel)
            {
                _channel.ExchangeDeclare(exchange: n.ExchangeName, n.ExchangeType, false, true, null);

                var replyQueueName = _channel.QueueDeclare().QueueName;
                _channel.QueueDeclare(n.ExchangeName, durable: false, exclusive: false, autoDelete: true, arguments: null);

                TaskCompletionSource <Message <U> > result = new TaskCompletionSource <Message <U> >();

                var corrId   = Guid.NewGuid().ToString();
                var consumer = new EventingBasicConsumer(_channel);
                consumer.Received += (s, e) =>
                {
                    if (e.BasicProperties.CorrelationId == corrId)
                    {
                        try
                        {
                            _channel.BasicCancel(_consumerTag);

                            var ser = _payloadSerializer.GetSerializer(e.BasicProperties.ContentType);

                            var answer = new Message <U>(ser.Deserialize <U>(e.Body));
                            result.SetResult(answer);
                        }
                        catch (Exception exception)
                        {
                            result.SetException(exception);
                        }
                    }
                };
                _consumerTag = _channel.BasicConsume(queue: replyQueueName, autoAck: true, consumer: consumer);


                var props = _channel.CreateBasicProperties();
                props.ContentType   = Serializer.ContentType;
                props.ReplyTo       = replyQueueName;
                props.CorrelationId = corrId;
                props.Persistent    = command.Persistent;


                _channel.BasicPublish(exchange: "", n.ExchangeName, basicProperties: props, body: Serializer.Serialize(command.Payload));

                return(result.Task);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RabbitMqEventPublisher"/> class.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="exchangeAddress">The exchange address.</param>
        /// <param name="address">The address.</param>
        public RabbitMqEventPublisher(IModel model, String exchangeAddress, PublicationAddress address)
        {
            var builder = new UriBuilder();

            builder.Scheme = "rabbitmq";
            builder.Host   = exchangeAddress;
            builder.Path   = string.Format("{0}/{1}",
                                           Uri.EscapeUriString(address.ExchangeName),
                                           Uri.EscapeUriString(address.RoutingKey));

            URI = builder.Uri;

            _model   = model;
            _address = address;
        }
Example #28
0
        private static void SetUpDirectExchange()
        {
            channel.ExchangeDeclare("my.first.exchange", ExchangeType.Direct, true, false, null);
            channel.QueueDeclare("my.first.queue", true, false, false, null);
            channel.QueueBind("my.first.queue", "my.first.exchange", "");

            IBasicProperties properties = channel.CreateBasicProperties();

            properties.Persistent  = true;
            properties.ContentType = "text/plain";
            PublicationAddress address = new PublicationAddress(ExchangeType.Fanout, "my.first.exchange", "aaa");

            channel.BasicPublish(address, properties, Encoding.UTF8.GetBytes("This is a message from the RabbitMq .NET driver"));
            //channel.BasicPublish("my.first.exchange", "", null, Encoding.UTF8.GetBytes("This is a message from the RabbitMq .NET driver bbb"));
        }
        public void TestExchangeTypeValidation()
        {
            string             uriLike = "direct:///";
            PublicationAddress addr    = PublicationAddress.Parse(uriLike);
            int found = 0;

            foreach (string exchangeType in ExchangeType.All())
            {
                if (exchangeType.Equals(addr.ExchangeType))
                {
                    found++;
                }
            }
            Assert.AreEqual(1, found);
        }
        static void Main(string[] args)
        {
            RabbitMqService rabbitMqService = new RabbitMqService();
            IConnection     connection      = rabbitMqService.GetRabbitMqConnection();
            IModel          model           = connection.CreateModel();

            SetupInitialTopicQueue(model);
            IBasicProperties basicProperties = model.CreateBasicProperties();

            basicProperties.Persistent = false;
            byte[]             payload = Encoding.UTF8.GetBytes("This is a message from Visual Studio");
            PublicationAddress address = new PublicationAddress(ExchangeType.Topic, "ArnoExchange", "pdf");

            model.BasicPublish(address, basicProperties, payload);
        }
        ///<summary>Process a single request received from our
        ///subscription.</summary>
        ///<remarks>
        ///<para>
        /// If the request's properties contain a non-null, non-empty
        /// CorrelationId string (see IBasicProperties), it is assumed
        /// to be a two-way call, requiring a response. The ReplyTo
        /// header property is used as the reply address (via
        /// PublicationAddress.Parse, unless that fails, in which case it
        /// is treated as a simple queue name), and the request is
        /// passed to HandleCall().
        ///</para>
        ///<para>
        /// If the CorrelationId is absent or empty, the request is
        /// treated as one-way asynchronous event, and is passed to
        /// HandleCast().
        ///</para>
        ///<para>
        /// Usually, overriding HandleCall(), HandleCast(), or one of
        /// their delegates is sufficient to implement a service, but
        /// in some cases overriding ProcessRequest() is
        /// required. Overriding ProcessRequest() gives the
        /// opportunity to implement schemes for detecting interaction
        /// patterns other than simple request/response or one-way
        /// communication.
        ///</para>
        ///</remarks>
        public virtual void ProcessRequest(BasicDeliverEventArgs evt)
        {
            IBasicProperties properties = evt.BasicProperties;
            if (properties.ReplyTo != null && properties.ReplyTo != "")
            {
                // It's a request.

                PublicationAddress replyAddress = PublicationAddress.Parse(properties.ReplyTo);
                if (replyAddress == null)
                {
                    replyAddress = new PublicationAddress(ExchangeType.Direct,
                        "",
                        properties.ReplyTo);
                }

                IBasicProperties replyProperties;
                byte[] reply = HandleCall(evt.Redelivered,
                    properties,
                    evt.Body,
                    out replyProperties);
                if (replyProperties == null)
                {
                    replyProperties = m_subscription.Model.CreateBasicProperties();
                }

                replyProperties.CorrelationId = properties.CorrelationId;
                m_subscription.Model.BasicPublish(replyAddress,
                    replyProperties,
                    reply);
            }
            else
            {
                // It's an asynchronous message.
                HandleCast(evt.Redelivered, properties, evt.Body);
            }
        }
 ///<summary>Construct an instance that will deliver to the
 ///given address.</summary>
 public SimpleRpcClient(IModel model, PublicationAddress address)
 {
     Model = model;
     Address = address;
     Subscription = null;
     TimeoutMilliseconds = Timeout.Infinite;
 }
 public void BasicPublish(PublicationAddress addr,
     IBasicProperties basicProperties,
     byte[] body)
 {
     m_delegate.BasicPublish(addr.ExchangeName,
         addr.RoutingKey,
         basicProperties,
         body);
 }