Example #1
0
        // this function is used to receive the feed back for the message sent
        private void ReceiveFeedback(ReceivedFeedBackData callback, string filter)
        {
            string audience    = Fx.Format("{0}/messages/servicebound/feedback", HOST);
            string resourceUri = Fx.Format("{0}/messages/servicebound/feedback", HOST);
            string sasToken    = GetSharedAccessSignature(SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, resourceUri, new TimeSpan(1, 0, 0));
            bool   cbs         = PutCbsToken(connection, HOST, sasToken, audience);

            if (cbs)
            {
                string entity = "/messages/servicebound/feedback";
                // Form the filter for receiving message based on the time stamp
                Map filters = new Map();
                if (filter != null)
                {
                    filters.Add(new Amqp.Types.Symbol("apache.org:selector-filter:string"),
                                new DescribedValue(new Amqp.Types.Symbol("apache.org:selector-filter:string"), filter));
                }
                ReceiverLink receiveLink = new ReceiverLink(session, "receive-link", new Source()
                {
                    Address = entity, FilterSet = filters
                },
                                                            null);
                Message received = receiveLink.Receive();
                if (received != null)
                {
                    receiveLink.Accept(received);
                    Data data = (Data)received.BodySection;
                    callback(Encoding.UTF8.GetString(data.Binary));
                    Debug.WriteLine(Encoding.UTF8.GetString(data.Binary));
                }
                receiveLink.Close();
            }
        }
Example #2
0
        public void TestMethod_ConnectionFrameSize()
        {
            string     testName   = "ConnectionFrameSize";
            const int  nMsgs      = 200;
            int        frameSize  = 4 * 1024;
            Connection connection = new Connection(testTarget.Address, null, new Open()
            {
                ContainerId = "c1", MaxFrameSize = (uint)frameSize
            }, null);
            Session    session = new Session(connection);
            SenderLink sender  = new SenderLink(session, "sender-" + testName, testTarget.Path);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message(new string('A', frameSize + (i - nMsgs / 2)));
                sender.Send(message, null, null);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = receiver.Receive();
                string  value   = (string)message.Body;
                Trace.WriteLine(TraceLevel.Verbose, "receive: {0}x{1}", value[0], value.Length);
                receiver.Accept(message);
            }

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
        static private async void ReceiveCommandsLoop()
        {
            string entity = Fx.Format("/devices/{0}/messages/deviceBound", deviceId);

            ReceiverLink receiveLink = new ReceiverLink(session, "receive-link", entity);

            while (true)
            {
                Message received = await receiveLink.ReceiveAsync();

                if (received != null)
                {
                    Data data = (Data)received.BodySection;

                    Console.WriteLine(UTF8Encoding.UTF8.GetString(data.Binary));
                    if (received.ApplicationProperties != null)
                    {
                        foreach (var property in received.ApplicationProperties.Map)
                        {
                            Console.WriteLine($" Key:{property.Key} Value:{property.Value}");
                        }
                    }
                    receiveLink.Accept(received);
                }
            }
            //await receiveLink.CloseAsync();
        }
Example #4
0
        private static void LogReceivedMessage(ReceiverLink receiver)
        {
            Message msg = receiver.Receive();

            receiver.Accept(msg);
            Console.WriteLine(receiver.Name + " received: " + msg.Body.ToString());
        }
Example #5
0
        /// <summary>
        /// Standart receiving
        /// </summary>
        /// <param name="receiver">receiver link</param>
        /// <param name="options">receiver options</param>
        private void Receive(ReceiverLink receiver, ReceiverOptions options)
        {
            int     nReceived = 0;
            Message message;

            while (((message = receiver.Receive(options.Timeout)) != null) && (nReceived < options.MsgCount || options.MsgCount == 0))
            {
                if (options.Duration > 0)
                {
                    Utils.Sleep4Next(ts, options.MsgCount, options.Duration, nReceived + 1);
                }

                receiver.Accept(message);

                Formatter.LogMessage(message, options);
                nReceived++;

                if (options.ProccessReplyTo)
                {
                    SenderLink sender = new SenderLink(session, "reply-to-sender", message.Properties.ReplyTo);
                    sender.Send(message);
                    sender.Close();
                }

                if ((options.MsgCount > 0) && (nReceived == options.MsgCount))
                {
                    break;
                }

                Utils.TsSnapStore(this.ptsdata, 'F', options.LogStats);
            }
        }
Example #6
0
            void RunOnce()
            {
                Message request = new Message("hello " + this.offset);

                request.Properties = new Properties()
                {
                    MessageId = "command-request", ReplyTo = this.replyTo
                };
                request.ApplicationProperties           = new ApplicationProperties();
                request.ApplicationProperties["offset"] = this.offset;
                sender.Send(request, null, null);
                Console.WriteLine("Sent request {0} body {1}", request.Properties, request.Body);

                while (true)
                {
                    Message response = receiver.Receive();
                    receiver.Accept(response);
                    Console.WriteLine("Received response: {0} body {1}", response.Properties, response.Body);

                    if (string.Equals("done", response.Body))
                    {
                        break;
                    }

                    this.offset = (int)response.ApplicationProperties["offset"];
                }
            }
Example #7
0
        public static void Main(string[] args)
        {
            String url     = (args.Length > 0) ? args[0] : "amqps://127.0.0.1:443";
            String address = (args.Length > 1) ? args[1] : "myqueue";


            Trace.TraceLevel    = TraceLevel.Frame;
            Trace.TraceListener = (l, f, a) => Console.WriteLine(
                DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));

            Connection.DisableServerCertValidation = true;
            Connection connection = new Connection(new Address(url));
            Session    session    = new Session(connection);
            SenderLink sender     = new SenderLink(session, "test-sender", address);

            Message messageSent = new Message("Test Message");

            sender.Send(messageSent);

            ReceiverLink receiver        = new ReceiverLink(session, "test-receiver", address);
            Message      messageReceived = receiver.Receive(TimeSpan.FromSeconds(2));

            Console.WriteLine(messageReceived.Body);
            receiver.Accept(messageReceived);

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Example #8
0
        async Task RunSampleAsync()
        {
            ConnectionFactory factory = new ConnectionFactory();

            factory.SASL.Profile = SaslProfile.Anonymous;

            Trace.WriteLine(TraceLevel.Information, "Establishing a connection...");
            Address address    = new Address(this.Namespace, 5671, null, null, "/", "amqps");
            var     connection = await factory.CreateAsync(address);

            // before any operation can be performed, a token must be put to the $cbs node
            Trace.WriteLine(TraceLevel.Information, "Putting a token to the $cbs node...");
            await PutTokenAsync(connection);

            Trace.WriteLine(TraceLevel.Information, "Sending a message...");
            var session = new Session(connection);
            var sender  = new SenderLink(session, "ServiceBus.Cbs:sender-link", this.Entity);
            await sender.SendAsync(new Message("test"));

            await sender.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Receiving the message back...");
            var receiver = new ReceiverLink(session, "ServiceBus.Cbs:receiver-link", this.Entity);
            var message  = await receiver.ReceiveAsync();

            receiver.Accept(message);
            await receiver.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Closing the connection...");
            await session.CloseAsync();

            await connection.CloseAsync();
        }
Example #9
0
        public void TestMethod_ConnectionWithIPAddress()
        {
            string     testName   = "ConnectionWithIPAddress";
            const int  nMsgs      = 20;
            Address    address    = new Address("127.0.0.1", 5672, "guest", "guest", "/", "amqp");
            Connection connection = new Connection(address);
            Session    session    = new Session(connection);
            SenderLink sender     = new SenderLink(session, "sender-" + testName, "q1");

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message("msg" + i);
                message.Properties = new Properties()
                {
                    GroupId = "abcdefg"
                };
                message.ApplicationProperties       = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                sender.Send(message, null, null);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1");

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
                receiver.Accept(message);
            }

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Example #10
0
        static async Task Run()
        {
            string address = "amqp://*****:*****@localhost:5672";

            Connection connection = await Connection.Factory.CreateAsync(new Address(address));

            Session    session = new Session(connection);
            SenderLink sender  = new SenderLink(session, "test-sender", "q1");

            Message message1 = new Message("Hello AMQP!");
            await sender.SendAsync(message1);

            ReceiverLink receiver = new ReceiverLink(session, "test-receiver", "q1");
            Message      message2 = await receiver.ReceiveAsync();

            Console.WriteLine(message2.GetBody <string>());
            receiver.Accept(message2);

            await sender.CloseAsync();

            await receiver.CloseAsync();

            await session.CloseAsync();

            await connection.CloseAsync();
        }
Example #11
0
        protected override void Renew(Session session)
        {
            oldReceiver = receiver;

            receiver = new ReceiverLink(session, "receiver", Environment.GetEnvironmentVariable("SERVICE_BUS_NAME"));

            receiver.Start(20, (receiver, message) =>
            {
                Console.WriteLine($"[{DateTime.UtcNow.ToString("dd/MM/yyyy HH:mm:ss")}] -> received message");

                try
                {
                    var queueMessage = JsonConvert.DeserializeObject <QueueMessage>(message.GetBody <string>());

                    OnMessage(queueMessage);

                    receiver.Accept(message);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"[{DateTime.UtcNow.ToString("dd/MM/yyyy HH:mm:ss")}] -> message threw an exception: {e.Message}");

                    receiver.Reject(message);
                }
            });

            if (oldReceiver != null)
            {
                oldReceiver.Close();
                oldReceiver = null;
            }
        }
Example #12
0
        static async Task Main()
        {
            var connection = await Connection.Factory.CreateAsync(
                new Address("amqp://*****:*****@localhost:5672"));

            Session      session  = new Session(connection);
            ReceiverLink receiver = new ReceiverLink(session, "reciever-link", "q1");

            Console.WriteLine("Reciever connected to broker.");
            while (true)
            {
                Message message = await receiver.ReceiveAsync();

                var ship = message.GetBody <Ship>();

                Console.WriteLine(ship.Name);
                receiver.Accept(message);

                if (ship.Name.Equals("Vessel is 999"))
                {
                    break;
                }
            }

            await receiver.CloseAsync();

            await session.CloseAsync();

            await connection.CloseAsync();

            Console.ReadLine();
        }
Example #13
0
        public void TestMethod_ReceiveWaiter()
        {
            string     testName   = "ReceiveWaiter";
            Connection connection = new Connection(address);
            Session    session    = new Session(connection);

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1");
            Thread       t        = new Thread(() =>
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId);
                receiver.Accept(message);
            });

            t.Start();

            SenderLink sender = new SenderLink(session, "sender-" + testName, "q1");
            Message    msg    = new Message()
            {
                Properties = new Properties()
                {
                    MessageId = "123456"
                }
            };

            sender.Send(msg, null, null);

            t.Join(10000);

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Example #14
0
        public void TestMethod_DynamicSenderLink()
        {
            string     testName   = "DynamicSenderLink";
            Connection connection = new Connection(testTarget.Address);
            Session    session    = new Session(connection);

            string     targetAddress = null;
            OnAttached onAttached    = (link, attach) =>
            {
                targetAddress = ((Target)attach.Target).Address;
            };

            SenderLink sender = new SenderLink(session, "sender-" + testName, new Target()
            {
                Dynamic = true
            }, onAttached);
            Message message = new Message("hello");

            sender.Send(message, 60000);

            Assert.IsTrue(targetAddress != null, "dynamic target not attached");
            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, targetAddress);

            message = receiver.Receive();
            Assert.IsTrue(message != null, "no message was received.");
            receiver.Accept(message);

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Example #15
0
        public void TestMethod_ConnectionFrameSize()
        {
            string     testName   = "ConnectionFrameSize";
            const int  nMsgs      = 200;
            Connection connection = new Connection(address);
            Session    session    = new Session(connection);
            SenderLink sender     = new SenderLink(session, "sender-" + testName, "q1");

            int frameSize = 16 * 1024;

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message(new string('A', frameSize + (i - nMsgs / 2)));
                sender.Send(message, null, null);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1");

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = receiver.Receive();
                string  value   = (string)message.Body;
                Trace.WriteLine(TraceLevel.Information, "receive: {0}x{1}", value[0], value.Length);
                receiver.Accept(message);
            }

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Example #16
0
        public void DuplicateLinkNameDifferentRoleTest()
        {
            string name = "DuplicateLinkNameDifferentRoleTest";

            this.linkProcessor = new TestLinkProcessor();
            this.host.RegisterLinkProcessor(this.linkProcessor);

            string linkName   = "same-link-for-different-role";
            var    connection = new Connection(Address);
            var    session1   = new Session(connection);
            var    sender     = new SenderLink(session1, linkName, name);

            sender.Send(new Message("msg1"), SendTimeout);

            var session2 = new Session(connection);
            var receiver = new ReceiverLink(session2, linkName, name);

            receiver.SetCredit(2, false);
            var message = receiver.Receive();

            Assert.IsTrue(message != null, "No message was received");
            receiver.Accept(message);

            connection.Close();
        }
Example #17
0
        public void TestMethod_BasicSendReceive()
        {
            string     testName   = "BasicSendReceive";
            const int  nMsgs      = 200;
            Connection connection = new Connection(testTarget.Address);
            Session    session    = new Session(connection);
            SenderLink sender     = new SenderLink(session, "sender-" + testName, testTarget.Path);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message("msg" + i);
                message.Properties = new Properties()
                {
                    GroupId = "abcdefg"
                };
                message.ApplicationProperties       = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                sender.Send(message, null, null);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
                receiver.Accept(message);
            }

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Example #18
0
        public async Task Start()
        {
            Running         = true;
            Connection      = new Connection(new Address(ConnectionString));
            ReceiverSession = new Session(Connection);
            var receiverLink = new ReceiverLink(ReceiverSession, $"{ClientName}-rc", Queue);

            while (Running)
            {
                var message = await receiverLink.ReceiveAsync(TimeSpan.FromMilliseconds(500));

                if (message == null)
                {
                    continue;
                }
                Console.WriteLine("Received Message");
                if (string.IsNullOrEmpty(message.Properties?.Subject) ||
                    string.IsNullOrEmpty(message.Properties.ReplyTo))
                {
                    receiverLink.Reject(message);
                    continue;
                }
                receiverLink.Accept(message);
                await ProcessMessage(message);
            }
        }
Example #19
0
        public void TestMethod_DynamicReceiverLink()
        {
            string     testName   = "DynamicReceiverLink";
            Connection connection = new Connection(testTarget.Address);
            Session    session    = new Session(connection);

            string           remoteSource = null;
            ManualResetEvent attached     = new ManualResetEvent(false);
            OnAttached       onAttached   = (link, attach) => { remoteSource = ((Source)attach.Source).Address; attached.Set(); };
            ReceiverLink     receiver     = new ReceiverLink(session, "receiver-" + testName, new Source()
            {
                Dynamic = true
            }, onAttached);

            attached.WaitOne(10000);

            Assert.IsTrue(remoteSource != null, "dynamic source not attached");

            SenderLink sender  = new SenderLink(session, "sender-" + testName, remoteSource);
            Message    message = new Message("hello");

            sender.Send(message, 60000);

            message = receiver.Receive();
            Assert.IsTrue(message != null, "no message was received.");
            receiver.Accept(message);

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Example #20
0
        static void Main(string[] args)
        {
            string broker  = args.Length >= 1 ? args[0] : "amqp://localhost:8583";
            string address = args.Length >= 2 ? args[1] : "address.helloworld";

            Address    brokerAddr = new Address(broker);
            Connection connection = new Connection(brokerAddr);
            Session    session    = new Session(connection);

            SenderLink   sender   = new SenderLink(session, "dotnetclient-sender", address);
            ReceiverLink receiver = new ReceiverLink(session, "dotnetclient-receiver", address);

            Message helloOut = new Message("This is an AMQP message sent by a Dot Net client!");

            sender.Send(helloOut);

            Message helloIn = receiver.Receive();

            receiver.Accept(helloIn);

            Console.WriteLine(helloIn.Body.ToString());

            receiver.Close();
            sender.Close();
            session.Close();
            connection.Close();
        }
        public void LinkProcessorAsyncTest()
        {
            string name      = "LinkProcessorAsyncTest";
            var    processor = new TestLinkProcessor();

            processor.SetHandler(
                a =>
            {
                Task.Delay(100).ContinueWith(_ => a.Complete(new TestLinkEndpoint(), 0));
                return(true);
            }
                );
            this.host.RegisterLinkProcessor(processor);

            int count      = 5;
            var connection = new Connection(Address);
            var session    = new Session(connection);
            var receiver   = new ReceiverLink(session, "recv-link", name);

            for (int i = 0; i < count; i++)
            {
                var message = receiver.Receive(TimeSpan.FromSeconds(4));
                Assert.IsTrue(message != null);
                receiver.Accept(message);
            }

            connection.Close();
        }
Example #22
0
        public void TestMethod_ReceiveWaiter()
        {
            string     testName   = "ReceiveWaiter";
            Connection connection = new Connection(testTarget.Address);
            Session    session    = new Session(connection);

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);

#if NETFX || NETFX_CORE
            Task t = Task.Run(() =>
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
                receiver.Accept(message);
            });
#else
            Thread t = new Thread(() =>
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
                receiver.Accept(message);
            });

            t.Start();
#endif

            SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
            Message    msg    = new Message()
            {
                Properties = new Properties()
                {
                    MessageId = "123456"
                }
            };
            sender.Send(msg, null, null);

#if NETFX || NETFX_CORE
            t.Wait(10000);
#else
            t.Join(10000);
#endif

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
        public void ContainerHostMessageSourceTest()
        {
            string          name     = "ContainerHostMessageSourceTest";
            int             count    = 100;
            Queue <Message> messages = new Queue <Message>();

            for (int i = 0; i < count; i++)
            {
                messages.Enqueue(new Message("test")
                {
                    Properties = new Properties()
                    {
                        MessageId = name + i
                    }
                });
            }

            var source = new TestMessageSource(messages);

            this.host.RegisterMessageSource(name, source);

            var connection = new Connection(Address);
            var session    = new Session(connection);
            var receiver   = new ReceiverLink(session, "receiver0", name);
            int released   = 0;
            int rejected   = 0;
            int ignored    = 0;

            for (int i = 1; i <= count; i++)
            {
                Message message = receiver.Receive();
                if (i % 5 == 0)
                {
                    receiver.Reject(message);
                    rejected++;
                }
                else if (i % 17 == 0)
                {
                    receiver.Release(message);
                    released++;
                }
                else if (i % 36 == 0)
                {
                    ignored++;
                }
                else
                {
                    receiver.Accept(message);
                }
            }

            receiver.Close();
            session.Close();
            connection.Close();

            Thread.Sleep(500);
            Assert.AreEqual(released + ignored, messages.Count, string.Join(",", messages.Select(m => m.Properties.MessageId)));
            Assert.AreEqual(rejected, source.DeadletterMessage.Count, string.Join(",", source.DeadletterMessage.Select(m => m.Properties.MessageId)));
        }
Example #24
0
        public void Monitorar(object parametros)
        {
            ErroParametros param                   = ((ErroParametros)parametros);
            string         topico                  = param.Topico;
            string         endrecoFila             = param.EnderecoFila;
            string         descricao               = param.Descricao;
            string         EndpointElasticSearchOK = param.EndpointElasticSearchOK;
            string         passoRetorno            = param.PassoRetorno;

            Console.WriteLine("ERRO Monitorado: " + topico);
            Console.WriteLine("Descricao: " + descricao);
            Connection connection = null;

            try
            {
                Address address = new Address(endrecoFila);
                connection = new Connection(address);
                Session      session           = new Session(connection);
                ReceiverLink receiver          = new ReceiverLink(session, NOME_FILA_CONSUMIDOR_MQ, topico);
                ElasticSearch.ElasticSearch ES = new ElasticSearch.ElasticSearch();

                while (true)
                {
                    Message request       = receiver.Receive(new TimeSpan(0, 30, 0));
                    string  replyTo       = request.Properties.ReplyTo;
                    string  correlationID = request.Properties.CorrelationId;

                    if (null != request)
                    {
                        //                        Console.WriteLine(request.Body);
                        string  stringData = request.Body.ToString();
                        dynamic results    = JsonConvert.DeserializeObject <dynamic>(stringData);

                        //Console.WriteLine("FIM de operacao: {0}", correlationID);
                        //Console.WriteLine(stringData);

                        results.passo        = passoRetorno;
                        results.dataExecucao = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");

                        stringData = JsonConvert.SerializeObject(results);

                        var contentDataES = new StringContent(stringData, System.Text.Encoding.UTF8, MIME_TYPE_JSON);

                        //Console.WriteLine("Gravando no ElasticSearch: {0}", EndpointElasticSearchOK);
                        ES.executa(EndpointElasticSearchOK, contentDataES);

                        receiver.Accept(request);
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Exception {0}.", e);
                if (null != connection)
                {
                    connection.Close();
                }
            }
        }
Example #25
0
        // This function is the core receive function
        void ReceiveMessages(string scenario, int count, string filter, string partition, ReceivedData callback)
        {
            Trace.WriteLine(Amqp.TraceLevel.Information, "Running scenario '{0}', filter '{1}'...", scenario, filter);

            Trace.WriteLine(Amqp.TraceLevel.Information, "Establishing a connection...");
            Address    address    = new Address(sbNamespace, PORT, keyName, keyValue);
            Connection connection = new Connection(address);

            Trace.WriteLine(Amqp.TraceLevel.Information, "Creating a session...");
            Session session = new Session(connection);

            Trace.WriteLine(Amqp.TraceLevel.Information, "Creating a receiver link on partition {0}...", partition);
            string partitionAddress = entity + "/ConsumerGroups/$default/Partitions/" + partition;
            // Form the filter for receiving message based on the time stamp
            Map filters = new Map();

            if (filter != null)
            {
                filters.Add(new Amqp.Types.Symbol("apache.org:selector-filter:string"),
                            new DescribedValue(new Amqp.Types.Symbol("apache.org:selector-filter:string"), filter));
            }

            string   lastOffset      = "-1";
            long     lastSeqNumber   = -1;
            DateTime lastEnqueueTime = DateTime.MinValue;

            ReceiverLink receiver = new ReceiverLink(
                session,
                "receiver-" + partition,
                new Source()
            {
                Address = partitionAddress, FilterSet = filters
            },
                null);

            // loop runs until clean up is called
            for (; g_bThreadActive;)
            {
                Message message = receiver.Receive(5000);
                if (message == null)
                {
                    continue;
                }

                receiver.Accept(message);
                Data data = (Data)message.BodySection;
                // Get the data such as offset, Seq number and Devicename from the response header
                lastOffset      = (string)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-offset")];
                lastSeqNumber   = (long)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-sequence-number")];
                lastEnqueueTime = (DateTime)message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-enqueued-time")];

                var DeviceName = (string)message.MessageAnnotations[new Amqp.Types.Symbol("iothub-connection-device-id")];
                callback(data.Binary, DeviceName);
            }

            receiver.Close();
            session.Close();
            connection.Close();
        }
Example #26
0
        /// <summary>
        /// Method for transactional receiving messages
        /// </summary>
        /// <param name="receiver">receiver link</param>
        /// <param name="options">receiver options</param>
        private void TransactionReceive(ReceiverLink receiver, ReceiverOptions options)
        {
            bool    txFlag    = true;
            int     nReceived = 0;
            Message message   = null;

            while (txFlag && (nReceived < options.MsgCount || options.MsgCount == 0) && options.TxSize > 0)
            {
                using (var txs = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    for (int i = 0; i < options.TxSize; i++)
                    {
                        message = receiver.Receive(options.Timeout);
                        if (message != null)
                        {
                            receiver.Accept(message);
                            Formatter.LogMessage(message, options);
                            nReceived++;
                        }
                    }
                    if (options.TxAction.ToLower() == "commit")
                    {
                        txs.Complete();
                    }
                }

                if (message == null || (options.MsgCount > 0 && ((options.MsgCount - nReceived) < options.TxSize)))
                {
                    txFlag = false;
                }
            }
            using (var txs = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                while ((message = receiver.Receive(options.Timeout)) != null && (nReceived < options.MsgCount || options.MsgCount == 0))
                {
                    receiver.Accept(message);
                    Formatter.LogMessage(message, options);
                    nReceived++;
                }

                if (options.TxLoopendAction.ToLower() == "commit")
                {
                    txs.Complete();
                }
            }
        }
Example #27
0
        public void monitorar()
        {
            Console.WriteLine("TERMINO DA OPERACAO");
            Connection connection = null;

            try
            {
                Settings             configs   = new Settings();
                ConfiguracoesValores config    = configs.ResgataParametro();
                string EndpointElasticSearchOK = config.Parametros.EndpointElasticSearch.DoctoOK;
                string enderecoFila            = config.Parametros.EnderecoFila;

                Address address = new Address(enderecoFila);
                connection = new Connection(address);
                Session      session           = new Session(connection);
                string       topicoEntrada     = config.Parametros.Termino.TopicoEntrada;
                ReceiverLink receiver          = new ReceiverLink(session, NOME_FILA_CONSUMIDOR_MQ, topicoEntrada);
                ElasticSearch.ElasticSearch ES = new ElasticSearch.ElasticSearch();

                while (true)
                {
                    Message request       = receiver.Receive(new TimeSpan(0, 30, 0));
                    string  replyTo       = request.Properties.ReplyTo;
                    string  correlationID = request.Properties.CorrelationId;

                    if (null != request)
                    {
                        //                        Console.WriteLine(request.Body);
                        string  stringData = request.Body.ToString();
                        dynamic results    = JsonConvert.DeserializeObject <dynamic>(stringData);

                        results.passo        = "TerminoProcesso";
                        results.dataExecucao = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                        string codigoTicket = correlationID;

                        stringData = JsonConvert.SerializeObject(results);

                        var contentDataES = new StringContent(stringData, System.Text.Encoding.UTF8, MIME_TYPE_JSON);

                        //                        Console.WriteLine("Gravando no ElasticSearch: {0}", EndpointElasticSearchOK + codigoTicket);
                        ES.executa(EndpointElasticSearchOK, contentDataES);


                        Console.WriteLine("FIM de operacao");
                        //                        Console.WriteLine(stringData);
                        receiver.Accept(request);
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Exception {0}.", e);
                if (null != connection)
                {
                    connection.Close();
                }
            }
        }
Example #28
0
        public async Task ReceiverSenderAsync()
        {
            string testName = "ReceiverSenderAsync";

            ConnectionFactory connectionFactory = new ConnectionFactory();

            // Creating first ReceiverLink
            Connection firstReceiverConnection = await connectionFactory.CreateAsync(this.testTarget.Address);

            Session      firstReceiverSession = new Session(firstReceiverConnection);
            ReceiverLink firstReceiverLink    = new ReceiverLink(firstReceiverSession, "receiver-link", testName);

            // Does not work when creating SenderLink after first ReceiverLink
            var senderConnection = await connectionFactory.CreateAsync(this.testTarget.Address);

            var senderSession = new Session(senderConnection);
            var senderLink    = new SenderLink(senderSession, "sender-link", testName);

            // Send and receive message
            await senderLink.SendAsync(new Message(testName));

            Message firstMessageReceived = await firstReceiverLink.ReceiveAsync(TimeSpan.FromMilliseconds(1000));

            // Close first reveiver link
            await firstReceiverLink.CloseAsync();

            await firstReceiverSession.CloseAsync();

            await firstReceiverConnection.CloseAsync();

            // Creating second ReceiverLink
            Connection secondReceiverConnection = await connectionFactory.CreateAsync(this.testTarget.Address);

            Session      secondReceiverSession = new Session(secondReceiverConnection);
            ReceiverLink secondReceiverLink    = new ReceiverLink(secondReceiverSession, "receiver-link", testName);

            // Send and receive message
            await senderLink.SendAsync(new Message(testName));

            Message message = await secondReceiverLink.ReceiveAsync(TimeSpan.FromMilliseconds(1000));

            Assert.IsTrue(message != null, "No message received");
            secondReceiverLink.Accept(message);

            // Close second reveiver link
            await secondReceiverLink.CloseAsync();

            await secondReceiverSession.CloseAsync();

            await secondReceiverConnection.CloseAsync();

            // Close sender link
            await senderLink.CloseAsync();

            await senderSession.CloseAsync();

            await senderConnection.CloseAsync();
        }
Example #29
0
        //
        // Sample invocation: Interop.Drain.exe --broker localhost:5672 --timeout 30 --address my-queue
        //
        static int Main(string[] args)
        {
            const int ERROR_SUCCESS    = 0;
            const int ERROR_NO_MESSAGE = 1;
            const int ERROR_OTHER      = 2;

            int        exitCode   = ERROR_SUCCESS;
            Connection connection = null;

            try
            {
                Options options = new Options(args);

                Address address = new Address(options.Url);
                connection = new Connection(address);
                Session      session  = new Session(connection);
                ReceiverLink receiver = new ReceiverLink(session, "receiver-drain", options.Address);
                TimeSpan     timeout  = TimeSpan.MaxValue;
                if (!options.Forever)
                {
                    timeout = TimeSpan.FromSeconds(options.Timeout);
                }
                Message message   = new Message();
                int     nReceived = 0;
                receiver.SetCredit(options.InitialCredit);
                while ((message = receiver.Receive(timeout)) != null)
                {
                    nReceived++;
                    if (!options.Quiet)
                    {
                        Console.WriteLine("Message(Properties={0}, ApplicationProperties={1}, Body={2}",
                                          message.Properties, message.ApplicationProperties, message.Body);
                    }
                    receiver.Accept(message);
                    if (options.Count > 0 && nReceived == options.Count)
                    {
                        break;
                    }
                }
                if (message == null)
                {
                    exitCode = ERROR_NO_MESSAGE;
                }
                receiver.Close();
                session.Close();
                connection.Close();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Exception {0}.", e);
                if (null != connection)
                {
                    connection.Close();
                }
                exitCode = ERROR_OTHER;
            }
            return(exitCode);
        }
Example #30
0
        string[] GetEventHubPartitions()
        {
            Trace.WriteLine(TraceLevel.Information, "Retrieving partitions...");
            Trace.WriteLine(TraceLevel.Information, "Establishing a connection...");
            Connection connection = new Connection(this.GetAddress());

            Trace.WriteLine(TraceLevel.Information, "Creating a session...");
            Session session = new Session(connection);

            // create a pair of links for request/response
            Trace.WriteLine(TraceLevel.Information, "Creating a request and a response link...");
            string       clientNode = "client-temp-node";
            SenderLink   sender     = new SenderLink(session, "mgmt-sender", "$management");
            ReceiverLink receiver   = new ReceiverLink(
                session,
                "mgmt-receiver",
                new Attach()
            {
                Source = new Source()
                {
                    Address = "$management"
                },
                Target = new Target()
                {
                    Address = clientNode
                }
            },
                null);

            Message request = new Message();

            request.Properties = new Properties()
            {
                MessageId = "request1", ReplyTo = clientNode
            };
            request.ApplicationProperties = new ApplicationProperties();
            request.ApplicationProperties["operation"] = "READ";
            request.ApplicationProperties["name"]      = this.Entity;
            request.ApplicationProperties["type"]      = "com.microsoft:eventhub";
            sender.Send(request, null, null);

            Message response = receiver.Receive();

            if (response == null)
            {
                throw new Exception("No response was received.");
            }

            receiver.Accept(response);
            receiver.Close();
            sender.Close();
            connection.Close();

            Trace.WriteLine(TraceLevel.Information, "Partition info: {0}", response.Body.ToString());
            string[] partitions = (string[])((Map)response.Body)["partition_ids"];

            return(partitions);
        }