示例#1
0
        public CFXEnvelope ExecuteRequest(string targetUri, CFXEnvelope request)
        {
            CFXEnvelope  response      = null;
            Connection   reqConn       = null;
            Session      reqSession    = null;
            ReceiverLink receiver      = null;
            SenderLink   sender        = null;
            Exception    ex            = null;
            Uri          targetAddress = new Uri(targetUri);

            try
            {
                if (string.IsNullOrWhiteSpace(request.RequestID))
                {
                    request.RequestID = "REQUEST-" + Guid.NewGuid().ToString();
                }
                Message req = AmqpUtilities.MessageFromEnvelope(request, UseCompression.Value);
                req.Properties.MessageId            = "command-request";
                req.Properties.ReplyTo              = CFXHandle;
                req.ApplicationProperties           = new ApplicationProperties();
                req.ApplicationProperties["offset"] = 1;

                Task.Run(() =>
                {
                    try
                    {
                        reqConn           = new Connection(new Address(targetAddress.ToString()));
                        reqSession        = new Session(reqConn);
                        Attach recvAttach = new Attach()
                        {
                            Source = new Source()
                            {
                                Address = CFXHandle
                            },
                            Target = new Target()
                            {
                                Address = request.Target
                            }
                        };

                        receiver = new ReceiverLink(reqSession, "request-receiver", recvAttach, null);
                        receiver.Start(300);
                        sender = new SenderLink(reqSession, CFXHandle, request.Target);

                        sender.Send(req);
                        Message resp = receiver.Receive(RequestTimeout.Value);
                        if (resp != null)
                        {
                            receiver.Accept(resp);
                            response = AmqpUtilities.EnvelopeFromMessage(resp);
                        }
                        else
                        {
                            throw new TimeoutException("A response was not received from target CFX endpoint in the alloted time.");
                        }
                    }
                    catch (Exception ex3)
                    {
                        AppLog.Error(ex3);
                        ex = ex3;
                    }
                }).Wait();
            }
            catch (Exception ex2)
            {
                AppLog.Error(ex2);
                if (ex == null)
                {
                    ex = ex2;
                }
            }
            finally
            {
                if (receiver != null && !receiver.IsClosed)
                {
                    receiver.Close();
                }
                if (sender != null && !sender.IsClosed)
                {
                    sender.Close();
                }
                if (reqSession != null && !reqSession.IsClosed)
                {
                    reqSession.Close();
                }
                if (reqConn != null && !reqConn.IsClosed)
                {
                    reqConn.Close();
                }
            }

            if (ex != null)
            {
                throw ex;
            }
            return(response);
        }
示例#2
0
        public void TransactedPosting()
        {
            string testName = "TransactedPosting";
            int    nMsgs    = 5;

            Connection connection = new Connection(testTarget.Address);
            Session    session    = new Session(connection);
            SenderLink sender     = new SenderLink(session, "sender-" + testName, testTarget.Path);

            // commit
            using (var ts = new TransactionScope())
            {
                for (int i = 0; i < nMsgs; i++)
                {
                    Message message = new Message("test");
                    message.Properties = new Properties()
                    {
                        MessageId = "commit" + i, GroupId = testName
                    };
                    sender.Send(message);
                }

                ts.Complete();
            }

            // rollback
            using (var ts = new TransactionScope())
            {
                for (int i = nMsgs; i < nMsgs * 2; i++)
                {
                    Message message = new Message("test");
                    message.Properties = new Properties()
                    {
                        MessageId = "rollback" + i, GroupId = testName
                    };
                    sender.Send(message);
                }
            }

            // commit
            using (var ts = new TransactionScope())
            {
                for (int i = 0; i < nMsgs; i++)
                {
                    Message message = new Message("test");
                    message.Properties = new Properties()
                    {
                        MessageId = "commit" + i, GroupId = testName
                    };
                    sender.Send(message);
                }

                ts.Complete();
            }

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

            for (int i = 0; i < nMsgs * 2; i++)
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId);
                receiver.Accept(message);
                Assert.IsTrue(message.Properties.MessageId.StartsWith("commit"));
            }

            connection.Close();
        }
 internal static Task <Outcome> SendAsync(this SenderLink link, global::Amqp.Message message, DeliveryState deliveryState, long timeoutMillis)
 {
     return(new AmqpSendTask(link, message, deliveryState, timeoutMillis).Task);
 }
示例#4
0
        public void ContainerHostRequestProcessorTest()
        {
            string name      = "ContainerHostRequestProcessorTest";
            var    processor = new TestRequestProcessor();

            this.host.RegisterRequestProcessor(name, processor);

            int count      = 500;
            var connection = new Connection(Address);
            var session    = new Session(connection);

            string replyTo    = "client-reply-to";
            Attach recvAttach = new Attach()
            {
                Source = new Source()
                {
                    Address = name
                },
                Target = new Target()
                {
                    Address = replyTo
                }
            };

            var           doneEvent = new ManualResetEvent(false);
            List <string> responses = new List <string>();
            ReceiverLink  receiver  = new ReceiverLink(session, "request-client-receiver", recvAttach, null);

            receiver.Start(
                20,
                (link, message) =>
            {
                responses.Add(message.GetBody <string>());
                link.Accept(message);
                if (responses.Count == count)
                {
                    doneEvent.Set();
                }
            });

            SenderLink sender = new SenderLink(session, "request-client-sender", name);

            for (int i = 0; i < count; i++)
            {
                Message request = new Message("Hello");
                request.Properties = new Properties()
                {
                    MessageId = "request" + i, ReplyTo = replyTo
                };
                sender.Send(request, null, null);
            }

            Assert.IsTrue(doneEvent.WaitOne(10000), "Not completed in time");

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

            Assert.AreEqual(count, processor.TotalCount);
            Assert.AreEqual(count, responses.Count);
            for (int i = 1; i <= count; i++)
            {
                Assert.AreEqual("OK" + i, responses[i - 1]);
            }
        }
示例#5
0
        public void TransactedRetiring()
        {
            string testName = "TransactedRetiring";
            int    nMsgs    = 10;

            Connection connection = new Connection(testTarget.Address);
            Session    session    = new Session(connection);
            SenderLink sender     = new SenderLink(session, "sender-" + testName, testTarget.Path);

            // send one extra for validation
            for (int i = 0; i < nMsgs + 1; i++)
            {
                Message message = new Message("test");
                message.Properties = new Properties()
                {
                    MessageId = "msg" + i, GroupId = testName
                };
                sender.Send(message);
            }

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

            Message[] messages = new Message[nMsgs];
            for (int i = 0; i < nMsgs; i++)
            {
                messages[i] = receiver.Receive();
                Trace.WriteLine(TraceLevel.Information, "receive: {0}", messages[i].Properties.MessageId);
            }

            // commit harf
            using (var ts = new TransactionScope())
            {
                for (int i = 0; i < nMsgs / 2; i++)
                {
                    receiver.Accept(messages[i]);
                }

                ts.Complete();
            }

            // rollback
            using (var ts = new TransactionScope())
            {
                for (int i = nMsgs / 2; i < nMsgs; i++)
                {
                    receiver.Accept(messages[i]);
                }
            }

            // after rollback, messages should be still acquired
            {
                Message message = receiver.Receive();
                Assert.AreEqual("msg" + nMsgs, message.Properties.MessageId);
                receiver.Release(message);
            }

            // commit
            using (var ts = new TransactionScope())
            {
                for (int i = nMsgs / 2; i < nMsgs; i++)
                {
                    receiver.Accept(messages[i]);
                }

                ts.Complete();
            }

            // only the last message is left
            {
                Message message = receiver.Receive();
                Assert.AreEqual("msg" + nMsgs, message.Properties.MessageId);
                receiver.Accept(message);
            }

            // at this point, the queue should have zero messages.
            // If there are messages, it is a bug in the broker.

            connection.Close();
        }
示例#6
0
        static void Main(string[] args)
        {
            if (args.Length != 3)
            {
                Console.Error.WriteLine("Usage: Request <connection-url> <address> <message-body>");
                Environment.Exit(1);
            }

            string connUrl     = args[0];
            string address     = args[1];
            string messageBody = args[2];

            Connection conn = new Connection(new Address(connUrl));

            try
            {
                Session session = new Session(conn);

                Target target = new Target()
                {
                    Address = address,
                };

                OnAttached onSenderAttached = (link, attach) =>
                {
                    Console.WriteLine("REQUEST: Opened sender for target address '{0}'", address);
                };

                SenderLink sender = new SenderLink(session, "s1", target, onSenderAttached);

                string           responseAddress = null;
                ManualResetEvent done            = new ManualResetEvent(false);

                Source source = new Source()
                {
                    Dynamic = true,
                };

                OnAttached onReceiverAttached = (link, attach) =>
                {
                    Console.WriteLine("REQUEST: Opened dynamic receiver for responses");

                    responseAddress = ((Source)attach.Source).Address;
                    done.Set();
                };

                ReceiverLink receiver = new ReceiverLink(session, "r1", source, onReceiverAttached);
                done.WaitOne();

                Message request = new Message(messageBody);

                request.Properties = new Properties()
                {
                    MessageId = Guid.NewGuid().ToString(),
                    ReplyTo   = responseAddress,
                };

                sender.Send(request);

                Console.WriteLine("REQUEST: Sent request '{0}'", messageBody);

                Message response = receiver.Receive();
                receiver.Accept(response);

                Console.WriteLine("REQUEST: Received response '{0}'", response.Body);
            }
            finally
            {
                conn.Close();
            }
        }
示例#7
0
        /// <summary>
        /// Method for transactional sending of messages
        /// </summary>
        /// <param name="sender">sender link</param>
        /// <param name="options">options</param>
        private void TransactionSend(SenderLink sender, SenderOptions options)
        {
            int     nSent  = 0;
            bool    txFlag = true;
            Message message;

            while (txFlag && options.TxSize > 0)
            {
                using (var txs = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    for (int i = 0; i < options.TxSize; i++)
                    {
                        message = CreateMessage(options, nSent);

                        if ((options.Duration > 0) && (options.DurationMode == "before-send"))
                        {
                            Utils.Sleep4Next(this.ts, options.MsgCount, (options.Duration), nSent + 1);
                        }

                        sender.Send(message, options.Timeout);

                        if ((options.Duration > 0) && (options.DurationMode == "after-send-before-tx-action"))
                        {
                            Utils.Sleep4Next(this.ts, options.MsgCount, (options.Duration), nSent + 1);
                        }

                        Formatter.LogMessage(message, options);

                        nSent++;
                    }

                    if (options.TxAction.ToLower() == "commit")
                    {
                        txs.Complete();
                    }

                    if ((options.Duration > 0) && (options.DurationMode == "after-send-after-tx-action"))
                    {
                        Utils.Sleep4Next(ts, options.MsgCount, (options.Duration), nSent);
                    }
                }
                //set up tx_batch_flag
                if ((options.MsgCount - nSent) < options.TxSize)
                {
                    txFlag = false;
                }
            }
            //rest of messages
            using (var txs = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                while (nSent < options.MsgCount)
                {
                    message = CreateMessage(options, nSent);
                    sender.Send(message, options.Timeout);
                    Formatter.LogMessage(message, options);
                    nSent++;
                }

                if (options.TxLoopendAction.ToLower() == "commit")
                {
                    txs.Complete();
                }
            }
        }
示例#8
0
        protected async Task OnMessageCallbackAsync(IReceiverLink receiver, Message message)
        {
            var messageTypeName = message.ApplicationProperties[Constants.MESSAGE_TYPE_KEY] as string;
            var properties      = new Dictionary <string, object> {
                ["CorrelationId"] = message.Properties.CorrelationId,
                ["MessageId"]     = message.Properties.MessageId,
                ["MessageType"]   = messageTypeName
            };

            // if message has correlationId, set it so that handling can be found by initial correlation
            if (!string.IsNullOrWhiteSpace(message.Properties.CorrelationId))
            {
                CorrelationContext.SetCorrelationId(message.Properties.CorrelationId);
            }

            var timer = new Stopwatch();

            timer.Start();

            using (Logger.BeginScope(properties)) {
                Logger.LogInformation($"Received message {message.Properties.MessageId}");

                try {
                    string body = DomainEventMessage.GetBody(message);
                    Logger.LogTrace("Received message {MessageId} with body: {MessageBody}", message.Properties.MessageId, body);

                    Logger.LogDebug($"Event type key: {messageTypeName}");
                    if (!EventTypeLookup.ContainsKey(messageTypeName))
                    {
                        Logger.LogError($"Message {message.Properties.MessageId} rejected because message type was not registered for type {messageTypeName}");
                        receiver.Reject(message);
                        return;
                    }

                    var dataType = EventTypeLookup[messageTypeName];
                    Logger.LogDebug($"Event type: {dataType}");
                    var handlerType = typeof(IDomainEventHandler <>).MakeGenericType(dataType);
                    Logger.LogDebug($"Event type handler interface: {handlerType}");
                    var handler = Provider.GetService(handlerType);
                    if (handler == null)
                    {
                        Logger.LogError($"Message {message.Properties.MessageId} rejected because handler was not found for type {messageTypeName}");
                        receiver.Reject(message);
                        return;
                    }
                    Logger.LogDebug($"Event type handler: {handler.GetType()}");

                    dynamic domainEvent;
                    try {
                        domainEvent = DomainEventMessage.CreateGenericInstance(dataType, message);
                        Logger.LogDebug($"Successfully deserialized body to {dataType}");
                    } catch (Exception ex) {
                        Logger.LogError(ex, ex.Message);
                        receiver.Reject(message);
                        return;
                    }

                    HandlerResult result;
                    dynamic       dhandler = handler;
                    try {
                        result = await dhandler.HandleAsync(domainEvent).ConfigureAwait(false);
                    } catch (Exception ex) {
                        Logger.LogError(ex, $"Message {message.Properties.MessageId} caught unhandled exception {ex.Message}");
                        result = HandlerResult.Failed;
                    }

                    timer.Stop();
                    var duration = timer.ElapsedMilliseconds;

                    var dp = new Dictionary <string, object> {
                        ["duration"] = duration
                    };

                    using (Logger.BeginScope(dp)) {
                        Logger.LogInformation($"Handler executed for message {message.Properties.MessageId} and returned result of {result}");

                        switch (result)
                        {
                        case HandlerResult.Success:
                            receiver.Accept(message);
                            Logger.LogInformation($"Message {message.Properties.MessageId} accepted");
                            break;

                        case HandlerResult.Retry:
                            var deliveryCount = message.Header.DeliveryCount;
                            var delay         = 10 * deliveryCount;
                            var scheduleTime  = DateTime.UtcNow.AddSeconds(delay);

                            using (var ts = new TransactionScope()) {
                                var sender = new SenderLink(Link.Session, Settings.AppName + "-retry", Settings.Queue);
                                // create a new message to be queued with scheduled delivery time
                                var retry = new Message(body)
                                {
                                    Header                = message.Header,
                                    Footer                = message.Footer,
                                    Properties            = message.Properties,
                                    ApplicationProperties = message.ApplicationProperties
                                };
                                retry.ApplicationProperties[Constants.SCHEDULED_ENQUEUE_TIME_UTC] = scheduleTime;
                                sender.Send(retry);
                                receiver.Accept(message);
                            }
                            Logger.LogInformation($"Message {message.Properties.MessageId} requeued with delay of {delay} seconds for {scheduleTime}");
                            break;

                        case HandlerResult.Failed:
                            receiver.Reject(message);
                            break;

                        case HandlerResult.Release:
                            receiver.Release(message);
                            break;

                        default:
                            throw new NotImplementedException($"Unknown HandlerResult value of {result}");
                        }
                    }
                } catch (Exception ex) {
                    timer.Stop();
                    var duration = timer.ElapsedMilliseconds;

                    var dp = new Dictionary <string, object> {
                        ["duration"] = duration
                    };

                    using (Logger.BeginScope(dp)) {
                        Logger.LogError(ex, $"Message {message.Properties.MessageId} rejected because of unhandled exception {ex.Message}");
                        receiver.Reject(message);
                    }
                }
            }
        }
示例#9
0
        async Task PutTokenAsync(Connection connection)
        {
            var session = new Session(connection);

            string cbsClientAddress = "cbs-client-reply-to";
            var    cbsSender        = new SenderLink(session, "cbs-sender", "$cbs");
            var    receiverAttach   = new Attach()
            {
                Source = new Source()
                {
                    Address = "$cbs"
                },
                Target = new Target()
                {
                    Address = cbsClientAddress
                }
            };
            var cbsReceiver = new ReceiverLink(session, "cbs-receiver", receiverAttach, null);
            var sasToken    = GetSASToken(this.KeyName, this.KeyValue, string.Format("http://{0}/{1}", this.Namespace, this.Entity), TimeSpan.FromMinutes(20));

            Trace.WriteLine(TraceLevel.Information, " sas token: {0}", sasToken);

            // construct the put-token message
            var request = new Message(sasToken);

            request.Properties            = new Properties();
            request.Properties.MessageId  = "1";
            request.Properties.ReplyTo    = cbsClientAddress;
            request.ApplicationProperties = new ApplicationProperties();
            request.ApplicationProperties["operation"] = "put-token";
            request.ApplicationProperties["type"]      = "servicebus.windows.net:sastoken";
            request.ApplicationProperties["name"]      = string.Format("amqp://{0}/{1}", this.Namespace, this.Entity);
            await cbsSender.SendAsync(request);

            Trace.WriteLine(TraceLevel.Information, " request: {0}", request.Properties);
            Trace.WriteLine(TraceLevel.Information, " request: {0}", request.ApplicationProperties);

            // receive the response
            var response = await cbsReceiver.ReceiveAsync();

            if (response == null || response.Properties == null || response.ApplicationProperties == null)
            {
                throw new Exception("invalid response received");
            }

            // validate message properties and status code.
            Trace.WriteLine(TraceLevel.Information, " response: {0}", response.Properties);
            Trace.WriteLine(TraceLevel.Information, " response: {0}", response.ApplicationProperties);
            int statusCode = (int)response.ApplicationProperties["status-code"];

            if (statusCode != (int)HttpStatusCode.Accepted && statusCode != (int)HttpStatusCode.OK)
            {
                throw new Exception("put-token message was not accepted. Error code: " + statusCode);
            }

            // the sender/receiver may be kept open for refreshing tokens
            await cbsSender.CloseAsync();

            await cbsReceiver.CloseAsync();

            await session.CloseAsync();
        }
示例#10
0
        public async Task WebSocketSslMutalAuthTest()
        {
            string testName      = "WebSocketSslMutalAuthTest";
            string listenAddress = "wss://localhost:18081/" + testName + "/";
            Uri    uri           = new Uri(listenAddress);

            X509Certificate2 cert = ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");

            string output;
            int    code = Exec("netsh.exe", string.Format("http show sslcert hostnameport={0}:{1}", uri.Host, uri.Port), out output);

            if (code != 0)
            {
                string args = string.Format("http add sslcert hostnameport={0}:{1} certhash={2} certstorename=MY appid={{{3}}} clientcertnegotiation=enable",
                                            uri.Host, uri.Port, cert.Thumbprint, Guid.NewGuid());
                code = Exec("netsh.exe", args, out output);
                Assert.AreEqual(0, code, "failed to add ssl cert: " + output);
            }

            X509Certificate serviceCert  = null;
            X509Certificate clientCert   = null;
            ListenerLink    listenerLink = null;

            var linkProcessor = new TestLinkProcessor();

            linkProcessor.SetHandler(a => { listenerLink = a.Link; return(false); });
            var host = new ContainerHost(new List <Uri>()
            {
                uri
            }, null, uri.UserInfo);

            host.Listeners[0].SASL.EnableExternalMechanism            = true;
            host.Listeners[0].SSL.ClientCertificateRequired           = true;
            host.Listeners[0].SSL.CheckCertificateRevocation          = true;
            host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => { clientCert = b; return(true); };
            host.RegisterLinkProcessor(linkProcessor);
            host.Open();

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { serviceCert = b; return(true); };
                var wssFactory = new WebSocketTransportFactory();
                wssFactory.Options = o =>
                {
                    o.ClientCertificates.Add(ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, uri.Host));
                };

                ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wssFactory });
                connectionFactory.SASL.Profile = SaslProfile.External;
                Connection connection = await connectionFactory.CreateAsync(new Address(listenAddress));

                Session    session = new Session(connection);
                SenderLink sender  = new SenderLink(session, "sender-" + testName, "q1");
                await sender.SendAsync(new Message("test") { Properties = new Properties()
                                                             {
                                                                 MessageId = testName
                                                             } });

                await connection.CloseAsync();

                Assert.IsTrue(serviceCert != null, "service cert not received");
                Assert.IsTrue(clientCert != null, "client cert not received");
                Assert.IsTrue(listenerLink != null, "link not attached");

                IPrincipal principal = ((ListenerConnection)listenerLink.Session.Connection).Principal;
                Assert.IsTrue(principal != null, "connection pricipal is null");
                Assert.IsTrue(principal.Identity is X509Identity, "identify should be established by client cert");
            }
            finally
            {
                host.Close();
            }
        }
示例#11
0
 public TransactionCoordinator(SenderLink senderLink)
 {
     _senderLink = senderLink;
 }
示例#12
0
        public static void Main(string[] args)
        {
            Trace.TraceLevel    = TraceLevel.Frame;
            Trace.TraceListener = (f, a) =>
            {
                var t = DateTime.Now.ToString("[hh:ss.fff]") + " " + string.Format(f, a);
                Console.WriteLine(t);
            };

            connection = new Connection(amqpAddress, null, new Open()
            {
                ContainerId  = Guid.NewGuid().ToString(),
                ChannelMax   = 64,
                MaxFrameSize = 200,
            }, null);
            connection.Closed = OnClosed;

            session        = new Session(connection);
            session.Closed = OnClosed;

            var linkName = Guid.NewGuid().ToString();

            senderLink = new SenderLink(session, linkName, new Attach()
            {
                Target = new Target()
                {
                    Address = "TestQueue1",
                },
                //RcvSettleMode = ReceiverSettleMode.Second,
                //SndSettleMode = SenderSettleMode.Settled,
            }, null);
            senderLink.Closed = OnClosed;

            for (int i = 0; i < 10; i++)
            {
                senderLink.Send(CreateMessage(), 5000);
            }

            senderLink.Close();

            linkName            = Guid.NewGuid().ToString();
            receiverLink        = new ReceiverLink(session, linkName, "TestQueue1");
            receiverLink.Closed = OnClosed;
            receiverLink.SetCredit(1);
            var message      = receiverLink.Receive(20000);
            int receiveCount = 0;

            while (message != null)
            {
                receiveCount++;
                //Console.WriteLine(message.Body.GetType());
                Console.WriteLine(message.BodySection.GetType());
                Console.WriteLine("Receive #{0}. Message = \"{1}\"", receiveCount.ToString(), Encoding.UTF8.GetString(message.GetBody <byte[]>()));
                if (receiveCount % 7 == 0)
                {
                    receiverLink.Release(message);
                }
                else if (receiveCount % 4 == 0)
                {
                    receiverLink.Reject(message);
                }
                else
                {
                    receiverLink.Accept(message);
                }
                Thread.Sleep(10000);
                message = receiverLink.Receive(20000);
            }
            receiverLink.Close();

            session.Close();
            connection.Close();
        }
示例#13
0
        /// <summary>
        /// Initialize AMQP connection
        /// we are using the connection to send data to Azure Event Hubs
        /// Connection information is retreived from the app configuration file
        /// </summary>
        /// <returns>
        /// true when successful
        /// false when unsuccessful
        /// </returns>
        private bool InitAMQPConnection(bool reset)
        {
            this.IsConnectionReady = false;

            if (reset)
            {
                // If the reset flag is set, we need to kill previous connection
                try
                {
                    this.logger.Info("Resetting connection to Azure Event Hub");
                    this.logger.Info("Closing any existing senderLink, session and connection.");
                    if (this.sender != null)
                    {
                        this.sender.Close();
                    }
                    if (this.session != null)
                    {
                        this.session.Close();
                    }
                    if (this.connection != null)
                    {
                        this.connection.Close();
                    }
                }
                catch (Exception e)
                {
                    this.logger.Error("Error closing AMQP connection to Azure Event Hub: {0}", e.Message);
                }
            }

            this.logger.Info("Initializing connection to Azure Event Hub");

            // Initialize AMQPS connection
            try
            {
                this.connection = new Connection(this.appAMQPAddress);
                this.session    = new Session(this.connection);
                this.sender     = new SenderLink(this.session, "send-link", this.appEHTarget);
            }
            catch (Exception e)
            {
                this.logger.Error("Error connecting to Azure Event Hub: {0}", e.Message);
                if (this.sender != null)
                {
                    this.sender.Close();
                }
                if (this.session != null)
                {
                    this.session.Close();
                }
                if (this.connection != null)
                {
                    this.connection.Close();
                }
                return(false);
            }

            this.IsConnectionReady = true;
            this.logger.Info("Connection to Azure Event Hub initialized.");
            return(true);
        }
示例#14
0
        private async void Process()
        {
            while (!Queue.IsEmpty)
            {
                LogDebug("Attempting to process queued messages...");

                bool success = false;
                if (!IsClosed)
                {
                    CFXEnvelope[] messages = Queue.PeekMany(AmqpCFXEndpoint.MaxMessagesPerTransmit.Value);
                    if (messages != null && messages.Any())
                    {
                        try
                        {
                            Message msg = AmqpUtilities.MessageFromEnvelopes(messages, AmqpCFXEndpoint.Codec.Value);
                            SenderLink.Send(msg);
                            success = true;
                        }
                        catch (Exception ex)
                        {
                            LogError(ex);
                            AppLog.Error(ex);
                        }

                        if (success)
                        {
                            Queue.Dequeue(messages.Length);
                        }

                        int remainingCount = Queue.Count;
                        if (success)
                        {
                            LogDebug($"{messages.Length} messages transmitted.  {Queue.Count} messages remaining in spool.");
                        }
                        else
                        {
                            LogDebug($"Messages NOT transmitted.  {Queue.Count} messages remaining in spool.");
                        }

                        if (remainingCount > 90)
                        {
                            LogWarn(string.Format("Warning.  Spool has {0} buffered messages.", remainingCount));
                        }
                    }
                }
                else
                {
                    int remainingCount = Queue.Count;
                    if (remainingCount > 0)
                    {
                        LogWarn($"Connection Bad or Error.  {Queue.Count} messages remaining in spool.");
                    }
                    await Task.Delay(Convert.ToInt32(AmqpCFXEndpoint.ReconnectInterval.Value.TotalMilliseconds));
                }
            }

            lock (this)
            {
                isProcessing = false;
            }

            await Task.Yield();
        }
示例#15
0
        //
        // Sample invocation: Interop.Spout.exe --broker localhost:5672 --timeout 30 --address my-queue
        //
        static int Main(string[] args)
        {
            const int ERROR_SUCCESS = 0;
            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);
                SenderLink sender  = new SenderLink(session, "sender-spout", options.Address);
                // TODO: ReplyTo

                Stopwatch stopwatch = new Stopwatch();
                TimeSpan  timespan  = new TimeSpan(0, 0, options.Timeout);
                stopwatch.Start();
                for (int nSent = 0;
                     (0 == options.Count || nSent < options.Count) &&
                     (0 == options.Timeout || stopwatch.Elapsed <= timespan);
                     nSent++)
                {
                    string id = options.Id;
                    if (id.Equals(""))
                    {
                        Guid g = Guid.NewGuid();
                        id = g.ToString();
                    }
                    id += ":" + nSent.ToString();

                    Message message = new Message(options.Content);
                    message.Properties = new Properties()
                    {
                        MessageId = id
                    };
                    sender.Send(message);
                    if (options.Print)
                    {
                        Console.WriteLine("Message(Properties={0}, ApplicationProperties={1}, Body={2}",
                                          message.Properties, message.ApplicationProperties, message.Body);
                    }
                }
                sender.Close();
                session.Close();
                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0}.", e);
                if (null != connection)
                {
                    connection.Close();
                }
                exitCode = ERROR_OTHER;
            }
            return(exitCode);
        }
示例#16
0
        public virtual JObject RequestReply(object message, string subject, string queue, TimeSpan?timeout = null, bool emptyResult = false)
        {
            JObject res = null;

            if (timeout == null)
            {
                timeout = TimeSpan.FromMilliseconds(3000);
            }

            var session = new Session(_amqpConnection);
            var sender  = new SenderLink(session, $"Sender-{Guid.NewGuid().ToString()}", queue);

            var replyTo          = "";
            var receiverAttached = new ManualResetEvent(false);

            void OnReceiverAttached(ILink l, Attach a)
            {
                replyTo = ((Source)a.Source).Address;
                receiverAttached.Set();
            }

            var source = new Source
            {
                Dynamic      = false,
                Address      = Guid.NewGuid().ToString(),
                Capabilities = new Symbol[] { new Symbol("topic") }
            };

            var receiver = new ReceiverLink(
                session, $"Receiver-{Guid.NewGuid().ToString()}", source, OnReceiverAttached);

            if (receiverAttached.WaitOne(timeout.Value))
            {
                var request = new Message(AmqpUtils.SerializeMessage(message))
                {
                    Properties = new Properties
                    {
                        Subject = subject,
                        ReplyTo = replyTo
                    }
                };

                sender.Send(request);
                sender.Close();

                var response = receiver.Receive(timeout.Value);

                if (null != response)
                {
                    receiver.Accept(response);

                    res = AmqpUtils.DeserializeMessage(response.Body);
                }

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

                if (res != null)
                {
                    return(res);
                }

                if (emptyResult)
                {
                    return(null);
                }

                throw new AmqpApiException("AMQP: Receiver timeout receiving response");
            }

            session.Close();

            throw new AmqpApiException("AMQP: Receiver attach timeout");
        }
示例#17
0
        public void Send(Message message)
        {
            Address address    = new Address(opts.Url);
            var     connection = new Connection(address);
            Session session    = new Session(connection);

            var attach = new Attach()
            {
                Target = new Target()
                {
                    Address = opts.Queue, Durable = Convert.ToUInt32(opts.Durable)
                },
                Source = new Source()
            };
            var sender = new SenderLink(session, "shovel", attach, null);

            string rawBody = null;

            // Get the body
            if (message.Body is string)
            {
                rawBody = message.Body as string;
            }
            else if (message.Body is byte[])
            {
                using (var reader = XmlDictionaryReader.CreateBinaryReader(
                           new MemoryStream(message.Body as byte[]),
                           null,
                           XmlDictionaryReaderQuotas.Max)) {
                    var doc = new XmlDocument();
                    doc.Load(reader);
                    rawBody = doc.InnerText;
                }
            }

            // duplicate message so that original can be ack'd
            var m = new Message(rawBody)
            {
                Header = message.Header,
                ApplicationProperties = message.ApplicationProperties,
                Properties            = message.Properties
            };

            logger.LogInformation($"publishing message {message.Properties.MessageId} to {opts.Queue} with event type {message.ApplicationProperties[MESSAGE_TYPE_KEY]} with body:\n{rawBody}");

            try {
                sender.Send(m);
                logger.LogInformation($"successfully published message {message.Properties.MessageId}");
            } finally {
                if (sender.Error != null)
                {
                    logger.LogError($"ERROR: [{sender.Error.Condition}] {sender.Error.Description}");
                }
                if (!sender.IsClosed)
                {
                    sender.Close(TimeSpan.FromSeconds(5));
                }
                session.Close();
                session.Connection.Close();
            }
            if (sender.Error != null)
            {
                throw new AmqpException(sender.Error);
            }
        }
示例#18
0
        static void Main(string[] args)
        {
            // number of queues (subscrubers) to be created
            int numQueues = Int32.Parse(args[0]);
            // number of broadcast messages to send
            int numMessages = Int32.Parse(args[1]);
            // number of benchmark subs to identify to sample send/recive speed.
            int numBenchmarks = Int32.Parse(args[2]);
            // broker URL
            String url = (args.Length > 3) ? args[3] : "amqp://localhost:5672";
            // topic name
            String address = (args.Length > 4) ? args[4] : "orders";

            Address    peerAddr   = new Address(url);
            Connection connection = new Connection(peerAddr);
            //Connection connection = new Connection(peerAddr, SaslProfile.Anonymous, new Open { ContainerId = null }, null);
            Session session = new Session(connection);

            ReceiverLink[] receivers         = new ReceiverLink[numQueues];
            Random         random            = new Random();
            List <int>     benchmarkIndicies = new List <int>();
            Stopwatch      stopwatch         = new Stopwatch();

            // populate array of random benchmarks, these won't receive broadcast messages
            while (benchmarkIndicies.Count < numBenchmarks)
            {
                int nextRandom = random.Next(0, numQueues - 1);
                if (!benchmarkIndicies.Contains(nextRandom))
                {
                    benchmarkIndicies.Add(nextRandom);
                }
            }

            Console.WriteLine("Creating subscribers...");
            for (var i = 0; i < numQueues; i++)
            {
                Console.Write("\rCreating subscriber " + (i + 1) + "/" + numQueues);
                if (!benchmarkIndicies.Contains(i))
                {
                    // create general subscribers, listening to broadcast messages and store-specific messages
                    receivers[i] = new ReceiverLink(session, "sub" + i, CreateSharedDurableSubscriberSource(address, new List <String>()
                    {
                        "store=" + i + " OR allstores=true"
                    }), null);
                }
                else
                {
                    // create benchmark subscribers, listening for only their store number
                    receivers[i] = new ReceiverLink(session, "sub" + i, CreateSharedDurableSubscriberSource(address, new List <String>()
                    {
                        "store=" + i
                    }), null);
                }
                Thread.Sleep(TimeSpan.FromSeconds(.0001));
            }
            Console.WriteLine("\nDone!");

            SenderLink sender = new SenderLink(session, "sender", address);

            // send broadcast messages
            Console.WriteLine("Sending broadcast messages...");
            stopwatch.Start();
            for (var i = 0; i < numMessages; i++)
            {
                Console.Write("\rSending message " + (i + 1) + "/" + numMessages);

                Message message = new Message(Guid.NewGuid().ToString());
                message.ApplicationProperties = new ApplicationProperties();
                message.ApplicationProperties["allstores"] = true;
                message.Header         = new Header();
                message.Header.Durable = true;

                try
                {
                    sender.Send(message);
                }
                catch
                {
                    Console.WriteLine("ERROR sending braodcast message");
                }
            }
            stopwatch.Stop();
            Console.WriteLine("\n" + numMessages + " messages broadcasted in " + stopwatch.ElapsedMilliseconds + "ms!");
            stopwatch.Reset();

            Console.WriteLine("Sending messages to randomly selected benchmark subs...");

            // send messages to our random benchmarks, tracking delta between send/receive
            benchmarkIndicies.ForEach(i => {
                Message benchmarkMessage = new Message("benchmark message " + i);
                benchmarkMessage.ApplicationProperties          = new ApplicationProperties();
                benchmarkMessage.ApplicationProperties["store"] = i;
                benchmarkMessage.Header         = new Header();
                benchmarkMessage.Header.Durable = true;
                stopwatch.Start();
                sender.Send(benchmarkMessage);

                Message receivedMessage = receivers[i].Receive(TimeSpan.FromSeconds(60));
                receivers[i].Accept(receivedMessage);
                stopwatch.Stop();
                Console.WriteLine("Benchmark " + receivers[i].Name + " received: \"" + receivedMessage.Body + "\" in " + stopwatch.ElapsedMilliseconds + "ms!");
                stopwatch.Reset();
                Thread.Sleep(TimeSpan.FromSeconds(1));
            });
            Console.WriteLine("Receiving broadcast message from random subs...");

            for (var i = 0; i < numMessages; i++)
            {
                {
                    int nextRandom = random.Next(0, numQueues - 1);
                    if (!benchmarkIndicies.Contains(nextRandom))
                    {
                        Message receivedMessage = receivers[nextRandom].Receive(TimeSpan.FromSeconds(60));
                        stopwatch.Start();
                        receivers[nextRandom].Accept(receivedMessage);
                        stopwatch.Stop();
                        Console.WriteLine(receivers[nextRandom].Name + " received broadcast message: \"" + receivedMessage.Body + "\" in " + stopwatch.ElapsedMilliseconds + "ms!");
                        Thread.Sleep(TimeSpan.FromSeconds(1));
                    }
                }
                stopwatch.Reset();
            }
        }
示例#19
0
        public static void Main(string[] args)
        {
            String url         = (args.Length > 0) ? args[0] : "amqp://127.0.0.1:5672";
            String destination = (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));

            Address address  = new Address(url);
            string  testName = "TransactedPosting";
            int     nMsgs    = 5;

            Connection connection = new Connection(address);
            Session    session    = new Session(connection);
            SenderLink sender     = new SenderLink(session, "sender-" + testName, destination);

            // commit
            using (var ts = new TransactionScope())
            {
                for (int i = 0; i < nMsgs; i++)
                {
                    Message message = new Message("test");
                    message.Properties = new Properties()
                    {
                        MessageId = "commit" + i, GroupId = testName
                    };
                    sender.Send(message);
                }

                ts.Complete();
            }
            Console.WriteLine("Commit");

            // rollback
            using (var ts = new TransactionScope())
            {
                for (int i = nMsgs; i < nMsgs * 2; i++)
                {
                    Message message = new Message("test");
                    message.Properties = new Properties()
                    {
                        MessageId = "rollback" + i, GroupId = testName
                    };
                    sender.Send(message); //error connection is closed
                }
            }
            Console.WriteLine("Rollback");

            // commit
            using (var ts = new TransactionScope())
            {
                for (int i = 0; i < nMsgs; i++)
                {
                    Message message = new Message("test");
                    message.Properties = new Properties()
                    {
                        MessageId = "commit" + i, GroupId = testName
                    };
                    sender.Send(message);
                }

                ts.Complete();
            }
            Console.WriteLine("Commit");

            //receive
            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, destination);

            for (int i = 0; i < nMsgs * 2; i++)
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId);
                receiver.Accept(message);
            }

            Console.WriteLine("Received messages");

            Message m = receiver.Receive(TimeSpan.FromSeconds(5));

            if (m != null)
            {
                throw new Exception("Broker contains uncommited messages");
            }

            connection.Close();
        }
示例#20
0
        /// <summary>
        /// Performs a direct, point-to-point request/response transaction with another CFX Endpoint.
        /// </summary>
        /// <param name="targetUri">The network address of the Endpoint to which the request will be sent.
        /// May use amqp:// or amqps:// topic (amqps for secure communications).
        /// May also include user information (for authentication), as well as a custom TCP port.
        /// </param>
        /// <param name="request">A CFX envelope containing the request.</param>
        /// <returns>A CFX envelope containing the response from the Endpoint.</returns>
        public async Task <CFXEnvelope> ExecuteRequestAsync(string targetUri, CFXEnvelope request)
        {
            CFXEnvelope  response      = null;
            Connection   reqConn       = null;
            Session      reqSession    = null;
            ReceiverLink receiver      = null;
            SenderLink   sender        = null;
            Exception    ex            = null;
            Uri          targetAddress = new Uri(targetUri);

            CurrentRequestTargetUri = targetAddress;

            try
            {
                if (string.IsNullOrWhiteSpace(request.RequestID))
                {
                    request.RequestID = "REQUEST-" + Guid.NewGuid().ToString();
                }
                if (string.IsNullOrWhiteSpace(request.Source))
                {
                    request.Source = CFXHandle;
                }

                Message req = AmqpUtilities.MessageFromEnvelope(request, UseCompression.Value);
                req.Properties.MessageId            = "command-request";
                req.Properties.ReplyTo              = CFXHandle;
                req.ApplicationProperties           = new ApplicationProperties();
                req.ApplicationProperties["offset"] = 1;

                await Task.Run(() =>
                {
                    try
                    {
                        ConnectionFactory factory = new ConnectionFactory();
                        if (targetAddress.Scheme.ToLower() == "amqps")
                        {
                            factory.SSL.RemoteCertificateValidationCallback = ValidateRequestServerCertificate;
                            factory.SASL.Profile = SaslProfile.External;
                        }

                        if (string.IsNullOrWhiteSpace(targetAddress.UserInfo))
                        {
                            factory.SASL.Profile = SaslProfile.Anonymous;
                        }

                        reqConn           = factory.CreateAsync(new Address(targetAddress.ToString())).Result;
                        reqSession        = new Session(reqConn);
                        Attach recvAttach = new Attach()
                        {
                            Source = new Source()
                            {
                                Address = request.Target
                            },
                            Target = new Target()
                            {
                                Address = CFXHandle
                            }
                        };

                        receiver = new ReceiverLink(reqSession, "request-receiver", recvAttach, null);
                        receiver.Start(300);
                        sender = new SenderLink(reqSession, CFXHandle, request.Target);

                        sender.Send(req);
                        Message resp = receiver.Receive(RequestTimeout.Value);
                        if (resp != null)
                        {
                            receiver.Accept(resp);
                            response = AmqpUtilities.EnvelopeFromMessage(resp);
                        }
                        else
                        {
                            throw new TimeoutException("A response was not received from target CFX endpoint in the alloted time.");
                        }
                    }
                    catch (Exception ex3)
                    {
                        AppLog.Error(ex3);
                        ex = ex3;
                    }
                });
            }
            catch (Exception ex2)
            {
                AppLog.Error(ex2);
                if (ex == null)
                {
                    ex = ex2;
                }
            }
            finally
            {
                if (receiver != null && !receiver.IsClosed)
                {
                    await receiver.CloseAsync();
                }
                if (sender != null && !sender.IsClosed)
                {
                    await sender.CloseAsync();
                }
                if (reqSession != null && !reqSession.IsClosed)
                {
                    await reqSession.CloseAsync();
                }
                if (reqConn != null && !reqConn.IsClosed)
                {
                    await reqConn.CloseAsync();
                }
            }

            if (ex != null)
            {
                if (ex.InnerException != null)
                {
                    throw ex.InnerException;
                }
                throw ex;
            }

            return(response);
        }
示例#21
0
        /// <summary>
        /// Main method of sender
        /// </summary>
        /// <param name="args">args from command line</param>
        /// <returns>int status exit code</returns>
        public void Run(string[] args)
        {
            SenderOptions options = new SenderOptions();

            try
            {
                this.ParseArguments(args, options);

                //init timestamping
                this.ptsdata = Utils.TsInit(options.LogStats);
                Utils.TsSnapStore(this.ptsdata, 'B', options.LogStats);

                this.SetAddress(options.Url);
                this.CreateConnection(options);

                Utils.TsSnapStore(this.ptsdata, 'C', options.LogStats);

                this.CreateSession();

                Utils.TsSnapStore(this.ptsdata, 'D', options.LogStats);

                SenderLink sender = this.PrepareSender(options);

                //enable transactions
                bool tx_batch_flag = String.IsNullOrEmpty(options.TxLoopendAction) ? (options.TxSize > 0) : true;

                Stopwatch stopwatch = new Stopwatch();
                TimeSpan  timespan  = options.Timeout;

                stopwatch.Start();

                this.ts = Utils.GetTime();
                Utils.TsSnapStore(this.ptsdata, 'E', options.LogStats);

                //sending of messages
                if (tx_batch_flag)
                {
                    this.TransactionSend(sender, options);
                }
                else
                {
                    this.Send(sender, options);
                }

                if (options.LogStats.IndexOf("endpoints") > -1)
                {
                    Dictionary <string, object> stats = GetSenderStats(sender);
                    Formatter.PrintStatistics(stats);
                }


                Utils.TsSnapStore(this.ptsdata, 'F', options.LogStats);
                //close-sleep
                if (options.CloseSleep > 0)
                {
                    System.Threading.Thread.Sleep(options.CloseSleep);
                }

                ///close connection and link
                this.CloseLink(sender);
                this.CloseConnection();

                Utils.TsSnapStore(this.ptsdata, 'G', options.LogStats);

                if (this.ptsdata.Count > 0)
                {
                    Console.WriteLine("STATS " + Utils.TsReport(this.ptsdata, options.MsgCount,
                                                                options.Content.Length * sizeof(Char), 0));
                }
                this.exitCode = ReturnCode.ERROR_SUCCESS;
            }
            catch (ArgumentException ex)
            {
                this.ArgumentExceptionHandler(ex, options);
            }
            catch (Exception ex)
            {
                this.OtherExceptionHandler(ex, options);
            }
            finally
            {
                this.CloseConnection();
            }
            Environment.Exit(this.exitCode);
        }
示例#22
0
        /// <summary>
        /// Tests if the specified network address and AMQP target address is capable of receiving messages published from this endpoint.
        /// </summary>
        /// <param name="networkAddress">The network address of the target channel.</param>
        /// <param name="address">The AMQP target address to which messages will be published.</param>
        /// <param name="error">In the case of an error, returns information about the nature of the error.</param>
        /// <param name="virtualHostName">The name of the virtual host at the destination endpoint.  Default is null for default virtual host.  For RabbitMQ broker, use format vhost:MYVHOST</param>
        /// <param name="certificate">If secure amqps is being used, this property may optionally include the certificate that will be matched
        /// against the server's certificate.  Leave null if you do not wish to perform certificate matching (secure communications will still be established
        /// using the server's certificate (if using amqps).</param>
        /// <returns>A boolean value indicated whether or not the channel is valid.</returns>
        public bool TestPublishChannel(Uri networkAddress, string address, out Exception error, string virtualHostName = null, X509Certificate certificate = null)
        {
            error = null;
            Connection conn = null;
            Session    sess = null;
            SenderLink link = null;
            Exception  ex   = null;

            try
            {
                Open o = new Open()
                {
                    ContainerId  = Guid.NewGuid().ToString(),
                    HostName     = virtualHostName,
                    MaxFrameSize = (uint)AmqpCFXEndpoint.MaxFrameSize.Value
                };

                ConnectionFactory fact = new ConnectionFactory();
                if (string.IsNullOrWhiteSpace(networkAddress.UserInfo))
                {
                    fact.SASL.Profile = SaslProfile.Anonymous;
                }

                if (networkAddress.Scheme.ToUpper() == "AMQPS")
                {
                    LastCertificate = certificate;
                    LastUri         = networkAddress;
                    fact.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
                }

                Task <Connection> tConn = fact.CreateAsync(new Address(networkAddress.ToString()), o);
                tConn.Wait(3000);
                if (tConn.Status != TaskStatus.RanToCompletion)
                {
                    throw new Exception("Timeout");
                }

                conn         = tConn.Result;
                conn.Closed += (IAmqpObject s, Error e) => { if (e != null)
                                                             {
                                                                 ex = new Exception(e.Description);
                                                             }
                };
                sess         = new Session(conn);
                sess.Closed += (IAmqpObject s, Error e) => { if (e != null)
                                                             {
                                                                 ex = new Exception(e.Description);
                                                             }
                };
                if (ex != null)
                {
                    throw ex;
                }
                link         = new SenderLink(sess, address, address);
                link.Closed += (IAmqpObject s, Error e) => { if (e != null)
                                                             {
                                                                 ex = new Exception(e.Description);
                                                             }
                };
                link.Close();
                Task.Delay(10).Wait();
                if (ex != null)
                {
                    throw ex;
                }
            }
            catch (Exception ex2)
            {
                error = ex2;
                Debug.WriteLine(ex2.Message);
            }
            finally
            {
                if (sess != null && !sess.IsClosed)
                {
                    sess.CloseAsync();
                }
                if (conn != null && !conn.IsClosed)
                {
                    conn.CloseAsync();
                }
            }

            if (error == null)
            {
                return(true);
            }
            return(false);
        }
示例#23
0
        public void ContainerHostCloseTest()
        {
            string name = "ContainerHostCloseTest";
            Uri    uri  = new Uri("amqp://*****:*****@localhost:15673");

            ContainerHost h = new ContainerHost(new List <Uri>()
            {
                uri
            }, null, uri.UserInfo);

            h.Open();
            h.RegisterMessageProcessor(name, new TestMessageProcessor());

            //Create a client to send data to the host message processor
            var closedEvent = new ManualResetEvent(false);
            var connection  = new Connection(new Address(uri.AbsoluteUri));

            connection.Closed += (AmqpObject obj, Error error) =>
            {
                closedEvent.Set();
            };

            var session = new Session(connection);
            var sender  = new SenderLink(session, "sender-link", name);

            //Send one message while the host is open
            sender.Send(new Message("Hello"), SendTimeout);

            //Close the host. this should close existing connections
            h.Close();

            Assert.IsTrue(closedEvent.WaitOne(10000), "connection is not closed after host is closed.");

            try
            {
                sender.Send(new Message("test"));
                Assert.IsTrue(false, "exception not thrown");
            }
            catch (AmqpException exception)
            {
                Assert.IsTrue(exception.Error != null, "Error is null");
                Assert.AreEqual((Symbol)ErrorCode.ConnectionForced, exception.Error.Condition, "Wrong error code");
            }

            connection.Close();

            // Reopen the host and send again
            // Use a different port as on some system the port is not released immediately
            uri = new Uri("amqp://*****:*****@localhost:15674");
            h   = new ContainerHost(new List <Uri>()
            {
                uri
            }, null, uri.UserInfo);
            h.RegisterMessageProcessor(name, new TestMessageProcessor());
            h.Open();

            connection = new Connection(new Address(uri.AbsoluteUri));
            session    = new Session(connection);
            sender     = new SenderLink(session, "sender-link", name);
            sender.Send(new Message("Hello"), SendTimeout);
            connection.Close();

            h.Close();
        }
        public void SendWithLinkDetachTest()
        {
            this.testListener.RegisterTarget(TestPoint.Transfer, (stream, channel, fields) =>
            {
                // detach the link
                TestListener.FRM(stream, 0x16UL, 0, channel, fields[0], true);
                return(TestOutcome.Stop);
            });
            this.testListener.RegisterTarget(TestPoint.Detach, (stream, channel, fields) =>
            {
                return(TestOutcome.Stop);
            });

            string testName = "SendWithLinkDetachTest";

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Connection connection = new Connection(this.address);
                Session    session    = new Session(connection);
                SenderLink sender     = new SenderLink(session, "sender-" + testName, "any");
                try
                {
                    sender.Send(new Message("test")
                    {
                        Properties = new Properties()
                        {
                            MessageId = testName
                        }
                    });
                    Assert.IsTrue(false, "Send should throw exception");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual(ErrorCode.MessageReleased, (string)exception.Error.Condition);
                }
                connection.Close();
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async() =>
            {
                Connection connection = await Connection.Factory.CreateAsync(this.address);
                Session session       = new Session(connection);
                SenderLink sender     = new SenderLink(session, "sender-" + testName, "any");
                try
                {
                    await sender.SendAsync(new Message("test")
                    {
                        Properties = new Properties()
                        {
                            MessageId = testName
                        }
                    });
                    Assert.IsTrue(false, "Send should throw exception");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual(ErrorCode.MessageReleased, (string)exception.Error.Condition);
                }
                await connection.CloseAsync();
            }).Unwrap().GetAwaiter().GetResult();
        }
示例#25
0
        public void TransactedRetiringAndPosting()
        {
            string testName = "TransactedRetiringAndPosting";
            int    nMsgs    = 10;

            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("test");
                message.Properties = new Properties()
                {
                    MessageId = "msg" + i, GroupId = testName
                };
                sender.Send(message);
            }

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

            receiver.SetCredit(2, false);
            Message message1 = receiver.Receive();
            Message message2 = receiver.Receive();

            // ack message1 and send a new message in a txn
            using (var ts = new TransactionScope())
            {
                receiver.Accept(message1);

                Message message = new Message("test");
                message.Properties = new Properties()
                {
                    MessageId = "msg" + nMsgs, GroupId = testName
                };
                sender.Send(message);

                ts.Complete();
            }

            // ack message2 and send a new message in a txn but abort the txn
            using (var ts = new TransactionScope())
            {
                receiver.Accept(message2);

                Message message = new Message("test");
                message.Properties = new Properties()
                {
                    MessageId = "msg" + (nMsgs + 1), GroupId = testName
                };
                sender.Send(message1);
            }

            receiver.Release(message2);

            // receive all messages. should see the effect of the first txn
            receiver.SetCredit(nMsgs, false);
            for (int i = 1; i <= nMsgs; i++)
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId);
                receiver.Accept(message);
                Assert.AreEqual("msg" + i, message.Properties.MessageId);
            }

            connection.Close();
        }
示例#26
0
        void GetSampleAndSendAmqpMessage(SenderLink sender)
        {
            // Obtain the last sample as gathered by the background thread
            // Interlocked.Exchange guarantees that changes are done atomically between main and background thread
            var sample = Interlocked.Exchange(ref lastDataSample, null);

            // No new sample since we checked last time: don't send anything
            if (sample == null)
            {
                return;
            }

            Message message = new Message();

            message.Properties = new Properties()
            {
                Subject      = AppSubject,      // Message type defined in App.config file for sensor
                CreationTime = DateTime.UtcNow, // Time of data sampling
            };

            message.MessageAnnotations = new MessageAnnotations();
            // Event Hub partition key: device id - ensures that all messages from this device go to the same partition and thus preserve order/co-location at processing time
            message.MessageAnnotations[new Symbol("x-opt-partition-key")] = deviceId;
            message.ApplicationProperties         = new ApplicationProperties();
            message.ApplicationProperties["time"] = message.Properties.CreationTime;
            message.ApplicationProperties["from"] = deviceId;             // Originating device
            message.ApplicationProperties["dspl"] = AppDeviceDisplayName; // Display name for originating device

            if (sample != null && sample.Count > 0)
            {
#if !SENDAPPPROPERTIES
                var outDictionary = new Dictionary <string, object>(sample);
                outDictionary["Subject"]       = message.Properties.Subject; // Message Type
                outDictionary["time"]          = message.Properties.CreationTime;
                outDictionary["from"]          = deviceId;                   // Originating device
                outDictionary["dspl"]          = AppDeviceDisplayName;       // Display name for originating device
                message.Properties.ContentType = "text/json";
                message.Body = new Data()
                {
                    Binary = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(outDictionary))
                };
#else
                foreach (var sampleProperty in sample)
                {
                    message.ApplicationProperties [sample.Key] = sample.Value;
                }
#endif
            }
            else
            {
                // No data: send an empty message with message type "weather error" to help diagnose problems "from the cloud"
                message.Properties.Subject = "wthrerr";
            }

            sender.Send(message, SendOutcome, null); // Send to the cloud asynchronously

#if LOG_MESSAGE_RATE
            if (g_messageCount >= 500)
            {
                float secondsElapsed = ((float)stopWatch.ElapsedMilliseconds) / (float)1000.0;
                if (secondsElapsed > 0)
                {
                    Console.WriteLine("Message rate: {0} msg/s", g_messageCount / secondsElapsed);
                    g_messageCount = 0;
                    stopWatch.Restart();
                }
            }
#endif
        }
示例#27
0
        public void TestMethod_ModifyMessage()
        {
            string     testName   = "ModifyMessage";
            const int  nMsgs      = 20;
            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();
                message.MessageAnnotations = new MessageAnnotations();
                message.MessageAnnotations[(Symbol)"a1"] = 12345L;
                message.Properties = new Properties()
                {
                    MessageId = "msg" + i
                };
                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.Properties.MessageId);
                if (i % 2 == 0)
                {
                    receiver.Accept(message);
                }
                else
                {
                    receiver.Modify(message, true, false, new Fields()
                    {
                        { (Symbol)"reason", "app offline" }
                    });
                }
            }
            receiver.Close();

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

            for (int i = 0; i < nMsgs / 2; ++i)
            {
                Message message = receiver2.Receive();
                Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.Properties.MessageId);
                Assert.IsTrue(message.Header != null, "header is null");
                Assert.IsTrue(message.Header.DeliveryCount > 0, "delivery-count is 0");
                Assert.IsTrue(message.MessageAnnotations != null, "annotation is null");
                Assert.IsTrue(message.MessageAnnotations[(Symbol)"a1"].Equals(12345L));
                Assert.IsTrue(message.MessageAnnotations[(Symbol)"reason"].Equals("app offline"));
                receiver2.Accept(message);
            }

            receiver2.Close();
            sender.Close();
            session.Close();
            connection.Close();
        }
示例#28
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="deviceId"></param>
        public void SendEvent(string deviceId)
        {
            string to = Fx.Format("/devices/{0}/messages/events", deviceId);

            string audience = Fx.Format("{0}/devices/{1}", IoThubURI, deviceId);

            Fx.Format($"{0}/devices/{1}", IoThubURI, deviceId);

            string sasToken = "SharedAccessSignature sr=IoTHubCookBook.azure-devices.net&sig=hU2tQbo1aYnFfGC8ctSfifeIV677KKlWpnCS%2F05SMxY%3D&se=1531101825&skn=iothubowner";
            bool   cbs      = PutCbsToken(_connection, sasToken, audience);

            if (cbs)
            {
                _session = new Session(_connection);
            }

            SenderLink senderevent = new SenderLink(_session, "senderevent", to);

            double avgWindSpeed = 10; // m/s
            Random rand         = new Random();


            int i = 0;

            while (i < 10)
            {
                var currentWindSpeed   = avgWindSpeed + rand.NextDouble() * 4 - 2;
                var telemetryDataPoint = new
                {
                    deviceId,
                    windSpeed = currentWindSpeed,
                    highTemp  = rand.Next(45, 95),
                    lowtemp   = rand.Next(-5, 25),
                    latitude  = "17.5122560",
                    longitude = "70.7760470"
                };

                var json = JsonConvert.SerializeObject(telemetryDataPoint);

                var messageValue = Encoding.UTF8.GetBytes(json);

                var telemetryMessage = new Message()
                {
                    BodySection = new Data()
                    {
                        Binary = messageValue
                    }
                };

                telemetryMessage.Properties            = new Properties();
                telemetryMessage.Properties.To         = to;
                telemetryMessage.Properties.MessageId  = Guid.NewGuid().ToString();
                telemetryMessage.ApplicationProperties = new ApplicationProperties();

                senderevent.Send(telemetryMessage);
                System.Threading.Thread.Sleep(5000);

                i++;
            }
            senderevent.Close();
        }
示例#29
0
        //
        // Sample invocation: Interop.Client amqp://guest:guest@localhost:5672 [loopcount]
        //
        static int Main(string[] args)
        {
            String url = "amqp://*****:*****@localhost:5672";
            String requestQueueName = "service_queue";
            int    loopcount        = 1;

            if (args.Length > 0)
            {
                url = args[0];
            }
            if (args.Length > 1)
            {
                loopcount = Convert.ToInt32(args[1]);
            }

            Connection.DisableServerCertValidation = true;
            // uncomment the following to write frame traces
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));

            Connection connection = null;

            try
            {
                Address address = new Address(url);
                connection = new Connection(address);
                Session session = new Session(connection);

                // Sender attaches to fixed request queue name
                SenderLink sender = new SenderLink(session, "Interop.Client-sender", requestQueueName);

                // Receiver attaches to dynamic address.
                // Discover its name when it attaches.
                String           replyTo            = "";
                ManualResetEvent receiverAttached   = new ManualResetEvent(false);
                OnAttached       onReceiverAttached = (l, a) =>
                {
                    replyTo = ((Source)a.Source).Address;
                    receiverAttached.Set();
                };

                // Create receiver and wait for it to attach.
                ReceiverLink receiver = new ReceiverLink(
                    session, "Interop.Client-receiver", new Source()
                {
                    Dynamic = true
                }, onReceiverAttached);
                if (receiverAttached.WaitOne(10000))
                {
                    // Receiver is attached.
                    // Send a series of requests, gather and print responses.
                    String[] requests = new String[] {
                        "Twas brillig, and the slithy toves",
                        "Did gire and gymble in the wabe.",
                        "All mimsy were the borogoves,",
                        "And the mome raths outgrabe."
                    };

                    for (int j = 0; j < loopcount; j++)
                    {
                        Console.WriteLine("Pass {0}", j);
                        for (int i = 0; i < requests.Length; i++)
                        {
                            Message request = new Message(requests[i]);
                            request.Properties = new Properties()
                            {
                                MessageId = "request" + i, ReplyTo = replyTo
                            };
                            sender.Send(request);
                            Message response = receiver.Receive(10000);
                            if (null != response)
                            {
                                receiver.Accept(response);
                                Console.WriteLine("Processed request: {0} -> {1}",
                                                  GetContent(request), GetContent(response));
                            }
                            else
                            {
                                Console.WriteLine("Receiver timeout receiving response {0}", i);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Receiver attach timeout");
                }
                receiver.Close();
                sender.Close();
                session.Close();
                connection.Close();
                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0}.", e);
                if (null != connection)
                {
                    connection.Close();
                }
            }
            return(1);
        }
示例#30
0
        static async Task RunAsync(string address)
        {
            var serializer = new AmqpSerializer(new PocoContractResolver()
            {
                PrefixList = new[] { "Serialization.Poco" }
            });

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

                Session    session = new Session(connection);
                SenderLink sender  = new SenderLink(session, "sender", "q1");
                Shape      shape1  = new Circle()
                {
                    Id         = Guid.NewGuid(),
                    Attributes = new Dictionary <string, object>()
                    {
                        { "Time", DateTime.UtcNow },
                        { "Source", "amqpnetlite.samples" }
                    },
                    Radius = 5.3
                };
                Console.WriteLine("Sending {0}", shape1);
                await sender.SendAsync(new Message()
                {
                    BodySection = new AmqpValue <object>(shape1, serializer)
                });

                Shape shape2 = new Rectangle()
                {
                    Id         = Guid.NewGuid(),
                    Attributes = new Dictionary <string, object>()
                    {
                        { "Color", new Symbol("blue") },
                        { "Line", true }
                    },
                    Width  = 8,
                    Height = 10
                };
                Console.WriteLine("Sending {0}", shape2);
                await sender.SendAsync(new Message()
                {
                    BodySection = new AmqpValue <object>(shape2, serializer)
                });

                await connection.CloseAsync();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
                return;
            }

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

                Session      session  = new Session(connection);
                ReceiverLink receiver = new ReceiverLink(session, "receiver", "q1");
                using (Message message = await receiver.ReceiveAsync())
                {
                    Shape shape = message.GetBody <Shape>(serializer);
                    Console.WriteLine("Received {0}", shape);
                    receiver.Accept(message);
                }
                using (Message message = await receiver.ReceiveAsync())
                {
                    Shape shape = message.GetBody <Shape>(serializer);
                    Console.WriteLine("Received {0}", shape);
                    receiver.Accept(message);
                }
                await connection.CloseAsync();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
            }
        }